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

Merge pull request #48 from tianhao64/master

VMware Cloud on AWS M3 release
This commit is contained in:
Tianhao He 2018-03-08 14:44:51 -08:00 committed by GitHub
commit 5347716f83
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
84 changed files with 2127 additions and 1128 deletions

Binary file not shown.

Binary file not shown.

View File

@ -1 +1 @@
<a href='vapi_client_bindings-1.0.0-py2.py3-none-any.whl'>vapi_client_bindings-1.0.0-py2.py3-none-any.whl</a><br /> <a href='vapi_client_bindings-1.1.0-py2.py3-none-any.whl'>vapi_client_bindings-1.1.0-py2.py3-none-any.whl</a><br />

View File

@ -1 +1 @@
<a href='vapi_runtime-2.7.1-py2.py3-none-any.whl'>vapi_runtime-2.7.1-py2.py3-none-any.whl</a><br /> <a href='vapi_runtime-2.9.0-py2.py3-none-any.whl'>vapi_runtime-2.9.0-py2.py3-none-any.whl</a><br />

View File

@ -1 +1 @@
<a href='vapi_vmc_client-2.7.1-py2.py3-none-any.whl'>vapi_vmc_client-2.7.1-py2.py3-none-any.whl</a><br /> <a href='vapi_vmc_client-2.9.0-py2.py3-none-any.whl'>vapi_vmc_client-2.9.0-py2.py3-none-any.whl</a><br />

View File

@ -1 +1 @@
<a href='vmc_client_bindings-1.0.0-py2.py3-none-any.whl'>vmc_client_bindings-1.0.0-py2.py3-none-any.whl</a><br /> <a href='vmc_client_bindings-1.1.0-py2.py3-none-any.whl'>vmc_client_bindings-1.1.0-py2.py3-none-any.whl</a><br />

View File

@ -2,6 +2,6 @@ pyVmomi >= 6.5
suds ; python_version < '3' suds ; python_version < '3'
suds-jurko ; python_version >= '3.0' suds-jurko ; python_version >= '3.0'
tabulate tabulate
vapi-client-bindings == 1.0.0 vapi-client-bindings == 1.1.0
vmc-client-bindings vmc-client-bindings == 1.1.0
vapi-vmc-client vapi-vmc-client

View File

@ -7,6 +7,4 @@ The steps included in the template code are:
* Cmd line argument parser. * Cmd line argument parser.
* Login to vAPI services using vSphere Automation API. * Login to vAPI services using vSphere Automation API.
* Login to Vim service using [pyVmomi](https://github.com/vmware/pyvmomi).
* Cleanup after sample execution. * Cleanup after sample execution.
* Logout from both services.

View File

@ -16,12 +16,12 @@
__author__ = 'TODO: <your name and email>' __author__ = 'TODO: <your name and email>'
__vcenter_version__ = 'TODO: <compatible vcenter versions>' __vcenter_version__ = 'TODO: <compatible vcenter versions>'
import atexit
from com.vmware.vcenter_client import VM from com.vmware.vcenter_client import VM
from vmware.vapi.vsphere.client import create_vsphere_client
from samples.vsphere.common import sample_cli from samples.vsphere.common import sample_cli
from samples.vsphere.common import sample_util from samples.vsphere.common import sample_util
from samples.vsphere.common.service_manager import ServiceManager from samples.vsphere.common.ssl_helper import get_unverified_session
class Sample(object): class Sample(object):
@ -32,13 +32,7 @@ class Sample(object):
Sample Prerequisites: Sample Prerequisites:
- vCenter - vCenter
""" """
def __init__(self): def __init__(self):
self.service_manager = None
self.vm_name = None
self.cleardata = None
def setup(self):
# Create argument parser for standard inputs: # Create argument parser for standard inputs:
# server, username, password, cleanup and skipverification # server, username, password, cleanup and skipverification
parser = sample_cli.build_arg_parser() parser = sample_cli.build_arg_parser()
@ -53,27 +47,24 @@ class Sample(object):
self.vm_name = args.vm_name self.vm_name = args.vm_name
self.cleardata = args.cleardata self.cleardata = args.cleardata
# Connect to both Vim and vAPI services # Skip server cert verification if needed.
self.service_manager = ServiceManager(args.server, # This is not recommended in production code.
args.username, session = get_unverified_session() if args.skipverification else None
args.password,
args.skipverification) # Connect to vSphere client
self.service_manager.connect() self.client = create_vsphere_client(server=args.server,
atexit.register(self.service_manager.disconnect) username=args.username,
password=args.password,
session=session)
def run(self): def run(self):
# TODO add your sample code here # TODO add your sample code here
# Using REST API service # Using REST API service
vm_service = VM(self.service_manager.stub_config)
filter_spec = VM.FilterSpec(names=set([self.vm_name])) filter_spec = VM.FilterSpec(names=set([self.vm_name]))
vms = vm_service.list(filter_spec) vms = self.client.vcenter.VM.list(filter_spec)
print(vms) print(vms)
# Using Vim API service (pyVmomi)
current_time = self.service_manager.si.CurrentTime()
print(current_time)
def cleanup(self): def cleanup(self):
if self.cleardata: if self.cleardata:
# TODO add cleanup code # TODO add cleanup code
@ -82,7 +73,6 @@ class Sample(object):
def main(): def main():
sample = Sample() sample = Sample()
sample.setup()
sample.run() sample.run()
sample.cleanup() sample.cleanup()

View File

@ -6,4 +6,6 @@ Directory | Description
----------------| ------------- ----------------| -------------
orgs | Samples for operations on organizations orgs | Samples for operations on organizations
sddc | Samples for operations on SDDCs sddc | Samples for operations on SDDCs
networks | Samples for networking APIs
helpers | Helper methods used by VMware Cloud on AWS API samples helpers | Helper methods used by VMware Cloud on AWS API samples

View File

@ -0,0 +1,25 @@
"""
* *******************************************************
* Copyright VMware, Inc. 2018. All Rights Reserved.
* SPDX-License-Identifier: MIT
* *******************************************************
*
* DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, WHETHER ORAL OR WRITTEN,
* EXPRESS OR IMPLIED. THE AUTHOR SPECIFICALLY DISCLAIMS ANY IMPLIED
* WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY,
* NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
"""
__author__ = 'VMware, Inc.'
# 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

@ -0,0 +1,180 @@
#!/usr/bin/env python
"""
* *******************************************************
* Copyright (c) VMware, Inc. 2018. All Rights Reserved.
* SPDX-License-Identifier: MIT
* *******************************************************
*
* DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, WHETHER ORAL OR WRITTEN,
* EXPRESS OR IMPLIED. THE AUTHOR SPECIFICALLY DISCLAIMS ANY IMPLIED
* WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY,
* NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
"""
__author__ = 'VMware, Inc.'
import argparse
from com.vmware.vmc.model_client import *
from tabulate import tabulate
from vmware.vapi.vmc.client import create_vmc_client
class DNSCrud(object):
"""
Demonstrates DNS CRUD operations
Sample Prerequisites:
- An organization associated with the calling user.
- A SDDC in the organization
"""
def __init__(self):
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-r', '--refresh-token',
required=True,
help='VMware Cloud API refresh token')
parser.add_argument('-o', '--org-id',
required=True,
help='Organization identifier.')
parser.add_argument('-s', '--sddc-id',
required=True,
help='Sddc Identifier.')
parser.add_argument('--use-compute-gateway',
action='store_true',
default=False,
help='Use compute gateway. Default is using '
'management gateway')
parser.add_argument('-c', '--cleardata',
action='store_true',
help='Clean up after sample run')
args = parser.parse_args()
self.edge_id = None
self.org_id = args.org_id
self.sddc_id = args.sddc_id
self.compute_gw = args.use_compute_gateway
self.cleanup = args.cleardata
self.vmc_client = create_vmc_client(args.refresh_token)
def setup(self):
# Check if the organization exists
orgs = self.vmc_client.Orgs.list()
if self.org_id not in [org.id for org in orgs]:
raise ValueError("Org with ID {} doesn't exist".format(self.org_id))
# Check if the SDDC exists
sddcs = self.vmc_client.orgs.Sddcs.list(self.org_id)
if self.sddc_id not in [sddc.id for sddc in sddcs]:
raise ValueError("SDDC with ID {} doesn't exist in org {}".
format(self.sddc_id, self.org_id))
print('\n# Setup: List network gateway edges:')
edges = self.vmc_client.orgs.sddcs.networks.Edges.get(
org=self.org_id,
sddc=self.sddc_id,
edge_type='gatewayServices').edge_page.data
print(' Management Gateway ID: {}'.format(edges[0].id))
print(' Compute Gateway ID: {}'.format(edges[1].id))
if self.compute_gw:
self.edge_id = edges[1].id
print('# Use Compute Gateway in this Sample')
else:
self.edge_id = edges[0].id
print('# Use Management Gateway in this Sample')
def get_dns(self):
print('\n# Example: List basic DNS specs')
# Get the first DNS
dns = self.vmc_client.orgs.sddcs.networks.edges.dns.Config.get(
org=self.org_id,
sddc=self.sddc_id,
edge_id=self.edge_id).dns_views.dns_view[0]
self.print_output(dns)
def enable_disable_dns(self):
if self.compute_gw:
print('\n# Example: Enable or disable Compute Gateway DNS')
else:
print('\n# Example: Enable or disable DNS Management Gateway DNS')
dns_config = self.vmc_client.orgs.sddcs.networks.edges.dns.Config.get(
org=self.org_id,
sddc=self.sddc_id,
edge_id=self.edge_id)
new_state = True
if dns_config.enabled:
print('# DNS was enabled. Disable it now..')
new_state = False
else:
print('# DNS was disabled. Enable it now..')
self.vmc_client.orgs.sddcs.networks.edges.dns.Config.create(
org=self.org_id,
sddc=self.sddc_id,
edge_id=self.edge_id,
enable=new_state)
def update_dns(self):
print('\n# Example: Update the DNS IP Addresses')
dns_config = self.vmc_client.orgs.sddcs.networks.edges.dns.Config.get(
org=self.org_id,
sddc=self.sddc_id,
edge_id=self.edge_id)
dns_config.dns_views.dns_view[0].forwarders = DnsForwarders(
ip_address=['9.9.9.9', '9.9.4.4'])
self.vmc_client.orgs.sddcs.networks.edges.dns.Config.update(
org=self.org_id,
sddc=self.sddc_id,
edge_id=self.edge_id,
dns_config=dns_config
)
print('# List updated DNS specs')
updated_vpn = self.vmc_client.orgs.sddcs.networks.edges.dns.Config.get(
org=self.org_id,
sddc=self.sddc_id,
edge_id=self.edge_id).dns_views.dns_view[0]
self.print_output(updated_vpn)
def delete_dns(self):
if self.cleanup:
self.vmc_client.orgs.sddcs.networks.edges.dns.Config.delete(
org=self.org_id,
sddc=self.sddc_id,
edge_id=self.edge_id)
print('\n# Example: DNS is deleted')
def print_output(self, dns):
# DNS IP address might be empty
ips = getattr(dns.forwarders, 'ip_address', [])
result = [[dns.name, ips]]
print(tabulate(result, ['Name', 'IP Addresses']))
def main():
dns_crud = DNSCrud()
dns_crud.setup()
dns_crud.get_dns()
dns_crud.enable_disable_dns()
dns_crud.update_dns()
dns_crud.delete_dns()
if __name__ == '__main__':
main()

View File

@ -0,0 +1,232 @@
#!/usr/bin/env python
"""
* *******************************************************
* Copyright (c) VMware, Inc. 2018. All Rights Reserved.
* SPDX-License-Identifier: MIT
* *******************************************************
*
* DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, WHETHER ORAL OR WRITTEN,
* EXPRESS OR IMPLIED. THE AUTHOR SPECIFICALLY DISCLAIMS ANY IMPLIED
* WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY,
* NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
"""
__author__ = 'VMware, Inc.'
import argparse
from com.vmware.vmc.model_client import *
from tabulate import tabulate
from vmware.vapi.vmc.client import create_vmc_client
class FirewallRulesCrud(object):
"""
Demonstrates firewall rule CRUD operations
Sample Prerequisites:
- An organization associated with the calling user.
- A SDDC in the organization
"""
def __init__(self):
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-r', '--refresh-token',
required=True,
help='VMware Cloud API refresh token')
parser.add_argument('-o', '--org-id',
required=True,
help='Organization identifier.')
parser.add_argument('-s', '--sddc-id',
required=True,
help='Sddc Identifier.')
parser.add_argument('--rule-name',
default='Sample Firewall Rule',
help='Name of the new firewall rule')
parser.add_argument('--use-compute-gateway',
action='store_true',
default=False,
help='Use compute gateway. Default is using '
'management gateway')
parser.add_argument('-c', '--cleardata',
action='store_true',
help='Clean up after sample run')
args = parser.parse_args()
self.edge_id = None
self.rule_id = None
self.nfwr = None
self.org_id = args.org_id
self.sddc_id = args.sddc_id
self.rule_name = args.rule_name
self.compute_gw = args.use_compute_gateway
self.cleanup = args.cleardata
self.vmc_client = create_vmc_client(args.refresh_token)
def setup(self):
# Check if the organization exists
orgs = self.vmc_client.Orgs.list()
if self.org_id not in [org.id for org in orgs]:
raise ValueError("Org with ID {} doesn't exist".format(self.org_id))
# Check if the SDDC exists
sddcs = self.vmc_client.orgs.Sddcs.list(self.org_id)
if self.sddc_id not in [sddc.id for sddc in sddcs]:
raise ValueError("SDDC with ID {} doesn't exist in org {}".
format(self.sddc_id, self.org_id))
def create_firewall_rule(self):
if self.compute_gw:
print('\n# Example: Add a firewall rule to the Compute Gateway')
else:
print('\n# Example: Add a firewall rule to the Management Gateway')
print('# List network gateway edges:')
edges = self.vmc_client.orgs.sddcs.networks.Edges.get(
org=self.org_id,
sddc=self.sddc_id,
edge_type='gatewayServices').edge_page.data
print(' Management Gateway ID: {}'.format(edges[0].id))
print(' Compute Gateway ID: {}'.format(edges[1].id))
self.edge_id = edges[1].id if self.compute_gw else edges[0].id
sddc = self.vmc_client.orgs.Sddcs.get(self.org_id, self.sddc_id)
# Construct an destination object for the new firewall rule
# You can use one of following destination IP addresses
# IPs for vCenter
ip_address = [sddc.resource_config.vc_public_ip,
sddc.resource_config.vc_management_ip]
# TODO: IPs for ESXi
# TODO: IPs for Site Recovery Manager
# TODO: IPs for vSphere Replication
# TODO: IPs for Management Gateway
# IPs for NSX Manager
# ip_address = [sddc.resource_config.nsx_mgr_management_ip]
destination = AddressFWSourceDestination(
exclude=False,
ip_address=ip_address,
grouping_object_id=[],
vnic_group_id=[])
# Construct a new NSX firewall rule object
self.nfwr = Nsxfirewallrule(rule_type='user',
name=self.rule_name,
enabled=True,
action='accept',
source=AddressFWSourceDestination(
exclude=False,
ip_address=['any'],
grouping_object_id=[],
vnic_group_id=[]),
destination=destination,
logging_enabled=False,
application=Application(
application_id=[],
service=[Nsxfirewallservice(
source_port=['any'],
protocol='TCP',
port=['443'],
icmp_type=None)]))
self.vmc_client.orgs.sddcs.networks.edges.firewall.config.Rules.add(
org=self.org_id,
sddc=self.sddc_id,
edge_id=self.edge_id,
firewall_rules=FirewallRules([self.nfwr]))
print('# New firewall rule "{}" is added'.format(self.rule_name))
def get_firewall_rule(self):
print('\n# Example: List basic firewall rule specs')
fw_config = self.vmc_client.orgs.sddcs.networks.edges.firewall.Config.get(
org=self.org_id,
sddc=self.sddc_id,
edge_id=self.edge_id)
fw_rules = fw_config.firewall_rules.firewall_rules
for r in fw_rules:
if r.name == self.rule_name:
self.rule_id = r.rule_id
break
else:
raise Exception("Can't find firewall rule with name {}".
format(self.rule_name))
rule = self.vmc_client.orgs.sddcs.networks.edges.firewall.config.Rules.get(
org=self.org_id,
sddc=self.sddc_id,
edge_id=self.edge_id,
rule_id=self.rule_id)
self.print_output(rule)
def update_firewall_rule(self):
print('\n# Example: Update the firewall rule')
self.nfwr.description = 'Updated description'
self.nfwr.name = 'Updated ' + self.rule_name
self.nfwr.action = 'deny'
self.nfwr.source.ip_address = ['127.0.0.1']
self.vmc_client.orgs.sddcs.networks.edges.firewall.config.Rules.update(
org=self.org_id,
sddc=self.sddc_id,
edge_id=self.edge_id,
rule_id=self.rule_id,
nsxfirewallrule=self.nfwr)
rule = self.vmc_client.orgs.sddcs.networks.edges.firewall.config.Rules.get(
org=self.org_id,
sddc=self.sddc_id,
edge_id=self.edge_id,
rule_id=self.rule_id)
print('# List the updated firewall rule specs')
self.print_output(rule)
def delete_firewall_rule(self):
if self.cleanup:
self.vmc_client.orgs.sddcs.networks.edges.firewall.config.Rules.delete(
org=self.org_id,
sddc=self.sddc_id,
edge_id=self.edge_id,
rule_id=self.rule_id)
print('\n# Example: Firewall rule {} is deleted'.
format(self.rule_name))
def print_output(self, rule):
result = [[rule.name, rule.action, rule.source.ip_address,
rule.destination.ip_address,
rule.application.service[0].protocol,
rule.application.service[0].port]]
print(tabulate(result, ['Name', 'Action', 'Source IPs',
'Destination IPs', 'Service Protocol',
'Service Port']))
def main():
firewall_rules = FirewallRulesCrud()
firewall_rules.setup()
firewall_rules.create_firewall_rule()
firewall_rules.get_firewall_rule()
firewall_rules.update_firewall_rule()
firewall_rules.delete_firewall_rule()
if __name__ == '__main__':
main()

View File

@ -0,0 +1,221 @@
#!/usr/bin/env python
"""
* *******************************************************
* Copyright (c) VMware, Inc. 2018. All Rights Reserved.
* SPDX-License-Identifier: MIT
* *******************************************************
*
* DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, WHETHER ORAL OR WRITTEN,
* EXPRESS OR IMPLIED. THE AUTHOR SPECIFICALLY DISCLAIMS ANY IMPLIED
* WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY,
* NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
"""
__author__ = 'VMware, Inc.'
import argparse
from com.vmware.vmc.model_client import *
from tabulate import tabulate
from vmware.vapi.vmc.client import create_vmc_client
class IpsecVPNsCrud(object):
"""
Demonstrates IPsec VPN CRUD operations
Sample Prerequisites:
- An organization associated with the calling user.
- A SDDC in the organization
"""
def __init__(self):
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-r', '--refresh-token',
required=True,
help='VMware Cloud API refresh token')
parser.add_argument('-o', '--org-id',
required=True,
help='Organization identifier.')
parser.add_argument('-s', '--sddc-id',
required=True,
help='Sddc Identifier.')
parser.add_argument('--use-compute-gateway',
action='store_true',
default=False,
help='Use compute gateway. Default is using '
'management gateway')
parser.add_argument('--vpn-name',
default='Sample IPsec VPN',
help='Name of the new VPN')
parser.add_argument('--public-ip',
default='10.10.10.10',
help='IP (IPv4) address or FQDN of the Peer')
parser.add_argument('--private-ip',
default='192.168.10.10',
help='Local IP of the IPsec Site')
parser.add_argument('--remote-networks',
default='192.168.20.10/24',
help='Peer subnets for which VPN is configured')
parser.add_argument('--local-networks',
default='192.168.30.10/24',
help='Local subnets for which VPN is configured')
parser.add_argument('--key',
default='00000000',
help='Pre Shared Key for the IPsec Site')
parser.add_argument('-c', '--cleardata',
action='store_true',
help='Clean up after sample run')
args = parser.parse_args()
self.edge_id = None
self.site_id = None
self.org_id = args.org_id
self.sddc_id = args.sddc_id
self.vpn_name = args.vpn_name
self.public_ip = args.public_ip
self.private_ip = args.private_ip
self.remote_networks = args.remote_networks
self.local_networks = args.local_networks
self.compute_gw = args.use_compute_gateway
self.key = args.key
self.cleanup = args.cleardata
self.vmc_client = create_vmc_client(args.refresh_token)
def setup(self):
# Check if the organization exists
orgs = self.vmc_client.Orgs.list()
if self.org_id not in [org.id for org in orgs]:
raise ValueError("Org with ID {} doesn't exist".format(self.org_id))
# Check if the SDDC exists
sddcs = self.vmc_client.orgs.Sddcs.list(self.org_id)
if self.sddc_id not in [sddc.id for sddc in sddcs]:
raise ValueError("SDDC with ID {} doesn't exist in org {}".
format(self.sddc_id, self.org_id))
print('\n# Setup: List network gateway edges:')
edges = self.vmc_client.orgs.sddcs.networks.Edges.get(
org=self.org_id,
sddc=self.sddc_id,
edge_type='gatewayServices').edge_page.data
print(' Management Gateway ID: {}'.format(edges[0].id))
print(' Compute Gateway ID: {}'.format(edges[1].id))
self.edge_id = edges[1].id if self.compute_gw else edges[0].id
def create_vpn(self):
if self.compute_gw:
print('\n# Example: Add a VPN to the Compute Gateway')
else:
print('\n# Example: Add a VPN to the Management Gateway')
ipsec_site = IpsecSite(
name=self.vpn_name,
psk=self.key,
enable_pfs=True,
authentication_mode='psk',
peer_subnets=Subnets(subnets=[self.remote_networks]),
peer_ip=self.public_ip,
local_ip=self.private_ip,
encryption_algorithm='aes256',
enabled=True,
local_subnets=Subnets(subnets=[self.local_networks]))
ipsec = Ipsec(enabled=True,
sites=IpsecSites(sites=[ipsec_site]))
# TODO: Find out how to add ipsec networks.
self.vmc_client.orgs.sddcs.networks.edges.ipsec.Config.update(
org=self.org_id,
sddc=self.sddc_id,
edge_id=self.edge_id,
ipsec=ipsec)
print('# New ipsec_vpn "{}" is added'.format(self.vpn_name))
def get_vpn(self):
print('\n# Example: List basic ipsec_vpn specs')
site = self.get_vpn_by_name(self.vpn_name)
self.site_id = site.site_id
self.print_output(site)
def update_vpn(self):
print('\n# Example: Update the IPsec VPN')
updated_name = 'Updated ' + self.vpn_name
ipsec = self.vmc_client.orgs.sddcs.networks.edges.ipsec.Config.get(
org=self.org_id,
sddc=self.sddc_id,
edge_id=self.edge_id)
for site in ipsec.sites.sites:
if site.name == self.vpn_name:
site.name = updated_name
self.vmc_client.orgs.sddcs.networks.edges.ipsec.Config.update(
org=self.org_id,
sddc=self.sddc_id,
edge_id=self.edge_id,
ipsec=ipsec)
print('# List updated VPN specs')
updated_vpn = self.get_vpn_by_name(updated_name)
self.print_output(updated_vpn)
def delete_vpn(self):
if self.cleanup:
self.vmc_client.orgs.sddcs.networks.edges.ipsec.Config.delete(
org=self.org_id,
sddc=self.sddc_id,
edge_id=self.edge_id)
print('\n# Example: IPsec VPN {} is deleted'.
format(self.vpn_name))
def get_vpn_by_name(self, name):
sites = self.vmc_client.orgs.sddcs.networks.edges.ipsec.Config.get(
org=self.org_id,
sddc=self.sddc_id,
edge_id=self.edge_id).sites.sites
for site in sites:
if site.name == name:
return site
else:
raise Exception("Can't find IPsec VPN with name {}".
format(self.vpn_name))
def print_output(self, site):
result = [[site.name, site.site_id, site.peer_ip, site.peer_id,
site.peer_subnets, site.local_ip, site.local_subnets]]
print(tabulate(result, ['Name', 'ID', 'Public IPs', 'Private IP',
'Remote Networks', 'Local Gateway IP',
'Local Network']))
def main():
ipsec_vpns = IpsecVPNsCrud()
ipsec_vpns.setup()
# TODO: Find out which API should be used to add IPsec VPN
# ipsec_vpns.create_vpn()
ipsec_vpns.get_vpn()
ipsec_vpns.update_vpn()
ipsec_vpns.delete_vpn()
if __name__ == '__main__':
main()

View File

@ -0,0 +1,208 @@
#!/usr/bin/env python
"""
* *******************************************************
* Copyright (c) VMware, Inc. 2018. All Rights Reserved.
* SPDX-License-Identifier: MIT
* *******************************************************
*
* DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, WHETHER ORAL OR WRITTEN,
* EXPRESS OR IMPLIED. THE AUTHOR SPECIFICALLY DISCLAIMS ANY IMPLIED
* WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY,
* NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
"""
__author__ = 'VMware, Inc.'
import argparse
from com.vmware.vmc.model_client import *
from tabulate import tabulate
from vmware.vapi.vmc.client import create_vmc_client
class LogicalNetworkCrud(object):
"""
Demonstrates logical network CRUD operations
Sample Prerequisites:
- An organization associated with the calling user.
- A SDDC in the organization
"""
def __init__(self):
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-r', '--refresh-token',
required=True,
help='VMware Cloud API refresh token')
parser.add_argument('-o', '--org-id',
required=True,
help='Organization identifier.')
parser.add_argument('-s', '--sddc-id',
required=True,
help='Sddc Identifier.')
parser.add_argument('--network-name',
default='Sample Logical Network',
help='Name of the new logical network')
parser.add_argument('--subnet',
default='192.168.100.1/24',
help='Logical network subnet')
parser.add_argument('--dhcp-range',
default='192.168.100.2-192.168.100.254',
help='DHCP IP range for the logical network')
parser.add_argument('-c', '--cleardata',
action='store_true',
help='Clean up after sample run')
args = parser.parse_args()
self.network_id = None
self.org_id = args.org_id
self.sddc_id = args.sddc_id
self.network_name = args.network_name
self.primary_address, self.prefix_length = args.subnet.split('/')
self.dhcp_range = args.dhcp_range
self.cleanup = args.cleardata
self.vmc_client = create_vmc_client(args.refresh_token)
def setup(self):
# Check if the organization exists
orgs = self.vmc_client.Orgs.list()
if self.org_id not in [org.id for org in orgs]:
raise ValueError("Org with ID {} doesn't exist".format(self.org_id))
# Check if the SDDC exists
sddcs = self.vmc_client.orgs.Sddcs.list(self.org_id)
if self.sddc_id not in [sddc.id for sddc in sddcs]:
raise ValueError("SDDC with ID {} doesn't exist in org {}".
format(self.sddc_id, self.org_id))
# Delete logical networks with same name
networks = self.vmc_client.orgs.sddcs.networks.Logical.get_0(
org=self.org_id,
sddc=self.sddc_id).data
for network in networks:
if network.name == self.network_name:
self.vmc_client.orgs.sddcs.networks.Logical.delete(
org=self.org_id,
sddc=self.sddc_id,
network_id=network.id)
print('\n# Setup: Logical network "{}" '
'with the same name is deleted'.format(network.id))
def create_logical_network(self):
print('\n# Example: Add a logical network to the compute gateway')
edges = self.vmc_client.orgs.sddcs.networks.Edges.get(
org=self.org_id,
sddc=self.sddc_id,
edge_type='gatewayServices').edge_page.data
print(' Compute Gateway ID: {}'.format(edges[1].id))
edge_id = edges[1].id
# Construct a new NSX logical network spec
network = SddcNetwork(
subnets=SddcNetworkAddressGroups(
address_groups=[SddcNetworkAddressGroup(
prefix_length=self.prefix_length,
primary_address=self.primary_address)]),
name=self.network_name,
cgw_id=edge_id,
dhcp_configs=SddcNetworkDhcpConfig(
ip_pools=[SddcNetworkDhcpIpPool(
ip_range=self.dhcp_range,
domain_name=None)]))
self.vmc_client.orgs.sddcs.networks.Logical.create(
org=self.org_id,
sddc=self.sddc_id,
sddc_network=network)
print('\n# New logical network "{}" is added'.format(self.network_name))
def get_logical_network(self):
print('\n# Example: List all logical networks')
networks = self.vmc_client.orgs.sddcs.networks.Logical.get_0(
org=self.org_id,
sddc=self.sddc_id).data
self.print_output(networks)
for network in networks:
if network.name == self.network_name:
self.network_id = network.id
break
else:
raise Exception("Can't find logical network with name {}".
format(self.network_name))
print('\n# Get the new logical network specs')
network = self.vmc_client.orgs.sddcs.networks.Logical.get(
org=self.org_id,
sddc=self.sddc_id,
network_id=self.network_id)
self.print_output([network])
def update_logical_network(self):
print('\n# Example: Update the logical network')
network = self.vmc_client.orgs.sddcs.networks.Logical.get(
org=self.org_id,
sddc=self.sddc_id,
network_id=self.network_id)
network.l2_extension = L2Extension(123)
network.subnets = None
network.dhcp_configs = None
self.vmc_client.orgs.sddcs.networks.Logical.update(
org=self.org_id,
sddc=self.sddc_id,
network_id=self.network_id,
sddc_network=network)
network = self.vmc_client.orgs.sddcs.networks.Logical.get(
org=self.org_id,
sddc=self.sddc_id,
network_id=self.network_id)
print('# List the updated logical network specs')
self.print_output([network])
def delete_logical_network(self):
if self.cleanup:
self.vmc_client.orgs.sddcs.networks.Logical.delete(
org=self.org_id,
sddc=self.sddc_id,
network_id=self.network_id)
print('\n# Example: Logical network "{}" is deleted'.
format(self.network_name))
def print_output(self, networks):
table = []
for network in networks:
table.append([network.cgw_name, network.id, network.name,
'{}/{}'.format(
network.subnets.address_groups[0].primary_address,
network.subnets.address_groups[0].prefix_length),
network.dhcp_configs.ip_pools[0].ip_range])
print(tabulate(table, ['Gateway', 'Network ID', 'Network Name',
'Subnets', 'DHCP']))
def main():
logical_network_crud = LogicalNetworkCrud()
logical_network_crud.setup()
logical_network_crud.create_logical_network()
logical_network_crud.get_logical_network()
# TODO: figure out the requirements for updating logical network
# logical_network_crud.update_logical_network()
logical_network_crud.delete_logical_network()
if __name__ == '__main__':
main()

View File

@ -0,0 +1,199 @@
#!/usr/bin/env python
"""
* *******************************************************
* Copyright (c) VMware, Inc. 2018. All Rights Reserved.
* SPDX-License-Identifier: MIT
* *******************************************************
*
* DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, WHETHER ORAL OR WRITTEN,
* EXPRESS OR IMPLIED. THE AUTHOR SPECIFICALLY DISCLAIMS ANY IMPLIED
* WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY,
* NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
"""
__author__ = 'VMware, Inc.'
import argparse
from com.vmware.vmc.model_client import *
from tabulate import tabulate
from vmware.vapi.vmc.client import create_vmc_client
class NatRuleCrud(object):
"""
Demonstrates NAT rule CRUD operations
Sample Prerequisites:
- An organization associated with the calling user.
- A SDDC in the organization
"""
def __init__(self):
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-r', '--refresh-token',
required=True,
help='VMware Cloud API refresh token')
parser.add_argument('-o', '--org-id',
required=True,
help='Organization identifier.')
parser.add_argument('-s', '--sddc-id',
required=True,
help='Sddc Identifier.')
parser.add_argument('--public-ip',
help='Public IP range for the NAT rule')
parser.add_argument('--rule-description',
default='Sample NAT rule',
help='Description for the rule')
parser.add_argument('--internal-ip',
default='192.168.200.1/24',
help='NAT rule subnet')
parser.add_argument('-c', '--cleardata',
action='store_true',
help='Clean up after sample run')
args = parser.parse_args()
self.network_id = None
self.edge_id = None
self.rule_id = None
self.org_id = args.org_id
self.sddc_id = args.sddc_id
self.public_ip = args.public_ip
self.internal_ip = args.internal_ip
self.rule_description = args.rule_description
self.internal_ip = args.internal_ip
self.cleanup = args.cleardata
self.vmc_client = create_vmc_client(args.refresh_token)
def setup(self):
# Check if the organization exists
orgs = self.vmc_client.Orgs.list()
if self.org_id not in [org.id for org in orgs]:
raise ValueError("Org with ID {} doesn't exist".format(self.org_id))
# Check if the SDDC exists
sddcs = self.vmc_client.orgs.Sddcs.list(self.org_id)
if self.sddc_id not in [sddc.id for sddc in sddcs]:
raise ValueError("SDDC with ID {} doesn't exist in org {}".
format(self.sddc_id, self.org_id))
edges = self.vmc_client.orgs.sddcs.networks.Edges.get(
org=self.org_id,
sddc=self.sddc_id,
edge_type='gatewayServices').edge_page.data
print('\n# Setup: Compute Gateway ID: {}'.format(edges[1].id))
self.edge_id = edges[1].id
# Delete NAT rules with same name
rules = self.get_nat_rules_by_description(self.rule_description)
for rule in rules:
self.vmc_client.orgs.sddcs.networks.edges.nat.config.Rules.delete(
org=self.org_id,
sddc=self.sddc_id,
edge_id=self.edge_id,
rule_id=rule.rule_id)
print('\n# Setup: NAT Rule "{}" '
'with the same name is deleted'.format(rule.description))
def create_net_rule(self):
print('\n# Example: Add a NAT rule to the compute gateway')
# Construct a new NSX NAT rule spec
rule = Nsxnatrule(vnic='0',
rule_type='user',
action='dnat', # Supported types are DNAT|SNAT
protocol='tcp',
description=self.rule_description,
original_address=self.public_ip,
original_port='443',
translated_address=self.internal_ip,
translated_port='443',
enabled=True)
self.vmc_client.orgs.sddcs.networks.edges.nat.config.Rules.add(
org=self.org_id,
sddc=self.sddc_id,
edge_id=self.edge_id,
nat_rules=NatRules([rule]))
print('\n# New NAT rule "{}" is added'.format(self.rule_description))
def get_net_rule(self):
print('\n# Example: List all NAT rules')
rules = self.vmc_client.orgs.sddcs.networks.edges.nat.Config.get(
org=self.org_id,
sddc=self.sddc_id,
edge_id=self.edge_id).rules.nat_rules_dtos
self.print_output(rules)
def update_net_rule(self):
print("\n# Example: Update the NAT rule")
rule = self.get_nat_rules_by_description(self.rule_description)[0]
rule.Description = 'Updated' + self.rule_description
rule.original_port = 'any'
self.vmc_client.orgs.sddcs.networks.edges.nat.config.Rules.update(
org=self.org_id,
sddc=self.sddc_id,
edge_id=self.edge_id,
rule_id=rule.rule_id,
nsxnatrule=rule)
self.rule_id = rule.rule_id
print('# List the updated NAT rule specs')
rule = self.get_nat_rules_by_description(self.rule_description)[0]
self.print_output([rule])
def delete_net_rule(self):
if self.cleanup:
self.vmc_client.orgs.sddcs.networks.edges.nat.config.Rules.delete(
org=self.org_id,
sddc=self.sddc_id,
edge_id=self.edge_id,
rule_id=self.rule_id)
print('\n# Example: NAT rule "{}" is deleted'.
format(self.rule_description))
def get_nat_rules_by_description(self, description):
rules = self.vmc_client.orgs.sddcs.networks.edges.nat.Config.get(
org=self.org_id,
sddc=self.sddc_id,
edge_id=self.edge_id).rules.nat_rules_dtos
result = []
for rule in rules:
if rule.description == description:
result.append(rule)
return result
def print_output(self, rules):
table = []
for rule in rules:
table.append([rule.description, rule.rule_id, rule.action,
rule.original_address, rule.original_port,
rule.translated_address, rule.translated_port])
print(tabulate(table, ['Description', 'Rule ID', 'Action',
'Public IP', 'Public Ports',
'Internal IP', 'Internal Ports']))
def main():
net_rule_crud = NatRuleCrud()
net_rule_crud.setup()
net_rule_crud.create_net_rule()
net_rule_crud.get_net_rule()
net_rule_crud.update_net_rule()
net_rule_crud.delete_net_rule()
if __name__ == '__main__':
main()

View File

