Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Context support with Tests #508

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
181 changes: 181 additions & 0 deletions pyVim/context.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
# VMware vSphere Python SDK
# Copyright (c) 2008-2017 VMware, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

__author__ = "VMware, Inc."

import logging

from pyVim import connect

class Connection():
"""
A context connection object for use with pyVmomi that is thread-safe and multi-processor safe.


with context.Connection(host='my_host', pwd='my_password') as si:
content = si.RetrieveContent()

container = content.rootFolder # starting point to look into
viewType = [vim.VirtualMachine] # object types to look for
recursive = True # whether we should look into it recursively
containerView = content.viewManager.CreateContainerView(
container, viewType, recursive)

children = containerView.view
for child in children:
print("VM Name: ", child.summary.config.name)

"""

def __init__(self, host='localhost', port=443, user='root', pwd='',
service="hostd", adapter="SOAP", namespace=None, path="/sdk",
version=None, keyFile=None, certFile=None, thumbprint=None,
sslContext=None, b64token=None, mechanism='userpass'):
"""
Most values are optional. Specify the minimum values for your use case.
:param host: default 'localhost' specify your host here
:param port: default '443' specify only if different
:param user: default 'root' specify only if needed
:param pwd: default '' specify only if different
:param service: defaults to 'hostd' specify only if you need to
:param adapter: defaults to SOAP specify only if required to do so
:param namespace: default will be calculated on connection
:param path: defaults to /sdk only specify if you must
:param version: default calculates the highest version number SDK + Host can use together
:param keyFile: specify only if using self-signed PEM key files
:param certFile: specify only if using self-signed certs
:param thumbprint: specify only if overriding based on known SSL thumbprints
:param sslContext: specify only if you are overriding default SSL context behaviors
:param b64token: specify if you have a Token such as the HoK Token
:param mechanism: specify as either 'userpass' or 'sspi'
"""
self.si = None
self.open_count = 0
self.host = host
self.port = port
self.user = user
self.pwd = pwd
self.service = service
self.adapter = adapter
self.namespace = namespace
self.path = path
self.version = version
self.keyFile = keyFile
self.certFile = certFile
self.thumbprint = thumbprint
self.sslContext = sslContext
self.b64token = b64token
self.mechanism = mechanism

def __enter__(self):
self.open_count += 1
if self.si is not None:
return self.si
self.si = open(host=self.host, port=self.port, user=self.user, pwd=self.pwd, service=self.service,
adapter=self.adapter, namespace=self.namespace, path=self.path, version=self.version,
keyFile=self.keyFile, certFile=self.certFile, thumbprint=self.thumbprint,
sslContext=self.sslContext, b64token=self.b64token, mechanism=self.mechanism)
return self.si

def __exit__(self, *args):
if (self.open_count == 1):
close(self.si)
self.si = None
self.open_count -= 1
return


def open(host='localhost', port=443, user='root', pwd='',
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems open and close functions are similar as Connect/Disconnect in connect.py beside SetSi(). I wonder if it's better to add these two methods in connect.py so we could reuse the existing logic?

service="hostd", adapter="SOAP", namespace=None, path="/sdk",
version=None, keyFile=None, certFile=None, thumbprint=None,
sslContext=None, b64token=None, mechanism='userpass'):
"""
Parallel processing friendly version of connect creates a new service instance on each call. This means you have
to be very careful to close the session in your process or else you will create orphaned sessions on the server.

:param host: vSphere host to connect to
:param port: port number if not 443
:param user: username if not root
:param pwd: password if not blank
:param service: service name if not hostd
:param adapter: adapter type if not SOAP
:param namespace: namespace if not None or global default namespace
:param path: if not the default /sdk specify here
:param version: specify a version if not the server's default
:param keyFile: specify a special SSL key file here
:param certFile: specify a special cert file here
:param thumbprint: allow a thumbprint override
:param sslContext: or ... optionally define an SSL context
:param b64token: or ... define a base 64 key token (ie: HOK token)
:param mechanism: either the default username/password as 'userpass' or 'sspi'
:return: your own copy of a session instance ... remember to close when finished!
"""
logging.debug("opening connection to vsphere")

try:
info = connect.re.match(connect._rx, host)
if info is not None:
host = info.group(1)
if host[0] == '[':
host = info.group(1)[1:-1]
if info.group(2) is not None:
port = int(info.group(2)[1:])
except ValueError as ve:
logging.info(ve)
pass

sslContext = connect.localSslFixup(host, sslContext)

if namespace:
assert (version is None)
version = connect.versionMap[namespace]
elif not version:
version = "vim.version.version6"

logging.debug("debug racksim.tools.async.open: active version = %(version)s", version=version)

si, stub = None, None
if mechanism == 'userpass':
si, stub = connect.__Login(host, port, user, pwd, service, adapter, version, path,
keyFile, certFile, thumbprint, sslContext)
elif mechanism == 'sspi':
si, stub = connect.__LoginBySSPI(host, port, service, adapter, version, path,
keyFile, certFile, thumbprint, sslContext, b64token)
else:
raise Exception('''The provided connection mechanism is not available, the
supported mechanisms are userpass or sspi''')

logging.debug("debug racksim.tools.async.open: connection complete.")

return si


def close(si):
"""

:param si: the session instance aka connection instance
:return:
"""
logging.debug("disconnecting connection session key %(key)s", key=si.content.sessionManager.currentSession.key)
try:
if si:
content = si.RetrieveContent()
content.sessionManager.Logout()
except Exception as e:
logging.exception("Logout action returned error: %s", e)
pass

logging.debug("disconnected session")
return
6 changes: 6 additions & 0 deletions tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import logging
import os
import socket
import ssl
import unittest

import vcr
Expand Down Expand Up @@ -46,3 +47,8 @@ def setUp(self):
logging.basicConfig()
vcr_log = logging.getLogger('vcr')
vcr_log.setLevel(logging.DEBUG)

sslContext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
sslContext.verify_mode = ssl.CERT_NONE

test_pwd = 'my_password'
Loading