Skip to content

Commit 4d36739

Browse files
authored
Merge pull request #262 from anusha94/master
7.0U2 readiness
2 parents 6e5f740 + 6fc10a7 commit 4d36739

File tree

3 files changed

+306
-4
lines changed

3 files changed

+306
-4
lines changed

README.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ samples require the vSphere Management SDK packages (pyVmomi) to be installed on
2121
The samples have been developed to work with python 2.7.x and 3.3+
2222

2323
## Supported OnPrem vCenter Releases
24-
vCenter 6.0, 6.5, 6.7, 7.0 and 7.0U1.
24+
vCenter 6.0, 6.5, 6.7, 7.0, 7.0U1 and 7.0U2.
2525
Certain APIs and samples that are introduced in 6.5 release, such as vCenter, Virtual Machine and Appliance Management. Please refer to the notes in each sample for detailed compatibility information.
2626

2727
## Supported NSX-T Releases
@@ -214,8 +214,8 @@ $ python samples/vsphere/vcenter/vm/list_vms.py -v
214214
### vSphere API Documentation
215215

216216
* [VMware Cloud on AWS vSphere (latest version)](https://vmware.github.io/vsphere-automation-sdk-python/vsphere/cloud/index.html)
217-
* [vSphere 7.0 Update 1 (latest)](https://vmware.github.io/vsphere-automation-sdk-python/vsphere/7.0.1.0/)
218-
* Previous releases: [7.0](https://vmware.github.io/vsphere-automation-sdk-python/vsphere/7.0.0.1/) [6.7.0](https://vmware.github.io/vsphere-automation-sdk-python/vsphere/6.7.0) [6.6.1](https://vmware.github.io/vsphere-automation-sdk-python/vsphere/6.6.1) [6.5](https://vmware.github.io/vsphere-automation-sdk-python/vsphere/6.5) [6.0](https://vmware.github.io/vsphere-automation-sdk-python/vsphere/6.0)
217+
* [vSphere 7.0 Update 2 (latest)](https://vmware.github.io/vsphere-automation-sdk-python/vsphere/7.0.2.0/)
218+
* Previous releases: [7.0 U1](https://vmware.github.io/vsphere-automation-sdk-python/vsphere/7.0.1.0/) [7.0](https://vmware.github.io/vsphere-automation-sdk-python/vsphere/7.0.0.1/) [6.7.0](https://vmware.github.io/vsphere-automation-sdk-python/vsphere/6.7.0) [6.6.1](https://vmware.github.io/vsphere-automation-sdk-python/vsphere/6.6.1) [6.5](https://vmware.github.io/vsphere-automation-sdk-python/vsphere/6.5) [6.0](https://vmware.github.io/vsphere-automation-sdk-python/vsphere/6.0)
219219

220220
### VMware Cloud on AWS API Documentation
221221

Lines changed: 302 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,302 @@
1+
#!/usr/bin/env python
2+
3+
"""
4+
* *******************************************************
5+
* Copyright (c) VMware, Inc. 2020. All Rights Reserved.
6+
* SPDX-License-Identifier: MIT
7+
* *******************************************************
8+
*
9+
* DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT
10+
* WARRANTIES OR CONDITIONS OF ANY KIND, WHETHER ORAL OR WRITTEN,
11+
* EXPRESS OR IMPLIED. THE AUTHOR SPECIFICALLY DISCLAIMS ANY IMPLIED
12+
* WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY,
13+
* NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
14+
"""
15+
16+
__author__ = 'VMware Inc.'
17+
__vcenter_version__ = 'VCenter 7.0 U2'
18+
19+
import os
20+
import ssl
21+
import time
22+
23+
from com.vmware.vcenter.vm.guest.filesystem_client import Transfers
24+
from com.vmware.vcenter.vm.guest_client import Credentials
25+
from com.vmware.vcenter.vm.guest_client import Processes
26+
from com.vmware.vcenter_client import VM
27+
from samples.vsphere.common import sample_cli
28+
from samples.vsphere.common import sample_util
29+
from samples.vsphere.common.ssl_helper import get_unverified_session
30+
from vmware.vapi.vsphere.client import create_vsphere_client
31+
32+
try:
33+
# Python 3
34+
from urllib.parse import urlparse
35+
import http.client as httpclient
36+
except ImportError:
37+
# Python 2
38+
from urlparse import urlparse
39+
import httplib as httpclient
40+
41+
42+
class GuestOps(object):
43+
"""
44+
Demonstrate the vAPI Guest Operations.
45+
46+
Show the basic procedure to start a program or process on a Linux
47+
guest VM and collect any output:
48+
- create a temporary directory and temporary files for the process
49+
stdout and stderr.
50+
- upload a script to the guest.
51+
- execute the script and collect the output.
52+
53+
Prerequisites:
54+
- vCenter
55+
- ESX host
56+
- running guest 'Photon-3.2-64-EFI-Open-VM-Tools-for-GuestOps-SDK'
57+
with open-vm-tools installed and running. The testbed created by
58+
samples/vsphere/vcenter/setup/main.py does not contain a guest
59+
with a runnable Linux or Windows OS.
60+
"""
61+
62+
# Create the Process.CreateSpec for initiating processes in the guest
63+
def _process_create_spec(self, path, args=None, dir=None, env={}):
64+
return Processes.CreateSpec(path=path,
65+
arguments=args,
66+
working_directory=dir,
67+
environment_variables=env)
68+
69+
# Create the Transfer.CreateSpec for the file transfer to/from the guest
70+
def _create_transfer_spec(self,
71+
path,
72+
attributes=None):
73+
return Transfers.CreateSpec(attributes=attributes,
74+
path=path)
75+
76+
# Create a FileAttributeCreateSpec for a generic (non-OS specific) guest
77+
def _fileAttributeCreateSpec_Plain(self,
78+
size,
79+
overwrite=None,
80+
last_modified=None,
81+
last_accessed=None):
82+
return Transfers.FileCreationAttributes(size,
83+
overwrite=overwrite,
84+
last_modified=last_modified,
85+
last_accessed=last_accessed)
86+
87+
# Create a FileAttributeCreateSpec for a linux (Posix) guest
88+
def _fileAttributeCreateSpec_Linux(self,
89+
size,
90+
overwrite=None,
91+
last_modified=None,
92+
last_accessed=None,
93+
owner_id=None,
94+
group_id=None,
95+
permissions=None):
96+
posix = Transfers.PosixFileAttributesCreateSpec(owner_id=owner_id,
97+
group_id=group_id,
98+
permissions=permissions)
99+
return Transfers.FileCreationAttributes(size,
100+
overwrite=overwrite,
101+
last_modified=last_modified,
102+
last_accessed=last_accessed,
103+
posix=posix)
104+
105+
def _download(self,
106+
url,
107+
expectedLen=None):
108+
urloptions = urlparse(url)
109+
# Skip server cert verification.
110+
# This is not recommended in production code.
111+
conn = httpclient.HTTPSConnection(urloptions.netloc,
112+
context=ssl._create_unverified_context())
113+
114+
conn.request("GET", urloptions.path + "?" + urloptions.query)
115+
res = conn.getresponse()
116+
if res.status != 200:
117+
print("GET request failed with errorcode : %s" % res.status)
118+
raise HTTPError(res.status, res.reason)
119+
body = res.read().decode()
120+
121+
return body
122+
123+
def _upload(self, url, body):
124+
urloptions = urlparse(url)
125+
conn = httpclient.HTTPSConnection(urloptions.netloc,
126+
context=ssl._create_unverified_context())
127+
128+
headers = {"Content-Length": len(body)}
129+
# Skip server cert verification.
130+
# This is not recommended in production code.
131+
conn.request("PUT", urloptions.path + "?" + urloptions.query,
132+
body,
133+
headers)
134+
res = conn.getresponse()
135+
if res.status != 200:
136+
print("PUT request failed with errorcode : %s" % res.status)
137+
raise HTTPError(res.status, res.reason)
138+
139+
return res
140+
141+
def __init__(self):
142+
# Create argument parser for standard inputs:
143+
# server, username, password, cleanup and skipverification
144+
parser = sample_cli.build_arg_parser()
145+
146+
# Add your custom input arguments
147+
parser.add_argument('--vm_name',
148+
action='store',
149+
help='Name of the testing vm')
150+
parser.add_argument('--root_user',
151+
action='store',
152+
help='Administrator account user name')
153+
parser.add_argument('--root_passwd',
154+
action='store',
155+
help='Administrator account password')
156+
157+
args = sample_util.process_cli_args(parser.parse_args())
158+
self.vm_name = args.vm_name
159+
self.root_user = args.root_user
160+
self.root_passwd = args.root_passwd
161+
162+
self.cleardata = args.cleardata
163+
164+
# Skip server cert verification if needed.
165+
# This is not recommended in production code.
166+
session = get_unverified_session() if args.skipverification else None
167+
168+
# Connect to vSphere client
169+
self.client = create_vsphere_client(server=args.server,
170+
username=args.username,
171+
password=args.password,
172+
session=session)
173+
174+
def run(self):
175+
# Using vAPI to find VM.
176+
filter_spec = VM.FilterSpec(names=set([self.vm_name]))
177+
vms = self.client.vcenter.VM.list(filter_spec)
178+
if len(vms) != 1:
179+
raise Exception('Could not locate the required VM with name ' +
180+
self.vm_name + '. Please create the vm first.')
181+
if vms[0].power_state != 'POWERED_ON':
182+
raise Exception('VM is not powered on: ' + vms[0].power_state)
183+
vm_id = vms[0].vm
184+
185+
# Check that vmtools svc (non-interactive user) is running.
186+
info = self.client.vcenter.vm.guest.Operations.get(vm_id)
187+
if info.guest_operations_ready is not True:
188+
raise Exception('VMware Tools/open-vm-tools is not running as required.')
189+
190+
# Establish the user credentials that will be needed for all Guest Ops
191+
# APIs.
192+
creds = Credentials(interactive_session=False,
193+
user_name=self.root_user,
194+
password=self.root_passwd,
195+
type=Credentials.Type.USERNAME_PASSWORD)
196+
197+
# Step 2 - Create a temporary directory from which to run the command
198+
# and capture any output
199+
tempDir = self.client.vcenter.vm.guest.filesystem.Directories.create_temporary(
200+
vm_id, creds, '', '', parent_path=None)
201+
202+
# Step 3 - Create temproary files to reveive stdout and stderr
203+
# as needed.
204+
stdout = self.client.vcenter.vm.guest.filesystem.Files.create_temporary(
205+
vm_id, creds, '', '.stdout', parent_path=tempDir)
206+
stderr = self.client.vcenter.vm.guest.filesystem.Files.create_temporary(
207+
vm_id, creds, '', '.stderr', parent_path=tempDir)
208+
209+
# Step 4 - (Optional) copy in the script to be run.
210+
# While optional, using this step to demo tranfer of a
211+
# file to a guest.
212+
scriptPath = self.client.vcenter.vm.guest.filesystem.Files.create_temporary(
213+
vm_id, creds, '', '.sh', tempDir)
214+
215+
# Create script contents and transfer to the guest.
216+
# TODO: Need generic pick up of script content
217+
baseFN = os.path.basename(scriptPath)
218+
script = ('#! /bin/bash\n'
219+
'# ' +
220+
baseFN + '\n'
221+
'\n'
222+
'sleep 5 # Adding a little length to the process.\n'
223+
'ps -ef\n'
224+
'echo\n'
225+
'rpm -qa | sort\n'
226+
'\n')
227+
print(script)
228+
attr = self._fileAttributeCreateSpec_Linux(size=len(script),
229+
overwrite=True,
230+
permissions='0755')
231+
spec = self._create_transfer_spec(path=scriptPath,
232+
attributes=attr)
233+
toURL = self.client.vcenter.vm.guest.filesystem.Transfers.create(vm_id,
234+
creds,
235+
spec)
236+
res = self._upload(toURL, script)
237+
238+
# Check that the uploaded file size is correct.
239+
info = self.client.vcenter.vm.guest.filesystem.Files.get(vm_id,
240+
creds,
241+
scriptPath)
242+
if info.size != len(script):
243+
raise Exception('Uploaded file size not as epected.')
244+
245+
# Step 5 - Start the program on the guest, capturing stdout and stderr
246+
# in the separate temp files obtained earlier.
247+
options = (" > " + stdout + " 2> " + stderr)
248+
249+
spec = self._process_create_spec(scriptPath,
250+
args=options,
251+
dir=tempDir)
252+
pid = self.client.vcenter.vm.guest.Processes.create(vm_id, creds, spec)
253+
print('process created with pid: %s\n' % pid)
254+
255+
# Step 6
256+
# Need a loop to wait for the process to finish to handle longer
257+
# running processes.
258+
while True:
259+
time.sleep(1.0)
260+
try:
261+
# List the single process for pid.
262+
result = self.client.vcenter.vm.guest.Processes.get(vm_id,
263+
creds,
264+
pid)
265+
if result.exit_code is not None:
266+
print('Command: ' + result.command)
267+
print('Exit code: %s\n' % result.exit_code)
268+
break
269+
if result.finished is None:
270+
print('Process with pid %s is still running.' % pid)
271+
continue
272+
except Exception as e:
273+
raise e
274+
275+
# Step 7 Copy out the results (stdout).
276+
spec = self._create_transfer_spec(path=stdout)
277+
# create the download URL
278+
fromURL = self.client.vcenter.vm.guest.filesystem.Transfers.create(vm_id,
279+
creds,
280+
spec)
281+
body = self._download(fromURL, expectedLen=info.size)
282+
print("----------- stdout ------------------")
283+
print(body)
284+
print("---------------------------------------")
285+
286+
# Optionally the contents of "stderr" could be downloaded.
287+
288+
# And finally, clean up the temporary files and directories on the
289+
# Linux guest. Deleting the temporary diretory and its contents.
290+
self.client.vcenter.vm.guest.filesystem.Directories.delete(vm_id,
291+
creds,
292+
tempDir,
293+
recursive=True)
294+
295+
296+
def main():
297+
sample = GuestOps()
298+
sample.run()
299+
300+
301+
if __name__ == '__main__':
302+
main()

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from setuptools import setup
66

77
setup(name='vSphere Automation SDK',
8-
version='1.49.0',
8+
version='1.50.0',
99
description='VMware vSphere Automation SDK for Python',
1010
url='https://github.com/vmware/vsphere-automation-sdk-python',
1111
author='VMware, Inc.',

0 commit comments

Comments
 (0)