@ -0,0 +1,171 @@
#!/usr/bin/env python
"""
* *******************************************************
* Copyright (c) VMware, Inc. 2018. All Rights Reserved.
* SPDX-License-Identifier: MIT
* *******************************************************
*
* DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, WHETHER ORAL OR WRITTEN,
* EXPRESS OR IMPLIED. THE AUTHOR SPECIFICALLY DISCLAIMS ANY IMPLIED
* WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY,
* NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
"""
__author__ = 'VMware, Inc.'
import argparse
from com.vmware.vmc.model_client import *
from tabulate import tabulate
from vmware.vapi.vmc.client import create_vmc_client
from samples.vmc.helpers.vmc_task_helper import wait_for_task
class PublicIPsCrud(object):
"""
Demonstrates public IP CRUD operations
Sample Prerequisites:
- An organization associated with the calling user.
- A SDDC in the organization
"""
def __init__(self):
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-r', '--refresh-token',
required=True,
help='VMware Cloud API refresh token')
parser.add_argument('-o', '--org-id',
required=True,
help='Organization identifier.')
parser.add_argument('-s', '--sddc-id',
required=True,
help='Sddc Identifier.')
parser.add_argument('--notes',
default='Sample public IP',
help='Notes of the new public IP')
parser.add_argument('-c', '--cleardata',
action='store_true',
help='Clean up after sample run')
args = parser.parse_args()
self.ip_id = None
self.org_id = args.org_id
self.sddc_id = args.sddc_id
self.notes = args.notes
self.cleanup = args.cleardata
self.vmc_client = create_vmc_client(args.refresh_token)
def setup(self):
# Check if the organization exists
orgs = self.vmc_client.Orgs.list()
if self.org_id not in [org.id for org in orgs]:
raise ValueError("Org with ID {} doesn't exist".format(self.org_id))
# Check if the SDDC exists
sddcs = self.vmc_client.orgs.Sddcs.list(self.org_id)
if self.sddc_id not in [sddc.id for sddc in sddcs]:
raise ValueError("SDDC with ID {} doesn't exist in org {}".
format(self.sddc_id, self.org_id))
def request_public_ip(self):
print('\n# Example: Request a new IP for SDDC')
ip_spec = SddcAllocatePublicIpSpec(names=[self.notes], count=1)
task = self.vmc_client.orgs.sddcs.Publicips.create(
org=self.org_id,
sddc=self.sddc_id,
spec=ip_spec)
wait_for_task(task_client=self.vmc_client.orgs.Tasks,
org_id=self.org_id,
task_id=task.id,
interval_sec=2)
ips = self.vmc_client.orgs.sddcs.Publicips.list(
org=self.org_id,
sddc=self.sddc_id)
for ip in ips:
if ip.name == self.notes:
self.ip_id = ip.allocation_id
print('# Successfully requested public IP {}'.
format(ip.public_ip))
break
else:
raise Exception("Can't find public IP with notes {}".
format(self.notes))
def get_public_ip(self):
print('\n# Example: List all public IPs for the SDDC')
ips = self.vmc_client.orgs.sddcs.Publicips.list(
org=self.org_id,
sddc=self.sddc_id)
self.print_output(ips)
print('\n# Example: Get the specific IP with ID {}'.format(self.ip_id))
ip = self.vmc_client.orgs.sddcs.Publicips.get(
org=self.org_id,
sddc=self.sddc_id,
id=self.ip_id)
self.print_output([ip])
def update_public_ip(self):
print('\n# Example: Update the public IP notes')
ip = self.vmc_client.orgs.sddcs.Publicips.get(
org=self.org_id,
sddc=self.sddc_id,
id=self.ip_id)
ip.name = 'Updated ' + ip.name
self.vmc_client.orgs.sddcs.Publicips.update(
org=self.org_id,
sddc=self.sddc_id,
id=self.ip_id,
action='rename',
sddc_public_ip_object=ip)
ip = self.vmc_client.orgs.sddcs.Publicips.get(
org=self.org_id,
sddc=self.sddc_id,
id=self.ip_id)
print('# List the updated public IP')
self.print_output([ip])
def delete_public_ip(self):
if self.cleanup:
self.vmc_client.orgs.sddcs.Publicips.delete(
org=self.org_id,
sddc=self.sddc_id,
id=self.ip_id)
print('\n# Example: Public IP "{}" is deleted'.
format(self.notes))
def print_output(self, ips):
result = []
for ip in ips:
result.append([ip.public_ip, ip.allocation_id, ip.name])
print(tabulate(result, ['Public IP', 'ID', 'Notes']))
def main():
public_ips_crud = PublicIPsCrud()
public_ips_crud.setup()
public_ips_crud.request_public_ip()
public_ips_crud.get_public_ip()
public_ips_crud.update_public_ip()
public_ips_crud.delete_public_ip()
if __name__ == '__main__':
main()

View File

@ -2,7 +2,7 @@ This directory contains samples for VMC organization APIs:
Running the samples Running the samples
$ python organization_operations.py <refresh_token> $ python organization_operations.py -r <refresh_token>
* Testbed Requirement: * Testbed Requirement:
- At least one org associated with the calling user. - At least one org associated with the calling user.

View File

@ -41,8 +41,10 @@ class OperationsOnOrganizations(object):
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter) formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('refresh_token', parser.add_argument('-r', '--refresh-token',
required=True,
help='VMware Cloud API refresh token') help='VMware Cloud API refresh token')
self.refresh_token = parser.parse_args().refresh_token self.refresh_token = parser.parse_args().refresh_token
def setup(self): def setup(self):

View File

@ -45,16 +45,19 @@ class AddRemoveHosts(object):
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter) formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('refresh_token', parser.add_argument('-r', '--refresh-token',
required=True,
help='VMware Cloud API refresh token') help='VMware Cloud API refresh token')
parser.add_argument('org_id', parser.add_argument('-o', '--org-id',
required=True,
help='Organization identifier.') help='Organization identifier.')
parser.add_argument('sddc_id', parser.add_argument('-s', '--sddc-id',
required=True,
help='Sddc Identifier.') help='Sddc Identifier.')
parser.add_argument('-i', '--interval_sec', parser.add_argument('-i', '--interval-sec',
default=60, default=60,
help='Task pulling interval in sec') help='Task pulling interval in sec')

View File

@ -48,17 +48,19 @@ class CreateDeleteSDDC(object):
def option(self): def option(self):
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument('refresh_token', parser.add_argument('-r', '--refresh-token',
required=True,
help='VMware Cloud API refresh token') help='VMware Cloud API refresh token')
parser.add_argument('org_id', parser.add_argument('-o', '--org-id',
help='Organization identifier') required=True,
help='Organization identifier.')
parser.add_argument('-sn', '--sddc_name', parser.add_argument('-sn', '--sddc-name',
help="Name of the SDDC to be created. " help="Name of the SDDC to be created. "
"Default is 'Sample SDDC xx'") "Default is 'Sample SDDC xx'")
parser.add_argument('-i', '--interval_sec', parser.add_argument('-i', '--interval-sec',
default=60, default=60,
help='Task pulling interval in sec') help='Task pulling interval in sec')

View File

@ -1,4 +1,4 @@
# vSphere Samples #Client Samples
The following table shows the sample sub-directories and their contents. The following table shows the sample sub-directories and their contents.

View File

@ -12,14 +12,14 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
# Required to distribute different parts of this # Required to distribute different parts of this
# package as multiple distribution # package as multiple distribution
try: try:
import pkg_resources import pkg_resources
pkg_resources.declare_namespace(__name__) pkg_resources.declare_namespace(__name__)
except ImportError: except ImportError:
from pkgutil import extend_path from pkgutil import extend_path
__path__ = extend_path(__path__, __name__) # @ReservedAssignment __path__ = extend_path(__path__, __name__) # @ReservedAssignment

View File

@ -2,7 +2,7 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2017. All Rights Reserved. * Copyright (c) VMware, Inc. 2017, 2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -14,14 +14,16 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2017 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.0+' __vcenter_version__ = '6.0+'
import atexit import requests
from com.vmware.cis.tagging_client import (Category, CategoryModel)
from samples.vsphere.common import vapiconnect from vmware.vapi.vsphere.client import create_vsphere_client
from com.vmware.cis.tagging_client import CategoryModel
from samples.vsphere.common.sample_util import process_cli_args from samples.vsphere.common.sample_util import process_cli_args
from samples.vsphere.common.sample_cli import build_arg_parser from samples.vsphere.common import sample_cli
class CertConnect(object): class CertConnect(object):
@ -31,66 +33,44 @@ class CertConnect(object):
""" """
def __init__(self): def __init__(self):
self.server = None parser = sample_cli.build_arg_parser()
self.username = None
self.password = None
self.stub_config = None
self.cleardata = None
self.skip_verification = False
self.cert_path = None
self.category_svc = None
self.category_id = None
def setup(self):
parser = build_arg_parser()
parser.add_argument('-cpath', '--cert_path', parser.add_argument('-cpath', '--cert_path',
action='store', action='store',
help='path to a CA_BUNDLE file or directory with certificates of trusted CAs') help='path to a CA_BUNDLE file or directory with certificates of trusted CAs')
args = parser.parse_args() args = parser.parse_args()
self.args = process_cli_args(args)
self.server, self.username, self.password, self.cleardata, self.skip_verification = \
process_cli_args(args)
if args.cert_path:
self.cert_path = args.cert_path
def run(self): def run(self):
print('\n\n#### Example: Login to vCenter server with ' print('\n\n#### Example: Login to vCenter server with '
'Valid Cert Verification') 'Valid Cert Verification')
# Create a requests session and load the CA cert
session = requests.session()
session.verify = self.args.cert_path
# Connect to VAPI # Connect to VAPI
self.stub_config = vapiconnect.connect(self.server, self.username, self.password, client = create_vsphere_client(server=self.args.server,
self.skip_verification, username=self.args.username,
cert_path=self.cert_path) password=self.args.password,
atexit.register(vapiconnect.logout, self.stub_config) session=session)
# Create and Delete TagCategory to Verify connection is successful # List Tag Categories to verify the connection is successful
print('\nStep 3: Creating and Deleting Tag Category...\n') print('\nStep 3: Listing the Tag Categories...\n')
self.category_svc = Category(self.stub_config) create_spec = client.tagging.Category.CreateSpec()
create_spec.name = 'TestTag_connect_with_cert'
self.category_id = self.create_tag_category('TestTagCat', 'TestTagDesc', create_spec.description = 'TestTagDesc'
CategoryModel.Cardinality.MULTIPLE) create_spec.cardinality = CategoryModel.Cardinality.MULTIPLE
assert self.category_id is not None create_spec.associable_types = set()
print('Tag category created; Id: {0}\n'.format(self.category_id)) category_id = client.tagging.Category.create(create_spec)
assert category_id is not None
print('Tag category created; Id: {0}\n'.format(category_id))
# Delete TagCategory # Delete TagCategory
self.category_svc.delete(self.category_id) client.tagging.Category.delete(category_id)
print('VAPI session disconnected successfully...')
def create_tag_category(self, name, description, cardinality):
"""create a category. User who invokes this needs create category privilege."""
create_spec = self.category_svc.CreateSpec()
create_spec.name = name
create_spec.description = description
create_spec.cardinality = cardinality
associableTypes = set()
create_spec.associable_types = associableTypes
return self.category_svc.create(create_spec)
def main(): def main():
connect_with_cert = CertConnect() connect_with_cert = CertConnect()
connect_with_cert.setup()
connect_with_cert.run() connect_with_cert.run()

View File

@ -1,6 +1,6 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -12,7 +12,6 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
from six.moves import cStringIO from six.moves import cStringIO
from vmware.vapi.bindings.struct import PrettyPrinter from vmware.vapi.bindings.struct import PrettyPrinter
@ -85,17 +84,17 @@ def process_cli_args(args):
class Context(object): class Context(object):
"""Class that holds common context for running vcenter samples.""" """Class that holds common context for running vcenter samples."""
def __init__(self, testbed, service_instance, stub_config): def __init__(self, testbed, service_instance, client):
# Testbed configuration # Testbed configuration
self.testbed = testbed self._testbed = testbed
# pyVmomi SOAP Service Instance # pyVmomi SOAP Service Instance
self.service_instance = service_instance self._service_instance = service_instance
# vAPI stub configuration used to make other stubs # vAPI vSphere client
self.stub_config = stub_config self._client = client
self.option = {} self._option = {}
@property @property
def testbed(self): def testbed(self):
@ -122,12 +121,12 @@ class Context(object):
self._soap_stub = value self._soap_stub = value
@property @property
def stub_config(self): def client(self):
return self._stub_config return self._client
@stub_config.setter @client.setter
def stub_config(self, value): def client(self, value):
self._stub_config = value self._client = value
@property @property
def option(self): def option(self):

View File

@ -12,9 +12,9 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
import ssl import ssl
import requests
def get_unverified_context(): def get_unverified_context():
@ -27,3 +27,16 @@ def get_unverified_context():
if hasattr(ssl, '_create_unverified_context'): if hasattr(ssl, '_create_unverified_context'):
context = ssl._create_unverified_context() context = ssl._create_unverified_context()
return context return context
def get_unverified_session():
"""
Get a requests session with cert verification disabled.
Also disable the insecure warnings message.
Note this is not recommended in production code.
@return: a requests session with verification disabled.
"""
session = requests.session()
session.verify = False
requests.packages.urllib3.disable_warnings()
return session

View File

@ -1,6 +1,6 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -12,7 +12,6 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
import re import re
@ -35,7 +34,7 @@ def parse_datastore_path(datastore_path):
def detect_directory(context, description, datacenter_name, datastore_path): def detect_directory(context, description, datacenter_name, datastore_path):
"""Find directory based on specific datacenter and datastore path""" """Find directory based on specific datacenter and datastore path"""
(datastore_name, path) = parse_datastore_path(datastore_path) (datastore_name, path) = parse_datastore_path(datastore_path)
datastore_mo = get_datastore_mo(context.stub_config, datastore_mo = get_datastore_mo(context.client,
context.service_instance._stub, context.service_instance._stub,
datacenter_name, datacenter_name,
datastore_name) datastore_name)
@ -57,7 +56,7 @@ def detect_directory(context, description, datacenter_name, datastore_path):
def create_directory(context, description, datacenter_name, datastore_path): def create_directory(context, description, datacenter_name, datastore_path):
"""Create directory in specific datacenter""" """Create directory in specific datacenter"""
(datastore_name, path) = parse_datastore_path(datastore_path) (datastore_name, path) = parse_datastore_path(datastore_path)
datastore_mo = get_datastore_mo(context.stub_config, datastore_mo = get_datastore_mo(context.client,
context.service_instance._stub, context.service_instance._stub,
datacenter_name, datacenter_name,
datastore_name) datastore_name)
@ -76,7 +75,7 @@ def create_directory(context, description, datacenter_name, datastore_path):
def delete_directory(context, description, datacenter_name, datastore_path): def delete_directory(context, description, datacenter_name, datastore_path):
"""Delete directory from specific datacenter""" """Delete directory from specific datacenter"""
(datastore_name, path) = parse_datastore_path(datastore_path) (datastore_name, path) = parse_datastore_path(datastore_path)
datastore_mo = get_datastore_mo(context.stub_config, datastore_mo = get_datastore_mo(context.client,
context.service_instance._stub, context.service_instance._stub,
datacenter_name, datacenter_name,
datastore_name) datastore_name)
@ -92,7 +91,7 @@ def delete_directory(context, description, datacenter_name, datastore_path):
def detect_file(context, description, datacenter_name, datastore_path): def detect_file(context, description, datacenter_name, datastore_path):
"""Find specific file in specific datacenter""" """Find specific file in specific datacenter"""
(datastore_name, path) = parse_datastore_path(datastore_path) (datastore_name, path) = parse_datastore_path(datastore_path)
datastore_mo = get_datastore_mo(context.stub_config, datastore_mo = get_datastore_mo(context.client,
context.service_instance._stub, context.service_instance._stub,
datacenter_name, datacenter_name,
datastore_name) datastore_name)
@ -111,11 +110,11 @@ def detect_file(context, description, datacenter_name, datastore_path):
return True return True
def delete_file(stub_config, service_instance, def delete_file(client, service_instance,
description, datacenter_name, datastore_path): description, datacenter_name, datastore_path):
"""Delete a file from specific datacenter""" """Delete a file from specific datacenter"""
(datastore_name, path) = parse_datastore_path(datastore_path) (datastore_name, path) = parse_datastore_path(datastore_path)
datastore_mo = get_datastore_mo(stub_config, datastore_mo = get_datastore_mo(client,
service_instance._stub, service_instance._stub,
datacenter_name, datacenter_name,
datastore_name) datastore_name)

View File

@ -1,6 +1,6 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -12,7 +12,6 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter__ = 'since 6.0' __vcenter__ = 'since 6.0'
from pyVmomi import vim from pyVmomi import vim
@ -20,12 +19,12 @@ from pyVmomi import vim
from samples.vsphere.vcenter.helper.datastore_helper import get_datastore from samples.vsphere.vcenter.helper.datastore_helper import get_datastore
def get_datastore_mo(stub_config, soap_stub, def get_datastore_mo(client, soap_stub,
datacenter_name, datastore_name): datacenter_name, datastore_name):
""" """
Return datastore managed object with specific datacenter and datastore name Return datastore managed object with specific datacenter and datastore name
""" """
datastore = get_datastore(stub_config, datacenter_name, datastore_name) datastore = get_datastore(client, datacenter_name, datastore_name)
if not datastore: if not datastore:
return None return None
datastore_mo = vim.Datastore(datastore, soap_stub) datastore_mo = vim.Datastore(datastore, soap_stub)

View File

@ -1,6 +1,6 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -12,7 +12,6 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
import pyVim.task import pyVim.task
from pyVmomi import vim from pyVmomi import vim
@ -42,10 +41,10 @@ def delete_vmdk(service_instance, datacenter_mo, datastore_path):
pyVim.task.WaitForTask(task) pyVim.task.WaitForTask(task)
def detect_vmdk(stub_config, soap_stub, datacenter_name, datastore_name, def detect_vmdk(client, soap_stub, datacenter_name, datastore_name,
datastore_path): datastore_path):
"""Find vmdk in specific datastore""" """Find vmdk in specific datastore"""
datastore_mo = get_datastore_mo(stub_config, datastore_mo = get_datastore_mo(client,
soap_stub, soap_stub,
datacenter_name, datacenter_name,
datastore_name) datastore_name)

View File

@ -7,8 +7,8 @@ This directory contains samples for Content Library APIs:
* Basic workflow to publish and subscribe content libraries - publishsubscribe/library_publish_subscribe.py * Basic workflow to publish and subscribe content libraries - publishsubscribe/library_publish_subscribe.py
* Workflow to capture a virtual machine into a content library - vmcapture/vm_template_capture.py * Workflow to capture a virtual machine into a content library - vmcapture/vm_template_capture.py
* Content library ISO item mount and unmount workflow - isomount/iso_mount.py * Content library ISO item mount and unmount workflow - isomount/iso_mount.py
* Create a library item containing a native VMware virtual machine template - vmtemplate/create_vm_template.py * Create a library item containing a virtual machine template - vmtemplate/create_vm_template.py
* Deploy a virtual machine from a library item containing a native VMware virtual machine template - vmtemplate/deploy_vm_template.py * Deploy a virtual machine from a library item containing a virtual machine template - vmtemplate/deploy_vm_template.py
Running the samples Running the samples
@ -23,7 +23,7 @@ The additional sample parameters are as follows (all parameters can be displayed
* library_publish_subscribe.py --datastorename <datastore-name> * library_publish_subscribe.py --datastorename <datastore-name>
* vm_template_capture.py --datastorename <datastore-name> --vmname <vm-name> * vm_template_capture.py --datastorename <datastore-name> --vmname <vm-name>
* iso_mount.py --datastorename <datastore-name> --vmname <vm-name> * iso_mount.py --datastorename <datastore-name> --vmname <vm-name>
* create_vm_template.py --datastorename <datastore-name> --vmname <vm-name> * create_vm_template.py --datacentername <datacenter-name> --resourcepoolname <resource-pool-name> --datastorename <datastore-name> --vmname <vm-name>
* deploy_vm_template.py --itemname <item-name> --datacentername <datacenter-name> --foldername <folder-name> --resourcepoolname <resource-pool-name> --datastorename <datastore-name> * deploy_vm_template.py --itemname <item-name> --datacentername <datacenter-name> --foldername <folder-name> --resourcepoolname <resource-pool-name> --datastorename <datastore-name>
* Testbed Requirement: * Testbed Requirement:

View File

@ -2,7 +2,7 @@
""" """
* ******************************************************* * *******************************************************
* Copyright VMware, Inc. 2016. All Rights Reserved. * Copyright VMware, Inc. 2016, 2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -14,13 +14,14 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+' __vcenter_version__ = '6.5+'
from vmware.vapi.vsphere.client import create_vsphere_client
from samples.vsphere.common.sample_base import SampleBase from samples.vsphere.common.sample_base import SampleBase
from samples.vsphere.common.ssl_helper import get_unverified_session
from samples.vsphere.contentlibrary.lib.cls_api_client import ClsApiClient from samples.vsphere.contentlibrary.lib.cls_api_client import ClsApiClient
from samples.vsphere.contentlibrary.lib.cls_api_helper import ClsApiHelper from samples.vsphere.contentlibrary.lib.cls_api_helper import ClsApiHelper
from samples.vsphere.vcenter.helper.vm_helper import get_vm from samples.vsphere.vcenter.helper.vm_helper import get_vm
@ -46,10 +47,12 @@ class IsoMount(SampleBase):
def _options(self): def _options(self):
self.argparser.add_argument('-datastorename', self.argparser.add_argument('-datastorename',
'--datastorename', '--datastorename',
required=True,
help='The name of a datastore (of type vmfs) that is' help='The name of a datastore (of type vmfs) that is'
' acceassible to the vm specified with --vmname.') ' accessible to the vm specified with --vmname.')
self.argparser.add_argument('-vmname', self.argparser.add_argument('-vmname',
'--vmname', '--vmname',
required=True,
help='The name of the vm where iso will be mounted. ' help='The name of the vm where iso will be mounted. '
'The vm needs to be already created on the vCenter') 'The vm needs to be already created on the vCenter')
@ -65,6 +68,12 @@ class IsoMount(SampleBase):
self.client = ClsApiClient(self.servicemanager) self.client = ClsApiClient(self.servicemanager)
self.helper = ClsApiHelper(self.client, self.skip_verification) self.helper = ClsApiHelper(self.client, self.skip_verification)
session = get_unverified_session() if self.skip_verification else None
self.vsphere_client = create_vsphere_client(server=self.server,
username=self.username,
password=self.password,
session=session)
def _execute(self): def _execute(self):
storage_backings = self.helper.create_storage_backings( storage_backings = self.helper.create_storage_backings(
self.servicemanager, self.datastore_name) self.servicemanager, self.datastore_name)
@ -77,7 +86,7 @@ class IsoMount(SampleBase):
self.iso_item_name, self.iso_item_name,
self.ISO_FILENAME) self.ISO_FILENAME)
vm_id = get_vm(self.servicemanager.stub_config, self.vm_name) vm_id = get_vm(self.vsphere_client, self.vm_name)
assert vm_id is not None assert vm_id is not None
# Mount the iso item as a CDROM device # Mount the iso item as a CDROM device

View File

@ -1,6 +1,6 @@
""" """
* ******************************************************* * *******************************************************
* Copyright VMware, Inc. 2016-2017. All Rights Reserved. * Copyright VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -12,7 +12,6 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016-2017 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.0+' __vcenter_version__ = '6.0+'
from com.vmware.content_client import (Library, from com.vmware.content_client import (Library,
@ -28,6 +27,7 @@ from com.vmware.vcenter.iso_client import Image
from com.vmware.vcenter.ovf_client import LibraryItem from com.vmware.vcenter.ovf_client import LibraryItem
from com.vmware.vcenter.vm_template_client import LibraryItems as VmtxLibraryItem from com.vmware.vcenter.vm_template_client import LibraryItems as VmtxLibraryItem
class ClsApiClient(object): class ClsApiClient(object):
""" """
This is a simplified wrapper around the Content Library APIs. This is a simplified wrapper around the Content Library APIs.
@ -73,8 +73,8 @@ class ClsApiClient(object):
# Returns the service for managing subscribed library items # Returns the service for managing subscribed library items
self.subscribed_item_service = SubscribedItem(self.service_manager.stub_config) self.subscribed_item_service = SubscribedItem(self.service_manager.stub_config)
# Returns the service for managing library items containing native # Returns the service for managing library items containing virtual
# VMware virtual machine templates # machine templates
self.vmtx_service = VmtxLibraryItem(self.service_manager.stub_config) self.vmtx_service = VmtxLibraryItem(self.service_manager.stub_config)
# Creates the service that communicates with virtual machines # Creates the service that communicates with virtual machines

View File

@ -1,6 +1,6 @@
""" """
* ******************************************************* * *******************************************************
* Copyright VMware, Inc. 2016-2017. All Rights Reserved. * Copyright VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -12,7 +12,6 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016-2017 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.0+' __vcenter_version__ = '6.0+'
import os import os

View File

@ -2,7 +2,7 @@
""" """
* ******************************************************* * *******************************************************
* Copyright VMware, Inc. 2016-2017. All Rights Reserved. * Copyright VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -14,7 +14,6 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016-2017 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.0+' __vcenter_version__ = '6.0+'
try: try:

View File

@ -2,7 +2,7 @@
""" """
* ******************************************************* * *******************************************************
* Copyright VMware, Inc. 2013, 2016. All Rights Reserved. * Copyright VMware, Inc. 2016, 2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -14,7 +14,6 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.0+' __vcenter_version__ = '6.0+'
try: try:
@ -22,11 +21,13 @@ try:
except ImportError: except ImportError:
import urllib.request as urllib2 import urllib.request as urllib2
from com.vmware.vcenter.ovf_client import LibraryItem from com.vmware.vcenter.ovf_client import LibraryItem
from vmware.vapi.vsphere.client import create_vsphere_client
from samples.vsphere.common.id_generator import generate_random_uuid from samples.vsphere.common.id_generator import generate_random_uuid
from samples.vsphere.common.sample_base import SampleBase from samples.vsphere.common.sample_base import SampleBase
from samples.vsphere.common.ssl_helper import get_unverified_session
from samples.vsphere.contentlibrary.lib.cls_api_client import ClsApiClient from samples.vsphere.contentlibrary.lib.cls_api_client import ClsApiClient
from samples.vsphere.contentlibrary.lib.cls_api_helper import ClsApiHelper from samples.vsphere.contentlibrary.lib.cls_api_helper import ClsApiHelper
from samples.vsphere.vcenter.helper.vm_helper import get_vm from samples.vsphere.vcenter.helper.vm_helper import get_vm
@ -53,9 +54,11 @@ class CaptureVMTemplateToContentLibrary(SampleBase):
def _options(self): def _options(self):
self.argparser.add_argument('-datastorename', '--datastorename', self.argparser.add_argument('-datastorename', '--datastorename',
required=True,
help='The name of the datastore for' help='The name of the datastore for'
' content library backing (of type vmfs)') ' content library backing (of type vmfs)')
self.argparser.add_argument('-vmname', '--vmname', self.argparser.add_argument('-vmname', '--vmname',
required=True,
help='Name of the VM to be captured') help='Name of the VM to be captured')
def _setup(self): def _setup(self):
@ -71,6 +74,12 @@ class CaptureVMTemplateToContentLibrary(SampleBase):
self.client = ClsApiClient(self.servicemanager) self.client = ClsApiClient(self.servicemanager)
self.helper = ClsApiHelper(self.client, self.skip_verification) self.helper = ClsApiHelper(self.client, self.skip_verification)
session = get_unverified_session() if self.skip_verification else None
self.vsphere_client = create_vsphere_client(server=self.server,
username=self.username,
password=self.password,
session=session)
def _execute(self): def _execute(self):
storage_backings = self.helper.create_storage_backings( storage_backings = self.helper.create_storage_backings(
self.servicemanager, self.servicemanager,
@ -82,7 +91,7 @@ class CaptureVMTemplateToContentLibrary(SampleBase):
self.cl_name) self.cl_name)
self.content_library = self.client.local_library_service.get(library_id) self.content_library = self.client.local_library_service.get(library_id)
vm_id = get_vm(self.servicemanager.stub_config, self.vm_name) vm_id = get_vm(self.vsphere_client, self.vm_name)
assert vm_id is not None assert vm_id is not None
param = self.create_capture_param(self.content_library, param = self.create_capture_param(self.content_library,

View File

@ -2,7 +2,7 @@
""" """
* ******************************************************* * *******************************************************
* Copyright VMware, Inc. 2017. All Rights Reserved. * Copyright VMware, Inc. 2017-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -15,26 +15,32 @@
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2017 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.6.2+' __vcenter_version__ = '6.6.2+'
from com.vmware.vcenter.vm_template_client import ( from com.vmware.vcenter.vm_template_client import (
LibraryItems as VmtxLibraryItem) LibraryItems as VmtxLibraryItem)
from vmware.vapi.vsphere.client import create_vsphere_client
from samples.vsphere.common.id_generator import rand from samples.vsphere.common.id_generator import rand
from samples.vsphere.common.sample_base import SampleBase from samples.vsphere.common.sample_base import SampleBase
from samples.vsphere.common.ssl_helper import get_unverified_session
from samples.vsphere.contentlibrary.lib.cls_api_client import ClsApiClient from samples.vsphere.contentlibrary.lib.cls_api_client import ClsApiClient
from samples.vsphere.contentlibrary.lib.cls_api_helper import ClsApiHelper from samples.vsphere.contentlibrary.lib.cls_api_helper import ClsApiHelper
from samples.vsphere.vcenter.helper.resource_pool_helper import (
get_resource_pool)
from samples.vsphere.vcenter.helper.vm_helper import get_vm from samples.vsphere.vcenter.helper.vm_helper import get_vm
class CreateVmTemplate(SampleBase): class CreateVmTemplate(SampleBase):
""" """
Demonstrates how to create a library item containing a native VMware Demonstrates how to create a library item containing a virtual machine
virtual machine template from a virtual machine. template from a virtual machine.
Prerequisites: Prerequisites:
- A virtual machine - A virtual machine
- A datacenter
- A resource pool
- A datastore - A datastore
""" """
@ -54,19 +60,29 @@ class CreateVmTemplate(SampleBase):
required=True, required=True,
help='The name of the source VM from ' help='The name of the source VM from '
'which to create a library item') 'which to create a library item')
self.argparser.add_argument('-datacentername', '--datacentername',
required=True,
help='The name of the datacenter in which '
'to place the VM template')
self.argparser.add_argument('-resourcepoolname', '--resourcepoolname',
required=True,
help='The name of the resource pool in '
'the datacenter in which to place '
'the VM template')
self.argparser.add_argument('-datastorename', '--datastorename', self.argparser.add_argument('-datastorename', '--datastorename',
required=True, required=True,
help='The name of the datastore in which ' help='The name of the datastore in which '
'to create a library and native VM ' 'to create a library and VM template')
'template')
self.argparser.add_argument('-itemname', '--itemname', self.argparser.add_argument('-itemname', '--itemname',
help='The name of the library item to ' help='The name of the library item to '
'create. The item will contain a ' 'create. The item will contain a '
'native VM template.') 'VM template.')
def _setup(self): def _setup(self):
# Required arguments # Required arguments
self.vm_name = self.args.vmname self.vm_name = self.args.vmname
self.datacenter_name = self.args.datacentername
self.resource_pool_name = self.args.resourcepoolname
self.datastore_name = self.args.datastorename self.datastore_name = self.args.datastorename
# Optional arguments # Optional arguments
@ -77,10 +93,20 @@ class CreateVmTemplate(SampleBase):
self.client = ClsApiClient(self.servicemanager) self.client = ClsApiClient(self.servicemanager)
self.helper = ClsApiHelper(self.client, self.skip_verification) self.helper = ClsApiHelper(self.client, self.skip_verification)
session = get_unverified_session() if self.skip_verification else None
self.vsphere_client = create_vsphere_client(server=self.server,
username=self.username,
password=self.password,
session=session)
def _execute(self): def _execute(self):
# Get the identifier of the source VM # Get the identifiers
vm_id = get_vm(self.servicemanager.stub_config, self.vm_name) vm_id = get_vm(self.vsphere_client, self.vm_name)
assert vm_id assert vm_id
resource_pool_id = get_resource_pool(self.vsphere_client,
self.datacenter_name,
self.resource_pool_name)
assert resource_pool_id
# Create a library # Create a library
storage_backings = self.helper.create_storage_backings( storage_backings = self.helper.create_storage_backings(
@ -93,6 +119,8 @@ class CreateVmTemplate(SampleBase):
create_spec.source_vm = vm_id create_spec.source_vm = vm_id
create_spec.library = self.library_id create_spec.library = self.library_id
create_spec.name = self.item_name create_spec.name = self.item_name
create_spec.placement = VmtxLibraryItem.CreatePlacementSpec(
resource_pool=resource_pool_id)
# Create a new library item from the source VM # Create a new library item from the source VM
self.item_id = self.client.vmtx_service.create(create_spec) self.item_id = self.client.vmtx_service.create(create_spec)

View File

@ -2,7 +2,7 @@
""" """
* ******************************************************* * *******************************************************
* Copyright VMware, Inc. 2017. All Rights Reserved. * Copyright VMware, Inc. 2017-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -15,15 +15,17 @@
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2017 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.6.2+' __vcenter_version__ = '6.6.2+'
from pyVmomi import vim from pyVmomi import vim
from com.vmware.vcenter.vm_template_client import ( from com.vmware.vcenter.vm_template_client import (
LibraryItems as VmtxLibraryItem) LibraryItems as VmtxLibraryItem)
from vmware.vapi.vsphere.client import create_vsphere_client
from samples.vsphere.common.id_generator import rand from samples.vsphere.common.id_generator import rand
from samples.vsphere.common.sample_base import SampleBase from samples.vsphere.common.sample_base import SampleBase
from samples.vsphere.common.ssl_helper import get_unverified_session
from samples.vsphere.common.vim.helpers.get_datastore_by_name import ( from samples.vsphere.common.vim.helpers.get_datastore_by_name import (
get_datastore_id) get_datastore_id)
from samples.vsphere.common.vim.helpers.vim_utils import ( from samples.vsphere.common.vim.helpers.vim_utils import (
@ -38,12 +40,13 @@ from samples.vsphere.vcenter.helper.resource_pool_helper import (
class DeployVmTemplate(SampleBase): class DeployVmTemplate(SampleBase):
""" """
Demonstrates how to deploy a virtual machine from a library item containing Demonstrates how to deploy a virtual machine from a library item containing
a native VMware virtual machine template. a virtual machine template.
Prerequisites: Prerequisites:
- A library item containing a native VMware virtual machine template - A library item containing a virtual machine template
- A datacenter - A datacenter
- A VM folder - A VM folder
- A resource pool
- A datastore - A datastore
""" """
@ -65,8 +68,8 @@ class DeployVmTemplate(SampleBase):
self.argparser.add_argument('-itemname', '--itemname', self.argparser.add_argument('-itemname', '--itemname',
required=True, required=True,
help='The name of the library item ' help='The name of the library item '
'containing a native VM template to ' 'containing a VM template to be '
'be deployed') 'deployed')
self.argparser.add_argument('-datacentername', '--datacentername', self.argparser.add_argument('-datacentername', '--datacentername',
required=True, required=True,
help='The name of the datacenter in which ' help='The name of the datacenter in which '
@ -103,15 +106,21 @@ class DeployVmTemplate(SampleBase):
self.client = ClsApiClient(self.servicemanager) self.client = ClsApiClient(self.servicemanager)
self.helper = ClsApiHelper(self.client, self.skip_verification) self.helper = ClsApiHelper(self.client, self.skip_verification)
session = get_unverified_session() if self.skip_verification else None
self.vsphere_client = create_vsphere_client(server=self.server,
username=self.username,
password=self.password,
session=session)
def _execute(self): def _execute(self):
# Get the identifiers of the resources used for deployment # Get the identifiers of the resources used for deployment
item_id = self.helper.get_item_id_by_name(self.item_name) item_id = self.helper.get_item_id_by_name(self.item_name)
assert item_id assert item_id
folder_id = get_folder(self.servicemanager.stub_config, folder_id = get_folder(self.vsphere_client,
self.datacenter_name, self.datacenter_name,
self.folder_name) self.folder_name)
assert folder_id assert folder_id
resource_pool_id = get_resource_pool(self.servicemanager.stub_config, resource_pool_id = get_resource_pool(self.vsphere_client,
self.datacenter_name, self.datacenter_name,
self.resource_pool_name) self.resource_pool_name)
assert resource_pool_id assert resource_pool_id
@ -120,7 +129,7 @@ class DeployVmTemplate(SampleBase):
assert datastore_id assert datastore_id
# Build the deployment specification # Build the deployment specification
placement_spec = VmtxLibraryItem.PlacementSpec( placement_spec = VmtxLibraryItem.DeployPlacementSpec(
folder=folder_id, folder=folder_id,
resource_pool=resource_pool_id) resource_pool=resource_pool_id)
vm_home_storage_spec = VmtxLibraryItem.DeploySpecVmHomeStorage( vm_home_storage_spec = VmtxLibraryItem.DeploySpecVmHomeStorage(

View File

@ -14,22 +14,17 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2017 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.0+' __vcenter_version__ = '6.0+'
import requests from vmware.vapi.vsphere.client import create_vsphere_client
from com.vmware.cis.tagging_client import (Category, CategoryModel) from com.vmware.cis.tagging_client import (Category, CategoryModel)
from com.vmware.cis_client import Session
from vmware.vapi.lib.connect import get_requests_connector
from vmware.vapi.security.session import create_session_security_context
from vmware.vapi.security.sso import create_saml_bearer_security_context
from vmware.vapi.stdlib.client.factories import StubConfigurationFactory
from samples.vsphere.common import sample_cli from samples.vsphere.common import sample_cli
from samples.vsphere.common import sample_util from samples.vsphere.common import sample_util
from samples.vsphere.common import sso 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.ssl_helper import get_unverified_session
class EmbeddedPscSsoWorkflow(object): class EmbeddedPscSsoWorkflow(object):
@ -39,13 +34,6 @@ class EmbeddedPscSsoWorkflow(object):
""" """
def __init__(self): def __init__(self):
self.args = None
self.session = None
self.session_id = None
self.category_svc = None
self.category_id = None
def setup(self):
parser = sample_cli.build_arg_parser() parser = sample_cli.build_arg_parser()
self.args = sample_util.process_cli_args(parser.parse_args()) self.args = sample_util.process_cli_args(parser.parse_args())
@ -55,12 +43,12 @@ 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.args.server) sso_url = '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(sso_url)
context = None context = None
if self.args.skipverification: if self.args.skipverification:
context = get_unverified_context() context = get_unverified_context()
@ -70,62 +58,30 @@ class EmbeddedPscSsoWorkflow(object):
delegatable=True, delegatable=True,
ssl_context=context) ssl_context=context)
# Creating SAML Bearer Security Context session = get_unverified_session() if self.args.skipverification else None
sec_ctx = create_saml_bearer_security_context(bearer_token)
print('\nStep 2. Login to vAPI services using the SAML bearer token.') # Connect to vSphere client
client = create_vsphere_client(server=self.args.server,
# The URL for the stub requests are made against the /api HTTP endpoint bearer_token=bearer_token,
# of the vCenter system. session=session)
vapi_url = 'https://{}/api'.format(self.args.server)
# Create an authenticated stub configuration object that can be used to
# issue requests against vCenter.
session = requests.Session()
if self.args.skipverification:
session = create_unverified_session(session)
connector = get_requests_connector(session=session, url=vapi_url)
connector.set_security_context(sec_ctx)
stub_config = StubConfigurationFactory.new_std_configuration(
connector)
self.session = Session(stub_config)
# Login to VAPI endpoint and get the session_id
self.session_id = self.session.create()
# Update the VAPI connection with session_id
session_sec_ctx = create_session_security_context(self.session_id)
connector.set_security_context(session_sec_ctx)
# Create and Delete TagCategory to Verify connection is successful # Create and Delete TagCategory to Verify connection is successful
print('\nStep 3: Creating and Deleting Tag Category...\n') print('\nStep 3: Creating and Deleting Tag Category...\n')
self.category_svc = Category(stub_config) create_spec = client.tagging.Category.CreateSpec()
create_spec.name = 'TestTag_embeded_psc_sso_workflow'
self.category_id = self.create_tag_category('TestTagCat', 'TestTagDesc', create_spec.description = 'TestTagDesc'
CategoryModel.Cardinality.MULTIPLE) create_spec.cardinality = CategoryModel.Cardinality.MULTIPLE
assert self.category_id is not None create_spec.associable_types = set()
print('Tag category created; Id: {0}\n'.format(self.category_id)) category_id = client.tagging.Category.create(create_spec)
assert category_id is not None
print('Tag category created; Id: {0}\n'.format(category_id))
# Delete TagCategory # Delete TagCategory
self.category_svc.delete(self.category_id) client.tagging.Category.delete(category_id)
self.session.delete()
print('VAPI session disconnected successfully...')
def create_tag_category(self, name, description, cardinality):
"""create a category. User who invokes this needs create category privilege."""
create_spec = self.category_svc.CreateSpec()
create_spec.name = name
create_spec.description = description
create_spec.cardinality = cardinality
associableTypes = set()
create_spec.associable_types = associableTypes
return self.category_svc.create(create_spec)
def main(): def main():
embedded_psc_sso_workflow = EmbeddedPscSsoWorkflow() embedded_psc_sso_workflow = EmbeddedPscSsoWorkflow()
embedded_psc_sso_workflow.setup()
embedded_psc_sso_workflow.run() embedded_psc_sso_workflow.run()

View File

@ -2,7 +2,7 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2017. All Rights Reserved. * Copyright (c) VMware, Inc. 2017, 2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -14,28 +14,20 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2017 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.0+' __vcenter_version__ = '6.0+'
import os import os
import argparse import argparse
import requests
from pprint import pprint
from six.moves.urllib import request, parse from six.moves.urllib import request, parse
from com.vmware.cis_client import Session from vmware.vapi.vsphere.client import create_vsphere_client
from com.vmware.cis.tagging_client import CategoryModel
from vmware.vapi.lib.connect import get_requests_connector
from vmware.vapi.security.session import create_session_security_context
from vmware.vapi.security.sso import create_saml_bearer_security_context
from vmware.vapi.stdlib.client.factories import StubConfigurationFactory
from com.vmware.cis.tagging_client import (Category, CategoryModel)
from samples.vsphere.common import sso from samples.vsphere.common import sso
from samples.vsphere.common.lookup_service_helper import LookupServiceHelper from samples.vsphere.common.lookup_service_helper import LookupServiceHelper
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.ssl_helper import get_unverified_session
class ExternalPscSsoWorkflow(object): class ExternalPscSsoWorkflow(object):
@ -45,21 +37,6 @@ class ExternalPscSsoWorkflow(object):
""" """
def __init__(self): def __init__(self):
self.lswsdl = None
self.lsurl = None
self.mgmtinstancename = None
self.username = None
self.password = None
self.session = None
self.session_id = None
self.args = None
self.argparser = None
self.mgmtinstancename = None
self.skip_verification = False
self.category_svc = None
self.category_id = None
def options(self):
self.argparser = argparse.ArgumentParser(description=self.__doc__) self.argparser = argparse.ArgumentParser(description=self.__doc__)
# setup the argument parser # setup the argument parser
self.argparser.add_argument('-w', '--lswsdl', self.argparser.add_argument('-w', '--lswsdl',
@ -83,7 +60,6 @@ class ExternalPscSsoWorkflow(object):
help='Do not verify server certificate') help='Do not verify server certificate')
self.args = self.argparser.parse_args() self.args = self.argparser.parse_args()
def setup(self):
if self.args.lswsdl: if self.args.lswsdl:
self.lswsdl = os.path.abspath(self.args.lswsdl) self.lswsdl = os.path.abspath(self.args.lswsdl)
else: else:
@ -145,66 +121,33 @@ class ExternalPscSsoWorkflow(object):
delegatable=True, delegatable=True,
ssl_context=context) ssl_context=context)
# Creating SAML Bearer Security Context
sec_ctx = create_saml_bearer_security_context(bearer_token)
print('\nStep 4. Discover the vAPI service URL from lookup service.') print('\nStep 4. Discover the vAPI service URL from lookup service.')
vapi_url = lookupservicehelper.find_vapi_url(self.mgmtnodeid) vapi_url = lookupservicehelper.find_vapi_url(self.mgmtnodeid)
print('vAPI URL: {0}'.format(vapi_url)) print('vAPI URL: {0}'.format(vapi_url))
print('\nStep 5. Login to vAPI service using the SAML bearer token.') print('\nStep 5. Login to vAPI service using the SAML bearer token.')
session = get_unverified_session() if self.skip_verification else None
# Create an authenticated stub configuration object that can be used to client = create_vsphere_client(server=parse.urlparse(vapi_url).hostname,
# issue requests against vCenter. bearer_token=bearer_token,
session = requests.Session() session=session)
if self.skip_verification:
session = create_unverified_session(session)
connector = get_requests_connector(session=session, url=vapi_url)
connector.set_security_context(sec_ctx)
stub_config = StubConfigurationFactory.new_std_configuration(
connector)
self.session = Session(stub_config)
# Login to VAPI endpoint and get the session_id
self.session_id = self.session.create()
# Update the VAPI connection with session_id
session_sec_ctx = create_session_security_context(self.session_id)
connector.set_security_context(session_sec_ctx)
# Create and Delete TagCategory to Verify connection is successful # Create and Delete TagCategory to Verify connection is successful
print('\nStep 6: Creating and Deleting Tag Category...\n') print('\nStep 3: Creating and Deleting Tag Category...\n')
self.category_svc = Category(stub_config) create_spec = client.tagging.Category.CreateSpec()
create_spec.name = 'TestTag_embeded_psc_sso_workflow'
self.category_id = self.create_tag_category('TestTagCat', 'TestTagDesc', create_spec.description = 'TestTagDesc'
CategoryModel.Cardinality.MULTIPLE) create_spec.cardinality = CategoryModel.Cardinality.MULTIPLE
assert self.category_id is not None create_spec.associable_types = set()
print('Tag category created; Id: {0}\n'.format(self.category_id)) category_id = client.tagging.Category.create(create_spec)
assert category_id is not None
print('Tag category created; Id: {0}\n'.format(category_id))
# Delete TagCategory # Delete TagCategory
self.category_svc.delete(self.category_id) client.tagging.Category.delete(category_id)
self.session.delete()
print('VAPI session disconnected successfully...')
def create_tag_category(self, name, description, cardinality):
"""create a category. User who invokes this needs create category privilege."""
create_spec = self.category_svc.CreateSpec()
create_spec.name = name
create_spec.description = description
create_spec.cardinality = cardinality
associableTypes = set()
create_spec.associable_types = associableTypes
return self.category_svc.create(create_spec)
self.session.delete()
print('VAPI session disconnected successfully...')
def main(): def main():
external_psc_sso_workflow = ExternalPscSsoWorkflow() external_psc_sso_workflow = ExternalPscSsoWorkflow()
external_psc_sso_workflow.options()
external_psc_sso_workflow.setup()
external_psc_sso_workflow.run() external_psc_sso_workflow.run()

View File

@ -1,6 +1,6 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -12,7 +12,6 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+' __vcenter_version__ = '6.5+'
from com.vmware.vcenter_client import Cluster from com.vmware.vcenter_client import Cluster
@ -20,14 +19,14 @@ from com.vmware.vcenter_client import Cluster
from samples.vsphere.vcenter.helper import datacenter_helper from samples.vsphere.vcenter.helper import datacenter_helper
def get_cluster(stub_config, datacenter_name, cluster_name): def get_cluster(client, datacenter_name, cluster_name):
""" """
Returns the identifier of a cluster Returns the identifier of a cluster
Note: The method assumes only one cluster and datacenter Note: The method assumes only one cluster and datacenter
with the mentioned name. with the mentioned name.
""" """
datacenter = datacenter_helper.get_datacenter(stub_config, datacenter_name) datacenter = datacenter_helper.get_datacenter(client, datacenter_name)
if not datacenter: if not datacenter:
print("Datacenter '{}' not found".format(datacenter_name)) print("Datacenter '{}' not found".format(datacenter_name))
return None return None
@ -35,8 +34,7 @@ def get_cluster(stub_config, datacenter_name, cluster_name):
filter_spec = Cluster.FilterSpec(names=set([cluster_name]), filter_spec = Cluster.FilterSpec(names=set([cluster_name]),
datacenters=set([datacenter])) datacenters=set([datacenter]))
cluster_svc = Cluster(stub_config) cluster_summaries = client.vcenter.Cluster.list(filter_spec)
cluster_summaries = cluster_svc.list(filter_spec)
if len(cluster_summaries) > 0: if len(cluster_summaries) > 0:
cluster = cluster_summaries[0].cluster cluster = cluster_summaries[0].cluster
print("Detected cluster '{}' as {}".format(cluster_name, cluster)) print("Detected cluster '{}' as {}".format(cluster_name, cluster))

View File

@ -1,6 +1,6 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -12,13 +12,12 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+' __vcenter_version__ = '6.5+'
from com.vmware.vcenter_client import Datacenter from com.vmware.vcenter_client import Datacenter
def get_datacenter(stub_config, datacenter_name): def get_datacenter(client, datacenter_name):
""" """
Returns the identifier of a datacenter Returns the identifier of a datacenter
Note: The method assumes only one datacenter with the mentioned name. Note: The method assumes only one datacenter with the mentioned name.
@ -26,8 +25,7 @@ def get_datacenter(stub_config, datacenter_name):
filter_spec = Datacenter.FilterSpec(names=set([datacenter_name])) filter_spec = Datacenter.FilterSpec(names=set([datacenter_name]))
datacenter_svc = Datacenter(stub_config) datacenter_summaries = client.vcenter.Datacenter.list(filter_spec)
datacenter_summaries = datacenter_svc.list(filter_spec)
if len(datacenter_summaries) > 0: if len(datacenter_summaries) > 0:
datacenter = datacenter_summaries[0].datacenter datacenter = datacenter_summaries[0].datacenter
return datacenter return datacenter

View File

@ -1,6 +1,6 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -12,7 +12,6 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+' __vcenter_version__ = '6.5+'
from com.vmware.vcenter_client import Datastore from com.vmware.vcenter_client import Datastore
@ -20,13 +19,13 @@ from com.vmware.vcenter_client import Datastore
from samples.vsphere.vcenter.helper import datacenter_helper from samples.vsphere.vcenter.helper import datacenter_helper
def get_datastore(stub_config, datacenter_name, datastore_name): def get_datastore(client, datacenter_name, datastore_name):
""" """
Returns the identifier of a datastore Returns the identifier of a datastore
Note: The method assumes that there is only one datastore and datacenter Note: The method assumes that there is only one datastore and datacenter
with the mentioned names. with the mentioned names.
""" """
datacenter = datacenter_helper.get_datacenter(stub_config, datacenter_name) datacenter = datacenter_helper.get_datacenter(client, datacenter_name)
if not datacenter: if not datacenter:
print("Datacenter '{}' not found".format(datacenter_name)) print("Datacenter '{}' not found".format(datacenter_name))
return None return None
@ -34,8 +33,7 @@ def get_datastore(stub_config, datacenter_name, datastore_name):
filter_spec = Datastore.FilterSpec(names=set([datastore_name]), filter_spec = Datastore.FilterSpec(names=set([datastore_name]),
datacenters=set([datacenter])) datacenters=set([datacenter]))
datastore_svc = Datastore(stub_config) datastore_summaries = client.vcenter.Datastore.list(filter_spec)
datastore_summaries = datastore_svc.list(filter_spec)
if len(datastore_summaries) > 0: if len(datastore_summaries) > 0:
datastore = datastore_summaries[0].datastore datastore = datastore_summaries[0].datastore
return datastore return datastore

View File

@ -1,6 +1,6 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -12,7 +12,6 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+' __vcenter_version__ = '6.5+'
from com.vmware.vcenter_client import Folder from com.vmware.vcenter_client import Folder
@ -20,13 +19,13 @@ from com.vmware.vcenter_client import Folder
from samples.vsphere.vcenter.helper import datacenter_helper from samples.vsphere.vcenter.helper import datacenter_helper
def get_folder(stub_config, datacenter_name, folder_name): def get_folder(client, datacenter_name, folder_name):
""" """
Returns the identifier of a folder Returns the identifier of a folder
Note: The method assumes that there is only one folder and datacenter Note: The method assumes that there is only one folder and datacenter
with the mentioned names. with the mentioned names.
""" """
datacenter = datacenter_helper.get_datacenter(stub_config, datacenter_name) datacenter = datacenter_helper.get_datacenter(client, datacenter_name)
if not datacenter: if not datacenter:
print("Datacenter '{}' not found".format(datacenter_name)) print("Datacenter '{}' not found".format(datacenter_name))
return None return None
@ -35,8 +34,7 @@ def get_folder(stub_config, datacenter_name, folder_name):
names=set([folder_name]), names=set([folder_name]),
datacenters=set([datacenter])) datacenters=set([datacenter]))
folder_svc = Folder(stub_config) folder_summaries = client.vcenter.Folder.list(filter_spec)
folder_summaries = folder_svc.list(filter_spec)
if len(folder_summaries) > 0: if len(folder_summaries) > 0:
folder = folder_summaries[0].folder folder = folder_summaries[0].folder
print("Detected folder '{}' as {}".format(folder_name, folder)) print("Detected folder '{}' as {}".format(folder_name, folder))

View File

@ -1,6 +1,6 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -12,7 +12,6 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+' __vcenter_version__ = '6.5+'
from com.vmware.vcenter_client import Network from com.vmware.vcenter_client import Network
@ -20,7 +19,7 @@ from com.vmware.vcenter_client import Network
from samples.vsphere.vcenter.helper import datacenter_helper from samples.vsphere.vcenter.helper import datacenter_helper
def get_standard_network_backing(stub_config, def get_standard_network_backing(client,
std_porggroup_name, std_porggroup_name,
datacenter_name): datacenter_name):
""" """
@ -28,18 +27,16 @@ def get_standard_network_backing(stub_config,
Note: The method assumes that there is only one standard portgroup Note: The method assumes that there is only one standard portgroup
and datacenter with the mentioned names. and datacenter with the mentioned names.
""" """
datacenter = datacenter_helper.get_datacenter(stub_config, datacenter_name) datacenter = datacenter_helper.get_datacenter(client, datacenter_name)
if not datacenter: if not datacenter:
print("Datacenter '{}' not found".format(datacenter_name)) print("Datacenter '{}' not found".format(datacenter_name))
return None return None
network_svc = Network(stub_config)
filter = Network.FilterSpec(datacenters=set([datacenter]), filter = Network.FilterSpec(datacenters=set([datacenter]),
names=set([std_porggroup_name]), names=set([std_porggroup_name]),
types=set([Network.Type.STANDARD_PORTGROUP])) types=set([Network.Type.STANDARD_PORTGROUP]))
network_summaries = network_svc.list(filter=filter) network_summaries = client.vcenter.Network.list(filter=filter)
network = None
if len(network_summaries) > 0: if len(network_summaries) > 0:
network = network_summaries[0].network network = network_summaries[0].network
print("Selecting Standard Portgroup Network '{}' ({})". print("Selecting Standard Portgroup Network '{}' ({})".
@ -51,7 +48,7 @@ def get_standard_network_backing(stub_config,
return None return None
def get_distributed_network_backing(stub_config, def get_distributed_network_backing(client,
dv_portgroup_name, dv_portgroup_name,
datacenter_name): datacenter_name):
""" """
@ -59,18 +56,16 @@ def get_distributed_network_backing(stub_config,
Note: The method assumes that there is only one distributed portgroup Note: The method assumes that there is only one distributed portgroup
and datacenter with the mentioned names. and datacenter with the mentioned names.
""" """
datacenter = datacenter_helper.get_datacenter(stub_config, datacenter_name) datacenter = datacenter_helper.get_datacenter(client, datacenter_name)
if not datacenter: if not datacenter:
print("Datacenter '{}' not found".format(datacenter_name)) print("Datacenter '{}' not found".format(datacenter_name))
return None return None
network_svc = Network(stub_config)
filter = Network.FilterSpec(datacenters=set([datacenter]), filter = Network.FilterSpec(datacenters=set([datacenter]),
names=set([dv_portgroup_name]), names=set([dv_portgroup_name]),
types=set([Network.Type.DISTRIBUTED_PORTGROUP])) types=set([Network.Type.DISTRIBUTED_PORTGROUP]))
network_summaries = network_svc.list(filter=filter) network_summaries = client.vcenter.Network.list(filter=filter)
network = None
if len(network_summaries) > 0: if len(network_summaries) > 0:
network = network_summaries[0].network network = network_summaries[0].network
print("Selecting Distributed Portgroup Network '{}' ({})". print("Selecting Distributed Portgroup Network '{}' ({})".

View File

@ -1,6 +1,6 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -12,7 +12,6 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+' __vcenter_version__ = '6.5+'
from com.vmware.vcenter_client import ResourcePool from com.vmware.vcenter_client import ResourcePool
@ -20,12 +19,12 @@ from com.vmware.vcenter_client import ResourcePool
from samples.vsphere.vcenter.helper import datacenter_helper from samples.vsphere.vcenter.helper import datacenter_helper
def get_resource_pool(stub_config, datacenter_name, resource_pool_name=None): def get_resource_pool(client, datacenter_name, resource_pool_name=None):
""" """
Returns the identifier of the resource pool with the given name or the Returns the identifier of the resource pool with the given name or the
first resource pool in the datacenter if the name is not provided. first resource pool in the datacenter if the name is not provided.
""" """
datacenter = datacenter_helper.get_datacenter(stub_config, datacenter_name) datacenter = datacenter_helper.get_datacenter(client, datacenter_name)
if not datacenter: if not datacenter:
print("Datacenter '{}' not found".format(datacenter_name)) print("Datacenter '{}' not found".format(datacenter_name))
return None return None
@ -34,8 +33,7 @@ def get_resource_pool(stub_config, datacenter_name, resource_pool_name=None):
filter_spec = ResourcePool.FilterSpec(datacenters=set([datacenter]), filter_spec = ResourcePool.FilterSpec(datacenters=set([datacenter]),
names=names) names=names)
resource_pool_svc = ResourcePool(stub_config) resource_pool_summaries = client.vcenter.ResourcePool.list(filter_spec)
resource_pool_summaries = resource_pool_svc.list(filter_spec)
if len(resource_pool_summaries) > 0: if len(resource_pool_summaries) > 0:
resource_pool = resource_pool_summaries[0].resource_pool resource_pool = resource_pool_summaries[0].resource_pool
print("Selecting ResourcePool '{}'".format(resource_pool)) print("Selecting ResourcePool '{}'".format(resource_pool))

View File

@ -1,6 +1,6 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -12,20 +12,18 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+' __vcenter_version__ = '6.5+'
from com.vmware.vcenter_client import VM from com.vmware.vcenter_client import VM
def get_vm(stub_config, vm_name): def get_vm(client, vm_name):
""" """
Return the identifier of a vm Return the identifier of a vm
Note: The method assumes that there is only one vm with the mentioned name. Note: The method assumes that there is only one vm with the mentioned name.
""" """
vm_svc = VM(stub_config)
names = set([vm_name]) names = set([vm_name])
vms = vm_svc.list(VM.FilterSpec(names=names)) vms = client.vcenter.VM.list(VM.FilterSpec(names=names))
if len(vms) == 0: if len(vms) == 0:
print("VM with name ({}) not found".format(vm_name)) print("VM with name ({}) not found".format(vm_name))
@ -36,10 +34,9 @@ def get_vm(stub_config, vm_name):
return vm return vm
def get_vms(stub_config, vm_names): def get_vms(client, vm_names):
"""Return identifiers of a list of vms""" """Return identifiers of a list of vms"""
vm_svc = VM(stub_config) vms = client.vcenter.VM.list(VM.FilterSpec(names=vm_names))
vms = vm_svc.list(VM.FilterSpec(names=vm_names))
if len(vms) == 0: if len(vms) == 0:
print('No vm found') print('No vm found')

View File

@ -1,6 +1,6 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -12,7 +12,6 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+' __vcenter_version__ = '6.5+'
from com.vmware.vcenter_client import VM from com.vmware.vcenter_client import VM
@ -22,7 +21,7 @@ from samples.vsphere.vcenter.helper import folder_helper
from samples.vsphere.vcenter.helper import resource_pool_helper from samples.vsphere.vcenter.helper import resource_pool_helper
def get_placement_spec_for_resource_pool(stub_config, def get_placement_spec_for_resource_pool(client,
datacenter_name, datacenter_name,
vm_folder_name, vm_folder_name,
datastore_name): datastore_name):
@ -30,14 +29,14 @@ def get_placement_spec_for_resource_pool(stub_config,
Returns a VM placement spec for a resourcepool. Ensures that the Returns a VM placement spec for a resourcepool. Ensures that the
vm folder and datastore are all in the same datacenter which is specified. vm folder and datastore are all in the same datacenter which is specified.
""" """
resource_pool = resource_pool_helper.get_resource_pool(stub_config, resource_pool = resource_pool_helper.get_resource_pool(client,
datacenter_name) datacenter_name)
folder = folder_helper.get_folder(stub_config, folder = folder_helper.get_folder(client,
datacenter_name, datacenter_name,
vm_folder_name) vm_folder_name)
datastore = datastore_helper.get_datastore(stub_config, datastore = datastore_helper.get_datastore(client,
datacenter_name, datacenter_name,
datastore_name) datastore_name)

View File

@ -1,6 +1,6 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -12,7 +12,6 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
from samples.vsphere.common.vim.file import (detect_directory, from samples.vsphere.common.vim.file import (detect_directory,

View File

@ -1,6 +1,6 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -12,11 +12,9 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
import pyVim.task import pyVim.task
from com.vmware.vcenter_client import Cluster from com.vmware.vcenter_client import Cluster, Folder
from pyVmomi import vim from pyVmomi import vim
from samples.vsphere.vcenter.helper import cluster_helper from samples.vsphere.vcenter.helper import cluster_helper
@ -27,7 +25,7 @@ def detect_cluster(context):
cluster1_name = context.testbed.config['CLUSTER1_NAME'] cluster1_name = context.testbed.config['CLUSTER1_NAME']
datacenter_name = context.testbed.config['VM_DATACENTER_NAME'] datacenter_name = context.testbed.config['VM_DATACENTER_NAME']
cluster = cluster_helper.get_cluster(context.stub_config, datacenter_name, cluster = cluster_helper.get_cluster(context.client, datacenter_name,
cluster1_name) cluster1_name)
if cluster: if cluster:
@ -43,8 +41,8 @@ def cleanup_cluster(context):
cluster1_name = context.testbed.config['CLUSTER1_NAME'] cluster1_name = context.testbed.config['CLUSTER1_NAME']
names = set([cluster1_name]) names = set([cluster1_name])
cluster_svc = Cluster(context.stub_config) cluster_summaries = context.client.vcenter.Cluster.list(
cluster_summaries = cluster_svc.list(Cluster.FilterSpec(names=names)) Cluster.FilterSpec(names=names))
print("Found '{}' Clusters matching names {}". print("Found '{}' Clusters matching names {}".
format(len(cluster_summaries), ", ".join(["'{}'". format(len(cluster_summaries), ", ".join(["'{}'".
format(n) for n in names]))) format(n) for n in names])))
@ -92,8 +90,7 @@ def setup_cluster_vapi2(context):
datacenter_name = context.testbed.config['DATACENTER2_NAME'] datacenter_name = context.testbed.config['DATACENTER2_NAME']
datacenter = context.testbed.entities['DATACENTER_IDS'][datacenter_name] datacenter = context.testbed.entities['DATACENTER_IDS'][datacenter_name]
folder_svc = Folder(context.stub_config) folder_summaries = context.client.vcenter.Folder.list(
folder_summaries = folder_svc.list(
Folder.FilterSpec(type=Folder.Type.HOST, datacenters=set([datacenter]))) Folder.FilterSpec(type=Folder.Type.HOST, datacenters=set([datacenter])))
folder = folder_summaries[0].folder folder = folder_summaries[0].folder

View File

@ -1,6 +1,6 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -12,22 +12,18 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
from com.vmware.vcenter_client import (Datacenter, Folder) from com.vmware.vcenter_client import (Datacenter, Folder)
def folder_list_datacenter_folder(context): def folder_list_datacenter_folder(context):
folder_svc = Folder(context.stub_config) return context.client.vcenter.Folder.list(Folder.FilterSpec(type=Folder.Type.DATACENTER))
return folder_svc.list(Folder.FilterSpec(type=Folder.Type.DATACENTER))
def detect_datacenter(context, datacenter_name): def detect_datacenter(context, datacenter_name):
"""Find the datacenter with the given name""" """Find the datacenter with the given name"""
datacenter_svc = Datacenter(context.stub_config)
names = set([datacenter_name]) names = set([datacenter_name])
datacenter_summaries = datacenter_svc.list( datacenter_summaries = context.client.vcenter.Datacenter.list(
Datacenter.FilterSpec(names=names)) Datacenter.FilterSpec(names=names))
if len(datacenter_summaries) > 0: if len(datacenter_summaries) > 0:
datacenter = datacenter_summaries[0].datacenter datacenter = datacenter_summaries[0].datacenter
@ -54,14 +50,13 @@ def detect_datacenters(context):
def cleanup_datacenters(context): def cleanup_datacenters(context):
"""Cleanup datacenters after sample run""" """Cleanup datacenters after sample run"""
datacenter_svc = Datacenter(context.stub_config)
# Look for the two datacenters # Look for the two datacenters
datacenter1_name = context.testbed.config['DATACENTER1_NAME'] datacenter1_name = context.testbed.config['DATACENTER1_NAME']
datacenter2_name = context.testbed.config['DATACENTER2_NAME'] datacenter2_name = context.testbed.config['DATACENTER2_NAME']
names = set([datacenter1_name, datacenter2_name]) names = set([datacenter1_name, datacenter2_name])
datacenter_summaries = datacenter_svc.list( datacenter_summaries = context.client.vcenter.Datacenter.list(
Datacenter.FilterSpec(names=names)) Datacenter.FilterSpec(names=names))
print("Found {} Datacenters matching names {}". print("Found {} Datacenters matching names {}".
format(len(datacenter_summaries), ", ". format(len(datacenter_summaries), ", ".
@ -71,7 +66,7 @@ def cleanup_datacenters(context):
datacenter = datacenter_summary.datacenter datacenter = datacenter_summary.datacenter
print("Deleting Datacenter '{}' ({})". print("Deleting Datacenter '{}' ({})".
format(datacenter, datacenter_summary.name)) format(datacenter, datacenter_summary.name))
datacenter_svc.delete(datacenter, force=True) context.client.vcenter.Datacenter.delete(datacenter, force=True)
def setup_datacenters(context): def setup_datacenters(context):
@ -82,18 +77,16 @@ def setup_datacenters(context):
print("Creating datacenters in Folder '{}' ({})". print("Creating datacenters in Folder '{}' ({})".
format(folder, folder_summaries[0].name)) format(folder, folder_summaries[0].name))
datacenter_svc = Datacenter(context.stub_config)
# Create first datacenter # Create first datacenter
datacenter1_name = context.testbed.config['DATACENTER1_NAME'] datacenter1_name = context.testbed.config['DATACENTER1_NAME']
datacenter1 = datacenter_svc.create( datacenter1 = context.client.vcenter.Datacenter.create(
Datacenter.CreateSpec(name=datacenter1_name, folder=folder) Datacenter.CreateSpec(name=datacenter1_name, folder=folder)
) )
print("Created Datacenter '{}' ({})".format(datacenter1, datacenter1_name)) print("Created Datacenter '{}' ({})".format(datacenter1, datacenter1_name))
# Create second datacenter # Create second datacenter
datacenter2_name = context.testbed.config['DATACENTER2_NAME'] datacenter2_name = context.testbed.config['DATACENTER2_NAME']
datacenter2 = datacenter_svc.create( datacenter2 = context.client.vcenter.Datacenter.create(
Datacenter.CreateSpec(name=datacenter2_name, folder=folder) Datacenter.CreateSpec(name=datacenter2_name, folder=folder)
) )
print("Created Datacenter '{}' ({})".format(datacenter2, datacenter2_name)) print("Created Datacenter '{}' ({})".format(datacenter2, datacenter2_name))

View File

@ -1,6 +1,6 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -12,7 +12,6 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
import pyVim.task import pyVim.task
from com.vmware.vcenter_client import Host from com.vmware.vcenter_client import Host
@ -25,8 +24,8 @@ def detect_nfs_datastore_on_host(context, host_name):
datastore_name = context.testbed.config['NFS_DATASTORE_NAME'] datastore_name = context.testbed.config['NFS_DATASTORE_NAME']
# Use vAPI find the Host managed identities # Use vAPI find the Host managed identities
host_svc = Host(context.stub_config) host_summaries = context.client.vcenter.Host.list(
host_summaries = host_svc.list(Host.FilterSpec(names=names)) Host.FilterSpec(names=names))
for host_summary in host_summaries: for host_summary in host_summaries:
# Convert the host identifier into a ManagedObject # Convert the host identifier into a ManagedObject
@ -67,8 +66,8 @@ def cleanup_nfs_datastore(context):
datastore_name = context.testbed.config['NFS_DATASTORE_NAME'] datastore_name = context.testbed.config['NFS_DATASTORE_NAME']
# Use vAPI find the Host managed identities # Use vAPI find the Host managed identities
host_svc = Host(context.stub_config) host_summaries = context.client.vcenter.Host.list(
host_summaries = host_svc.list(Host.FilterSpec(names=names)) Host.FilterSpec(names=names))
for host_summary in host_summaries: for host_summary in host_summaries:
# Convert the host identifier into a ManagedObject # Convert the host identifier into a ManagedObject
@ -154,8 +153,8 @@ def detect_vmfs_datastore(context, host_name, datastore_name):
names = set([host_name]) names = set([host_name])
# Use vAPI find the Host managed identities # Use vAPI find the Host managed identities
host_svc = Host(context.stub_config) host_summaries = context.client.vcenter.Host.list(
host_summaries = host_svc.list(Host.FilterSpec(names=names)) Host.FilterSpec(names=names))
for host_summary in host_summaries: for host_summary in host_summaries:
# Convert the host identifier into a ManagedObject # Convert the host identifier into a ManagedObject
@ -199,8 +198,8 @@ def setup_vmfs_datastore(context, host_name, datastore_name):
names = set([host_name]) names = set([host_name])
# Use vAPI find the Host managed identities # Use vAPI find the Host managed identities
host_svc = Host(context.stub_config) host_summaries = context.client.vcenter.Host.list(
host_summaries = host_svc.list(Host.FilterSpec(names=names)) Host.FilterSpec(names=names))
host_summary = host_summaries[0] host_summary = host_summaries[0]
# Convert the host identifier into a ManagedObject # Convert the host identifier into a ManagedObject

View File

@ -1,6 +1,6 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -12,7 +12,6 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
from samples.vsphere.common.vim.file import (detect_file, delete_file, from samples.vsphere.common.vim.file import (detect_file, delete_file,
@ -29,7 +28,7 @@ def setup_floppy_image(context):
datastore_path = context.testbed.config['FLOPPY_DATASTORE_PATH'] datastore_path = context.testbed.config['FLOPPY_DATASTORE_PATH']
(datastore_name, path) = parse_datastore_path(datastore_path) (datastore_name, path) = parse_datastore_path(datastore_path)
datastore_mo = get_datastore_mo(context.stub_config, datastore_mo = get_datastore_mo(context.client,
context.service_instance._stub, context.service_instance._stub,
datacenter_name, datacenter_name,
datastore_name) datastore_name)
@ -49,7 +48,7 @@ def cleanup_floppy_image(context):
"""Delete floppy image after running samples""" """Delete floppy image after running samples"""
datacenter_name = context.testbed.config['FLOPPY_DATACENTER_NAME'] datacenter_name = context.testbed.config['FLOPPY_DATACENTER_NAME']
datastore_path = context.testbed.config['FLOPPY_DATASTORE_PATH'] datastore_path = context.testbed.config['FLOPPY_DATASTORE_PATH']
delete_file(context.stub_config, delete_file(context.client,
context.service_instance, context.service_instance,
'Floppy Image', 'Floppy Image',
datacenter_name, datacenter_name,

View File

@ -1,6 +1,6 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -12,7 +12,6 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
import pyVim.task import pyVim.task
@ -24,14 +23,13 @@ from samples.vsphere.vcenter.helper import datacenter_helper
def detect_vm_folder(context, datacenter_name, folder_name): def detect_vm_folder(context, datacenter_name, folder_name):
"""Find vm folder based on datacenter and folder name""" """Find vm folder based on datacenter and folder name"""
datacenter = datacenter_helper.get_datacenter(context.stub_config, datacenter = datacenter_helper.get_datacenter(context.client,
datacenter_name) datacenter_name)
if not datacenter: if not datacenter:
print("Datacenter '{}' not found".format(datacenter_name)) print("Datacenter '{}' not found".format(datacenter_name))
return None return None
folder_svc = Folder(context.stub_config) folder_summaries = context.client.vcenter.Folder.list(
folder_summaries = folder_svc.list(
Folder.FilterSpec(type=Folder.Type.VIRTUAL_MACHINE, Folder.FilterSpec(type=Folder.Type.VIRTUAL_MACHINE,
names=set([folder_name]), names=set([folder_name]),
datacenters=set([datacenter]))) datacenters=set([datacenter])))

View File

@ -1,6 +1,6 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -12,7 +12,6 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
import pyVim.task import pyVim.task
@ -22,10 +21,10 @@ from pyVmomi import vim
def detect_host(context, host_name): def detect_host(context, host_name):
"""Find host based on host name""" """Find host based on host name"""
host_svc = Host(context.stub_config)
names = set([host_name]) names = set([host_name])
host_summaries = host_svc.list(Host.FilterSpec(names=names)) host_summaries = context.client.vcenter.Host.list(
Host.FilterSpec(names=names))
if len(host_summaries) > 0: if len(host_summaries) > 0:
host = host_summaries[0].host host = host_summaries[0].host
print("Detected Host '{}' as {}".format(host_name, host)) print("Detected Host '{}' as {}".format(host_name, host))
@ -47,13 +46,12 @@ def detect_hosts(context):
def cleanup_hosts(context): def cleanup_hosts(context):
"""Delete hosts after sample run""" """Delete hosts after sample run"""
host_svc = Host(context.stub_config)
host1_name = context.testbed.config['ESX_HOST1'] host1_name = context.testbed.config['ESX_HOST1']
host2_name = context.testbed.config['ESX_HOST2'] host2_name = context.testbed.config['ESX_HOST2']
names = set([host1_name, host2_name]) names = set([host1_name, host2_name])
host_summaries = host_svc.list(Host.FilterSpec(names=names)) host_summaries = context.client.vcenter.Host.list(
Host.FilterSpec(names=names))
print('Found {} Hosts matching names {}'. print('Found {} Hosts matching names {}'.
format(len(host_summaries), ', '. format(len(host_summaries), ', '.
join(["'{}'".format(n) for n in names]))) join(["'{}'".format(n) for n in names])))
@ -61,7 +59,7 @@ def cleanup_hosts(context):
for host_summary in host_summaries: for host_summary in host_summaries:
host = host_summary.host host = host_summary.host
print("Deleting Host '{}' ({})".format(host_summary.name, host)) print("Deleting Host '{}' ({})".format(host_summary.name, host))
host_svc.delete(host) context.client.vcenter.Host.delete(host)
def create_host_vapi(context, host_name, datacenter_name): def create_host_vapi(context, host_name, datacenter_name):
@ -69,16 +67,12 @@ def create_host_vapi(context, host_name, datacenter_name):
Adds a single Host to the vCenter inventory under the named Datacenter Adds a single Host to the vCenter inventory under the named Datacenter
using vAPI. using vAPI.
""" """
host_svc = Host(context.stub_config)
user = context.testbed.config['ESX_USER'] user = context.testbed.config['ESX_USER']
pwd = context.testbed.config['ESX_PASS'] pwd = context.testbed.config['ESX_PASS']
# Get the host folder for the Datacenter1 using the folder query # Get the host folder for the Datacenter1 using the folder query
datacenter = context.testbed.entities['DATACENTER_IDS'][datacenter_name] datacenter = context.testbed.entities['DATACENTER_IDS'][datacenter_name]
folder_summaries = context.client.vcenter.Folder.list(
folder_svc = Folder(context.stub_config)
folder_summaries = folder_svc.list(
Folder.FilterSpec(type=Folder.Type.HOST, datacenters=set([datacenter]))) Folder.FilterSpec(type=Folder.Type.HOST, datacenters=set([datacenter])))
folder = folder_summaries[0].folder folder = folder_summaries[0].folder
@ -88,7 +82,7 @@ def create_host_vapi(context, host_name, datacenter_name):
password=pwd, password=pwd,
folder=folder, folder=folder,
thumbprint_verification=Host.CreateSpec.ThumbprintVerification.NONE) thumbprint_verification=Host.CreateSpec.ThumbprintVerification.NONE)
host = host_svc.create(create_spec) host = context.client.vcenter.Host.create(create_spec)
print("Created Host '{}' ({})".format(host, host_name)) print("Created Host '{}' ({})".format(host, host_name))
return host return host

View File

@ -1,6 +1,6 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -12,7 +12,6 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
from samples.vsphere.common.vim.file import (detect_file, delete_file, from samples.vsphere.common.vim.file import (detect_file, delete_file,
@ -28,7 +27,7 @@ def setup_iso_image(context):
datacenter_name = context.testbed.config['ISO_DATACENTER_NAME'] datacenter_name = context.testbed.config['ISO_DATACENTER_NAME']
datastore_path = context.testbed.config['ISO_DATASTORE_PATH'] datastore_path = context.testbed.config['ISO_DATASTORE_PATH']
(datastore_name, path) = parse_datastore_path(datastore_path) (datastore_name, path) = parse_datastore_path(datastore_path)
datastore_mo = get_datastore_mo(context.stub_config, datastore_mo = get_datastore_mo(context.client,
context.service_instance._stub, context.service_instance._stub,
datacenter_name, datacenter_name,
datastore_name) datastore_name)
@ -47,7 +46,7 @@ def cleanup_iso_image(context):
"""Cleanup iso image after sample run""" """Cleanup iso image after sample run"""
datacenter_name = context.testbed.config['ISO_DATACENTER_NAME'] datacenter_name = context.testbed.config['ISO_DATACENTER_NAME']
datastore_path = context.testbed.config['ISO_DATASTORE_PATH'] datastore_path = context.testbed.config['ISO_DATASTORE_PATH']
delete_file(context.stub_config, delete_file(context.client,
context.service_instance, context.service_instance,
"ISO Image", "ISO Image",
datacenter_name, datacenter_name,

View File

@ -2,7 +2,7 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -13,46 +13,43 @@
* NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
""" """
""" """
Script that runs through all the setup and samples. Script that runs through all the setup and samples.
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
import pyVim.connect import pyVim.connect
from vmware.vapi.vsphere.client import create_vsphere_client
from samples.vsphere.common import sample_util from samples.vsphere.common import sample_util
from samples.vsphere.common import vapiconnect
from samples.vsphere.vcenter.setup import testbed from samples.vsphere.vcenter.setup import testbed
from samples.vsphere.vcenter.setup.setup_cli import build_arg_parser from samples.vsphere.vcenter.setup import setup_cli
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 VMSetup from samples.vsphere.vcenter.vm.main import VMSetup
from samples.vsphere.common.ssl_helper import get_unverified_context, \
from samples.vsphere.common.ssl_helper import get_unverified_context get_unverified_session
# Parse command line params for setup script # Parse command line params for setup script
args = build_arg_parser().parse_args() args = setup_cli.build_arg_parser().parse_args()
_testbed = testbed.get() _testbed = testbed.get()
# If VC/ESX/NFS Server IPs are passed as arguments, # If VC/ESX/NFS Server IPs are passed as arguments,
# then override testbed.py values # then override testbed.py values
if (args.vcenterserver): if args.vcenterserver:
_testbed.config['SERVER'] = args.vcenterserver _testbed.config['SERVER'] = args.vcenterserver
if (args.vcenterpassword): if args.vcenterpassword:
_testbed.config['PASSWORD'] = args.vcenterpassword _testbed.config['PASSWORD'] = args.vcenterpassword
if (args.esxhost1): if args.esxhost1:
_testbed.config['ESX_HOST1'] = args.esxhost1 _testbed.config['ESX_HOST1'] = args.esxhost1
if (args.esxhost2): if args.esxhost2:
_testbed.config['ESX_HOST2'] = args.esxhost2 _testbed.config['ESX_HOST2'] = args.esxhost2
if (args.esxpassword): if args.esxpassword:
_testbed.config['ESX_PASS'] = args.esxpassword _testbed.config['ESX_PASS'] = args.esxpassword
if (args.nfsserver): if args.nfsserver:
_testbed.config['NFS_HOST'] = args.nfsserver _testbed.config['NFS_HOST'] = args.nfsserver
@ -68,12 +65,13 @@ service_instance = pyVim.connect.SmartConnect(host=_testbed.config['SERVER'],
sslContext=context) sslContext=context)
# Connect to vAPI Endpoint on vCenter system # Connect to vAPI Endpoint on vCenter system
stub_config = vapiconnect.connect(host=_testbed.config['SERVER'], session = get_unverified_session() if args.skipverification else None
user=_testbed.config['USERNAME'], client = create_vsphere_client(server=_testbed.config['SERVER'],
pwd=_testbed.config['PASSWORD'], username=_testbed.config['USERNAME'],
skip_verification=args.skipverification) password=_testbed.config['PASSWORD'],
session=session)
context = sample_util.Context(_testbed, service_instance, stub_config) context = sample_util.Context(_testbed, service_instance, client)
context.option['DO_TESTBED_SETUP'] = args.testbed_setup context.option['DO_TESTBED_SETUP'] = args.testbed_setup
context.option['DO_TESTBED_VALIDATE'] = args.testbed_validate context.option['DO_TESTBED_VALIDATE'] = args.testbed_validate

View File

@ -1,6 +1,6 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -12,7 +12,6 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
import pyVim.task import pyVim.task
from com.vmware.vcenter_client import Host from com.vmware.vcenter_client import Host
@ -235,8 +234,8 @@ def detect_stdportgroup(context, host_name, network_name):
names = set([host_name]) names = set([host_name])
# Use vAPI find the Host managed identities # Use vAPI find the Host managed identities
host_svc = Host(context.stub_config) host_summaries = context.client.vcenter.Host.list(
host_summaries = host_svc.list(Host.FilterSpec(names=names)) Host.FilterSpec(names=names))
for host_summary in host_summaries: for host_summary in host_summaries:
# Convert the host identifier into a ManagedObject # Convert the host identifier into a ManagedObject

View File

@ -2,7 +2,7 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -14,22 +14,20 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+' __vcenter_version__ = '6.5+'
import atexit
from com.vmware.vcenter.vm.hardware.boot_client import Device as BootDevice from com.vmware.vcenter.vm.hardware.boot_client import Device as BootDevice
from com.vmware.vcenter.vm.hardware_client import ( from com.vmware.vcenter.vm.hardware_client import (
Disk, Ethernet) Disk, Ethernet)
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 vmware.vapi.vsphere.client import create_vsphere_client
from samples.vsphere.common.ssl_helper import get_unverified_session
from samples.vsphere.common import sample_cli from samples.vsphere.common import sample_cli
from samples.vsphere.common import sample_util 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.helper.vm_helper import get_vm
@ -48,15 +46,14 @@ class CreateBasicVM(object):
- standard switch network - standard switch network
""" """
def __init__(self, stub_config=None, placement_spec=None): def __init__(self, client=None, placement_spec=None):
self.context = None self.client = client
self.service_manager = None
self.stub_config = stub_config
self.placement_spec = placement_spec self.placement_spec = placement_spec
self.vm_name = testbed.config['VM_NAME_BASIC'] self.vm_name = testbed.config['VM_NAME_BASIC']
self.cleardata = None self.cleardata = None
def setup(self): # Execute the sample in standalone mode.
if not self.client:
parser = sample_cli.build_arg_parser() parser = sample_cli.build_arg_parser()
parser.add_argument('-n', '--vm_name', parser.add_argument('-n', '--vm_name',
action='store', action='store',
@ -66,14 +63,11 @@ class CreateBasicVM(object):
self.vm_name = args.vm_name self.vm_name = args.vm_name
self.cleardata = args.cleardata self.cleardata = args.cleardata
self.service_manager = ServiceManager(args.server, session = get_unverified_session() if args.skipverification else None
args.username, self.client = create_vsphere_client(server=args.server,
args.password, username=args.username,
args.skipverification) password=args.password,
self.service_manager.connect() session=session)
atexit.register(self.service_manager.disconnect)
self.stub_config = self.service_manager.stub_config
def run(self): def run(self):
# Get a placement spec # Get a placement spec
@ -84,14 +78,14 @@ class CreateBasicVM(object):
if not self.placement_spec: if not self.placement_spec:
self.placement_spec = vm_placement_helper.get_placement_spec_for_resource_pool( self.placement_spec = vm_placement_helper.get_placement_spec_for_resource_pool(
self.stub_config, self.client,
datacenter_name, datacenter_name,
vm_folder_name, vm_folder_name,
datastore_name) datastore_name)
# Get a standard network backing # Get a standard network backing
standard_network = network_helper.get_standard_network_backing( standard_network = network_helper.get_standard_network_backing(
self.stub_config, self.client,
std_portgroup_name, std_portgroup_name,
datacenter_name) datacenter_name)
@ -135,34 +129,30 @@ class CreateBasicVM(object):
print(pp(vm_create_spec)) print(pp(vm_create_spec))
print('-----') print('-----')
vm_svc = VM(self.stub_config) vm = self.client.vcenter.VM.create(vm_create_spec)
vm = vm_svc.create(vm_create_spec)
print("create_basic_vm: Created VM '{}' ({})".format(self.vm_name, vm)) print("create_basic_vm: Created VM '{}' ({})".format(self.vm_name, vm))
vm_info = vm_svc.get(vm) vm_info = self.client.vcenter.VM.get(vm)
print('vm.get({}) -> {}'.format(vm, pp(vm_info))) print('vm.get({}) -> {}'.format(vm, pp(vm_info)))
return vm return vm
def cleanup(self): def cleanup(self):
vm = get_vm(self.stub_config, self.vm_name) vm = get_vm(self.client, self.vm_name)
if vm: if vm:
power_svc = Power(self.stub_config) state = self.client.vcenter.vm.Power.get(vm)
vm_svc = VM(self.stub_config)
state = power_svc.get(vm)
if state == Power.Info(state=Power.State.POWERED_ON): if state == Power.Info(state=Power.State.POWERED_ON):
power_svc.stop(vm) self.client.vcenter.vm.Power.stop(vm)
elif state == Power.Info(state=Power.State.SUSPENDED): elif state == Power.Info(state=Power.State.SUSPENDED):
power_svc.start(vm) self.client.vcenter.vm.Power.start(vm)
power_svc.stop(vm) self.client.vcenter.vm.Power.stop(vm)
print("Deleting VM '{}' ({})".format(self.vm_name, vm)) print("Deleting VM '{}' ({})".format(self.vm_name, vm))
vm_svc.delete(vm) self.client.vcenter.VM.delete(vm)
def main(): def main():
create_basic_vm = CreateBasicVM() create_basic_vm = CreateBasicVM()
create_basic_vm.setup()
create_basic_vm.cleanup() create_basic_vm.cleanup()
create_basic_vm.run() create_basic_vm.run()
if create_basic_vm.cleardata: if create_basic_vm.cleardata:

View File

@ -2,7 +2,7 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -14,18 +14,16 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+' __vcenter_version__ = '6.5+'
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 vmware.vapi.vsphere.client import create_vsphere_client
from samples.vsphere.common import sample_cli from samples.vsphere.common import sample_cli
from samples.vsphere.common import sample_util from samples.vsphere.common import sample_util
from samples.vsphere.common.ssl_helper import get_unverified_session
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.helper.vm_helper import get_vm
from samples.vsphere.vcenter.setup import testbed from samples.vsphere.vcenter.setup import testbed
@ -41,32 +39,29 @@ class CreateDefaultVM(object):
- datastore - datastore
""" """
def __init__(self, stub_config=None, placement_spec=None): def __init__(self, client=None, placement_spec=None):
self.context = None self.client = client
self.service_manager = None
self.stub_config = stub_config
self.placement_spec = placement_spec self.placement_spec = placement_spec
self.vm_name = testbed.config['VM_NAME_DEFAULT'] self.vm_name = testbed.config['VM_NAME_DEFAULT']
self.cleardata = None self.cleardata = None
def setup(self): # Execute the sample in standalone mode.
if not self.client:
parser = sample_cli.build_arg_parser() parser = sample_cli.build_arg_parser()
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 = sample_util.process_cli_args(parser.parse_args()) args = sample_util.process_cli_args(parser.parse_args())
if args.vm_name: if args.vm_name:
self.vm_name = args.vm_name self.vm_name = args.vm_name
self.cleardata = args.cleardata self.cleardata = args.cleardata
self.service_manager = ServiceManager(args.server, session = get_unverified_session() if args.skipverification else None
args.username, self.client = create_vsphere_client(server=args.server,
args.password, username=args.username,
args.skipverification) password=args.password,
self.service_manager.connect() session=session)
atexit.register(self.service_manager.disconnect)
self.stub_config = self.service_manager.stub_config
def run(self): def run(self):
# Get a placement spec # Get a placement spec
@ -76,7 +71,7 @@ class CreateDefaultVM(object):
if not self.placement_spec: if not self.placement_spec:
self.placement_spec = vm_placement_helper.get_placement_spec_for_resource_pool( self.placement_spec = vm_placement_helper.get_placement_spec_for_resource_pool(
self.stub_config, self.client,
datacenter_name, datacenter_name,
vm_folder_name, vm_folder_name,
datastore_name) datastore_name)
@ -95,32 +90,28 @@ class CreateDefaultVM(object):
print(pp(vm_create_spec)) print(pp(vm_create_spec))
print('-----') print('-----')
vm_svc = VM(self.stub_config) vm = self.client.vcenter.VM.create(vm_create_spec)
vm = vm_svc.create(vm_create_spec)
print("create_default_vm: Created VM '{}' ({})".format(self.vm_name, vm)) print("create_default_vm: Created VM '{}' ({})".format(self.vm_name, vm))
vm_info = vm_svc.get(vm) vm_info = self.client.vcenter.VM.get(vm)
print('vm.get({}) -> {}'.format(vm, pp(vm_info))) print('vm.get({}) -> {}'.format(vm, pp(vm_info)))
return vm return vm
def cleanup(self): def cleanup(self):
vm = get_vm(self.stub_config, self.vm_name) vm = get_vm(self.client, self.vm_name)
if vm: if vm:
power_svc = Power(self.stub_config) state = self.client.vcenter.vm.Power.get(vm)
vm_svc = VM(self.stub_config)
state = power_svc.get(vm)
if state == Power.Info(state=Power.State.POWERED_ON): if state == Power.Info(state=Power.State.POWERED_ON):
power_svc.stop(vm) self.client.vcenter.vm.Power.stop(vm)
elif state == Power.Info(state=Power.State.SUSPENDED): elif state == Power.Info(state=Power.State.SUSPENDED):
power_svc.start(vm) self.client.vcenter.vm.Power.start(vm)
power_svc.stop(vm) self.client.vcenter.vm.Power.stop(vm)
print("Deleting VM '{}' ({})".format(self.vm_name, vm)) print("Deleting VM '{}' ({})".format(self.vm_name, vm))
vm_svc.delete(vm) self.client.vcenter.VM.delete(vm)
def main(): def main():
create_default_vm = CreateDefaultVM() create_default_vm = CreateDefaultVM()
create_default_vm.setup()
create_default_vm.cleanup() create_default_vm.cleanup()
create_default_vm.run() create_default_vm.run()
if create_default_vm.cleardata: if create_default_vm.cleardata:

View File

@ -2,7 +2,7 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -14,22 +14,20 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+' __vcenter_version__ = '6.5+'
import atexit
from com.vmware.vcenter.vm.hardware.boot_client import Device as BootDevice from com.vmware.vcenter.vm.hardware.boot_client import Device as BootDevice
from com.vmware.vcenter.vm.hardware_client import ( from com.vmware.vcenter.vm.hardware_client import (
Cpu, Memory, Disk, Ethernet, Cdrom, Serial, Parallel, Floppy, Boot) Cpu, Memory, Disk, Ethernet, Cdrom, Serial, Parallel, Floppy, Boot)
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 vmware.vapi.vsphere.client import create_vsphere_client
from samples.vsphere.common.ssl_helper import get_unverified_session
from samples.vsphere.common import sample_cli from samples.vsphere.common import sample_cli
from samples.vsphere.common import sample_util 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.helper.vm_helper import get_vm
@ -52,18 +50,18 @@ class CreateExhaustiveVM(object):
- An iso file on the datastore mentioned above - An iso file on the datastore mentioned above
""" """
def __init__(self, stub_config=None, placement_spec=None, def __init__(self, client=None, placement_spec=None,
standard_network=None, distributed_network=None): standard_network=None, distributed_network=None):
self.context = None self.client = client
self.service_manager = None
self.stub_config = stub_config
self.placement_spec = placement_spec self.placement_spec = placement_spec
self.standard_network = standard_network self.standard_network = standard_network
self.distributed_network = distributed_network self.distributed_network = distributed_network
self.vm_name = testbed.config['VM_NAME_EXHAUSTIVE'] self.vm_name = testbed.config['VM_NAME_EXHAUSTIVE']
self.cleardata = None self.cleardata = None
def setup(self): # Execute the sample in standalone mode.
if not self.client:
parser = sample_cli.build_arg_parser() parser = sample_cli.build_arg_parser()
parser.add_argument('-n', '--vm_name', parser.add_argument('-n', '--vm_name',
action='store', action='store',
@ -73,14 +71,11 @@ class CreateExhaustiveVM(object):
self.vm_name = args.vm_name self.vm_name = args.vm_name
self.cleardata = args.cleardata self.cleardata = args.cleardata
self.service_manager = ServiceManager(args.server, session = get_unverified_session() if args.skipverification else None
args.username, self.client = create_vsphere_client(server=args.server,
args.password, username=args.username,
args.skipverification) password=args.password,
self.service_manager.connect() session=session)
atexit.register(self.service_manager.disconnect)
self.stub_config = self.service_manager.stub_config
def run(self): def run(self):
# Get a placement spec # Get a placement spec
@ -92,7 +87,7 @@ class CreateExhaustiveVM(object):
if not self.placement_spec: if not self.placement_spec:
self.placement_spec = vm_placement_helper.get_placement_spec_for_resource_pool( self.placement_spec = vm_placement_helper.get_placement_spec_for_resource_pool(
self.stub_config, self.client,
datacenter_name, datacenter_name,
vm_folder_name, vm_folder_name,
datastore_name) datastore_name)
@ -100,14 +95,14 @@ class CreateExhaustiveVM(object):
# Get a standard network backing # Get a standard network backing
if not self.standard_network: if not self.standard_network:
self.standard_network = network_helper.get_standard_network_backing( self.standard_network = network_helper.get_standard_network_backing(
self.stub_config, self.client,
std_portgroup_name, std_portgroup_name,
datacenter_name) datacenter_name)
# Get a distributed network backing # Get a distributed network backing
if not self.distributed_network: if not self.distributed_network:
self.distributed_network = network_helper.get_distributed_network_backing( self.distributed_network = network_helper.get_distributed_network_backing(
self.stub_config, self.client,
dv_portgroup_name, dv_portgroup_name,
datacenter_name) datacenter_name)
@ -228,35 +223,31 @@ class CreateExhaustiveVM(object):
print(pp(vm_create_spec)) print(pp(vm_create_spec))
print('-----') print('-----')
vm_svc = VM(self.stub_config) vm = self.client.vcenter.VM.create(vm_create_spec)
vm = vm_svc.create(vm_create_spec)
print("create_exhaustive_vm: Created VM '{}' ({})".format(self.vm_name, print("create_exhaustive_vm: Created VM '{}' ({})".format(self.vm_name,
vm)) vm))
vm_info = vm_svc.get(vm) vm_info = self.client.vcenter.VM.get(vm)
print('vm.get({}) -> {}'.format(vm, pp(vm_info))) print('vm.get({}) -> {}'.format(vm, pp(vm_info)))
return vm return vm
def cleanup(self): def cleanup(self):
vm = get_vm(self.stub_config, self.vm_name) vm = get_vm(self.client, self.vm_name)
if vm: if vm:
power_svc = Power(self.stub_config) state = self.client.vcenter.vm.Power.get(vm)
vm_svc = VM(self.stub_config)
state = power_svc.get(vm)
if state == Power.Info(state=Power.State.POWERED_ON): if state == Power.Info(state=Power.State.POWERED_ON):
power_svc.stop(vm) self.client.vcenter.vm.Power.stop(vm)
elif state == Power.Info(state=Power.State.SUSPENDED): elif state == Power.Info(state=Power.State.SUSPENDED):
power_svc.start(vm) self.client.vcenter.vm.Power.start(vm)
power_svc.stop(vm) self.client.vcenter.vm.Power.stop(vm)
print("Deleting VM '{}' ({})".format(self.vm_name, vm)) print("Deleting VM '{}' ({})".format(self.vm_name, vm))
vm_svc.delete(vm) self.client.vcenter.VM.delete(vm)
def main(): def main():
create_exhaustive_vm = CreateExhaustiveVM() create_exhaustive_vm = CreateExhaustiveVM()
create_exhaustive_vm.setup()
create_exhaustive_vm.cleanup() create_exhaustive_vm.cleanup()
create_exhaustive_vm.run() create_exhaustive_vm.run()
if create_exhaustive_vm.cleardata: if create_exhaustive_vm.cleardata:

View File

@ -2,7 +2,7 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2017. All Rights Reserved. * Copyright (c) VMware, Inc. 2017, 2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -14,18 +14,16 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2017 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+' __vcenter_version__ = '6.5+'
import atexit from vmware.vapi.vsphere.client import create_vsphere_client
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_cli
from samples.vsphere.common import sample_util 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
from samples.vsphere.common.ssl_helper import get_unverified_session
class DeleteVM(object): class DeleteVM(object):
@ -36,10 +34,6 @@ class DeleteVM(object):
""" """
def __init__(self): def __init__(self):
self.service_manager = None
self.vm_name = None
def setup(self):
parser = sample_cli.build_arg_parser() parser = sample_cli.build_arg_parser()
parser.add_argument('-n', '--vm_name', parser.add_argument('-n', '--vm_name',
action='store', action='store',
@ -48,37 +42,35 @@ class DeleteVM(object):
args = sample_util.process_cli_args(parser.parse_args()) args = sample_util.process_cli_args(parser.parse_args())
self.vm_name = args.vm_name self.vm_name = args.vm_name
self.service_manager = ServiceManager(args.server, session = get_unverified_session() if args.skipverification else None
args.username,
args.password, # Connect to vSphere client
args.skipverification) self.client = create_vsphere_client(server=args.server,
self.service_manager.connect() username=args.username,
atexit.register(self.service_manager.disconnect) password=args.password,
session=session)
def run(self): def run(self):
""" """
Delete User specified VM from Server Delete User specified VM from Server
""" """
vm_svc = VM(self.service_manager.stub_config) vm = get_vm(self.client, self.vm_name)
power_svc = Power(self.service_manager.stub_config)
vm = get_vm(self.service_manager.stub_config, self.vm_name)
if not vm: if not vm:
raise Exception('Sample requires an existing vm with name ({}).' raise Exception('Sample requires an existing vm with name ({}).'
'Please create the vm first.'.format(vm_name)) 'Please create the vm first.'.format(self.vm_name))
print("Deleting VM -- '{}-({})')".format(self.vm_name, vm)) print("Deleting VM -- '{}-({})')".format(self.vm_name, vm))
state = power_svc.get(vm) state = self.client.vcenter.vm.Power.get(vm)
if state == Power.Info(state=Power.State.POWERED_ON): if state == Power.Info(state=Power.State.POWERED_ON):
power_svc.stop(vm) self.client.vcenter.vm.Power.stop(vm)
elif state == Power.Info(state=Power.State.SUSPENDED): elif state == Power.Info(state=Power.State.SUSPENDED):
power_svc.start(vm) self.client.vcenter.vm.Power.start(vm)
power_svc.stop(vm) self.client.vcenter.vm.Power.stop(vm)
vm_svc.delete(vm) self.client.vcenter.VM.delete(vm)
print("Deleted VM -- '{}-({})".format(self.vm_name, vm)) print("Deleted VM -- '{}-({})".format(self.vm_name, vm))
def main(): def main():
delete_vm = DeleteVM() delete_vm = DeleteVM()
delete_vm.setup()
delete_vm.run() delete_vm.run()

View File

@ -2,7 +2,7 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -14,18 +14,17 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+' __vcenter_version__ = '6.5+'
import atexit from vmware.vapi.vsphere.client import create_vsphere_client
from com.vmware.vcenter.vm.hardware.adapter_client import Sata from com.vmware.vcenter.vm.hardware.adapter_client import Sata
from samples.vsphere.common import vapiconnect
from samples.vsphere.common.sample_util import pp, \ from samples.vsphere.common.sample_util import pp, \
parse_cli_args_vm parse_cli_args_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 from samples.vsphere.vcenter.helper.vm_helper import get_vm
from samples.vsphere.common.ssl_helper import get_unverified_session
""" """
Demonstrates how to configure virtual SATA adapters of a virtual machine. Demonstrates how to configure virtual SATA adapters of a virtual machine.
@ -36,44 +35,41 @@ The sample needs an existing VM.
vm = None vm = None
vm_name = None vm_name = None
stub_config = None client = None
sata_svc = None
cleardata = False cleardata = False
satas_to_delete = [] satas_to_delete = []
orig_sata_summaries = None orig_sata_summaries = None
def setup(context=None): def setup(context=None):
global vm, vm_name, stub_config, cleardata global vm, vm_name, client, cleardata
if context: if context:
# Run sample suite via setup script # Run sample suite via setup script
stub_config = context.stub_config client = context.client
vm_name = testbed.config['VM_NAME_DEFAULT'] vm_name = testbed.config['VM_NAME_DEFAULT']
else: else:
# Run sample in standalone mode # Run sample in standalone mode
server, username, password, cleardata, skip_verification, vm_name = \ server, username, password, cleardata, skip_verification, vm_name = \
parse_cli_args_vm(testbed.config['VM_NAME_DEFAULT']) parse_cli_args_vm(testbed.config['VM_NAME_DEFAULT'])
stub_config = vapiconnect.connect(server, session = get_unverified_session() if skip_verification else None
username,
password, # Connect to vSphere client
skip_verification) client = create_vsphere_client(server=server,
atexit.register(vapiconnect.logout, stub_config) username=username,
password=password,
session=session)
def run(): def run():
global vm global vm
vm = get_vm(stub_config, vm_name) vm = get_vm(client, vm_name)
if not vm: if not vm:
raise Exception('Sample requires an existing vm with name ({}). ' raise Exception('Sample requires an existing vm with name ({}). '
'Please create the vm first.'.format(vm_name)) 'Please create the vm first.'.format(vm_name))
print("Using VM '{}' ({}) for SATA Sample".format(vm_name, vm)) print("Using VM '{}' ({}) for SATA Sample".format(vm_name, vm))
# Create SATA adapter stub used for making requests
global sata_svc
sata_svc = Sata(stub_config)
print('\n# Example: List all SATA adapters for a VM') print('\n# Example: List all SATA adapters for a VM')
sata_summaries = sata_svc.list(vm=vm) sata_summaries = client.vcenter.vm.hardware.adapter.Sata.list(vm=vm)
print('vm.hardware.adapter.Sata.list({}) -> {}'.format(vm, sata_summaries)) print('vm.hardware.adapter.Sata.list({}) -> {}'.format(vm, sata_summaries))
# Save current list of SATA adapters to verify that we have cleaned up # Save current list of SATA adapters to verify that we have cleaned up
@ -84,7 +80,7 @@ def run():
# Get information for each SATA adapter on the VM # Get information for each SATA adapter on the VM
for sata_summary in sata_summaries: for sata_summary in sata_summaries:
sata = sata_summary.adapter sata = sata_summary.adapter
sata_info = sata_svc.get(vm=vm, adapter=sata) sata_info = client.vcenter.vm.hardware.adapter.Sata.get(vm=vm, adapter=sata)
print('vm.hardware.adapter.Sata.get({}, {}) -> {}'. print('vm.hardware.adapter.Sata.get({}, {}) -> {}'.
format(vm, sata, pp(sata_info))) format(vm, sata, pp(sata_info)))
@ -92,36 +88,36 @@ def run():
print('\n# Example: Create SATA adapter with defaults') print('\n# Example: Create SATA adapter with defaults')
sata_create_spec = Sata.CreateSpec() sata_create_spec = Sata.CreateSpec()
sata = sata_svc.create(vm, sata_create_spec) sata = client.vcenter.vm.hardware.adapter.Sata.create(vm, sata_create_spec)
print('vm.hardware.adapter.Sata.create({}, {}) -> {}'. print('vm.hardware.adapter.Sata.create({}, {}) -> {}'.
format(vm, sata_create_spec, sata)) format(vm, sata_create_spec, sata))
satas_to_delete.append(sata) satas_to_delete.append(sata)
sata_info = sata_svc.get(vm, sata) sata_info = client.vcenter.vm.hardware.adapter.Sata.get(vm, sata)
print('vm.hardware.adapter.Sata.get({}, {}) -> {}'. print('vm.hardware.adapter.Sata.get({}, {}) -> {}'.
format(vm, sata, pp(sata_info))) format(vm, sata, pp(sata_info)))
print('\n# Example: Create SATA adapter with a specific bus') print('\n# Example: Create SATA adapter with a specific bus')
sata_create_spec = Sata.CreateSpec(bus=2) sata_create_spec = Sata.CreateSpec(bus=2)
sata = sata_svc.create(vm, sata_create_spec) sata = client.vcenter.vm.hardware.adapter.Sata.create(vm, sata_create_spec)
print('vm.hardware.adapter.Sata.create({}, {}) -> {}'. print('vm.hardware.adapter.Sata.create({}, {}) -> {}'.
format(vm, sata_create_spec, sata)) format(vm, sata_create_spec, sata))
satas_to_delete.append(sata) satas_to_delete.append(sata)
sata_info = sata_svc.get(vm, sata) sata_info = client.vcenter.vm.hardware.adapter.Sata.get(vm, sata)
print('vm.hardware.adapter.Sata.get({}, {}) -> {}'. print('vm.hardware.adapter.Sata.get({}, {}) -> {}'.
format(vm, sata, pp(sata_info))) format(vm, sata, pp(sata_info)))
# List all SATA adapters for a VM # List all SATA adapters for a VM
sata_summaries = sata_svc.list(vm=vm) sata_summaries = client.vcenter.vm.hardware.adapter.Sata.list(vm=vm)
print('vm.hardware.adapter.Sata.list({}) -> {}'.format(vm, sata_summaries)) print('vm.hardware.adapter.Sata.list({}) -> {}'.format(vm, sata_summaries))
def cleanup(): def cleanup():
print('\n# Cleanup: Delete VM SATA adapters that were added') print('\n# Cleanup: Delete VM SATA adapters that were added')
for sata in satas_to_delete: for sata in satas_to_delete:
sata_svc.delete(vm, sata) client.vcenter.vm.hardware.adapter.Sata.delete(vm, sata)
print('vm.hardware.adapter.Sata.delete({}, {})'.format(vm, sata)) print('vm.hardware.adapter.Sata.delete({}, {})'.format(vm, sata))
sata_summaries = sata_svc.list(vm) sata_summaries = client.vcenter.vm.hardware.adapter.Sata.list(vm)
print('vm.hardware.adapter.Sata.list({}) -> {}'.format(vm, sata_summaries)) print('vm.hardware.adapter.Sata.list({}) -> {}'.format(vm, sata_summaries))
if set(orig_sata_summaries) != set(sata_summaries): if set(orig_sata_summaries) != set(sata_summaries):
print('vm.hardware.adapter.Sata WARNING: ' print('vm.hardware.adapter.Sata WARNING: '

View File

@ -2,7 +2,7 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -14,18 +14,16 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+' __vcenter_version__ = '6.5+'
import atexit from vmware.vapi.vsphere.client import create_vsphere_client
from com.vmware.vcenter.vm.hardware.adapter_client import Scsi from com.vmware.vcenter.vm.hardware.adapter_client import Scsi
from samples.vsphere.common import vapiconnect
from samples.vsphere.common.sample_util import pp, \ from samples.vsphere.common.sample_util import pp, \
parse_cli_args_vm parse_cli_args_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 from samples.vsphere.vcenter.helper.vm_helper import get_vm
from samples.vsphere.common.ssl_helper import get_unverified_session
""" """
Demonstrates how to configure virtual SCSI adapters of a virtual machine. Demonstrates how to configure virtual SCSI adapters of a virtual machine.
@ -36,44 +34,41 @@ The sample needs an existing VM.
vm = None vm = None
vm_name = None vm_name = None
stub_config = None client = None
scsi_svc = None
cleardata = False cleardata = False
scsis_to_delete = [] scsis_to_delete = []
orig_scsi_summaries = None orig_scsi_summaries = None
def setup(context=None): def setup(context=None):
global vm, vm_name, stub_config, cleardata global vm, vm_name, client, cleardata
if context: if context:
# Run sample suite via setup script # Run sample suite via setup script
stub_config = context.stub_config client = context.client
vm_name = testbed.config['VM_NAME_DEFAULT'] vm_name = testbed.config['VM_NAME_DEFAULT']
else: else:
# Run sample in standalone mode # Run sample in standalone mode
server, username, password, cleardata, skip_verification, vm_name = \ server, username, password, cleardata, skip_verification, vm_name = \
parse_cli_args_vm(testbed.config['VM_NAME_DEFAULT']) parse_cli_args_vm(testbed.config['VM_NAME_DEFAULT'])
stub_config = vapiconnect.connect(server, session = get_unverified_session() if skip_verification else None
username,
password, # Connect to vSphere client
skip_verification) client = create_vsphere_client(server=server,
atexit.register(vapiconnect.logout, stub_config) username=username,
password=password,
session=session)
def run(): def run():
global vm global vm
vm = get_vm(stub_config, vm_name) vm = get_vm(client, vm_name)
if not vm: if not vm:
raise Exception('Sample requires an existing vm with name ({}). ' raise Exception('Sample requires an existing vm with name ({}). '
'Please create the vm first.'.format(vm_name)) 'Please create the vm first.'.format(vm_name))
print("Using VM '{}' ({}) for SCSI Sample".format(vm_name, vm)) print("Using VM '{}' ({}) for SCSI Sample".format(vm_name, vm))
# Create SCSI adapter stub used for making requests
global scsi_svc
scsi_svc = Scsi(stub_config)
print('\n# Example: List all SCSI adapters for a VM') print('\n# Example: List all SCSI adapters for a VM')
scsi_summaries = scsi_svc.list(vm=vm) scsi_summaries = client.vcenter.vm.hardware.adapter.Scsi.list(vm=vm)
print('vm.hardware.adapter.Scsi.list({}) -> {}'.format(vm, scsi_summaries)) print('vm.hardware.adapter.Scsi.list({}) -> {}'.format(vm, scsi_summaries))
# Save current list of SCSI adapters to verify that we have cleaned up # Save current list of SCSI adapters to verify that we have cleaned up
@ -84,7 +79,7 @@ def run():
# Get information for each SCSI adapter on the VM # Get information for each SCSI adapter on the VM
for scsi_summary in scsi_summaries: for scsi_summary in scsi_summaries:
scsi = scsi_summary.adapter scsi = scsi_summary.adapter
scsi_info = scsi_svc.get(vm=vm, adapter=scsi) scsi_info = client.vcenter.vm.hardware.adapter.Scsi.get(vm=vm, adapter=scsi)
print('vm.hardware.adapter.Scsi.get({}, {}) -> {}'. print('vm.hardware.adapter.Scsi.get({}, {}) -> {}'.
format(vm, scsi, pp(scsi_info))) format(vm, scsi, pp(scsi_info)))
@ -92,11 +87,11 @@ def run():
print('\n# Example: Create SCSI adapter with defaults') print('\n# Example: Create SCSI adapter with defaults')
scsi_create_spec = Scsi.CreateSpec() scsi_create_spec = Scsi.CreateSpec()
scsi = scsi_svc.create(vm, scsi_create_spec) scsi = client.vcenter.vm.hardware.adapter.Scsi.create(vm, scsi_create_spec)
print('vm.hardware.adapter.Scsi.create({}, {}) -> {}'. print('vm.hardware.adapter.Scsi.create({}, {}) -> {}'.
format(vm, scsi_create_spec, scsi)) format(vm, scsi_create_spec, scsi))
scsis_to_delete.append(scsi) scsis_to_delete.append(scsi)
scsi_info = scsi_svc.get(vm, scsi) scsi_info = client.vcenter.vm.hardware.adapter.Scsi.get(vm, scsi)
print('vm.hardware.adapter.Scsi.get({}, {}) -> {}'. print('vm.hardware.adapter.Scsi.get({}, {}) -> {}'.
format(vm, scsi, pp(scsi_info))) format(vm, scsi, pp(scsi_info)))
@ -104,35 +99,35 @@ def run():
'and sharing=True') 'and sharing=True')
scsi_create_spec = Scsi.CreateSpec(bus=2, scsi_create_spec = Scsi.CreateSpec(bus=2,
sharing=Scsi.Sharing.VIRTUAL) sharing=Scsi.Sharing.VIRTUAL)
scsi = scsi_svc.create(vm, scsi_create_spec) scsi = client.vcenter.vm.hardware.adapter.Scsi.create(vm, scsi_create_spec)
print('vm.hardware.adapter.Scsi.create({}, {}) -> {}'. print('vm.hardware.adapter.Scsi.create({}, {}) -> {}'.
format(vm, scsi_create_spec, scsi)) format(vm, scsi_create_spec, scsi))
scsis_to_delete.append(scsi) scsis_to_delete.append(scsi)
scsi_info = scsi_svc.get(vm, scsi) scsi_info = client.vcenter.vm.hardware.adapter.Scsi.get(vm, scsi)
print('vm.hardware.adapter.Scsi.get({}, {}) -> {}'. print('vm.hardware.adapter.Scsi.get({}, {}) -> {}'.
format(vm, scsi, pp(scsi_info))) format(vm, scsi, pp(scsi_info)))
print('\n# Example: Update SCSI adapter by setting sharing=False') print('\n# Example: Update SCSI adapter by setting sharing=False')
scsi_update_spec = Scsi.UpdateSpec(sharing=Scsi.Sharing.NONE) scsi_update_spec = Scsi.UpdateSpec(sharing=Scsi.Sharing.NONE)
scsi_svc.update(vm, scsi, scsi_update_spec) client.vcenter.vm.hardware.adapter.Scsi.update(vm, scsi, scsi_update_spec)
print('vm.hardware.adapter.Scsi.update({}, {}, {})'. print('vm.hardware.adapter.Scsi.update({}, {}, {})'.
format(vm, scsi, scsi_create_spec)) format(vm, scsi, scsi_create_spec))
scsi_info = scsi_svc.get(vm, scsi) scsi_info = client.vcenter.vm.hardware.adapter.Scsi.get(vm, scsi)
print('vm.hardware.adapter.Scsi.get({}, {}) -> {}'. print('vm.hardware.adapter.Scsi.get({}, {}) -> {}'.
format(vm, scsi, pp(scsi_info))) format(vm, scsi, pp(scsi_info)))
# List all SCSI adapters for a VM # List all SCSI adapters for a VM
scsi_summaries = scsi_svc.list(vm=vm) scsi_summaries = client.vcenter.vm.hardware.adapter.Scsi.list(vm=vm)
print('vm.hardware.adapter.Scsi.list({}) -> {}'.format(vm, scsi_summaries)) print('vm.hardware.adapter.Scsi.list({}) -> {}'.format(vm, scsi_summaries))
def cleanup(): def cleanup():
print('\n# Cleanup: Delete VM SCSI adapters that were added') print('\n# Cleanup: Delete VM SCSI adapters that were added')
for scsi in scsis_to_delete: for scsi in scsis_to_delete:
scsi_svc.delete(vm, scsi) client.vcenter.vm.hardware.adapter.Scsi.delete(vm, scsi)
print('vm.hardware.adapter.Scsi.delete({}, {})'.format(vm, scsi)) print('vm.hardware.adapter.Scsi.delete({}, {})'.format(vm, scsi))
scsi_summaries = scsi_svc.list(vm) scsi_summaries = client.vcenter.vm.hardware.adapter.Scsi.list(vm)
print('vm.hardware.adapter.Scsi.list({}) -> {}'.format(vm, scsi_summaries)) print('vm.hardware.adapter.Scsi.list({}) -> {}'.format(vm, scsi_summaries))
if set(orig_scsi_summaries) != set(scsi_summaries): if set(orig_scsi_summaries) != set(scsi_summaries):
print('vm.hardware.adapter.Scsi WARNING: ' print('vm.hardware.adapter.Scsi WARNING: '

View File

@ -2,7 +2,7 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -14,18 +14,18 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+' __vcenter_version__ = '6.5+'
import atexit
from com.vmware.vcenter.vm.hardware_client import Boot from com.vmware.vcenter.vm.hardware_client import Boot
from samples.vsphere.common import vapiconnect from vmware.vapi.vsphere.client import create_vsphere_client
from samples.vsphere.common.sample_util import parse_cli_args_vm from samples.vsphere.common.sample_util import parse_cli_args_vm
from samples.vsphere.common.sample_util import pp from samples.vsphere.common.sample_util import pp
from samples.vsphere.vcenter.setup import testbed from samples.vsphere.vcenter.setup import testbed
from samples.vsphere.vcenter.helper.vm_helper import get_vm from samples.vsphere.vcenter.helper.vm_helper import get_vm
from samples.vsphere.common.ssl_helper import get_unverified_session
""" """
Demonstrates how to configure the settings used when booting a virtual machine. Demonstrates how to configure the settings used when booting a virtual machine.
@ -36,43 +36,41 @@ The sample needs an existing VM.
vm = None vm = None
vm_name = None vm_name = None
stub_config = None client = None
boot_svc = None
cleardata = False cleardata = False
orig_boot_info = None orig_boot_info = None
def setup(context=None): def setup(context=None):
global vm, vm_name, stub_config, cleardata global vm, vm_name, client, cleardata
if context: if context:
# Run sample suite via setup script # Run sample suite via setup script
stub_config = context.stub_config client = context.client
vm_name = testbed.config['VM_NAME_DEFAULT'] vm_name = testbed.config['VM_NAME_DEFAULT']
else: else:
# Run sample in standalone mode # Run sample in standalone mode
server, username, password, cleardata, skip_verification, vm_name = \ server, username, password, cleardata, skip_verification, vm_name = \
parse_cli_args_vm(testbed.config['VM_NAME_DEFAULT']) parse_cli_args_vm(testbed.config['VM_NAME_DEFAULT'])
stub_config = vapiconnect.connect(server,
username, session = get_unverified_session() if skip_verification else None
password,
skip_verification) # Connect to vSphere client
atexit.register(vapiconnect.logout, stub_config) client = create_vsphere_client(server=server,
username=username,
password=password,
session=session)
def run(): def run():
global vm global vm
vm = get_vm(stub_config, vm_name) vm = get_vm(client, vm_name)
if not vm: if not vm:
raise Exception('Sample requires an existing vm with name ({}). ' raise Exception('Sample requires an existing vm with name ({}). '
'Please create the vm first.'.format(vm_name)) 'Please create the vm first.'.format(vm_name))
print("Using VM '{}' ({}) for Boot Sample".format(vm_name, vm)) print("Using VM '{}' ({}) for Boot Sample".format(vm_name, vm))
# Create Boot stub used for making requests
global boot_svc
boot_svc = Boot(stub_config)
print('\n# Example: Get current Boot configuration') print('\n# Example: Get current Boot configuration')
boot_info = boot_svc.get(vm) boot_info = client.vcenter.vm.hardware.Boot.get(vm)
print('vm.hardware.Boot.get({}) -> {}'.format(vm, pp(boot_info))) print('vm.hardware.Boot.get({}) -> {}'.format(vm, pp(boot_info)))
# Save current Boot info to verify that we have cleaned up properly # Save current Boot info to verify that we have cleaned up properly
@ -82,16 +80,16 @@ def run():
print('\n# Example: Update firmware to EFI for Boot configuration') print('\n# Example: Update firmware to EFI for Boot configuration')
update_spec = Boot.UpdateSpec(type=Boot.Type.EFI) update_spec = Boot.UpdateSpec(type=Boot.Type.EFI)
print('vm.hardware.Boot.update({}, {})'.format(vm, update_spec)) print('vm.hardware.Boot.update({}, {})'.format(vm, update_spec))
boot_svc.update(vm, update_spec) client.vcenter.vm.hardware.Boot.update(vm, update_spec)
boot_info = boot_svc.get(vm) boot_info = client.vcenter.vm.hardware.Boot.get(vm)
print('vm.hardware.Boot.get({}) -> {}'.format(vm, pp(boot_info))) print('vm.hardware.Boot.get({}) -> {}'.format(vm, pp(boot_info)))
print('\n# Example: Update boot firmware to tell it to enter setup mode on ' print('\n# Example: Update boot firmware to tell it to enter setup mode on '
'next boot') 'next boot')
update_spec = Boot.UpdateSpec(enter_setup_mode=True) update_spec = Boot.UpdateSpec(enter_setup_mode=True)
print('vm.hardware.Boot.update({}, {})'.format(vm, update_spec)) print('vm.hardware.Boot.update({}, {})'.format(vm, update_spec))
boot_svc.update(vm, update_spec) client.vcenter.vm.hardware.Boot.update(vm, update_spec)
boot_info = boot_svc.get(vm) boot_info = client.vcenter.vm.hardware.Boot.get(vm)
print('vm.hardware.Boot.get({}) -> {}'.format(vm, pp(boot_info))) print('vm.hardware.Boot.get({}) -> {}'.format(vm, pp(boot_info)))
print('\n# Example: Update boot firmware to introduce a delay in boot' print('\n# Example: Update boot firmware to introduce a delay in boot'
@ -103,8 +101,8 @@ def run():
retry=True, retry=True,
retry_delay=30000) retry_delay=30000)
print('vm.hardware.Boot.update({}, {})'.format(vm, update_spec)) print('vm.hardware.Boot.update({}, {})'.format(vm, update_spec))
boot_svc.update(vm, update_spec) client.vcenter.vm.hardware.Boot.update(vm, update_spec)
boot_info = boot_svc.get(vm) boot_info = client.vcenter.vm.hardware.Boot.get(vm)
print('vm.hardware.Boot.get({}) -> {}'.format(vm, pp(boot_info))) print('vm.hardware.Boot.get({}) -> {}'.format(vm, pp(boot_info)))
@ -119,8 +117,8 @@ def cleanup():
retry_delay=orig_boot_info.retry_delay, retry_delay=orig_boot_info.retry_delay,
enter_setup_mode=orig_boot_info.enter_setup_mode) enter_setup_mode=orig_boot_info.enter_setup_mode)
print('vm.hardware.Boot.update({}, {})'.format(vm, update_spec)) print('vm.hardware.Boot.update({}, {})'.format(vm, update_spec))
boot_svc.update(vm, update_spec) client.vcenter.vm.hardware.Boot.update(vm, update_spec)
boot_info = boot_svc.get(vm) boot_info = client.vcenter.vm.hardware.Boot.get(vm)
print('vm.hardware.Boot.get({}) -> {}'.format(vm, pp(boot_info))) print('vm.hardware.Boot.get({}) -> {}'.format(vm, pp(boot_info)))
if boot_info != orig_boot_info: if boot_info != orig_boot_info:

View File

@ -2,7 +2,7 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -14,18 +14,16 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+' __vcenter_version__ = '6.5+'
import atexit from vmware.vapi.vsphere.client import create_vsphere_client
from com.vmware.vcenter.vm.hardware.boot_client import Device as BootDevice from com.vmware.vcenter.vm.hardware.boot_client import Device as BootDevice
from com.vmware.vcenter.vm.hardware_client import (Disk, Ethernet)
from samples.vsphere.common import vapiconnect
from samples.vsphere.common.sample_util import parse_cli_args_vm from samples.vsphere.common.sample_util import parse_cli_args_vm
from samples.vsphere.common.sample_util import pp from samples.vsphere.common.sample_util import pp
from samples.vsphere.vcenter.setup import testbed from samples.vsphere.vcenter.setup import testbed
from samples.vsphere.vcenter.helper.vm_helper import get_vm from samples.vsphere.vcenter.helper.vm_helper import get_vm
from samples.vsphere.common.ssl_helper import get_unverified_session
""" """
Demonstrates how to modify the boot devices used by a virtual machine, and in Demonstrates how to modify the boot devices used by a virtual machine, and in
@ -41,43 +39,39 @@ The sample needs an existing VM with the following configuration:
vm = None vm = None
vm_name = None vm_name = None
stub_config = None client = None
boot_device_svc = None
cleardata = False cleardata = False
orig_boot_device_entries = None orig_boot_device_entries = None
def setup(context=None): def setup(context=None):
global vm, vm_name, stub_config, cleardata global vm, vm_name, client, cleardata
if context: if context:
# Run sample suite via setup script # Run sample suite via setup script
stub_config = context.stub_config client = context.client
vm_name = testbed.config['VM_NAME_EXHAUSTIVE'] vm_name = testbed.config['VM_NAME_EXHAUSTIVE']
else: else:
# Run sample in standalone mode # Run sample in standalone mode
server, username, password, cleardata, skip_verification, vm_name = \ server, username, password, cleardata, skip_verification, vm_name = \
parse_cli_args_vm(testbed.config['VM_NAME_EXHAUSTIVE']) parse_cli_args_vm(testbed.config['VM_NAME_EXHAUSTIVE'])
stub_config = vapiconnect.connect(server, session = get_unverified_session() if skip_verification else None
username,
password,
skip_verification)
atexit.register(vapiconnect.logout, stub_config)
# Connect to vSphere client
client = create_vsphere_client(server=server,
username=username,
password=password,
session=session)
def run(): def run():
global vm global vm
vm = get_vm(stub_config, vm_name) vm = get_vm(client, vm_name)
if not vm: if not vm:
raise Exception('Sample requires an existing vm with name ({}). ' raise Exception('Sample requires an existing vm with name ({}). '
'Please create the vm first.'.format(vm_name)) 'Please create the vm first.'.format(vm_name))
print("Using VM '{}' ({}) for BootDevice Sample".format(vm_name, vm)) print("Using VM '{}' ({}) for BootDevice Sample".format(vm_name, vm))
# Create BootDevice stub used for making requests
global boot_device_svc
boot_device_svc = BootDevice(stub_config)
print('\n# Example: Get current BootDevice configuration') print('\n# Example: Get current BootDevice configuration')
boot_device_entries = boot_device_svc.get(vm) boot_device_entries = client.vcenter.vm.hardware.boot.Device.get(vm)
print('vm.hardware.boot.Device.get({}) -> {}'. print('vm.hardware.boot.Device.get({}) -> {}'.
format(vm, pp(boot_device_entries))) format(vm, pp(boot_device_entries)))
@ -86,14 +80,12 @@ def run():
orig_boot_device_entries = boot_device_entries orig_boot_device_entries = boot_device_entries
# Get device identifiers for Disks # Get device identifiers for Disks
disk_svc = Disk(stub_config) disk_summaries = client.vcenter.vm.hardware.Disk.list(vm)
disk_summaries = disk_svc.list(vm)
print('vm.hardware.Disk.list({}) -> {}'.format(vm, pp(disk_summaries))) print('vm.hardware.Disk.list({}) -> {}'.format(vm, pp(disk_summaries)))
disks = [disk_summary.disk for disk_summary in disk_summaries] disks = [disk_summary.disk for disk_summary in disk_summaries]
# Get device identifiers for Ethernet nics # Get device identifiers for Ethernet nics
ethernet_svc = Ethernet(stub_config) nic_summaries = client.vcenter.vm.hardware.Ethernet.list(vm)
nic_summaries = ethernet_svc.list(vm)
print('vm.hardware.Ethernet.list({}) -> {}'.format(vm, pp(nic_summaries))) print('vm.hardware.Ethernet.list({}) -> {}'.format(vm, pp(nic_summaries)))
nics = [nic_summary.nic for nic_summary in nic_summaries] nics = [nic_summary.nic for nic_summary in nic_summaries]
@ -108,8 +100,8 @@ def run():
boot_device_entries.append( boot_device_entries.append(
BootDevice.Entry(BootDevice.Type.ETHERNET, nic=nic)) BootDevice.Entry(BootDevice.Type.ETHERNET, nic=nic))
print('vm.hardware.boot.Device.set({}, {})'.format(vm, boot_device_entries)) print('vm.hardware.boot.Device.set({}, {})'.format(vm, boot_device_entries))
boot_device_svc.set(vm, boot_device_entries) client.vcenter.vm.hardware.boot.Device.set(vm, boot_device_entries)
boot_device_entries = boot_device_svc.get(vm) boot_device_entries = client.vcenter.vm.hardware.boot.Device.get(vm)
print('vm.hardware.boot.Device.get({}) -> {}'. print('vm.hardware.boot.Device.get({}) -> {}'.
format(vm, pp(boot_device_entries))) format(vm, pp(boot_device_entries)))
@ -118,8 +110,8 @@ def cleanup():
print('\n# Cleanup: Revert BootDevice configuration') print('\n# Cleanup: Revert BootDevice configuration')
boot_device_entries = orig_boot_device_entries boot_device_entries = orig_boot_device_entries
print('vm.hardware.boot.Device.set({}, {})'.format(vm, boot_device_entries)) print('vm.hardware.boot.Device.set({}, {})'.format(vm, boot_device_entries))
boot_device_svc.set(vm, boot_device_entries) client.vcenter.vm.hardware.boot.Device.set(vm, boot_device_entries)
boot_device_entries = boot_device_svc.get(vm) boot_device_entries = client.vcenter.vm.hardware.boot.Device.get(vm)
print('vm.hardware.boot.Device.get({}) -> {}'. print('vm.hardware.boot.Device.get({}) -> {}'.
format(vm, pp(boot_device_entries))) format(vm, pp(boot_device_entries)))

View File

@ -2,7 +2,7 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -14,22 +14,20 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+' __vcenter_version__ = '6.5+'
import atexit from vmware.vapi.vsphere.client import create_vsphere_client
from com.vmware.vcenter.vm.hardware.adapter_client import Sata from com.vmware.vcenter.vm.hardware.adapter_client import Sata
from com.vmware.vcenter.vm.hardware_client import (Cdrom, from com.vmware.vcenter.vm.hardware_client import (Cdrom,
IdeAddressSpec, IdeAddressSpec,
SataAddressSpec) SataAddressSpec)
from com.vmware.vcenter.vm_client import Power
from samples.vsphere.common import vapiconnect
from samples.vsphere.common.sample_util import parse_cli_args_vm from samples.vsphere.common.sample_util import parse_cli_args_vm
from samples.vsphere.common.sample_util import pp from samples.vsphere.common.sample_util import pp
from samples.vsphere.vcenter.setup import testbed from samples.vsphere.vcenter.setup import testbed
from samples.vsphere.vcenter.helper.vm_helper import get_vm from samples.vsphere.vcenter.helper.vm_helper import get_vm
from samples.vsphere.common.ssl_helper import get_unverified_session
""" """
Demonstrates how to configure CD-ROM devices for a VM. Demonstrates how to configure CD-ROM devices for a VM.
@ -41,58 +39,50 @@ The sample needs an existing VM.
vm = None vm = None
vm_name = None vm_name = None
sata = None sata = None
stub_config = None client = None
cdrom_svc = None
vm_power_svc = None
sata_svc = None
cleardata = False cleardata = False
cdroms_to_delete = [] cdroms_to_delete = []
orig_cdrom_summaries = None orig_cdrom_summaries = None
def setup(context=None): def setup(context=None):
global vm, vm_name, stub_config, cleardata global vm, vm_name, client, cleardata
if context: if context:
# Run sample suite via setup script # Run sample suite via setup script
stub_config = context.stub_config client = context.client
vm_name = testbed.config['VM_NAME_DEFAULT'] vm_name = testbed.config['VM_NAME_DEFAULT']
else: else:
# Run sample in standalone mode # Run sample in standalone mode
server, username, password, cleardata, skip_verification, vm_name = \ server, username, password, cleardata, skip_verification, vm_name = \
parse_cli_args_vm(testbed.config['VM_NAME_DEFAULT']) parse_cli_args_vm(testbed.config['VM_NAME_DEFAULT'])
stub_config = vapiconnect.connect(server, session = get_unverified_session() if skip_verification else None
username,
password,
skip_verification)
atexit.register(vapiconnect.logout, stub_config)
# Connect to vSphere client
client = create_vsphere_client(server=server,
username=username,
password=password,
session=session)
def run(): def run():
global vm global vm
vm = get_vm(stub_config, vm_name) vm = get_vm(client, vm_name)
if not vm: if not vm:
raise Exception('Sample requires an existing vm with name ({}). ' raise Exception('Sample requires an existing vm with name ({}). '
'Please create the vm first.'.format(vm_name)) 'Please create the vm first.'.format(vm_name))
print("Using VM '{}' ({}) for CD-ROM Sample".format(vm_name, vm)) print("Using VM '{}' ({}) for CD-ROM Sample".format(vm_name, vm))
iso_datastore_path = testbed.config['ISO_DATASTORE_PATH'] iso_datastore_path = testbed.config['ISO_DATASTORE_PATH']
# Create CD-ROM stub used for making requests
global cdrom_svc, vm_power_svc, sata_svc
cdrom_svc = Cdrom(stub_config)
vm_power_svc = Power(stub_config)
# Create SATA controller # Create SATA controller
print('\n# Setup: Create a SATA controller') print('\n# Setup: Create a SATA controller')
sata_svc = Sata(stub_config)
sata_create_spec = Sata.CreateSpec() sata_create_spec = Sata.CreateSpec()
print('# Adding SATA controller for SATA Disk samples') print('# Adding SATA controller for SATA Disk samples')
global sata global sata
sata = sata_svc.create(vm, sata_create_spec) sata = client.vcenter.vm.hardware.adapter.Sata.create(vm, sata_create_spec)
print('vm.hardware.adapter.Sata.create({}, {}) -> {}'. print('vm.hardware.adapter.Sata.create({}, {}) -> {}'.
format(vm, sata_create_spec, sata)) format(vm, sata_create_spec, sata))
print('\n# Example: List all Cdroms for a VM') print('\n# Example: List all Cdroms for a VM')
cdrom_summaries = cdrom_svc.list(vm=vm) cdrom_summaries = client.vcenter.vm.hardware.Cdrom.list(vm=vm)
print('vm.hardware.Cdrom.list({}) -> {}'.format(vm, cdrom_summaries)) print('vm.hardware.Cdrom.list({}) -> {}'.format(vm, cdrom_summaries))
# Save current list of Cdroms to verify that we have cleaned up properly # Save current list of Cdroms to verify that we have cleaned up properly
@ -102,7 +92,7 @@ def run():
# Get information for each CD-ROM on the VM # Get information for each CD-ROM on the VM
for cdrom_summary in cdrom_summaries: for cdrom_summary in cdrom_summaries:
cdrom = cdrom_summary.cdrom cdrom = cdrom_summary.cdrom
cdrom_info = cdrom_svc.get(vm=vm, cdrom=cdrom) cdrom_info = client.vcenter.vm.hardware.Cdrom.get(vm=vm, cdrom=cdrom)
print('vm.hardware.Cdrom.get({}, {}) -> {}'. print('vm.hardware.Cdrom.get({}, {}) -> {}'.
format(vm, cdrom, pp(cdrom_info))) format(vm, cdrom, pp(cdrom_info)))
@ -113,31 +103,31 @@ def run():
start_connected=True, start_connected=True,
backing=Cdrom.BackingSpec(type=Cdrom.BackingType.ISO_FILE, backing=Cdrom.BackingSpec(type=Cdrom.BackingType.ISO_FILE,
iso_file=iso_datastore_path)) iso_file=iso_datastore_path))
cdrom = cdrom_svc.create(vm, cdrom_create_spec) cdrom = client.vcenter.vm.hardware.Cdrom.create(vm, cdrom_create_spec)
cdroms_to_delete.append(cdrom) cdroms_to_delete.append(cdrom)
cdrom_info = cdrom_svc.get(vm, cdrom) cdrom_info = client.vcenter.vm.hardware.Cdrom.get(vm, cdrom)
print('vm.hardware.Cdrom.get({}, {}) -> {}'. print('vm.hardware.Cdrom.get({}, {}) -> {}'.
format(vm, cdrom, pp(cdrom_info))) format(vm, cdrom, pp(cdrom_info)))
print('\n# Example: Create CD-ROM with CLIENT_DEVICE backing') print('\n# Example: Create CD-ROM with CLIENT_DEVICE backing')
cdrom_create_spec = Cdrom.CreateSpec( cdrom_create_spec = Cdrom.CreateSpec(
backing=Cdrom.BackingSpec(type=Cdrom.BackingType.CLIENT_DEVICE)) backing=Cdrom.BackingSpec(type=Cdrom.BackingType.CLIENT_DEVICE))
cdrom = cdrom_svc.create(vm, cdrom_create_spec) cdrom = client.vcenter.vm.hardware.Cdrom.create(vm, cdrom_create_spec)
print('vm.hardware.Cdrom.create({}, {}) -> {}'. print('vm.hardware.Cdrom.create({}, {}) -> {}'.
format(vm, cdrom_create_spec, cdrom)) format(vm, cdrom_create_spec, cdrom))
cdroms_to_delete.append(cdrom) cdroms_to_delete.append(cdrom)
cdrom_info = cdrom_svc.get(vm, cdrom) cdrom_info = client.vcenter.vm.hardware.Cdrom.get(vm, cdrom)
print('vm.hardware.Cdrom.get({}, {}) -> {}'. print('vm.hardware.Cdrom.get({}, {}) -> {}'.
format(vm, cdrom, pp(cdrom_info))) format(vm, cdrom, pp(cdrom_info)))
print('\n# Example: Create CD-ROM using auto-detect HOST_DEVICE backing') print('\n# Example: Create CD-ROM using auto-detect HOST_DEVICE backing')
cdrom_create_spec = Cdrom.CreateSpec( cdrom_create_spec = Cdrom.CreateSpec(
backing=Cdrom.BackingSpec(type=Cdrom.BackingType.HOST_DEVICE)) backing=Cdrom.BackingSpec(type=Cdrom.BackingType.HOST_DEVICE))
cdrom = cdrom_svc.create(vm, cdrom_create_spec) cdrom = client.vcenter.vm.hardware.Cdrom.create(vm, cdrom_create_spec)
print('vm.hardware.Cdrom.create({}, {}) -> {}'. print('vm.hardware.Cdrom.create({}, {}) -> {}'.
format(vm, cdrom_create_spec, cdrom)) format(vm, cdrom_create_spec, cdrom))
cdroms_to_delete.append(cdrom) cdroms_to_delete.append(cdrom)
cdrom_info = cdrom_svc.get(vm, cdrom) cdrom_info = client.vcenter.vm.hardware.Cdrom.get(vm, cdrom)
print('vm.hardware.Cdrom.get({}, {}) -> {}'. print('vm.hardware.Cdrom.get({}, {}) -> {}'.
format(vm, cdrom, pp(cdrom_info))) format(vm, cdrom, pp(cdrom_info)))
@ -145,11 +135,11 @@ def run():
cdrom_create_spec = Cdrom.CreateSpec( cdrom_create_spec = Cdrom.CreateSpec(
type=Cdrom.HostBusAdapterType.SATA, type=Cdrom.HostBusAdapterType.SATA,
backing=Cdrom.BackingSpec(type=Cdrom.BackingType.CLIENT_DEVICE)) backing=Cdrom.BackingSpec(type=Cdrom.BackingType.CLIENT_DEVICE))
cdrom = cdrom_svc.create(vm, cdrom_create_spec) cdrom = client.vcenter.vm.hardware.Cdrom.create(vm, cdrom_create_spec)
print('vm.hardware.Cdrom.create({}, {}) -> {}'. print('vm.hardware.Cdrom.create({}, {}) -> {}'.
format(vm, cdrom_create_spec, cdrom)) format(vm, cdrom_create_spec, cdrom))
cdroms_to_delete.append(cdrom) cdroms_to_delete.append(cdrom)
cdrom_info = cdrom_svc.get(vm, cdrom) cdrom_info = client.vcenter.vm.hardware.Cdrom.get(vm, cdrom)
print('vm.hardware.Cdrom.get({}, {}) -> {}'. print('vm.hardware.Cdrom.get({}, {}) -> {}'.
format(vm, cdrom, pp(cdrom_info))) format(vm, cdrom, pp(cdrom_info)))
@ -159,11 +149,11 @@ def run():
type=Cdrom.HostBusAdapterType.SATA, type=Cdrom.HostBusAdapterType.SATA,
sata=SataAddressSpec(bus=0), sata=SataAddressSpec(bus=0),
backing=Cdrom.BackingSpec(type=Cdrom.BackingType.CLIENT_DEVICE)) backing=Cdrom.BackingSpec(type=Cdrom.BackingType.CLIENT_DEVICE))
cdrom = cdrom_svc.create(vm, cdrom_create_spec) cdrom = client.vcenter.vm.hardware.Cdrom.create(vm, cdrom_create_spec)
print('vm.hardware.Cdrom.create({}, {}) -> {}'. print('vm.hardware.Cdrom.create({}, {}) -> {}'.
format(vm, cdrom_create_spec, cdrom)) format(vm, cdrom_create_spec, cdrom))
cdroms_to_delete.append(cdrom) cdroms_to_delete.append(cdrom)
cdrom_info = cdrom_svc.get(vm, cdrom) cdrom_info = client.vcenter.vm.hardware.Cdrom.get(vm, cdrom)
print('vm.hardware.Cdrom.get({}, {}) -> {}'. print('vm.hardware.Cdrom.get({}, {}) -> {}'.
format(vm, cdrom, pp(cdrom_info))) format(vm, cdrom, pp(cdrom_info)))
@ -173,11 +163,11 @@ def run():
type=Cdrom.HostBusAdapterType.SATA, type=Cdrom.HostBusAdapterType.SATA,
sata=SataAddressSpec(bus=0, unit=10), sata=SataAddressSpec(bus=0, unit=10),
backing=Cdrom.BackingSpec(type=Cdrom.BackingType.CLIENT_DEVICE)) backing=Cdrom.BackingSpec(type=Cdrom.BackingType.CLIENT_DEVICE))
cdrom = cdrom_svc.create(vm, cdrom_create_spec) cdrom = client.vcenter.vm.hardware.Cdrom.create(vm, cdrom_create_spec)
print('vm.hardware.Cdrom.create({}, {}) -> {}'. print('vm.hardware.Cdrom.create({}, {}) -> {}'.
format(vm, cdrom_create_spec, cdrom)) format(vm, cdrom_create_spec, cdrom))
cdroms_to_delete.append(cdrom) cdroms_to_delete.append(cdrom)
cdrom_info = cdrom_svc.get(vm, cdrom) cdrom_info = client.vcenter.vm.hardware.Cdrom.get(vm, cdrom)
print('vm.hardware.Cdrom.get({}, {}) -> {}'. print('vm.hardware.Cdrom.get({}, {}) -> {}'.
format(vm, cdrom, pp(cdrom_info))) format(vm, cdrom, pp(cdrom_info)))
@ -185,11 +175,11 @@ def run():
cdrom_create_spec = Cdrom.CreateSpec( cdrom_create_spec = Cdrom.CreateSpec(
type=Cdrom.HostBusAdapterType.IDE, type=Cdrom.HostBusAdapterType.IDE,
backing=Cdrom.BackingSpec(type=Cdrom.BackingType.CLIENT_DEVICE)) backing=Cdrom.BackingSpec(type=Cdrom.BackingType.CLIENT_DEVICE))
cdrom = cdrom_svc.create(vm, cdrom_create_spec) cdrom = client.vcenter.vm.hardware.Cdrom.create(vm, cdrom_create_spec)
print('vm.hardware.Cdrom.create({}, {}) -> {}'. print('vm.hardware.Cdrom.create({}, {}) -> {}'.
format(vm, cdrom_create_spec, cdrom)) format(vm, cdrom_create_spec, cdrom))
cdroms_to_delete.append(cdrom) cdroms_to_delete.append(cdrom)
cdrom_info = cdrom_svc.get(vm, cdrom) cdrom_info = client.vcenter.vm.hardware.Cdrom.get(vm, cdrom)
print('vm.hardware.Cdrom.get({}, {}) -> {}'. print('vm.hardware.Cdrom.get({}, {}) -> {}'.
format(vm, cdrom, pp(cdrom_info))) format(vm, cdrom, pp(cdrom_info)))
@ -199,11 +189,11 @@ def run():
type=Cdrom.HostBusAdapterType.IDE, type=Cdrom.HostBusAdapterType.IDE,
ide=IdeAddressSpec(False, True), ide=IdeAddressSpec(False, True),
backing=Cdrom.BackingSpec(type=Cdrom.BackingType.CLIENT_DEVICE)) backing=Cdrom.BackingSpec(type=Cdrom.BackingType.CLIENT_DEVICE))
cdrom = cdrom_svc.create(vm, cdrom_create_spec) cdrom = client.vcenter.vm.hardware.Cdrom.create(vm, cdrom_create_spec)
print('vm.hardware.Cdrom.create({}, {}) -> {}'. print('vm.hardware.Cdrom.create({}, {}) -> {}'.
format(vm, cdrom_create_spec, cdrom)) format(vm, cdrom_create_spec, cdrom))
cdroms_to_delete.append(cdrom) cdroms_to_delete.append(cdrom)
cdrom_info = cdrom_svc.get(vm, cdrom) cdrom_info = client.vcenter.vm.hardware.Cdrom.get(vm, cdrom)
print('vm.hardware.Cdrom.get({}, {}) -> {}'. print('vm.hardware.Cdrom.get({}, {}) -> {}'.
format(vm, cdrom, pp(cdrom_info))) format(vm, cdrom, pp(cdrom_info)))
@ -215,8 +205,8 @@ def run():
iso_file=iso_datastore_path)) iso_file=iso_datastore_path))
print('vm.hardware.Cdrom.update({}, {}, {})'. print('vm.hardware.Cdrom.update({}, {}, {})'.
format(vm, cdrom, cdrom_update_spec)) format(vm, cdrom, cdrom_update_spec))
cdrom_svc.update(vm, cdrom, cdrom_update_spec) client.vcenter.vm.hardware.Cdrom.update(vm, cdrom, cdrom_update_spec)
cdrom_info = cdrom_svc.get(vm, cdrom) cdrom_info = client.vcenter.vm.hardware.Cdrom.get(vm, cdrom)
print('vm.hardware.Cdrom.get({}, {}) -> {}'. print('vm.hardware.Cdrom.get({}, {}) -> {}'.
format(vm, cdrom, pp(cdrom_info))) format(vm, cdrom, pp(cdrom_info)))
@ -226,55 +216,55 @@ def run():
start_connected=False, allow_guest_control=False) start_connected=False, allow_guest_control=False)
print('vm.hardware.Cdrom.update({}, {}, {})'. print('vm.hardware.Cdrom.update({}, {}, {})'.
format(vm, cdrom, cdrom_update_spec)) format(vm, cdrom, cdrom_update_spec))
cdrom_svc.update(vm, cdrom, cdrom_update_spec) client.vcenter.vm.hardware.Cdrom.update(vm, cdrom, cdrom_update_spec)
cdrom_info = cdrom_svc.get(vm, cdrom) cdrom_info = client.vcenter.vm.hardware.Cdrom.get(vm, cdrom)
print('vm.hardware.Cdrom.get({}, {}) -> {}'. print('vm.hardware.Cdrom.get({}, {}) -> {}'.
format(vm, cdrom, pp(cdrom_info))) format(vm, cdrom, pp(cdrom_info)))
print('\n# Starting VM to run connect/disconnect sample') print('\n# Starting VM to run connect/disconnect sample')
print('vm.Power.start({})'.format(vm)) print('vm.Power.start({})'.format(vm))
vm_power_svc.start(vm) client.vcenter.vm.Power.start(vm)
cdrom_info = cdrom_svc.get(vm, cdrom) cdrom_info = client.vcenter.vm.hardware.Cdrom.get(vm, cdrom)
print('vm.hardware.Cdrom.get({}, {}) -> {}'. print('vm.hardware.Cdrom.get({}, {}) -> {}'.
format(vm, cdrom, pp(cdrom_info))) format(vm, cdrom, pp(cdrom_info)))
print('\n# Example: Connect CD-ROM after powering on VM') print('\n# Example: Connect CD-ROM after powering on VM')
cdrom_svc.connect(vm, cdrom) client.vcenter.vm.hardware.Cdrom.connect(vm, cdrom)
print('vm.hardware.Cdrom.connect({}, {})'.format(vm, cdrom)) print('vm.hardware.Cdrom.connect({}, {})'.format(vm, cdrom))
cdrom_info = cdrom_svc.get(vm, cdrom) cdrom_info = client.vcenter.vm.hardware.Cdrom.get(vm, cdrom)
print('vm.hardware.Cdrom.get({}, {}) -> {}'. print('vm.hardware.Cdrom.get({}, {}) -> {}'.
format(vm, cdrom, pp(cdrom_info))) format(vm, cdrom, pp(cdrom_info)))
print('\n# Example: Disconnect CD-ROM while VM is powered on') print('\n# Example: Disconnect CD-ROM while VM is powered on')
cdrom_svc.disconnect(vm, cdrom) client.vcenter.vm.hardware.Cdrom.disconnect(vm, cdrom)
print('vm.hardware.Cdrom.disconnect({}, {})'.format(vm, cdrom)) print('vm.hardware.Cdrom.disconnect({}, {})'.format(vm, cdrom))
cdrom_info = cdrom_svc.get(vm, cdrom) cdrom_info = client.vcenter.vm.hardware.Cdrom.get(vm, cdrom)
print('vm.hardware.Cdrom.get({}, {}) -> {}'. print('vm.hardware.Cdrom.get({}, {}) -> {}'.
format(vm, cdrom, pp(cdrom_info))) format(vm, cdrom, pp(cdrom_info)))
print('\n# Stopping VM after connect/disconnect sample') print('\n# Stopping VM after connect/disconnect sample')
print('vm.Power.start({})'.format(vm)) print('vm.Power.start({})'.format(vm))
vm_power_svc.stop(vm) client.vcenter.vm.Power.stop(vm)
cdrom_info = cdrom_svc.get(vm, cdrom) cdrom_info = client.vcenter.vm.hardware.Cdrom.get(vm, cdrom)
print('vm.hardware.Cdrom.get({}, {}) -> {}'. print('vm.hardware.Cdrom.get({}, {}) -> {}'.
format(vm, cdrom, pp(cdrom_info))) format(vm, cdrom, pp(cdrom_info)))
# List all Cdroms for a VM # List all Cdroms for a VM
cdrom_summaries = cdrom_svc.list(vm=vm) cdrom_summaries = client.vcenter.vm.hardware.Cdrom.list(vm=vm)
print('vm.hardware.Cdrom.list({}) -> {}'.format(vm, cdrom_summaries)) print('vm.hardware.Cdrom.list({}) -> {}'.format(vm, cdrom_summaries))
def cleanup(): def cleanup():
print('\n# Cleanup: Delete VM Cdroms that were added') print('\n# Cleanup: Delete VM Cdroms that were added')
for cdrom in cdroms_to_delete: for cdrom in cdroms_to_delete:
cdrom_svc.delete(vm, cdrom) client.vcenter.vm.hardware.Cdrom.delete(vm, cdrom)
print('vm.hardware.Cdrom.delete({}, {})'.format(vm, cdrom)) print('vm.hardware.Cdrom.delete({}, {})'.format(vm, cdrom))
print('\n# Cleanup: Remove SATA controller') print('\n# Cleanup: Remove SATA controller')
print('vm.hardware.adapter.Sata.delete({}, {})'.format(vm, sata)) print('vm.hardware.adapter.Sata.delete({}, {})'.format(vm, sata))
sata_svc.delete(vm, sata) client.vcenter.vm.hardware.adapter.Sata.delete(vm, sata)
cdrom_summaries = cdrom_svc.list(vm) cdrom_summaries = client.vcenter.vm.hardware.Cdrom.list(vm)
print('vm.hardware.Cdrom.list({}) -> {}'.format(vm, cdrom_summaries)) print('vm.hardware.Cdrom.list({}) -> {}'.format(vm, cdrom_summaries))
if set(orig_cdrom_summaries) != set(cdrom_summaries): if set(orig_cdrom_summaries) != set(cdrom_summaries):
print('vm.hardware.Cdrom WARNING: ' print('vm.hardware.Cdrom WARNING: '

View File

@ -2,7 +2,7 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -14,18 +14,17 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+' __vcenter_version__ = '6.5+'
import atexit from vmware.vapi.vsphere.client import create_vsphere_client
from com.vmware.vcenter.vm.hardware_client import Cpu from com.vmware.vcenter.vm.hardware_client import Cpu
from samples.vsphere.common import vapiconnect
from samples.vsphere.common.sample_util import parse_cli_args_vm from samples.vsphere.common.sample_util import parse_cli_args_vm
from samples.vsphere.common.sample_util import pp from samples.vsphere.common.sample_util import pp
from samples.vsphere.vcenter.setup import testbed from samples.vsphere.vcenter.setup import testbed
from samples.vsphere.vcenter.helper.vm_helper import get_vm from samples.vsphere.vcenter.helper.vm_helper import get_vm
from samples.vsphere.common.ssl_helper import get_unverified_session
""" """
Demonstrates how to configure CPU settings for a VM. Demonstrates how to configure CPU settings for a VM.
@ -36,43 +35,39 @@ The sample needs an existing VM.
vm = None vm = None
vm_name = None vm_name = None
stub_config = None client = None
cpu_svc = None
cleardata = False cleardata = False
orig_cpu_info = None orig_cpu_info = None
def setup(context=None): def setup(context=None):
global vm, vm_name, stub_config, cleardata global vm, vm_name, client, cleardata
if context: if context:
# Run sample suite via setup script # Run sample suite via setup script
stub_config = context.stub_config client = context.client
vm_name = testbed.config['VM_NAME_DEFAULT'] vm_name = testbed.config['VM_NAME_DEFAULT']
else: else:
# Run sample in standalone mode # Run sample in standalone mode
server, username, password, cleardata, skip_verification, vm_name = \ server, username, password, cleardata, skip_verification, vm_name = \
parse_cli_args_vm(testbed.config['VM_NAME_DEFAULT']) parse_cli_args_vm(testbed.config['VM_NAME_DEFAULT'])
stub_config = vapiconnect.connect(server, session = get_unverified_session() if skip_verification else None
username,
password,
skip_verification)
atexit.register(vapiconnect.logout, stub_config)
# Connect to vSphere client
client = create_vsphere_client(server=server,
username=username,
password=password,
session=session)
def run(): def run():
global vm global vm
vm = get_vm(stub_config, vm_name) vm = get_vm(client, vm_name)
if not vm: if not vm:
raise Exception('Sample requires an existing vm with name ({}). ' raise Exception('Sample requires an existing vm with name ({}). '
'Please create the vm first.'.format(vm_name)) 'Please create the vm first.'.format(vm_name))
print("Using VM '{}' ({}) for Cpu Sample".format(vm_name, vm)) print("Using VM '{}' ({}) for Cpu Sample".format(vm_name, vm))
# Create Cpu stub used for making requests
global cpu_svc
cpu_svc = Cpu(stub_config)
print('\n# Example: Get current Cpu configuration') print('\n# Example: Get current Cpu configuration')
cpu_info = cpu_svc.get(vm) cpu_info = client.vcenter.vm.hardware.Cpu.get(vm)
print('vm.hardware.Cpu.get({}) -> {}'.format(vm, pp(cpu_info))) print('vm.hardware.Cpu.get({}) -> {}'.format(vm, pp(cpu_info)))
# Save current Cpu info to verify that we have cleaned up properly # Save current Cpu info to verify that we have cleaned up properly
@ -82,19 +77,19 @@ def run():
print('\n# Example: Update cpu field of Cpu configuration') print('\n# Example: Update cpu field of Cpu configuration')
update_spec = Cpu.UpdateSpec(count=2) update_spec = Cpu.UpdateSpec(count=2)
print('vm.hardware.Cpu.update({}, {})'.format(vm, update_spec)) print('vm.hardware.Cpu.update({}, {})'.format(vm, update_spec))
cpu_svc.update(vm, update_spec) client.vcenter.vm.hardware.Cpu.update(vm, update_spec)
# Get new Cpu configuration # Get new Cpu configuration
cpu_info = cpu_svc.get(vm) cpu_info = client.vcenter.vm.hardware.Cpu.get(vm)
print('vm.hardware.Cpu.get({}) -> {}'.format(vm, pp(cpu_info))) print('vm.hardware.Cpu.get({}) -> {}'.format(vm, pp(cpu_info)))
print('\n# Example: Update other less likely used fields of Cpu configuration') print('\n# Example: Update other less likely used fields of Cpu configuration')
update_spec = Cpu.UpdateSpec(cores_per_socket=2, hot_add_enabled=True) update_spec = Cpu.UpdateSpec(cores_per_socket=2, hot_add_enabled=True)
print('vm.hardware.Cpu.update({}, {})'.format(vm, update_spec)) print('vm.hardware.Cpu.update({}, {})'.format(vm, update_spec))
cpu_svc.update(vm, update_spec) client.vcenter.vm.hardware.Cpu.update(vm, update_spec)
# Get new Cpu configuration # Get new Cpu configuration
cpu_info = cpu_svc.get(vm) cpu_info = client.vcenter.vm.hardware.Cpu.get(vm)
print('vm.hardware.Cpu.get({}) -> {}'.format(vm, pp(cpu_info))) print('vm.hardware.Cpu.get({}) -> {}'.format(vm, pp(cpu_info)))
@ -106,10 +101,10 @@ def cleanup():
hot_add_enabled=orig_cpu_info.hot_add_enabled, hot_add_enabled=orig_cpu_info.hot_add_enabled,
hot_remove_enabled=orig_cpu_info.hot_remove_enabled) hot_remove_enabled=orig_cpu_info.hot_remove_enabled)
print('vm.hardware.Cpu.update({}, {})'.format(vm, update_spec)) print('vm.hardware.Cpu.update({}, {})'.format(vm, update_spec))
cpu_svc.update(vm, update_spec) client.vcenter.vm.hardware.Cpu.update(vm, update_spec)
# Get final Cpu configuration # Get final Cpu configuration
cpu_info = cpu_svc.get(vm) cpu_info = client.vcenter.vm.hardware.Cpu.get(vm)
print('vm.hardware.Cpu.get({}) -> {}'.format(vm, pp(cpu_info))) print('vm.hardware.Cpu.get({}) -> {}'.format(vm, pp(cpu_info)))
if cpu_info != orig_cpu_info: if cpu_info != orig_cpu_info:

View File

@ -2,7 +2,7 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -14,10 +14,10 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+' __vcenter_version__ = '6.5+'
import atexit import atexit
from vmware.vapi.vsphere.client import create_vsphere_client
from com.vmware.vcenter.vm.hardware.adapter_client import Sata from com.vmware.vcenter.vm.hardware.adapter_client import Sata
from com.vmware.vcenter.vm.hardware_client import Disk from com.vmware.vcenter.vm.hardware_client import Disk
@ -27,7 +27,6 @@ from com.vmware.vcenter.vm.hardware_client import (IdeAddressSpec,
from pyVim.connect import SmartConnect, Disconnect from pyVim.connect import SmartConnect, Disconnect
from samples.vsphere.common.vim.vmdk import (create_vmdk, delete_vmdk, detect_vmdk) from samples.vsphere.common.vim.vmdk import (create_vmdk, delete_vmdk, detect_vmdk)
from samples.vsphere.common import vapiconnect
from samples.vsphere.common.sample_util import parse_cli_args_vm from samples.vsphere.common.sample_util import parse_cli_args_vm
from samples.vsphere.common.sample_util import pp from samples.vsphere.common.sample_util import pp
from samples.vsphere.common.ssl_helper import get_unverified_context from samples.vsphere.common.ssl_helper import get_unverified_context
@ -35,6 +34,7 @@ from samples.vsphere.common.vim.inventory import \
(get_datacenter_for_datastore, get_datastore_mo) (get_datacenter_for_datastore, get_datastore_mo)
from samples.vsphere.vcenter.helper.vm_helper import get_vm 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.common.ssl_helper import get_unverified_session
""" """
Demonstrates how to configure disk settings for a VM. Demonstrates how to configure disk settings for a VM.
@ -44,11 +44,9 @@ The sample needs an existing VM.
""" """
vm = None vm = None
stub_config = None client = None
soap_stub = None soap_stub = None
service_instance = None service_instance = None
sata_svc = None
disk_svc = None
cleardata = False cleardata = False
saved_disk_info = None saved_disk_info = None
datacenter_mo = None datacenter_mo = None
@ -57,23 +55,24 @@ orig_disk_summaries = None
def setup(context=None): def setup(context=None):
global stub_config, service_instance, cleardata global client, service_instance, cleardata
if context: if context:
# Run sample suite via setup script # Run sample suite via setup script
vm_name = testbed.config['VM_NAME_DEFAULT'] vm_name = testbed.config['VM_NAME_DEFAULT']
stub_config = context.stub_config client = context.client
service_instance = context.service_instance service_instance = context.service_instance
else: else:
# Run sample in standalone mode # Run sample in standalone mode
server, username, password, cleardata, skip_verification, vm_name = \ server, username, password, cleardata, skip_verification, vm_name = \
parse_cli_args_vm(testbed.config['VM_NAME_DEFAULT']) parse_cli_args_vm(testbed.config['VM_NAME_DEFAULT'])
# Connect to vAPI Endpoint on vCenter system session = get_unverified_session() if skip_verification else None
stub_config = vapiconnect.connect(server,
username, # Connect to vSphere client
password, client = create_vsphere_client(server=server,
skip_verification) username=username,
atexit.register(vapiconnect.logout, stub_config) password=password,
session=session)
# Connect to VIM API Endpoint on vCenter system # Connect to VIM API Endpoint on vCenter system
context = None context = None
@ -87,7 +86,7 @@ def setup(context=None):
global vm, datacenter_name, datastore_name global vm, datacenter_name, datastore_name
global datastore_mo, datacenter_mo, datastore_root_path global datastore_mo, datacenter_mo, datastore_root_path
vm = get_vm(stub_config, vm_name) vm = get_vm(client, vm_name)
if not vm: if not vm:
raise Exception('Sample requires an existing vm with name ({}). ' raise Exception('Sample requires an existing vm with name ({}). '
'Please create the vm first.'.format(vm_name)) 'Please create the vm first.'.format(vm_name))
@ -97,7 +96,7 @@ def setup(context=None):
# delete VMDKs, which are backings for a VM Disk. # delete VMDKs, which are backings for a VM Disk.
datacenter_name = testbed.config['VM_DATACENTER_NAME'] datacenter_name = testbed.config['VM_DATACENTER_NAME']
datastore_name = testbed.config['VM_DATASTORE_NAME'] datastore_name = testbed.config['VM_DATASTORE_NAME']
datastore_mo = get_datastore_mo(stub_config, datastore_mo = get_datastore_mo(client,
service_instance._stub, service_instance._stub,
datacenter_name, datacenter_name,
datastore_name) datastore_name)
@ -111,12 +110,8 @@ def setup(context=None):
def run(): def run():
GiB = 1024 * 1024 * 1024 GiB = 1024 * 1024 * 1024
# Create Disk stub used for making requests
global disk_svc
disk_svc = Disk(stub_config)
print('\n# Example: List all Disks for a VM') print('\n# Example: List all Disks for a VM')
disk_summaries = disk_svc.list(vm=vm) disk_summaries = client.vcenter.vm.hardware.Disk.list(vm=vm)
print('vm.hardware.Disk.list({}) -> {}'.format(vm, disk_summaries)) print('vm.hardware.Disk.list({}) -> {}'.format(vm, disk_summaries))
# Save current list of disks to verify that we have cleaned up properly # Save current list of disks to verify that we have cleaned up properly
@ -126,18 +121,18 @@ def run():
# Get information for each Disk on the VM # Get information for each Disk on the VM
for disk_summary in disk_summaries: for disk_summary in disk_summaries:
disk = disk_summary.disk disk = disk_summary.disk
disk_info = disk_svc.get(vm=vm, disk=disk) disk_info = client.vcenter.vm.hardware.Disk.get(vm=vm, disk=disk)
print('vm.hardware.Disk.get({}, {}) -> {}'. print('vm.hardware.Disk.get({}, {}) -> {}'.
format(vm, disk, pp(disk_info))) format(vm, disk, pp(disk_info)))
print('\n# Example: Create a new Disk using default settings') print('\n# Example: Create a new Disk using default settings')
disk_create_spec = Disk.CreateSpec(new_vmdk=Disk.VmdkCreateSpec()) disk_create_spec = Disk.CreateSpec(new_vmdk=Disk.VmdkCreateSpec())
disk = disk_svc.create(vm=vm, spec=disk_create_spec) disk = client.vcenter.vm.hardware.Disk.create(vm=vm, spec=disk_create_spec)
print('vm.hardware.Disk.create({}, {}) -> {}'. print('vm.hardware.Disk.create({}, {}) -> {}'.
format(vm, disk_create_spec, disk)) format(vm, disk_create_spec, disk))
global disks_to_delete global disks_to_delete
disks_to_delete.append(disk) disks_to_delete.append(disk)
disk_info = disk_svc.get(vm, disk) disk_info = client.vcenter.vm.hardware.Disk.get(vm, disk)
print('vm.hardware.Disk.get({}, {}) -> {}'. print('vm.hardware.Disk.get({}, {}) -> {}'.
format(vm, disk, pp(disk_info))) format(vm, disk, pp(disk_info)))
@ -145,22 +140,22 @@ def run():
'# and that the flat format (ie. SeSparse format) should be used.') '# and that the flat format (ie. SeSparse format) should be used.')
disk_create_spec = Disk.CreateSpec( disk_create_spec = Disk.CreateSpec(
new_vmdk=Disk.VmdkCreateSpec(capacity=10 * GiB)) new_vmdk=Disk.VmdkCreateSpec(capacity=10 * GiB))
disk = disk_svc.create(vm=vm, spec=disk_create_spec) disk = client.vcenter.vm.hardware.Disk.create(vm=vm, spec=disk_create_spec)
print('vm.hardware.Disk.create({}, {}) -> {}'. print('vm.hardware.Disk.create({}, {}) -> {}'.
format(vm, disk_create_spec, disk)) format(vm, disk_create_spec, disk))
disks_to_delete.append(disk) disks_to_delete.append(disk)
disk_info = disk_svc.get(vm, disk) disk_info = client.vcenter.vm.hardware.Disk.get(vm, disk)
print('vm.hardware.Disk.get({}, {}) -> {}'.format(vm, disk, pp(disk_info))) print('vm.hardware.Disk.get({}, {}) -> {}'.format(vm, disk, pp(disk_info)))
print('\n# Example: Create a new SCSI Disk') print('\n# Example: Create a new SCSI Disk')
disk_create_spec = Disk.CreateSpec( disk_create_spec = Disk.CreateSpec(
type=Disk.HostBusAdapterType.SCSI, type=Disk.HostBusAdapterType.SCSI,
new_vmdk=Disk.VmdkCreateSpec(capacity=10 * GiB)) new_vmdk=Disk.VmdkCreateSpec(capacity=10 * GiB))
disk = disk_svc.create(vm=vm, spec=disk_create_spec) disk = client.vcenter.vm.hardware.Disk.create(vm=vm, spec=disk_create_spec)
print('vm.hardware.Disk.create({}, {}) -> {}'. print('vm.hardware.Disk.create({}, {}) -> {}'.
format(vm, disk_create_spec, disk)) format(vm, disk_create_spec, disk))
disks_to_delete.append(disk) disks_to_delete.append(disk)
disk_info = disk_svc.get(vm, disk) disk_info = client.vcenter.vm.hardware.Disk.get(vm, disk)
print('vm.hardware.Disk.get({}, {}) -> {}'. print('vm.hardware.Disk.get({}, {}) -> {}'.
format(vm, disk, pp(disk_info))) format(vm, disk, pp(disk_info)))
@ -169,11 +164,11 @@ def run():
type=Disk.HostBusAdapterType.SCSI, type=Disk.HostBusAdapterType.SCSI,
scsi=ScsiAddressSpec(bus=0), scsi=ScsiAddressSpec(bus=0),
new_vmdk=Disk.VmdkCreateSpec(capacity=10 * GiB)) new_vmdk=Disk.VmdkCreateSpec(capacity=10 * GiB))
disk = disk_svc.create(vm=vm, spec=disk_create_spec) disk = client.vcenter.vm.hardware.Disk.create(vm=vm, spec=disk_create_spec)
print('vm.hardware.Disk.create({}, {}) -> {}'. print('vm.hardware.Disk.create({}, {}) -> {}'.
format(vm, disk_create_spec, disk)) format(vm, disk_create_spec, disk))
disks_to_delete.append(disk) disks_to_delete.append(disk)
disk_info = disk_svc.get(vm, disk) disk_info = client.vcenter.vm.hardware.Disk.get(vm, disk)
print('vm.hardware.Disk.get({}, {}) -> {}'.format(vm, disk, pp(disk_info))) print('vm.hardware.Disk.get({}, {}) -> {}'.format(vm, disk, pp(disk_info)))
print( print(
@ -182,20 +177,18 @@ def run():
type=Disk.HostBusAdapterType.SCSI, type=Disk.HostBusAdapterType.SCSI,
scsi=ScsiAddressSpec(bus=0, unit=10), scsi=ScsiAddressSpec(bus=0, unit=10),
new_vmdk=Disk.VmdkCreateSpec(capacity=10 * GiB)) new_vmdk=Disk.VmdkCreateSpec(capacity=10 * GiB))
disk = disk_svc.create(vm=vm, spec=disk_create_spec) disk = client.vcenter.vm.hardware.Disk.create(vm=vm, spec=disk_create_spec)
print('vm.hardware.Disk.create({}, {}) -> {}'. print('vm.hardware.Disk.create({}, {}) -> {}'.
format(vm, disk_create_spec, disk)) format(vm, disk_create_spec, disk))
disks_to_delete.append(disk) disks_to_delete.append(disk)
disk_info = disk_svc.get(vm, disk) disk_info = client.vcenter.vm.hardware.Disk.get(vm, disk)
print('vm.hardware.Disk.get({}, {}) -> {}'.format(vm, disk, pp(disk_info))) print('vm.hardware.Disk.get({}, {}) -> {}'.format(vm, disk, pp(disk_info)))
print('\n# Example: Create a SATA controller') print('\n# Example: Create a SATA controller')
global sata_svc
sata_svc = Sata(stub_config)
sata_create_spec = Sata.CreateSpec() sata_create_spec = Sata.CreateSpec()
print('# Adding SATA controller for SATA Disk') print('# Adding SATA controller for SATA Disk')
global sata global sata
sata = sata_svc.create(vm, sata_create_spec) sata = client.vcenter.vm.hardware.adapter.Sata.create(vm, sata_create_spec)
print('vm.hardware.adapter.Sata.create({}, {}) -> {}'. print('vm.hardware.adapter.Sata.create({}, {}) -> {}'.
format(vm, sata_create_spec, sata)) format(vm, sata_create_spec, sata))
@ -203,11 +196,11 @@ def run():
disk_create_spec = Disk.CreateSpec( disk_create_spec = Disk.CreateSpec(
type=Disk.HostBusAdapterType.SATA, type=Disk.HostBusAdapterType.SATA,
new_vmdk=Disk.VmdkCreateSpec(capacity=10 * GiB)) new_vmdk=Disk.VmdkCreateSpec(capacity=10 * GiB))
disk = disk_svc.create(vm=vm, spec=disk_create_spec) disk = client.vcenter.vm.hardware.Disk.create(vm=vm, spec=disk_create_spec)
print('vm.hardware.Disk.create({}, {}) -> {}'. print('vm.hardware.Disk.create({}, {}) -> {}'.
format(vm, disk_create_spec, disk)) format(vm, disk_create_spec, disk))
disks_to_delete.append(disk) disks_to_delete.append(disk)
disk_info = disk_svc.get(vm, disk) disk_info = client.vcenter.vm.hardware.Disk.get(vm, disk)
print('vm.hardware.Disk.get({}, {}) -> {}'.format(vm, disk, pp(disk_info))) print('vm.hardware.Disk.get({}, {}) -> {}'.format(vm, disk, pp(disk_info)))
print('\n# Example: Create a new SATA disk on a specific bus') print('\n# Example: Create a new SATA disk on a specific bus')
@ -215,11 +208,11 @@ def run():
type=Disk.HostBusAdapterType.SATA, type=Disk.HostBusAdapterType.SATA,
sata=SataAddressSpec(bus=0), sata=SataAddressSpec(bus=0),
new_vmdk=Disk.VmdkCreateSpec(capacity=10 * GiB)) new_vmdk=Disk.VmdkCreateSpec(capacity=10 * GiB))
disk = disk_svc.create(vm=vm, spec=disk_create_spec) disk = client.vcenter.vm.hardware.Disk.create(vm=vm, spec=disk_create_spec)
print('vm.hardware.Disk.create({}, {}) -> {}'. print('vm.hardware.Disk.create({}, {}) -> {}'.
format(vm, disk_create_spec, disk)) format(vm, disk_create_spec, disk))
disks_to_delete.append(disk) disks_to_delete.append(disk)
disk_info = disk_svc.get(vm, disk) disk_info = client.vcenter.vm.hardware.Disk.get(vm, disk)
print('vm.hardware.Disk.get({}, {}) -> {}'.format(vm, disk, pp(disk_info))) print('vm.hardware.Disk.get({}, {}) -> {}'.format(vm, disk, pp(disk_info)))
print('\n# Example: Create a new SATA disk on a specific bus and specific ' print('\n# Example: Create a new SATA disk on a specific bus and specific '
@ -228,11 +221,11 @@ def run():
type=Disk.HostBusAdapterType.SATA, type=Disk.HostBusAdapterType.SATA,
sata=SataAddressSpec(bus=0, unit=20), sata=SataAddressSpec(bus=0, unit=20),
new_vmdk=Disk.VmdkCreateSpec(capacity=10 * GiB)) new_vmdk=Disk.VmdkCreateSpec(capacity=10 * GiB))
disk = disk_svc.create(vm=vm, spec=disk_create_spec) disk = client.vcenter.vm.hardware.Disk.create(vm=vm, spec=disk_create_spec)
print('vm.hardware.Disk.create({}, {}) -> {}'. print('vm.hardware.Disk.create({}, {}) -> {}'.
format(vm, disk_create_spec, disk)) format(vm, disk_create_spec, disk))
disks_to_delete.append(disk) disks_to_delete.append(disk)
disk_info = disk_svc.get(vm, disk) disk_info = client.vcenter.vm.hardware.Disk.get(vm, disk)
print('vm.hardware.Disk.get({}, {}) -> {}'. print('vm.hardware.Disk.get({}, {}) -> {}'.
format(vm, disk, pp(disk_info))) format(vm, disk, pp(disk_info)))
@ -240,11 +233,11 @@ def run():
disk_create_spec = Disk.CreateSpec( disk_create_spec = Disk.CreateSpec(
type=Disk.HostBusAdapterType.IDE, type=Disk.HostBusAdapterType.IDE,
new_vmdk=Disk.VmdkCreateSpec(capacity=10 * GiB)) new_vmdk=Disk.VmdkCreateSpec(capacity=10 * GiB))
disk = disk_svc.create(vm=vm, spec=disk_create_spec) disk = client.vcenter.vm.hardware.Disk.create(vm=vm, spec=disk_create_spec)
print('vm.hardware.Disk.create({}, {}) -> {}'. print('vm.hardware.Disk.create({}, {}) -> {}'.
format(vm, disk_create_spec, disk)) format(vm, disk_create_spec, disk))
disks_to_delete.append(disk) disks_to_delete.append(disk)
disk_info = disk_svc.get(vm, disk) disk_info = client.vcenter.vm.hardware.Disk.get(vm, disk)
print('vm.hardware.Disk.get({}, {}) -> {}'.format(vm, disk, pp(disk_info))) print('vm.hardware.Disk.get({}, {}) -> {}'.format(vm, disk, pp(disk_info)))
print('\n# Example: Create a new IDE disk on a specific bus and ' print('\n# Example: Create a new IDE disk on a specific bus and '
@ -253,31 +246,31 @@ def run():
type=Disk.HostBusAdapterType.IDE, type=Disk.HostBusAdapterType.IDE,
ide=IdeAddressSpec(False, False), ide=IdeAddressSpec(False, False),
new_vmdk=Disk.VmdkCreateSpec(capacity=10 * GiB)) new_vmdk=Disk.VmdkCreateSpec(capacity=10 * GiB))
disk = disk_svc.create(vm=vm, spec=disk_create_spec) disk = client.vcenter.vm.hardware.Disk.create(vm=vm, spec=disk_create_spec)
print('vm.hardware.Disk.create({}, {}) -> {}'. print('vm.hardware.Disk.create({}, {}) -> {}'.
format(vm, disk_create_spec, disk)) format(vm, disk_create_spec, disk))
disks_to_delete.append(disk) disks_to_delete.append(disk)
disk_info = disk_svc.get(vm, disk) disk_info = client.vcenter.vm.hardware.Disk.get(vm, disk)
print('vm.hardware.Disk.get({}, {}) -> {}'.format(vm, disk, pp(disk_info))) print('vm.hardware.Disk.get({}, {}) -> {}'.format(vm, disk, pp(disk_info)))
print('\n# Example: Attach an existing VMDK using the default bus and unit') print('\n# Example: Attach an existing VMDK using the default bus and unit')
datastore_path = datastore_root_path + '/attach-defaults.vmdk' datastore_path = datastore_root_path + '/attach-defaults.vmdk'
delete_vmdk_if_exist(stub_config, service_instance._stub, datacenter_name, delete_vmdk_if_exist(client, service_instance._stub, datacenter_name,
datastore_name, datastore_path) datastore_name, datastore_path)
create_vmdk(service_instance, datacenter_mo, datastore_path) create_vmdk(service_instance, datacenter_mo, datastore_path)
disk_create_spec = Disk.CreateSpec( disk_create_spec = Disk.CreateSpec(
backing=Disk.BackingSpec(type=Disk.BackingType.VMDK_FILE, backing=Disk.BackingSpec(type=Disk.BackingType.VMDK_FILE,
vmdk_file=datastore_path)) vmdk_file=datastore_path))
disk = disk_svc.create(vm=vm, spec=disk_create_spec) disk = client.vcenter.vm.hardware.Disk.create(vm=vm, spec=disk_create_spec)
print('vm.hardware.Disk.create({}, {}) -> {}'. print('vm.hardware.Disk.create({}, {}) -> {}'.
format(vm, disk_create_spec, disk)) format(vm, disk_create_spec, disk))
disks_to_delete.append(disk) disks_to_delete.append(disk)
disk_info = disk_svc.get(vm, disk) disk_info = client.vcenter.vm.hardware.Disk.get(vm, disk)
print('vm.hardware.Disk.get({}, {}) -> {}'.format(vm, disk, pp(disk_info))) print('vm.hardware.Disk.get({}, {}) -> {}'.format(vm, disk, pp(disk_info)))
print('\n# Example: Attach an existing VMDK as a SCSI disk') print('\n# Example: Attach an existing VMDK as a SCSI disk')
datastore_path = datastore_root_path + '/attach-scsi.vmdk' datastore_path = datastore_root_path + '/attach-scsi.vmdk'
delete_vmdk_if_exist(stub_config, service_instance._stub, datacenter_name, delete_vmdk_if_exist(client, service_instance._stub, datacenter_name,
datastore_name, datastore_path) datastore_name, datastore_path)
create_vmdk(service_instance, datacenter_mo, datastore_path) create_vmdk(service_instance, datacenter_mo, datastore_path)
@ -285,18 +278,18 @@ def run():
type=Disk.HostBusAdapterType.SCSI, type=Disk.HostBusAdapterType.SCSI,
backing=Disk.BackingSpec(type=Disk.BackingType.VMDK_FILE, backing=Disk.BackingSpec(type=Disk.BackingType.VMDK_FILE,
vmdk_file=datastore_path)) vmdk_file=datastore_path))
disk = disk_svc.create(vm=vm, spec=disk_create_spec) disk = client.vcenter.vm.hardware.Disk.create(vm=vm, spec=disk_create_spec)
print('vm.hardware.Disk.create({}, {}) -> {}'. print('vm.hardware.Disk.create({}, {}) -> {}'.
format(vm, disk_create_spec, disk)) format(vm, disk_create_spec, disk))
disks_to_delete.append(disk) disks_to_delete.append(disk)
disk_info = disk_svc.get(vm, disk) disk_info = client.vcenter.vm.hardware.Disk.get(vm, disk)
print('vm.hardware.Disk.get({}, {}) -> {}'. print('vm.hardware.Disk.get({}, {}) -> {}'.
format(vm, disk, pp(disk_info))) format(vm, disk, pp(disk_info)))
print('\n# Example: Attach an existing VMDK as a SCSI disk ' print('\n# Example: Attach an existing VMDK as a SCSI disk '
'to a specific bus') 'to a specific bus')
datastore_path = datastore_root_path + '/attach-scsi0.vmdk' datastore_path = datastore_root_path + '/attach-scsi0.vmdk'
delete_vmdk_if_exist(stub_config, service_instance._stub, datacenter_name, delete_vmdk_if_exist(client, service_instance._stub, datacenter_name,
datastore_name, datastore_path) datastore_name, datastore_path)
create_vmdk(service_instance, datacenter_mo, datastore_path) create_vmdk(service_instance, datacenter_mo, datastore_path)
disk_create_spec = Disk.CreateSpec( disk_create_spec = Disk.CreateSpec(
@ -304,17 +297,17 @@ def run():
scsi=ScsiAddressSpec(bus=0), scsi=ScsiAddressSpec(bus=0),
backing=Disk.BackingSpec(type=Disk.BackingType.VMDK_FILE, backing=Disk.BackingSpec(type=Disk.BackingType.VMDK_FILE,
vmdk_file=datastore_path)) vmdk_file=datastore_path))
disk = disk_svc.create(vm=vm, spec=disk_create_spec) disk = client.vcenter.vm.hardware.Disk.create(vm=vm, spec=disk_create_spec)
print('vm.hardware.Disk.create({}, {}) -> {}'. print('vm.hardware.Disk.create({}, {}) -> {}'.
format(vm, disk_create_spec, disk)) format(vm, disk_create_spec, disk))
disks_to_delete.append(disk) disks_to_delete.append(disk)
disk_info = disk_svc.get(vm, disk) disk_info = client.vcenter.vm.hardware.Disk.get(vm, disk)
print('vm.hardware.Disk.get({}, {}) -> {}'.format(vm, disk, pp(disk_info))) print('vm.hardware.Disk.get({}, {}) -> {}'.format(vm, disk, pp(disk_info)))
print('\n# Example: Attach an existing VMDK as a SCSI disk ' print('\n# Example: Attach an existing VMDK as a SCSI disk '
'to a specific bus and specific unit') 'to a specific bus and specific unit')
datastore_path = datastore_root_path + '/attach-scsi0:11.vmdk' datastore_path = datastore_root_path + '/attach-scsi0:11.vmdk'
delete_vmdk_if_exist(stub_config, service_instance._stub, datacenter_name, delete_vmdk_if_exist(client, service_instance._stub, datacenter_name,
datastore_name, datastore_path) datastore_name, datastore_path)
create_vmdk(service_instance, datacenter_mo, datastore_path) create_vmdk(service_instance, datacenter_mo, datastore_path)
disk_create_spec = Disk.CreateSpec( disk_create_spec = Disk.CreateSpec(
@ -322,11 +315,11 @@ def run():
scsi=ScsiAddressSpec(bus=0, unit=11), scsi=ScsiAddressSpec(bus=0, unit=11),
backing=Disk.BackingSpec(type=Disk.BackingType.VMDK_FILE, backing=Disk.BackingSpec(type=Disk.BackingType.VMDK_FILE,
vmdk_file=datastore_path)) vmdk_file=datastore_path))
disk = disk_svc.create(vm=vm, spec=disk_create_spec) disk = client.vcenter.vm.hardware.Disk.create(vm=vm, spec=disk_create_spec)
print('vm.hardware.Disk.create({}, {}) -> {}'. print('vm.hardware.Disk.create({}, {}) -> {}'.
format(vm, disk_create_spec, disk)) format(vm, disk_create_spec, disk))
disks_to_delete.append(disk) disks_to_delete.append(disk)
disk_info = disk_svc.get(vm, disk) disk_info = client.vcenter.vm.hardware.Disk.get(vm, disk)
print('vm.hardware.Disk.get({}, {}) -> {}'.format(vm, disk, pp(disk_info))) print('vm.hardware.Disk.get({}, {}) -> {}'.format(vm, disk, pp(disk_info)))
# Samples to update operation to change backing # Samples to update operation to change backing
@ -336,7 +329,7 @@ def run():
print( print(
'\n# Example: Change the backing of the last disk to a new VMDK file.') '\n# Example: Change the backing of the last disk to a new VMDK file.')
datastore_path = datastore_root_path + '/update-scsi0:11.vmdk' datastore_path = datastore_root_path + '/update-scsi0:11.vmdk'
delete_vmdk_if_exist(stub_config, service_instance._stub, datacenter_name, delete_vmdk_if_exist(client, service_instance._stub, datacenter_name,
datastore_name, datastore_path) datastore_name, datastore_path)
create_vmdk(service_instance, datacenter_mo, datastore_path) create_vmdk(service_instance, datacenter_mo, datastore_path)
disk_update_spec = Disk.UpdateSpec( disk_update_spec = Disk.UpdateSpec(
@ -344,8 +337,8 @@ def run():
vmdk_file=datastore_path)) vmdk_file=datastore_path))
print('vm.hardware.Disk.update({}, {}, {})'. print('vm.hardware.Disk.update({}, {}, {})'.
format(vm, disk, disk_update_spec)) format(vm, disk, disk_update_spec))
disk_svc.update(vm=vm, disk=disk, spec=disk_update_spec) client.vcenter.vm.hardware.Disk.update(vm=vm, disk=disk, spec=disk_update_spec)
disk_info = disk_svc.get(vm, disk) disk_info = client.vcenter.vm.hardware.Disk.get(vm, disk)
print('vm.hardware.Disk.get({}, {}) -> {}'.format(vm, disk, pp(disk_info))) print('vm.hardware.Disk.get({}, {}) -> {}'.format(vm, disk, pp(disk_info)))
@ -356,17 +349,17 @@ def cleanup():
delete_vmdk(service_instance, datacenter_mo, vmdk_file) delete_vmdk(service_instance, datacenter_mo, vmdk_file)
# List all Disks for a VM # List all Disks for a VM
disk_summaries = disk_svc.list(vm=vm) disk_summaries = client.vcenter.vm.hardware.Disk.list(vm=vm)
print('vm.hardware.Disk.list({}) -> {}'.format(vm, disk_summaries)) print('vm.hardware.Disk.list({}) -> {}'.format(vm, disk_summaries))
print('\n# Cleanup: Delete VM Disks that were added') print('\n# Cleanup: Delete VM Disks that were added')
for disk in disks_to_delete: for disk in disks_to_delete:
disk_info = disk_svc.get(vm, disk) disk_info = client.vcenter.vm.hardware.Disk.get(vm, disk)
print('vm.hardware.Disk.get({}, {}) -> {}'. print('vm.hardware.Disk.get({}, {}) -> {}'.
format(vm, disk, pp(disk_info))) format(vm, disk, pp(disk_info)))
vmdk_file = disk_info.backing.vmdk_file vmdk_file = disk_info.backing.vmdk_file
disk_svc.delete(vm, disk) client.vcenter.vm.hardware.Disk.delete(vm, disk)
print('vm.hardware.Disk.delete({}, {})'.format(vm, disk)) print('vm.hardware.Disk.delete({}, {})'.format(vm, disk))
print("\n# Cleanup: Delete VMDK '{}'".format(vmdk_file)) print("\n# Cleanup: Delete VMDK '{}'".format(vmdk_file))
@ -374,18 +367,18 @@ def cleanup():
print('\n# Cleanup: Remove SATA controller') print('\n# Cleanup: Remove SATA controller')
print('vm.hardware.adapter.Sata.delete({}, {})'.format(vm, sata)) print('vm.hardware.adapter.Sata.delete({}, {})'.format(vm, sata))
sata_svc.delete(vm, sata) client.vcenter.vm.hardware.adapter.Sata.delete(vm, sata)
disk_summaries = disk_svc.list(vm) disk_summaries = client.vcenter.vm.hardware.Disk.list(vm)
print('vm.hardware.Disk.list({}) -> {}'.format(vm, disk_summaries)) print('vm.hardware.Disk.list({}) -> {}'.format(vm, disk_summaries))
if set(orig_disk_summaries) != set(disk_summaries): if set(orig_disk_summaries) != set(disk_summaries):
print( print(
'vm.hardware.Disk WARNING: Final Disk info does not match original') 'vm.hardware.Disk WARNING: Final Disk info does not match original')
def delete_vmdk_if_exist(stub_config, soap_stub, datacenter_name, def delete_vmdk_if_exist(client, soap_stub, datacenter_name,
datastore_name, datastore_path): datastore_name, datastore_path):
if detect_vmdk(stub_config, soap_stub, datacenter_name, if detect_vmdk(client, soap_stub, datacenter_name,
datastore_name, datastore_path): datastore_name, datastore_path):
print("Detected VMDK '{}' {}".format(datastore_name, datastore_path)) print("Detected VMDK '{}' {}".format(datastore_name, datastore_path))
delete_vmdk(service_instance, datacenter_mo, datastore_path) delete_vmdk(service_instance, datacenter_mo, datastore_path)

View File

@ -2,7 +2,7 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -14,19 +14,17 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+' __vcenter_version__ = '6.5+'
import atexit from vmware.vapi.vsphere.client import create_vsphere_client
from com.vmware.vcenter.vm.hardware_client import Ethernet from com.vmware.vcenter.vm.hardware_client import Ethernet
from com.vmware.vcenter.vm_client import Power
from samples.vsphere.common import vapiconnect
from samples.vsphere.common.sample_util import parse_cli_args_vm from samples.vsphere.common.sample_util import parse_cli_args_vm
from samples.vsphere.common.sample_util import pp from samples.vsphere.common.sample_util import pp
from samples.vsphere.vcenter.helper import network_helper from samples.vsphere.vcenter.helper import network_helper
from samples.vsphere.vcenter.setup import testbed from samples.vsphere.vcenter.setup import testbed
from samples.vsphere.vcenter.helper.vm_helper import get_vm from samples.vsphere.vcenter.helper.vm_helper import get_vm
from samples.vsphere.common.ssl_helper import get_unverified_session
""" """
Demonstrates how to configure virtual ethernet adapters of a virtual machine. Demonstrates how to configure virtual ethernet adapters of a virtual machine.
@ -37,33 +35,33 @@ The sample needs an existing VM.
vm = None vm = None
vm_name = None vm_name = None
stub_config = None client = None
ethernet_svc = None
cleardata = False cleardata = False
nics_to_delete = [] nics_to_delete = []
orig_nic_summaries = None orig_nic_summaries = None
def setup(context=None): def setup(context=None):
global vm, vm_name, stub_config, cleardata global vm, vm_name, client, cleardata
if context: if context:
# Run sample suite via setup script # Run sample suite via setup script
stub_config = context.stub_config client = context.client
vm_name = testbed.config['VM_NAME_DEFAULT'] vm_name = testbed.config['VM_NAME_DEFAULT']
else: else:
# Run sample in standalone mode # Run sample in standalone mode
server, username, password, cleardata, skip_verification, vm_name = \ server, username, password, cleardata, skip_verification, vm_name = \
parse_cli_args_vm(testbed.config['VM_NAME_DEFAULT']) parse_cli_args_vm(testbed.config['VM_NAME_DEFAULT'])
stub_config = vapiconnect.connect(server, session = get_unverified_session() if skip_verification else None
username,
password,
skip_verification)
atexit.register(vapiconnect.logout, stub_config)
# Connect to vSphere client
client = create_vsphere_client(server=server,
username=username,
password=password,
session=session)
def run(): def run():
global vm global vm
vm = get_vm(stub_config, vm_name) vm = get_vm(client, vm_name)
if not vm: if not vm:
raise Exception('Sample requires an existing vm with name ({}). ' raise Exception('Sample requires an existing vm with name ({}). '
'Please create the vm first.'.format(vm_name)) 'Please create the vm first.'.format(vm_name))
@ -71,23 +69,18 @@ def run():
# Get standard portgroup to use as backing for sample # Get standard portgroup to use as backing for sample
standard_network = network_helper.get_standard_network_backing( standard_network = network_helper.get_standard_network_backing(
stub_config, client,
testbed.config['STDPORTGROUP_NAME'], testbed.config['STDPORTGROUP_NAME'],
testbed.config['VM_DATACENTER_NAME']) testbed.config['VM_DATACENTER_NAME'])
# Get distributed portgroup to use as backing for sample # Get distributed portgroup to use as backing for sample
distributed_network = network_helper.get_distributed_network_backing( distributed_network = network_helper.get_distributed_network_backing(
stub_config, client,
testbed.config['VDPORTGROUP1_NAME'], testbed.config['VDPORTGROUP1_NAME'],
testbed.config['VM_DATACENTER_NAME']) testbed.config['VM_DATACENTER_NAME'])
# Create Ethernet stub used for making requests
global ethernet_svc
ethernet_svc = Ethernet(stub_config)
vm_power_svc = Power(stub_config)
print('\n# Example: List all Ethernet adapters for a VM') print('\n# Example: List all Ethernet adapters for a VM')
nic_summaries = ethernet_svc.list(vm=vm) nic_summaries = client.vcenter.vm.hardware.Ethernet.list(vm=vm)
print('vm.hardware.Ethernet.list({}) -> {}'.format(vm, nic_summaries)) print('vm.hardware.Ethernet.list({}) -> {}'.format(vm, nic_summaries))
# Save current list of Ethernet adapters to verify that we have cleaned # Save current list of Ethernet adapters to verify that we have cleaned
@ -98,7 +91,7 @@ def run():
# Get information for each Ethernet on the VM # Get information for each Ethernet on the VM
for nic_summary in nic_summaries: for nic_summary in nic_summaries:
nic = nic_summary.nic nic = nic_summary.nic
nic_info = ethernet_svc.get(vm=vm, nic=nic) nic_info = client.vcenter.vm.hardware.Ethernet.get(vm=vm, nic=nic)
print('vm.hardware.Ethernet.get({}, {}) -> {}'. print('vm.hardware.Ethernet.get({}, {}) -> {}'.
format(vm, nic, nic_info)) format(vm, nic, nic_info))
@ -110,11 +103,11 @@ def run():
backing=Ethernet.BackingSpec( backing=Ethernet.BackingSpec(
type=Ethernet.BackingType.STANDARD_PORTGROUP, type=Ethernet.BackingType.STANDARD_PORTGROUP,
network=standard_network)) network=standard_network))
nic = ethernet_svc.create(vm, nic_create_spec) nic = client.vcenter.vm.hardware.Ethernet.create(vm, nic_create_spec)
print('vm.hardware.Ethernet.create({}, {}) -> {}'. print('vm.hardware.Ethernet.create({}, {}) -> {}'.
format(vm, nic_create_spec, nic)) format(vm, nic_create_spec, nic))
nics_to_delete.append(nic) nics_to_delete.append(nic)
nic_info = ethernet_svc.get(vm, nic) nic_info = client.vcenter.vm.hardware.Ethernet.get(vm, nic)
print('vm.hardware.Ethernet.get({}, {}) -> {}'. print('vm.hardware.Ethernet.get({}, {}) -> {}'.
format(vm, nic, pp(nic_info))) format(vm, nic, pp(nic_info)))
@ -124,11 +117,11 @@ def run():
backing=Ethernet.BackingSpec( backing=Ethernet.BackingSpec(
type=Ethernet.BackingType.DISTRIBUTED_PORTGROUP, type=Ethernet.BackingType.DISTRIBUTED_PORTGROUP,
network=distributed_network)) network=distributed_network))
nic = ethernet_svc.create(vm, nic_create_spec) nic = client.vcenter.vm.hardware.Ethernet.create(vm, nic_create_spec)
print('vm.hardware.Ethernet.create({}, {}) -> {}'. print('vm.hardware.Ethernet.create({}, {}) -> {}'.
format(vm, nic_create_spec, nic)) format(vm, nic_create_spec, nic))
nics_to_delete.append(nic) nics_to_delete.append(nic)
nic_info = ethernet_svc.get(vm, nic) nic_info = client.vcenter.vm.hardware.Ethernet.get(vm, nic)
print('vm.hardware.Ethernet.get({}, {}) -> {}'. print('vm.hardware.Ethernet.get({}, {}) -> {}'.
format(vm, nic, pp(nic_info))) format(vm, nic, pp(nic_info)))
@ -145,11 +138,11 @@ def run():
backing=Ethernet.BackingSpec( backing=Ethernet.BackingSpec(
type=Ethernet.BackingType.STANDARD_PORTGROUP, type=Ethernet.BackingType.STANDARD_PORTGROUP,
network=standard_network)) network=standard_network))
nic = ethernet_svc.create(vm, nic_create_spec) nic = client.vcenter.vm.hardware.Ethernet.create(vm, nic_create_spec)
print('vm.hardware.Ethernet.create({}, {}) -> {}'. print('vm.hardware.Ethernet.create({}, {}) -> {}'.
format(vm, nic_create_spec, nic)) format(vm, nic_create_spec, nic))
nics_to_delete.append(nic) nics_to_delete.append(nic)
nic_info = ethernet_svc.get(vm, nic) nic_info = client.vcenter.vm.hardware.Ethernet.get(vm, nic)
print('vm.hardware.Ethernet.get({}, {}) -> {}'. print('vm.hardware.Ethernet.get({}, {}) -> {}'.
format(vm, nic, pp(nic_info))) format(vm, nic, pp(nic_info)))
@ -166,11 +159,11 @@ def run():
backing=Ethernet.BackingSpec( backing=Ethernet.BackingSpec(
type=Ethernet.BackingType.DISTRIBUTED_PORTGROUP, type=Ethernet.BackingType.DISTRIBUTED_PORTGROUP,
network=distributed_network)) network=distributed_network))
nic = ethernet_svc.create(vm, nic_create_spec) nic = client.vcenter.vm.hardware.Ethernet.create(vm, nic_create_spec)
print('vm.hardware.Ethernet.create({}, {}) -> {}'. print('vm.hardware.Ethernet.create({}, {}) -> {}'.
format(vm, nic_create_spec, nic)) format(vm, nic_create_spec, nic))
nics_to_delete.append(nic) nics_to_delete.append(nic)
nic_info = ethernet_svc.get(vm, nic) nic_info = client.vcenter.vm.hardware.Ethernet.get(vm, nic)
print('vm.hardware.Ethernet.get({}, {}) -> {}'. print('vm.hardware.Ethernet.get({}, {}) -> {}'.
format(vm, nic, pp(nic_info))) format(vm, nic, pp(nic_info)))
@ -182,8 +175,8 @@ def run():
network=standard_network)) network=standard_network))
print('vm.hardware.Ethernet.update({}, {}, {})'. print('vm.hardware.Ethernet.update({}, {}, {})'.
format(vm, nic, nic_update_spec)) format(vm, nic, nic_update_spec))
ethernet_svc.update(vm, nic, nic_update_spec) client.vcenter.vm.hardware.Ethernet.update(vm, nic, nic_update_spec)
nic_info = ethernet_svc.get(vm, nic) nic_info = client.vcenter.vm.hardware.Ethernet.get(vm, nic)
print('vm.hardware.Ethernet.get({}, {}) -> {}'. print('vm.hardware.Ethernet.get({}, {}) -> {}'.
format(vm, nic, pp(nic_info))) format(vm, nic, pp(nic_info)))
@ -198,51 +191,51 @@ def run():
allow_guest_control=False) allow_guest_control=False)
print('vm.hardware.Ethernet.update({}, {}, {})'. print('vm.hardware.Ethernet.update({}, {}, {})'.
format(vm, nic, nic_update_spec)) format(vm, nic, nic_update_spec))
ethernet_svc.update(vm, nic, nic_update_spec) client.vcenter.vm.hardware.Ethernet.update(vm, nic, nic_update_spec)
nic_info = ethernet_svc.get(vm, nic) nic_info = client.vcenter.vm.hardware.Ethernet.get(vm, nic)
print('vm.hardware.Ethernet.get({}, {}) -> {}'. print('vm.hardware.Ethernet.get({}, {}) -> {}'.
format(vm, nic, pp(nic_info))) format(vm, nic, pp(nic_info)))
print('\n# Starting VM to run connect/disconnect sample') print('\n# Starting VM to run connect/disconnect sample')
print('vm.Power.start({})'.format(vm)) print('vm.Power.start({})'.format(vm))
vm_power_svc.start(vm) client.vcenter.vm.Power.start(vm)
nic_info = ethernet_svc.get(vm, nic) nic_info = client.vcenter.vm.hardware.Ethernet.get(vm, nic)
print('vm.hardware.Ethernet.get({}, {}) -> {}'. print('vm.hardware.Ethernet.get({}, {}) -> {}'.
format(vm, nic, pp(nic_info))) format(vm, nic, pp(nic_info)))
print('\n# Example: Connect Ethernet Nic after powering on VM') print('\n# Example: Connect Ethernet Nic after powering on VM')
ethernet_svc.connect(vm, nic) client.vcenter.vm.hardware.Ethernet.connect(vm, nic)
print('vm.hardware.Ethernet.connect({}, {})'.format(vm, nic)) print('vm.hardware.Ethernet.connect({}, {})'.format(vm, nic))
nic_info = ethernet_svc.get(vm, nic) nic_info = client.vcenter.vm.hardware.Ethernet.get(vm, nic)
print('vm.hardware.Ethernet.get({}, {}) -> {}'. print('vm.hardware.Ethernet.get({}, {}) -> {}'.
format(vm, nic, pp(nic_info))) format(vm, nic, pp(nic_info)))
print('\n# Example: Disconnect Ethernet Nic while VM is powered on') print('\n# Example: Disconnect Ethernet Nic while VM is powered on')
ethernet_svc.disconnect(vm, nic) client.vcenter.vm.hardware.Ethernet.disconnect(vm, nic)
print('vm.hardware.Ethernet.disconnect({}, {})'.format(vm, nic)) print('vm.hardware.Ethernet.disconnect({}, {})'.format(vm, nic))
nic_info = ethernet_svc.get(vm, nic) nic_info = client.vcenter.vm.hardware.Ethernet.get(vm, nic)
print('vm.hardware.Ethernet.get({}, {}) -> {}'. print('vm.hardware.Ethernet.get({}, {}) -> {}'.
format(vm, nic, pp(nic_info))) format(vm, nic, pp(nic_info)))
print('\n# Stopping VM after connect/disconnect sample') print('\n# Stopping VM after connect/disconnect sample')
print('vm.Power.start({})'.format(vm)) print('vm.Power.start({})'.format(vm))
vm_power_svc.stop(vm) client.vcenter.vm.Power.stop(vm)
nic_info = ethernet_svc.get(vm, nic) nic_info = client.vcenter.vm.hardware.Ethernet.get(vm, nic)
print('vm.hardware.Ethernet.get({}, {}) -> {}'. print('vm.hardware.Ethernet.get({}, {}) -> {}'.
format(vm, nic, pp(nic_info))) format(vm, nic, pp(nic_info)))
# List all Nics for a VM # List all Nics for a VM
nic_summaries = ethernet_svc.list(vm=vm) nic_summaries = client.vcenter.vm.hardware.Ethernet.list(vm=vm)
print('vm.hardware.Ethernet.list({}) -> {}'.format(vm, nic_summaries)) print('vm.hardware.Ethernet.list({}) -> {}'.format(vm, nic_summaries))
def cleanup(): def cleanup():
print('\n# Cleanup: Delete VM Nics that were added') print('\n# Cleanup: Delete VM Nics that were added')
for nic in nics_to_delete: for nic in nics_to_delete:
ethernet_svc.delete(vm, nic) client.vcenter.vm.hardware.Ethernet.delete(vm, nic)
print('vm.hardware.Ethernet.delete({}, {})'.format(vm, nic)) print('vm.hardware.Ethernet.delete({}, {})'.format(vm, nic))
nic_summaries = ethernet_svc.list(vm) nic_summaries = client.vcenter.vm.hardware.Ethernet.list(vm)
print('vm.hardware.Ethernet.list({}) -> {}'.format(vm, nic_summaries)) print('vm.hardware.Ethernet.list({}) -> {}'.format(vm, nic_summaries))
if set(orig_nic_summaries) != set(nic_summaries): if set(orig_nic_summaries) != set(nic_summaries):
print('vm.hardware.Ethernet WARNING: ' print('vm.hardware.Ethernet WARNING: '

View File

@ -2,7 +2,7 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -14,19 +14,17 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+' __vcenter_version__ = '6.5+'
import atexit from vmware.vapi.vsphere.client import create_vsphere_client
from com.vmware.vcenter.vm.hardware_client import Floppy from com.vmware.vcenter.vm.hardware_client import Floppy
from com.vmware.vcenter.vm_client import Power
from samples.vsphere.common import vapiconnect
from samples.vsphere.common.sample_util import parse_cli_args_vm from samples.vsphere.common.sample_util import parse_cli_args_vm
from samples.vsphere.common.sample_util import pp from samples.vsphere.common.sample_util import pp
from samples.vsphere.vcenter.setup import testbed from samples.vsphere.vcenter.setup import testbed
from samples.vsphere.vcenter.helper.vm_helper import get_vm from samples.vsphere.vcenter.helper.vm_helper import get_vm
from samples.vsphere.common.ssl_helper import get_unverified_session
""" """
Demonstrates how to configure Floppy settings for a VM. Demonstrates how to configure Floppy settings for a VM.
@ -38,46 +36,42 @@ The sample needs an existing VM.
vm = None vm = None
vm_name = None vm_name = None
floppy = None floppy = None
stub_config = None client = None
cleardata = False cleardata = False
orig_floppy_summaries = None orig_floppy_summaries = None
def setup(context=None): def setup(context=None):
global vm, vm_name, stub_config, cleardata global vm, vm_name, client, cleardata
if context: if context:
# Run sample suite via setup script # Run sample suite via setup script
stub_config = context.stub_config client = context.client
vm_name = testbed.config['VM_NAME_DEFAULT'] vm_name = testbed.config['VM_NAME_DEFAULT']
else: else:
# Run sample in standalone mode # Run sample in standalone mode
server, username, password, cleardata, skip_verification, vm_name = \ server, username, password, cleardata, skip_verification, vm_name = \
parse_cli_args_vm(testbed.config['VM_NAME_DEFAULT']) parse_cli_args_vm(testbed.config['VM_NAME_DEFAULT'])
stub_config = vapiconnect.connect(server, session = get_unverified_session() if skip_verification else None
username,
password,
skip_verification)
atexit.register(vapiconnect.logout, stub_config)
# Connect to vSphere client
client = create_vsphere_client(server=server,
username=username,
password=password,
session=session)
def run(): def run():
# * Floppy images must be pre-existing. This API does not expose # * Floppy images must be pre-existing. This API does not expose
# a way to create new floppy images. # a way to create new floppy images.
global vm global vm
vm = get_vm(stub_config, vm_name) vm = get_vm(client, vm_name)
if not vm: if not vm:
raise Exception('Sample requires an existing vm with name ({}). ' raise Exception('Sample requires an existing vm with name ({}). '
'Please create the vm first.'.format(vm_name)) 'Please create the vm first.'.format(vm_name))
print("Using VM '{}' ({}) for Floppy Sample".format(vm_name, vm)) print("Using VM '{}' ({}) for Floppy Sample".format(vm_name, vm))
img_datastore_path = testbed.config['FLOPPY_DATASTORE_PATH'] img_datastore_path = testbed.config['FLOPPY_DATASTORE_PATH']
# Create Floppy stub used for making requests
global floppy_svc
floppy_svc = Floppy(stub_config)
vm_power_svc = Power(stub_config)
print('\n# Example: List all Floppys for a VM') print('\n# Example: List all Floppys for a VM')
floppy_summaries = floppy_svc.list(vm=vm) floppy_summaries = client.vcenter.vm.hardware.Floppy.list(vm=vm)
print('vm.hardware.Floppy.list({}) -> {}'.format(vm, floppy_summaries)) print('vm.hardware.Floppy.list({}) -> {}'.format(vm, floppy_summaries))
# Save current list of Floppys to verify that we have cleaned up properly # Save current list of Floppys to verify that we have cleaned up properly
@ -88,7 +82,7 @@ def run():
global floppy global floppy
for floppy_summary in floppy_summaries: for floppy_summary in floppy_summaries:
floppy = floppy_summary.floppy floppy = floppy_summary.floppy
floppy_info = floppy_svc.get(vm=vm, floppy=floppy) floppy_info = client.vcenter.vm.hardware.Floppy.get(vm=vm, floppy=floppy)
print('vm.hardware.Floppy.get({}, {}) -> {}'. print('vm.hardware.Floppy.get({}, {}) -> {}'.
format(vm, floppy, pp(floppy_info))) format(vm, floppy, pp(floppy_info)))
@ -97,25 +91,25 @@ def run():
print('\n# Example: Create Floppy port with defaults') print('\n# Example: Create Floppy port with defaults')
floppy_create_spec = Floppy.CreateSpec() floppy_create_spec = Floppy.CreateSpec()
floppy = floppy_svc.create(vm, floppy_create_spec) floppy = client.vcenter.vm.hardware.Floppy.create(vm, floppy_create_spec)
print('vm.hardware.Floppy.create({}, {}) -> {}'. print('vm.hardware.Floppy.create({}, {}) -> {}'.
format(vm, floppy_create_spec, floppy)) format(vm, floppy_create_spec, floppy))
floppy_info = floppy_svc.get(vm, floppy) floppy_info = client.vcenter.vm.hardware.Floppy.get(vm, floppy)
print('vm.hardware.Floppy.get({}, {}) -> {}'. print('vm.hardware.Floppy.get({}, {}) -> {}'.
format(vm, floppy, pp(floppy_info))) format(vm, floppy, pp(floppy_info)))
floppy_svc.delete(vm, floppy) client.vcenter.vm.hardware.Floppy.delete(vm, floppy)
print('vm.hardware.Floppy.delete({}, {})'.format(vm, floppy)) print('vm.hardware.Floppy.delete({}, {})'.format(vm, floppy))
print('\n# Example: Create Floppy with CLIENT_DEVICE backing') print('\n# Example: Create Floppy with CLIENT_DEVICE backing')
floppy_create_spec = Floppy.CreateSpec( floppy_create_spec = Floppy.CreateSpec(
backing=Floppy.BackingSpec(type=Floppy.BackingType.CLIENT_DEVICE)) backing=Floppy.BackingSpec(type=Floppy.BackingType.CLIENT_DEVICE))
floppy = floppy_svc.create(vm, floppy_create_spec) floppy = client.vcenter.vm.hardware.Floppy.create(vm, floppy_create_spec)
print('vm.hardware.Floppy.create({}, {}) -> {}'. print('vm.hardware.Floppy.create({}, {}) -> {}'.
format(vm, floppy_create_spec, floppy)) format(vm, floppy_create_spec, floppy))
floppy_info = floppy_svc.get(vm, floppy) floppy_info = client.vcenter.vm.hardware.Floppy.get(vm, floppy)
print('vm.hardware.Floppy.get({}, {}) -> {}'. print('vm.hardware.Floppy.get({}, {}) -> {}'.
format(vm, floppy, pp(floppy_info))) format(vm, floppy, pp(floppy_info)))
floppy_svc.delete(vm, floppy) client.vcenter.vm.hardware.Floppy.delete(vm, floppy)
print('vm.hardware.Floppy.delete({}, {})'.format(vm, floppy)) print('vm.hardware.Floppy.delete({}, {})'.format(vm, floppy))
print('\n# Example: Create Floppy with IMAGE_FILE backing, ' print('\n# Example: Create Floppy with IMAGE_FILE backing, '
@ -126,8 +120,8 @@ def run():
start_connected=True, start_connected=True,
backing=Floppy.BackingSpec(type=Floppy.BackingType.IMAGE_FILE, backing=Floppy.BackingSpec(type=Floppy.BackingType.IMAGE_FILE,
image_file=img_datastore_path)) image_file=img_datastore_path))
floppy = floppy_svc.create(vm, floppy_create_spec) floppy = client.vcenter.vm.hardware.Floppy.create(vm, floppy_create_spec)
floppy_info = floppy_svc.get(vm, floppy) floppy_info = client.vcenter.vm.hardware.Floppy.get(vm, floppy)
print('vm.hardware.Floppy.get({}, {}) -> {}'. print('vm.hardware.Floppy.get({}, {}) -> {}'.
format(vm, floppy, pp(floppy_info))) format(vm, floppy, pp(floppy_info)))
@ -137,50 +131,50 @@ def run():
start_connected=False, allow_guest_control=False) start_connected=False, allow_guest_control=False)
print('vm.hardware.Floppy.update({}, {}, {})'. print('vm.hardware.Floppy.update({}, {}, {})'.
format(vm, floppy, floppy_update_spec)) format(vm, floppy, floppy_update_spec))
floppy_svc.update(vm, floppy, floppy_update_spec) client.vcenter.vm.hardware.Floppy.update(vm, floppy, floppy_update_spec)
floppy_info = floppy_svc.get(vm, floppy) floppy_info = client.vcenter.vm.hardware.Floppy.get(vm, floppy)
print('vm.hardware.Floppy.get({}, {}) -> {}'. print('vm.hardware.Floppy.get({}, {}) -> {}'.
format(vm, floppy, pp(floppy_info))) format(vm, floppy, pp(floppy_info)))
print('\n# Starting VM to run connect/disconnect sample') print('\n# Starting VM to run connect/disconnect sample')
print('vm.Power.start({})'.format(vm)) print('vm.Power.start({})'.format(vm))
vm_power_svc.start(vm) client.vcenter.vm.Power.start(vm)
floppy_info = floppy_svc.get(vm, floppy) floppy_info = client.vcenter.vm.hardware.Floppy.get(vm, floppy)
print('vm.hardware.Floppy.get({}, {}) -> {}'. print('vm.hardware.Floppy.get({}, {}) -> {}'.
format(vm, floppy, pp(floppy_info))) format(vm, floppy, pp(floppy_info)))
print('\n# Example: Connect Floppy after powering on VM') print('\n# Example: Connect Floppy after powering on VM')
floppy_svc.connect(vm, floppy) client.vcenter.vm.hardware.Floppy.connect(vm, floppy)
print('vm.hardware.Floppy.connect({}, {})'.format(vm, floppy)) print('vm.hardware.Floppy.connect({}, {})'.format(vm, floppy))
floppy_info = floppy_svc.get(vm, floppy) floppy_info = client.vcenter.vm.hardware.Floppy.get(vm, floppy)
print('vm.hardware.Floppy.get({}, {}) -> {}'. print('vm.hardware.Floppy.get({}, {}) -> {}'.
format(vm, floppy, pp(floppy_info))) format(vm, floppy, pp(floppy_info)))
print('\n# Example: Disconnect Floppy while VM is powered on') print('\n# Example: Disconnect Floppy while VM is powered on')
floppy_svc.disconnect(vm, floppy) client.vcenter.vm.hardware.Floppy.disconnect(vm, floppy)
print('vm.hardware.Floppy.disconnect({}, {})'.format(vm, floppy)) print('vm.hardware.Floppy.disconnect({}, {})'.format(vm, floppy))
floppy_info = floppy_svc.get(vm, floppy) floppy_info = client.vcenter.vm.hardware.Floppy.get(vm, floppy)
print('vm.hardware.Floppy.get({}, {}) -> {}'. print('vm.hardware.Floppy.get({}, {}) -> {}'.
format(vm, floppy, pp(floppy_info))) format(vm, floppy, pp(floppy_info)))
print('\n# Stopping VM after connect/disconnect sample') print('\n# Stopping VM after connect/disconnect sample')
print('vm.Power.start({})'.format(vm)) print('vm.Power.start({})'.format(vm))
vm_power_svc.stop(vm) client.vcenter.vm.Power.stop(vm)
floppy_info = floppy_svc.get(vm, floppy) floppy_info = client.vcenter.vm.hardware.Floppy.get(vm, floppy)
print('vm.hardware.Floppy.get({}, {}) -> {}'. print('vm.hardware.Floppy.get({}, {}) -> {}'.
format(vm, floppy, pp(floppy_info))) format(vm, floppy, pp(floppy_info)))
# List all Floppys for a VM # List all Floppys for a VM
floppy_summaries = floppy_svc.list(vm=vm) floppy_summaries = client.vcenter.vm.hardware.Floppy.list(vm=vm)
print('vm.hardware.Floppy.list({}) -> {}'.format(vm, floppy_summaries)) print('vm.hardware.Floppy.list({}) -> {}'.format(vm, floppy_summaries))
def cleanup(): def cleanup():
print('\n# Cleanup: Delete VM Floppys that were added') print('\n# Cleanup: Delete VM Floppys that were added')
floppy_svc.delete(vm, floppy) client.vcenter.vm.hardware.Floppy.delete(vm, floppy)
print('vm.hardware.Floppy.delete({}, {})'.format(vm, floppy)) print('vm.hardware.Floppy.delete({}, {})'.format(vm, floppy))
floppy_summaries = floppy_svc.list(vm) floppy_summaries = client.vcenter.vm.hardware.Floppy.list(vm)
print('vm.hardware.Floppy.list({}) -> {}'.format(vm, floppy_summaries)) print('vm.hardware.Floppy.list({}) -> {}'.format(vm, floppy_summaries))
if set(orig_floppy_summaries) != set(floppy_summaries): if set(orig_floppy_summaries) != set(floppy_summaries):
print('vm.hardware.Floppy WARNING: ' print('vm.hardware.Floppy WARNING: '

View File

@ -1,6 +1,6 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -12,7 +12,6 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+' __vcenter_version__ = '6.5+'
import samples.vsphere.vcenter.vm.hardware.adapter.sata import samples.vsphere.vcenter.vm.hardware.adapter.sata
@ -73,7 +72,7 @@ def validate(context):
testbed.config['VM_NAME_EXHAUSTIVE']]) testbed.config['VM_NAME_EXHAUSTIVE']])
valid = True valid = True
for name in names: for name in names:
if not get_vm(context.stub_config, name): if not get_vm(context.client, name):
valid = False valid = False
if not valid: if not valid:
raise Exception('==> Samples Setup validation failed: ' raise Exception('==> Samples Setup validation failed: '

View File

@ -2,7 +2,7 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -14,18 +14,17 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+' __vcenter_version__ = '6.5+'
import atexit
from com.vmware.vcenter.vm.hardware_client import Memory from com.vmware.vcenter.vm.hardware_client import Memory
from samples.vsphere.common import vapiconnect from vmware.vapi.vsphere.client import create_vsphere_client
from samples.vsphere.common.sample_util import parse_cli_args_vm from samples.vsphere.common.sample_util import parse_cli_args_vm
from samples.vsphere.common.sample_util import pp from samples.vsphere.common.sample_util import pp
from samples.vsphere.vcenter.setup import testbed from samples.vsphere.vcenter.setup import testbed
from samples.vsphere.vcenter.helper.vm_helper import get_vm from samples.vsphere.vcenter.helper.vm_helper import get_vm
from samples.vsphere.common.ssl_helper import get_unverified_session
""" """
Demonstrates how to configure the memory related settings of a virtual machine. Demonstrates how to configure the memory related settings of a virtual machine.
@ -36,43 +35,39 @@ The sample needs an existing VM.
vm = None vm = None
vm_name = None vm_name = None
stub_config = None client = None
memory_svc = None
cleardata = False cleardata = False
orig_memory_info = None orig_memory_info = None
def setup(context=None): def setup(context=None):
global vm, vm_name, stub_config, cleardata global vm, vm_name, client, cleardata
if context: if context:
# Run sample suite via setup script # Run sample suite via setup script
stub_config = context.stub_config client = context.client
vm_name = testbed.config['VM_NAME_DEFAULT'] vm_name = testbed.config['VM_NAME_DEFAULT']
else: else:
# Run sample in standalone mode # Run sample in standalone mode
server, username, password, cleardata, skip_verification, vm_name = \ server, username, password, cleardata, skip_verification, vm_name = \
parse_cli_args_vm(testbed.config['VM_NAME_DEFAULT']) parse_cli_args_vm(testbed.config['VM_NAME_DEFAULT'])
stub_config = vapiconnect.connect(server, session = get_unverified_session() if skip_verification else None
username,
password,
skip_verification)
atexit.register(vapiconnect.logout, stub_config)
# Connect to vSphere client
client = create_vsphere_client(server=server,
username=username,
password=password,
session=session)
def run(): def run():
global vm global vm
vm = get_vm(stub_config, vm_name) vm = get_vm(client, vm_name)
if not vm: if not vm:
raise Exception('Sample requires an existing vm with name ({}). ' raise Exception('Sample requires an existing vm with name ({}). '
'Please create the vm first.'.format(vm_name)) 'Please create the vm first.'.format(vm_name))
print("Using VM '{}' ({}) for Memory Sample".format(vm_name, vm)) print("Using VM '{}' ({}) for Memory Sample".format(vm_name, vm))
# Create Memory stub used for making requests
global memory_svc
memory_svc = Memory(stub_config)
print('\n# Example: Get current Memory configuration') print('\n# Example: Get current Memory configuration')
memory_info = memory_svc.get(vm) memory_info = client.vcenter.vm.hardware.Memory.get(vm)
print('vm.hardware.Memory.get({}) -> {}'.format(vm, pp(memory_info))) print('vm.hardware.Memory.get({}) -> {}'.format(vm, pp(memory_info)))
# Save current Memory info to verify that we have cleaned up properly # Save current Memory info to verify that we have cleaned up properly
@ -82,19 +77,19 @@ def run():
print('\n# Example: Update memory size_mib field of Memory configuration') print('\n# Example: Update memory size_mib field of Memory configuration')
update_spec = Memory.UpdateSpec(size_mib=8 * 1024) update_spec = Memory.UpdateSpec(size_mib=8 * 1024)
print('vm.hardware.Memory.update({}, {})'.format(vm, update_spec)) print('vm.hardware.Memory.update({}, {})'.format(vm, update_spec))
memory_svc.update(vm, update_spec) client.vcenter.vm.hardware.Memory.update(vm, update_spec)
# Get new Memory configuration # Get new Memory configuration
memory_info = memory_svc.get(vm) memory_info = client.vcenter.vm.hardware.Memory.get(vm)
print('vm.hardware.Memory.get({}) -> {}'.format(vm, pp(memory_info))) print('vm.hardware.Memory.get({}) -> {}'.format(vm, pp(memory_info)))
print('\n# Example: Update hot_add_enabled field of Memory configuration') print('\n# Example: Update hot_add_enabled field of Memory configuration')
update_spec = Memory.UpdateSpec(hot_add_enabled=True) update_spec = Memory.UpdateSpec(hot_add_enabled=True)
print('vm.hardware.Memory.update({}, {})'.format(vm, update_spec)) print('vm.hardware.Memory.update({}, {})'.format(vm, update_spec))
memory_svc.update(vm, update_spec) client.vcenter.vm.hardware.Memory.update(vm, update_spec)
# Get new Memory configuration # Get new Memory configuration
memory_info = memory_svc.get(vm) memory_info = client.vcenter.vm.hardware.Memory.get(vm)
print('vm.hardware.Memory.get({}) -> {}'.format(vm, pp(memory_info))) print('vm.hardware.Memory.get({}) -> {}'.format(vm, pp(memory_info)))
@ -104,10 +99,10 @@ def cleanup():
hot_add_enabled=orig_memory_info. hot_add_enabled=orig_memory_info.
hot_add_enabled) hot_add_enabled)
print('vm.hardware.Memory.update({}, {})'.format(vm, update_spec)) print('vm.hardware.Memory.update({}, {})'.format(vm, update_spec))
memory_svc.update(vm, update_spec) client.vcenter.vm.hardware.Memory.update(vm, update_spec)
# Get final Memory configuration # Get final Memory configuration
memory_info = memory_svc.get(vm) memory_info = client.vcenter.vm.hardware.Memory.get(vm)
print('vm.hardware.Memory.get({}) -> {}'.format(vm, pp(memory_info))) print('vm.hardware.Memory.get({}) -> {}'.format(vm, pp(memory_info)))
if memory_info != orig_memory_info: if memory_info != orig_memory_info:

View File

@ -2,7 +2,7 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -12,21 +12,20 @@
* WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, * WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY,
* NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
""" """
from vmware.vapi.vsphere.client import create_vsphere_client
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+' __vcenter_version__ = '6.5+'
import atexit import atexit
from com.vmware.vcenter.vm.hardware_client import Parallel from com.vmware.vcenter.vm.hardware_client import Parallel
from com.vmware.vcenter.vm_client import Power
from pyVim.connect import SmartConnect, Disconnect from pyVim.connect import SmartConnect, Disconnect
from samples.vsphere.common import vapiconnect
from samples.vsphere.common.sample_util import parse_cli_args_vm from samples.vsphere.common.sample_util import parse_cli_args_vm
from samples.vsphere.common.sample_util import pp from samples.vsphere.common.sample_util import pp
from samples.vsphere.common.ssl_helper import get_unverified_context from samples.vsphere.common.ssl_helper import get_unverified_context, \
get_unverified_session
from samples.vsphere.common.vim.file import delete_file from samples.vsphere.common.vim.file import delete_file
from samples.vsphere.vcenter.helper.vm_helper import get_vm from samples.vsphere.vcenter.helper.vm_helper import get_vm
from samples.vsphere.vcenter.setup import testbed from samples.vsphere.vcenter.setup import testbed
@ -40,30 +39,29 @@ The sample needs an existing VM.
vm = None vm = None
vm_name = None vm_name = None
stub_config = None client = None
service_instance = None service_instance = None
parallel_svc = None
cleardata = False cleardata = False
parallels_to_delete = [] parallels_to_delete = []
orig_parallel_summaries = None orig_parallel_summaries = None
def setup(context=None): def setup(context=None):
global vm_name, stub_config, service_instance, cleardata global vm_name, client, service_instance, cleardata
if context: if context:
# Run sample suite via setup script # Run sample suite via setup script
stub_config = context.stub_config client = context.client
vm_name = testbed.config['VM_NAME_DEFAULT'] vm_name = testbed.config['VM_NAME_DEFAULT']
service_instance = context.service_instance service_instance = context.service_instance
else: else:
# Run sample in standalone mode # Run sample in standalone mode
server, username, password, cleardata, skip_verification, vm_name = \ server, username, password, cleardata, skip_verification, vm_name = \
parse_cli_args_vm(testbed.config['VM_NAME_DEFAULT']) parse_cli_args_vm(testbed.config['VM_NAME_DEFAULT'])
stub_config = vapiconnect.connect(server, session = get_unverified_session() if skip_verification else None
username, client = create_vsphere_client(server=server,
password, username=username,
skip_verification) password=password,
atexit.register(vapiconnect.logout, stub_config) session=session)
context = None context = None
if skip_verification: if skip_verification:
@ -76,19 +74,15 @@ def setup(context=None):
def run(): def run():
global vm, parallel_svc global vm, client
vm = get_vm(stub_config, vm_name) vm = get_vm(client, vm_name)
if not vm: if not vm:
raise Exception('Sample requires an existing vm with name ({}). ' raise Exception('Sample requires an existing vm with name ({}). '
'Please create the vm first.'.format(vm_name)) 'Please create the vm first.'.format(vm_name))
print("Using VM '{}' ({}) for Parallel Sample".format(vm_name, vm)) print("Using VM '{}' ({}) for Parallel Sample".format(vm_name, vm))
# Create Parallel port stub used for making requests
parallel_svc = Parallel(stub_config)
vm_power_svc = Power(stub_config)
print('\n# Example: List all Parallel ports for a VM') print('\n# Example: List all Parallel ports for a VM')
parallel_summaries = parallel_svc.list(vm=vm) parallel_summaries = client.vcenter.vm.hardware.Parallel.list(vm=vm)
print('vm.hardware.Parallel.list({}) -> {}'.format(vm, parallel_summaries)) print('vm.hardware.Parallel.list({}) -> {}'.format(vm, parallel_summaries))
# Save current list of Parallel ports to verify that we have cleaned up # Save current list of Parallel ports to verify that we have cleaned up
@ -99,7 +93,8 @@ def run():
# Get information for each Parallel port on the VM # Get information for each Parallel port on the VM
for parallel_summary in parallel_summaries: for parallel_summary in parallel_summaries:
parallel = parallel_summary.port parallel = parallel_summary.port
parallel_info = parallel_svc.get(vm=vm, port=parallel) parallel_info = client.vcenter.vm.hardware.Parallel.get(vm=vm,
port=parallel)
print('vm.hardware.Parallel.get({}, {}) -> {}'.format(vm, parallel, pp( print('vm.hardware.Parallel.get({}, {}) -> {}'.format(vm, parallel, pp(
parallel_info))) parallel_info)))
@ -108,12 +103,12 @@ def run():
print('\n# Example: Create Parallel port with defaults') print('\n# Example: Create Parallel port with defaults')
parallel_create_spec = Parallel.CreateSpec() parallel_create_spec = Parallel.CreateSpec()
parallel = parallel_svc.create(vm, parallel_create_spec) parallel = client.vcenter.vm.hardware.Parallel.create(vm, parallel_create_spec)
print('vm.hardware.Parallel.create({}, {}) -> {}'. print('vm.hardware.Parallel.create({}, {}) -> {}'.
format(vm, parallel_create_spec, parallel)) format(vm, parallel_create_spec, parallel))
global parallels_to_delete global parallels_to_delete
parallels_to_delete.append(parallel) parallels_to_delete.append(parallel)
parallel_info = parallel_svc.get(vm, parallel) parallel_info = client.vcenter.vm.hardware.Parallel.get(vm, parallel)
print('vm.hardware.Parallel.get({}, {}) -> {}'.format(vm, parallel, print('vm.hardware.Parallel.get({}, {}) -> {}'.format(vm, parallel,
pp(parallel_info))) pp(parallel_info)))
@ -125,11 +120,11 @@ def run():
allow_guest_control=True, allow_guest_control=True,
backing=Parallel.BackingSpec(type=Parallel.BackingType.FILE, backing=Parallel.BackingSpec(type=Parallel.BackingType.FILE,
file=parallel_port_datastore_path)) file=parallel_port_datastore_path))
parallel = parallel_svc.create(vm, parallel_create_spec) parallel = client.vcenter.vm.hardware.Parallel.create(vm, parallel_create_spec)
print('vm.hardware.Parallel.create({}, {}) -> {}'. print('vm.hardware.Parallel.create({}, {}) -> {}'.
format(vm, parallel_create_spec, parallel)) format(vm, parallel_create_spec, parallel))
parallels_to_delete.append(parallel) parallels_to_delete.append(parallel)
parallel_info = parallel_svc.get(vm, parallel) parallel_info = client.vcenter.vm.hardware.Parallel.get(vm, parallel)
print('vm.hardware.Parallel.get({}, {}) -> {}'. print('vm.hardware.Parallel.get({}, {}) -> {}'.
format(vm, parallel, pp(parallel_info))) format(vm, parallel, pp(parallel_info)))
@ -143,43 +138,43 @@ def run():
allow_guest_control=False, allow_guest_control=False,
backing=Parallel.BackingSpec(type=Parallel.BackingType.FILE, backing=Parallel.BackingSpec(type=Parallel.BackingType.FILE,
file=parallel_port_datastore_path)) file=parallel_port_datastore_path))
parallel_svc.update(vm, parallel, parallel_update_spec) client.vcenter.vm.hardware.Parallel.update(vm, parallel, parallel_update_spec)
print('vm.hardware.Parallel.update({}, {}) -> {}'. print('vm.hardware.Parallel.update({}, {}) -> {}'.
format(vm, parallel_update_spec, parallel)) format(vm, parallel_update_spec, parallel))
parallel_info = parallel_svc.get(vm, parallel) parallel_info = client.vcenter.vm.hardware.Parallel.get(vm, parallel)
print('vm.hardware.Parallel.get({}, {}) -> {}'. print('vm.hardware.Parallel.get({}, {}) -> {}'.
format(vm, parallel, pp(parallel_info))) format(vm, parallel, pp(parallel_info)))
print('\n# Starting VM to run connect/disconnect sample') print('\n# Starting VM to run connect/disconnect sample')
print('vm.Power.start({})'.format(vm)) print('vm.Power.start({})'.format(vm))
vm_power_svc.start(vm) client.vcenter.vm.Power.start(vm)
parallel_info = parallel_svc.get(vm, parallel) parallel_info = client.vcenter.vm.hardware.Parallel.get(vm, parallel)
print('vm.hardware.Parallel.get({}, {}) -> {}'. print('vm.hardware.Parallel.get({}, {}) -> {}'.
format(vm, parallel, pp(parallel_info))) format(vm, parallel, pp(parallel_info)))
print('\n# Example: Connect Parallel port after powering on VM') print('\n# Example: Connect Parallel port after powering on VM')
parallel_svc.connect(vm, parallel) client.vcenter.vm.hardware.Parallel.connect(vm, parallel)
print('vm.hardware.Parallel.connect({}, {})'.format(vm, parallel)) print('vm.hardware.Parallel.connect({}, {})'.format(vm, parallel))
parallel_info = parallel_svc.get(vm, parallel) parallel_info = client.vcenter.vm.hardware.Parallel.get(vm, parallel)
print('vm.hardware.Parallel.get({}, {}) -> {}'. print('vm.hardware.Parallel.get({}, {}) -> {}'.
format(vm, parallel, pp(parallel_info))) format(vm, parallel, pp(parallel_info)))
print('\n# Example: Disconnect Parallel port while VM is powered on') print('\n# Example: Disconnect Parallel port while VM is powered on')
parallel_svc.disconnect(vm, parallel) client.vcenter.vm.hardware.Parallel.disconnect(vm, parallel)
print('vm.hardware.Parallel.disconnect({}, {})'.format(vm, parallel)) print('vm.hardware.Parallel.disconnect({}, {})'.format(vm, parallel))
parallel_info = parallel_svc.get(vm, parallel) parallel_info = client.vcenter.vm.hardware.Parallel.get(vm, parallel)
print('vm.hardware.Parallel.get({}, {}) -> {}'. print('vm.hardware.Parallel.get({}, {}) -> {}'.
format(vm, parallel, pp(parallel_info))) format(vm, parallel, pp(parallel_info)))
print('\n# Stopping VM after connect/disconnect sample') print('\n# Stopping VM after connect/disconnect sample')
print('vm.Power.start({})'.format(vm)) print('vm.Power.start({})'.format(vm))
vm_power_svc.stop(vm) client.vcenter.vm.Power.stop(vm)
parallel_info = parallel_svc.get(vm, parallel) parallel_info = client.vcenter.vm.hardware.Parallel.get(vm, parallel)
print('vm.hardware.Parallel.get({}, {}) -> {}'. print('vm.hardware.Parallel.get({}, {}) -> {}'.
format(vm, parallel, pp(parallel_info))) format(vm, parallel, pp(parallel_info)))
# List all Parallel ports for a VM # List all Parallel ports for a VM
parallel_summaries = parallel_svc.list(vm=vm) parallel_summaries = client.vcenter.vm.hardware.Parallel.list(vm=vm)
print('vm.hardware.Parallel.list({}) -> {}'. print('vm.hardware.Parallel.list({}) -> {}'.
format(vm, parallel_summaries)) format(vm, parallel_summaries))
@ -190,10 +185,10 @@ def run():
def cleanup(): def cleanup():
print('\n# Cleanup: Delete VM Parallel ports that were added') print('\n# Cleanup: Delete VM Parallel ports that were added')
for parallel in parallels_to_delete: for parallel in parallels_to_delete:
parallel_svc.delete(vm, parallel) client.vcenter.vm.hardware.Parallel.delete(vm, parallel)
print('vm.hardware.Parallel.delete({}, {})'.format(vm, parallel)) print('vm.hardware.Parallel.delete({}, {})'.format(vm, parallel))
parallel_summaries = parallel_svc.list(vm) parallel_summaries = client.vcenter.vm.hardware.Parallel.list(vm)
print('vm.hardware.Parallel.list({}) -> {}'.format(vm, parallel_summaries)) print('vm.hardware.Parallel.list({}) -> {}'.format(vm, parallel_summaries))
if set(orig_parallel_summaries) != set(parallel_summaries): if set(orig_parallel_summaries) != set(parallel_summaries):
print('vm.hardware.Parallel WARNING: ' print('vm.hardware.Parallel WARNING: '
@ -212,7 +207,7 @@ def cleanup_backends():
""" """
datacenter_name = testbed.config['PARALLEL_PORT_DATACENTER_NAME'] datacenter_name = testbed.config['PARALLEL_PORT_DATACENTER_NAME']
datastore_path = testbed.config['PARALLEL_PORT_DATASTORE_PATH'] datastore_path = testbed.config['PARALLEL_PORT_DATASTORE_PATH']
delete_file(stub_config, delete_file(client,
service_instance, service_instance,
'Parallel Port', 'Parallel Port',
datacenter_name, datacenter_name,

View File

@ -2,7 +2,7 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -14,21 +14,22 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.' __vcenter_version__ = '6.5+'
import atexit import atexit
from vmware.vapi.vsphere.client import create_vsphere_client
from com.vmware.vcenter.vm.hardware_client import Serial from com.vmware.vcenter.vm.hardware_client import Serial
from com.vmware.vcenter.vm_client import Power
from pyVim.connect import SmartConnect, Disconnect from pyVim.connect import SmartConnect, Disconnect
from samples.vsphere.common import vapiconnect
from samples.vsphere.common.sample_util import parse_cli_args_vm from samples.vsphere.common.sample_util import parse_cli_args_vm
from samples.vsphere.common.sample_util import pp from samples.vsphere.common.sample_util import pp
from samples.vsphere.common.ssl_helper import get_unverified_context from samples.vsphere.common.ssl_helper import get_unverified_context
from samples.vsphere.common.vim.file import delete_file from samples.vsphere.common.vim.file import delete_file
from samples.vsphere.vcenter.helper.vm_helper import get_vm 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.common.ssl_helper import get_unverified_session
""" """
Demonstrates how to configure Serial ports for a VM. Demonstrates how to configure Serial ports for a VM.
@ -48,30 +49,31 @@ delete them after running the sample.
vm = None vm = None
vm_name = None vm_name = None
stub_config = None client = None
service_instance = None service_instance = None
serial_svc = None
cleardata = False cleardata = False
serials_to_delete = [] serials_to_delete = []
orig_serial_summaries = None orig_serial_summaries = None
def setup(context=None): def setup(context=None):
global vm_name, stub_config, service_instance, cleardata global vm_name, client, service_instance, cleardata
if context: if context:
# Run sample suite via setup script # Run sample suite via setup script
stub_config = context.stub_config client = context.client
vm_name = testbed.config['VM_NAME_DEFAULT'] vm_name = testbed.config['VM_NAME_DEFAULT']
service_instance = context.service_instance service_instance = context.service_instance
else: else:
# Run sample in standalone mode # Run sample in standalone mode
server, username, password, cleardata, skip_verification, vm_name = \ server, username, password, cleardata, skip_verification, vm_name = \
parse_cli_args_vm(testbed.config['VM_NAME_DEFAULT']) parse_cli_args_vm(testbed.config['VM_NAME_DEFAULT'])
stub_config = vapiconnect.connect(server, session = get_unverified_session() if skip_verification else None
username,
password, # Connect to vSphere client
skip_verification) client = create_vsphere_client(server=server,
atexit.register(vapiconnect.logout, stub_config) username=username,
password=password,
session=session)
context = None context = None
if skip_verification: if skip_verification:
@ -92,19 +94,15 @@ def run():
# * Proxy: https://www.vmware.com/support/developer/vc-sdk/visdk41pubs # * Proxy: https://www.vmware.com/support/developer/vc-sdk/visdk41pubs
# /vsp41_usingproxy_virtual_serial_ports.pdf # /vsp41_usingproxy_virtual_serial_ports.pdf
global vm, serial_svc global vm
vm = get_vm(stub_config, vm_name) vm = get_vm(client, vm_name)
if not vm: if not vm:
raise Exception('Sample requires an existing vm with name ({}). ' raise Exception('Sample requires an existing vm with name ({}). '
'Please create the vm first.'.format(vm_name)) 'Please create the vm first.'.format(vm_name))
print("Using VM '{}' ({}) for Serial Sample".format(vm_name, vm)) print("Using VM '{}' ({}) for Serial Sample".format(vm_name, vm))
# Create Serial port stub used for making requests
serial_svc = Serial(stub_config)
vm_power_svc = Power(stub_config)
print('\n# Example: List all Serial ports for a VM') print('\n# Example: List all Serial ports for a VM')
serial_summaries = serial_svc.list(vm=vm) serial_summaries = client.vcenter.vm.hardware.Serial.list(vm=vm)
print('vm.hardware.Serial.list({}) -> {}'.format(vm, serial_summaries)) print('vm.hardware.Serial.list({}) -> {}'.format(vm, serial_summaries))
# Save current list of Serial ports to verify that we have cleaned up # Save current list of Serial ports to verify that we have cleaned up
@ -115,7 +113,7 @@ def run():
# Get information for each Serial port on the VM # Get information for each Serial port on the VM
for serial_summary in serial_summaries: for serial_summary in serial_summaries:
serial = serial_summary.port serial = serial_summary.port
serial_info = serial_svc.get(vm=vm, port=serial) serial_info = client.vcenter.vm.hardware.Serial.get(vm=vm, port=serial)
print('vm.hardware.Serial.get({}, {}) -> {}'.format(vm, serial, print('vm.hardware.Serial.get({}, {}) -> {}'.format(vm, serial,
pp(serial_info))) pp(serial_info)))
@ -123,11 +121,11 @@ def run():
print('\n# Example: Create Serial port with defaults') print('\n# Example: Create Serial port with defaults')
serial_create_spec = Serial.CreateSpec() serial_create_spec = Serial.CreateSpec()
serial = serial_svc.create(vm, serial_create_spec) serial = client.vcenter.vm.hardware.Serial.create(vm, serial_create_spec)
print('vm.hardware.Serial.create({}, {}) -> {}'. print('vm.hardware.Serial.create({}, {}) -> {}'.
format(vm, serial_create_spec, serial)) format(vm, serial_create_spec, serial))
serials_to_delete.append(serial) serials_to_delete.append(serial)
serial_info = serial_svc.get(vm, serial) serial_info = client.vcenter.vm.hardware.Serial.get(vm, serial)
print('vm.hardware.Serial.get({}, {}) -> {}'. print('vm.hardware.Serial.get({}, {}) -> {}'.
format(vm, serial, pp(serial_info))) format(vm, serial, pp(serial_info)))
@ -141,11 +139,11 @@ def run():
allow_guest_control=True, allow_guest_control=True,
backing=Serial.BackingSpec(type=Serial.BackingType.FILE, backing=Serial.BackingSpec(type=Serial.BackingType.FILE,
file=serial_port_datastore_path)) file=serial_port_datastore_path))
serial = serial_svc.create(vm, serial_create_spec) serial = client.vcenter.vm.hardware.Serial.create(vm, serial_create_spec)
print('vm.hardware.Serial.create({}, {}) -> {}'. print('vm.hardware.Serial.create({}, {}) -> {}'.
format(vm, serial_create_spec, serial)) format(vm, serial_create_spec, serial))
serials_to_delete.append(serial) serials_to_delete.append(serial)
serial_info = serial_svc.get(vm, serial) serial_info = client.vcenter.vm.hardware.Serial.get(vm, serial)
print('vm.hardware.Serial.get({}, {}) -> {}'. print('vm.hardware.Serial.get({}, {}) -> {}'.
format(vm, serial, pp(serial_info))) format(vm, serial, pp(serial_info)))
@ -157,11 +155,11 @@ def run():
allow_guest_control=True, allow_guest_control=True,
backing=Serial.BackingSpec(type=Serial.BackingType.NETWORK_SERVER, backing=Serial.BackingSpec(type=Serial.BackingType.NETWORK_SERVER,
network_location=serial_port_network_server_location)) network_location=serial_port_network_server_location))
serial = serial_svc.create(vm, serial_create_spec) serial = client.vcenter.vm.hardware.Serial.create(vm, serial_create_spec)
print('vm.hardware.Serial.create({}, {}) -> {}'. print('vm.hardware.Serial.create({}, {}) -> {}'.
format(vm, serial_create_spec, serial)) format(vm, serial_create_spec, serial))
serials_to_delete.append(serial) serials_to_delete.append(serial)
serial_info = serial_svc.get(vm, serial) serial_info = client.vcenter.vm.hardware.Serial.get(vm, serial)
print('vm.hardware.Serial.get({}, {}) -> {}'. print('vm.hardware.Serial.get({}, {}) -> {}'.
format(vm, serial, pp(serial_info))) format(vm, serial, pp(serial_info)))
@ -175,43 +173,43 @@ def run():
backing=Serial.BackingSpec(type=Serial.BackingType.NETWORK_CLIENT, backing=Serial.BackingSpec(type=Serial.BackingType.NETWORK_CLIENT,
network_location=serial_port_network_client_location, network_location=serial_port_network_client_location,
proxy=serial_port_network_proxy)) proxy=serial_port_network_proxy))
serial_svc.update(vm, serial, serial_update_spec) client.vcenter.vm.hardware.Serial.update(vm, serial, serial_update_spec)
print('vm.hardware.Serial.update({}, {}) -> {}'. print('vm.hardware.Serial.update({}, {}) -> {}'.
format(vm, serial_update_spec, serial)) format(vm, serial_update_spec, serial))
serial_info = serial_svc.get(vm, serial) serial_info = client.vcenter.vm.hardware.Serial.get(vm, serial)
print('vm.hardware.Serial.get({}, {}) -> {}'. print('vm.hardware.Serial.get({}, {}) -> {}'.
format(vm, serial, pp(serial_info))) format(vm, serial, pp(serial_info)))
print('\n# Starting VM to run connect/disconnect sample') print('\n# Starting VM to run connect/disconnect sample')
print('vm.Power.start({})'.format(vm)) print('vm.Power.start({})'.format(vm))
vm_power_svc.start(vm) client.vcenter.vm.Power.start(vm)
serial_info = serial_svc.get(vm, serial) serial_info = client.vcenter.vm.hardware.Serial.get(vm, serial)
print('vm.hardware.Serial.get({}, {}) -> {}'. print('vm.hardware.Serial.get({}, {}) -> {}'.
format(vm, serial, pp(serial_info))) format(vm, serial, pp(serial_info)))
print('\n# Example: Connect Serial port after powering on VM') print('\n# Example: Connect Serial port after powering on VM')
serial_svc.connect(vm, serial) client.vcenter.vm.hardware.Serial.connect(vm, serial)
print('vm.hardware.Serial.connect({}, {})'.format(vm, serial)) print('vm.hardware.Serial.connect({}, {})'.format(vm, serial))
serial_info = serial_svc.get(vm, serial) serial_info = client.vcenter.vm.hardware.Serial.get(vm, serial)
print('vm.hardware.Serial.get({}, {}) -> {}'. print('vm.hardware.Serial.get({}, {}) -> {}'.
format(vm, serial, pp(serial_info))) format(vm, serial, pp(serial_info)))
print('\n# Example: Disconnect Serial port while VM is powered on') print('\n# Example: Disconnect Serial port while VM is powered on')
serial_svc.disconnect(vm, serial) client.vcenter.vm.hardware.Serial.disconnect(vm, serial)
print('vm.hardware.Serial.disconnect({}, {})'.format(vm, serial)) print('vm.hardware.Serial.disconnect({}, {})'.format(vm, serial))
serial_info = serial_svc.get(vm, serial) serial_info = client.vcenter.vm.hardware.Serial.get(vm, serial)
print('vm.hardware.Serial.get({}, {}) -> {}'. print('vm.hardware.Serial.get({}, {}) -> {}'.
format(vm, serial, pp(serial_info))) format(vm, serial, pp(serial_info)))
print('\n# Stopping VM after connect/disconnect sample') print('\n# Stopping VM after connect/disconnect sample')
print('vm.Power.start({})'.format(vm)) print('vm.Power.start({})'.format(vm))
vm_power_svc.stop(vm) client.vcenter.vm.Power.stop(vm)
serial_info = serial_svc.get(vm, serial) serial_info = client.vcenter.vm.hardware.Serial.get(vm, serial)
print('vm.hardware.Serial.get({}, {}) -> {}'. print('vm.hardware.Serial.get({}, {}) -> {}'.
format(vm, serial, pp(serial_info))) format(vm, serial, pp(serial_info)))
# List all Serial ports for a VM # List all Serial ports for a VM
serial_summaries = serial_svc.list(vm=vm) serial_summaries = client.vcenter.vm.hardware.Serial.list(vm=vm)
print('vm.hardware.Serial.list({}) -> {}'.format(vm, serial_summaries)) print('vm.hardware.Serial.list({}) -> {}'.format(vm, serial_summaries))
# Always cleanup output file so the VM can be powered on next time # Always cleanup output file so the VM can be powered on next time
@ -221,10 +219,10 @@ def run():
def cleanup(): def cleanup():
print('\n# Delete VM Serial ports that were added') print('\n# Delete VM Serial ports that were added')
for serial in serials_to_delete: for serial in serials_to_delete:
serial_svc.delete(vm, serial) client.vcenter.vm.hardware.Serial.delete(vm, serial)
print('vm.hardware.Serial.delete({}, {})'.format(vm, serial)) print('vm.hardware.Serial.delete({}, {})'.format(vm, serial))
serial_summaries = serial_svc.list(vm) serial_summaries = client.vcenter.vm.hardware.Serial.list(vm)
print('vm.hardware.Serial.list({}) -> {}'.format(vm, serial_summaries)) print('vm.hardware.Serial.list({}) -> {}'.format(vm, serial_summaries))
if set(orig_serial_summaries) != set(serial_summaries): if set(orig_serial_summaries) != set(serial_summaries):
print('vm.hardware.Serial WARNING: ' print('vm.hardware.Serial WARNING: '
@ -243,7 +241,7 @@ def cleanup_backends():
""" """
datacenter_name = testbed.config['SERIAL_PORT_DATACENTER_NAME'] datacenter_name = testbed.config['SERIAL_PORT_DATACENTER_NAME']
datastore_path = testbed.config['SERIAL_PORT_DATASTORE_PATH'] datastore_path = testbed.config['SERIAL_PORT_DATASTORE_PATH']
delete_file(stub_config, delete_file(client,
service_instance, service_instance,
'Serial Port', 'Serial Port',
datacenter_name, datacenter_name,

View File

@ -17,14 +17,13 @@ __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2017 VMware, Inc. All rights reserved.' __copyright__ = 'Copyright 2017 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+' __vcenter_version__ = '6.5+'
import atexit from pprint import pprint
from com.vmware.vcenter_client import VM from vmware.vapi.vsphere.client import create_vsphere_client
from samples.vsphere.common import sample_cli from samples.vsphere.common import sample_cli
from samples.vsphere.common import sample_util from samples.vsphere.common import sample_util
from samples.vsphere.common.service_manager import ServiceManager from samples.vsphere.common.ssl_helper import get_unverified_session
from pprint import pprint
class ListVM(object): class ListVM(object):
@ -33,27 +32,20 @@ class ListVM(object):
Sample Prerequisites: Sample Prerequisites:
vCenter/ESX vCenter/ESX
""" """
def __init__(self): def __init__(self):
self.service_manager = None
def setup(self):
parser = sample_cli.build_arg_parser() parser = sample_cli.build_arg_parser()
args = sample_util.process_cli_args(parser.parse_args()) args = sample_util.process_cli_args(parser.parse_args())
session = get_unverified_session() if args.skipverification else None
self.service_manager = ServiceManager(args.server, self.client = create_vsphere_client(server=args.server,
args.username, username=args.username,
args.password, password=args.password,
args.skipverification) session=session)
self.service_manager.connect()
atexit.register(self.service_manager.disconnect)
def run(self): def run(self):
""" """
List VMs present in server List VMs present in server
""" """
vm_svc = VM(self.service_manager.stub_config) list_of_vms = self.client.vcenter.VM.list()
list_of_vms = vm_svc.list()
print("----------------------------") print("----------------------------")
print("List Of VMs") print("List Of VMs")
print("----------------------------") print("----------------------------")
@ -63,7 +55,6 @@ class ListVM(object):
def main(): def main():
list_vm = ListVM() list_vm = ListVM()
list_vm.setup()
list_vm.run() list_vm.run()

View File

@ -1,6 +1,6 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -12,7 +12,6 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+' __vcenter_version__ = '6.5+'
import samples.vsphere.vcenter.helper.network_helper import samples.vsphere.vcenter.helper.network_helper
@ -57,24 +56,24 @@ class VMSetup(object):
########################################################################### ###########################################################################
standard_network = samples.vsphere.vcenter.helper \ standard_network = samples.vsphere.vcenter.helper \
.network_helper.get_standard_network_backing( .network_helper.get_standard_network_backing(
context.stub_config, context.client,
context.testbed.config['STDPORTGROUP_NAME'], context.testbed.config['STDPORTGROUP_NAME'],
context.testbed.config['VM_DATACENTER_NAME']) context.testbed.config['VM_DATACENTER_NAME'])
print('standard_network={}'.format(standard_network)) print('standard_network={}'.format(standard_network))
distributed_network = samples.vsphere.vcenter.helper \ distributed_network = samples.vsphere.vcenter.helper \
.network_helper.get_distributed_network_backing( .network_helper.get_distributed_network_backing(
context.stub_config, context.client,
context.testbed.config['VDPORTGROUP1_NAME'], context.testbed.config['VDPORTGROUP1_NAME'],
context.testbed.config['VM_DATACENTER_NAME']) context.testbed.config['VM_DATACENTER_NAME'])
print('distributed_network={}'.format(distributed_network)) print('distributed_network={}'.format(distributed_network))
print('=' * 79) print('=' * 79)
self.default_vm = CreateDefaultVM(context.stub_config, self.default_vm = CreateDefaultVM(context.client,
placement_spec) placement_spec)
self.basic_vm = CreateBasicVM(context.stub_config, placement_spec) self.basic_vm = CreateBasicVM(context.client, placement_spec)
self.exhaustive_vm = CreateExhaustiveVM(context.stub_config, self.exhaustive_vm = CreateExhaustiveVM(context.client,
placement_spec, placement_spec,
standard_network, standard_network,
distributed_network) distributed_network)
@ -84,9 +83,9 @@ class VMSetup(object):
def cleanup(self): def cleanup(self):
print('Cleanup Samples Started') print('Cleanup Samples Started')
CreateDefaultVM(self.context.stub_config).cleanup() CreateDefaultVM(self.context.client).cleanup()
CreateBasicVM(self.context.stub_config).cleanup() CreateBasicVM(self.context.client).cleanup()
CreateExhaustiveVM(self.context.stub_config).cleanup() CreateExhaustiveVM(self.context.client).cleanup()
print('Cleanup Samples Complete\n') print('Cleanup Samples Complete\n')
def validate(self): def validate(self):

View File

@ -1,6 +1,6 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -12,7 +12,6 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+' __vcenter_version__ = '6.5+'
from com.vmware.vcenter_client import (Cluster, Datastore, Folder, ResourcePool, from com.vmware.vcenter_client import (Cluster, Datastore, Folder, ResourcePool,
@ -45,17 +44,13 @@ def get_placement_spec_for_cluster(context):
# Select a Cluster meeting our requirements # Select a Cluster meeting our requirements
datacenter_name = context.testbed.config['DATACENTER2_NAME'] datacenter_name = context.testbed.config['DATACENTER2_NAME']
datacenter = context.testbed.entities['DATACENTER_IDS'][datacenter_name] datacenter = context.testbed.entities['DATACENTER_IDS'][datacenter_name]
cluster_name = context.testbed.config['CLUSTER1_NAME'] cluster_name = context.testbed.config['CLUSTER1_NAME']
names = set([cluster_name])
cluster_svc = Cluster(context.stub_config)
filter = Cluster.FilterSpec( filter = Cluster.FilterSpec(
names=set([cluster_name]), names=set([cluster_name]),
datacenters=set([datacenter])) datacenters=set([datacenter]))
cluster_summaries = cluster_svc.list(filter=filter) cluster_summaries = context.client.vcenter.Cluster.list(filter=filter)
cluster = None
if len(cluster_summaries) > 0: if len(cluster_summaries) > 0:
cluster = cluster_summaries[0].cluster cluster = cluster_summaries[0].cluster
print("Selecting Cluster '{}' ({})".format(cluster_name, cluster)) print("Selecting Cluster '{}' ({})".format(cluster_name, cluster))
@ -71,13 +66,11 @@ def get_placement_spec_for_cluster(context):
folder_name = context.testbed.config['VM_FOLDER2_NAME'] folder_name = context.testbed.config['VM_FOLDER2_NAME']
folder_svc = Folder(context.stub_config)
filter = Folder.FilterSpec( filter = Folder.FilterSpec(
names=set([folder_name]), names=set([folder_name]),
datacenters=set([datacenter])) datacenters=set([datacenter]))
folder_summaries = folder_svc.list(filter=filter) folder_summaries = context.client.vcenter.Folder.list(filter=filter)
folder = None
if len(folder_summaries) > 0: if len(folder_summaries) > 0:
folder = folder_summaries[0].folder folder = folder_summaries[0].folder
print("Selecting Folder '{}' ({})".format(folder_name, folder)) print("Selecting Folder '{}' ({})".format(folder_name, folder))
@ -95,13 +88,11 @@ def get_placement_spec_for_cluster(context):
# TODO Parameterize based on NFS or VMFS # TODO Parameterize based on NFS or VMFS
datastore_name = context.testbed.config['NFS_DATASTORE_NAME'] datastore_name = context.testbed.config['NFS_DATASTORE_NAME']
datastore_svc = Datastore(context.stub_config)
filter = Datastore.FilterSpec( filter = Datastore.FilterSpec(
names=set([datastore_name]), names=set([datastore_name]),
datacenters=set([datacenter])) datacenters=set([datacenter]))
datastore_summaries = datastore_svc.list(filter=filter) datastore_summaries = context.client.vcenter.Datastore.list(filter=filter)
datastore = None
if len(datastore_summaries) > 0: if len(datastore_summaries) > 0:
datastore = datastore_summaries[0].datastore datastore = datastore_summaries[0].datastore
print("Selecting Datastore '{}' ({})".format(datastore_name, datastore)) print("Selecting Datastore '{}' ({})".format(datastore_name, datastore))
@ -122,11 +113,9 @@ def get_placement_spec_for_resource_pool(context):
datacenter_name = context.testbed.config['DATACENTER2_NAME'] datacenter_name = context.testbed.config['DATACENTER2_NAME']
datacenter = context.testbed.entities['DATACENTER_IDS'][datacenter_name] datacenter = context.testbed.entities['DATACENTER_IDS'][datacenter_name]
resource_pool_svc = ResourcePool(context.stub_config)
filter = ResourcePool.FilterSpec(datacenters=set([datacenter])) filter = ResourcePool.FilterSpec(datacenters=set([datacenter]))
resource_pool_summaries = resource_pool_svc.list(filter=filter) resource_pool_summaries = context.client.vcenter.ResourcePool.list(filter=filter)
resource_pool = None
if len(resource_pool_summaries) > 0: if len(resource_pool_summaries) > 0:
resource_pool = resource_pool_summaries[0].resource_pool resource_pool = resource_pool_summaries[0].resource_pool
print('Selecting ResourcePool ({})'.format(resource_pool)) print('Selecting ResourcePool ({})'.format(resource_pool))
@ -143,13 +132,11 @@ def get_placement_spec_for_resource_pool(context):
folder_name = context.testbed.config['VM_FOLDER2_NAME'] folder_name = context.testbed.config['VM_FOLDER2_NAME']
folder_svc = Folder(context.stub_config)
filter = Folder.FilterSpec( filter = Folder.FilterSpec(
names=set([folder_name]), names=set([folder_name]),
datacenters=set([datacenter])) datacenters=set([datacenter]))
folder_summaries = folder_svc.list(filter=filter) folder_summaries = context.client.vcenter.Folder.list(filter=filter)
folder = None
if len(folder_summaries) > 0: if len(folder_summaries) > 0:
folder = folder_summaries[0].folder folder = folder_summaries[0].folder
print("Selecting Folder '{}' ({})".format(folder_name, folder)) print("Selecting Folder '{}' ({})".format(folder_name, folder))
@ -166,13 +153,11 @@ def get_placement_spec_for_resource_pool(context):
# TODO Parameterize based on NFS or VMFS # TODO Parameterize based on NFS or VMFS
datastore_name = context.testbed.config['NFS_DATASTORE_NAME'] datastore_name = context.testbed.config['NFS_DATASTORE_NAME']
datastore_svc = Datastore(context.stub_config)
filter = Datastore.FilterSpec( filter = Datastore.FilterSpec(
names=set([datastore_name]), names=set([datastore_name]),
datacenters=set([datacenter])) datacenters=set([datacenter]))
datastore_summaries = datastore_svc.list(filter=filter) datastore_summaries = context.client.vcenter.Datastore.list(filter=filter)
datastore = None
if len(datastore_summaries) > 0: if len(datastore_summaries) > 0:
datastore = datastore_summaries[0].datastore datastore = datastore_summaries[0].datastore
print("Selecting Datastore '{}' ({})".format(datastore_name, datastore)) print("Selecting Datastore '{}' ({})".format(datastore_name, datastore))

View File

@ -2,7 +2,7 @@
""" """
* ******************************************************* * *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved. * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
* ******************************************************* * *******************************************************
* *
@ -14,18 +14,18 @@
""" """
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+' __vcenter_version__ = '6.5+'
import atexit
from com.vmware.vcenter.vm_client import Power from com.vmware.vcenter.vm_client import Power
from samples.vsphere.common import vapiconnect from vmware.vapi.vsphere.client import create_vsphere_client
from samples.vsphere.common.sample_util import parse_cli_args_vm from samples.vsphere.common.sample_util import parse_cli_args_vm
from samples.vsphere.common.sample_util import pp from samples.vsphere.common.sample_util import pp
from samples.vsphere.vcenter.setup import testbed from samples.vsphere.vcenter.setup import testbed
from samples.vsphere.vcenter.helper.vm_helper import get_vm from samples.vsphere.vcenter.helper.vm_helper import get_vm
from samples.vsphere.common.ssl_helper import get_unverified_session
""" """
Demonstrates the virtual machine power lifecycle Demonstrates the virtual machine power lifecycle
@ -36,78 +36,75 @@ The sample needs an existing VM.
vm = None vm = None
vm_name = None vm_name = None
stub_config = None client = None
vm_power_svc = None
cleardata = False cleardata = False
def setup(context=None): def setup(context=None):
global stub_config, cleardata, vm_name global client, cleardata, vm_name
if context: if context:
# Run sample suite via setup script # Run sample suite via setup script
vm_name = testbed.config['VM_NAME_DEFAULT'] vm_name = testbed.config['VM_NAME_DEFAULT']
stub_config = context.stub_config client = context.client
else: else:
# Run sample in standalone mode # Run sample in standalone mode
server, username, password, cleardata, skip_verification, vm_name = \ server, username, password, cleardata, skip_verification, vm_name = \
parse_cli_args_vm(testbed.config['VM_NAME_DEFAULT']) parse_cli_args_vm(testbed.config['VM_NAME_DEFAULT'])
stub_config = vapiconnect.connect(server, session = get_unverified_session() if skip_verification else None
username,
password, # Connect to vSphere client
skip_verification) client = create_vsphere_client(server=server,
atexit.register(vapiconnect.logout, stub_config) username=username,
password=password,
session=session)
def run(): def run():
global vm global vm
vm = get_vm(stub_config, vm_name) vm = get_vm(client, vm_name)
if not vm: if not vm:
raise Exception('Sample requires an existing vm with name ({}).' raise Exception('Sample requires an existing vm with name ({}).'
'Please create the vm first.'.format(vm_name)) 'Please create the vm first.'.format(vm_name))
print("Using VM '{}' ({}) for Power Sample".format(vm_name, vm)) print("Using VM '{}' ({}) for Power Sample".format(vm_name, vm))
# Create Power stub used for making requests
global vm_power_svc
vm_power_svc = Power(stub_config)
# Get the vm power state # Get the vm power state
print('\n# Example: Get current vm power state') print('\n# Example: Get current vm power state')
status = vm_power_svc.get(vm) status = client.vcenter.vm.Power.get(vm)
print('vm.Power.get({}) -> {}'.format(vm, pp(status))) print('vm.Power.get({}) -> {}'.format(vm, pp(status)))
# Power off the vm if it is on # Power off the vm if it is on
if status == Power.Info(state=Power.State.POWERED_ON): if status == Power.Info(state=Power.State.POWERED_ON):
print('\n# Example: VM is powered on, power it off') print('\n# Example: VM is powered on, power it off')
vm_power_svc.stop(vm) client.vcenter.vm.Power.stop(vm)
print('vm.Power.stop({})'.format(vm)) print('vm.Power.stop({})'.format(vm))
# Power on the vm # Power on the vm
print('# Example: Power on the vm') print('# Example: Power on the vm')
vm_power_svc.start(vm) client.vcenter.vm.Power.start(vm)
print('vm.Power.start({})'.format(vm)) print('vm.Power.start({})'.format(vm))
# Suspend the vm # Suspend the vm
print('\n# Example: Suspend the vm') print('\n# Example: Suspend the vm')
vm_power_svc.suspend(vm) client.vcenter.vm.Power.suspend(vm)
print('vm.Power.suspend({})'.format(vm)) print('vm.Power.suspend({})'.format(vm))
# Resume the vm # Resume the vm
print('\n# Example: Resume the vm') print('\n# Example: Resume the vm')
vm_power_svc.start(vm) client.vcenter.vm.Power.start(vm)
print('vm.Power.start({})'.format(vm)) print('vm.Power.start({})'.format(vm))
# Reset the vm # Reset the vm
print('\n# Example: Reset the vm') print('\n# Example: Reset the vm')
vm_power_svc.reset(vm) client.vcenter.vm.Power.reset(vm)
print('vm.Power.reset({})'.format(vm)) print('vm.Power.reset({})'.format(vm))
def cleanup(): def cleanup():
# Power off the vm # Power off the vm
print('\n# Cleanup: Power off the vm') print('\n# Cleanup: Power off the vm')
vm_power_svc.stop(vm) client.vcenter.vm.Power.stop(vm)
print('vm.Power.stop({})'.format(vm)) print('vm.Power.stop({})'.format(vm))
status = vm_power_svc.get(vm) status = client.vcenter.vm.Power.get(vm)
if status == Power.Info(state=Power.State.POWERED_OFF, if status == Power.Info(state=Power.State.POWERED_OFF,
clean_power_off=True): clean_power_off=True):
print('VM is powered off') print('VM is powered off')