Refactor the PBM support
Having a Pbm class that inherits from Vim is a design mistake that we need to fix before start using Pbm features in other projects like Nova. This patch introduces a new base class 'Service' which provides common functionality for invoking vSphere APIs and both Vim and Pbm inherit from it. That will allow to further evolve our APIs and add features which are specific to only Vim or Pbm. Existing clients which use the Vim object through VMwareAPISession are not impacted by this change. The interface of VMwareAPISession is unchanged. Change-Id: Icf54e3d0305b30c73d0ff7d9c85da1893392c3aa
This commit is contained in:
parent
bcf2ff400c
commit
1dc80c7f85
@ -180,21 +180,21 @@ class VMwareAPISession(object):
|
||||
self._vim = vim.Vim(protocol=self._scheme,
|
||||
host=self._host,
|
||||
port=self._port,
|
||||
wsdl_loc=self._vim_wsdl_loc)
|
||||
wsdl_url=self._vim_wsdl_loc)
|
||||
return self._vim
|
||||
|
||||
@property
|
||||
def pbm(self):
|
||||
if not self._pbm and self._pbm_wsdl_loc:
|
||||
self._pbm = pbm.PBMClient(self._pbm_wsdl_loc,
|
||||
protocol=self._scheme,
|
||||
host=self._host,
|
||||
port=self._port)
|
||||
self._pbm = pbm.Pbm(protocol=self._scheme,
|
||||
host=self._host,
|
||||
port=self._port,
|
||||
wsdl_url=self._pbm_wsdl_loc)
|
||||
if self._session_id:
|
||||
# To handle the case where pbm property is accessed after
|
||||
# session creation. If pbm property is accessed before session
|
||||
# creation, we set the cookie in _create_session.
|
||||
self._pbm.set_cookie(self._get_session_cookie())
|
||||
self._pbm.set_soap_cookie(self._vim.get_http_cookie())
|
||||
return self._pbm
|
||||
|
||||
@RetryDecorator(exceptions=(exceptions.VimConnectionException,))
|
||||
@ -238,7 +238,7 @@ class VMwareAPISession(object):
|
||||
|
||||
# Set PBM client cookie.
|
||||
if self._pbm is not None:
|
||||
self._pbm.set_cookie(self._get_session_cookie())
|
||||
self._pbm.set_soap_cookie(self._vim.get_http_cookie())
|
||||
|
||||
def logout(self):
|
||||
"""Log out and terminate the current session."""
|
||||
@ -487,14 +487,3 @@ class VMwareAPISession(object):
|
||||
lease,
|
||||
exc_info=True)
|
||||
return "Unknown"
|
||||
|
||||
def _get_session_cookie(self):
|
||||
"""Get the cookie corresponding to the current session.
|
||||
|
||||
:returns: cookie corresponding to the current session
|
||||
"""
|
||||
cookies = self.vim.client.options.transport.cookiejar
|
||||
for c in cookies:
|
||||
if c.name.lower() == 'vmware_soap_session':
|
||||
return c.value
|
||||
return None
|
||||
|
@ -14,61 +14,57 @@
|
||||
# under the License.
|
||||
|
||||
"""
|
||||
VMware PBM client and PBM related utility methods
|
||||
VMware PBM service client and PBM related utility methods
|
||||
|
||||
PBM is used for policy based placement in VMware datastores.
|
||||
Refer http://goo.gl/GR2o6U for more details.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import suds
|
||||
import suds.sax.element as element
|
||||
|
||||
from oslo.vmware import vim
|
||||
from oslo.vmware import service
|
||||
from oslo.vmware import vim_util
|
||||
|
||||
|
||||
SERVICE_INSTANCE = 'ServiceInstance'
|
||||
SERVICE_TYPE = 'PbmServiceInstance'
|
||||
|
||||
LOG = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class PBMClient(vim.Vim):
|
||||
"""SOAP based PBM client."""
|
||||
class Pbm(service.Service):
|
||||
"""Service class that provides access to the Storage Policy API."""
|
||||
|
||||
def __init__(self, pbm_wsdl_loc, protocol='https', host='localhost',
|
||||
port=443):
|
||||
"""Constructs a PBM client object.
|
||||
def __init__(self, protocol='https', host='localhost', port=443,
|
||||
wsdl_url=None):
|
||||
"""Constructs a PBM service client object.
|
||||
|
||||
:param pbm_wsdl_loc: PBM WSDL file location
|
||||
:param protocol: http or https
|
||||
:param host: server IP address or host name
|
||||
:param port: port for connection
|
||||
:param wsdl_url: PBM WSDL url
|
||||
"""
|
||||
self._url = vim_util.get_soap_url(protocol, host, port, 'pbm')
|
||||
self._pbm_client = suds.client.Client(pbm_wsdl_loc, location=self._url)
|
||||
self._pbm_service_content = None
|
||||
base_url = service.Service.build_base_url(protocol, host, port)
|
||||
soap_url = base_url + '/pbm'
|
||||
super(Pbm, self).__init__(wsdl_url, soap_url)
|
||||
|
||||
def set_cookie(self, cookie):
|
||||
"""Set the authenticated VIM session's cookie in the SOAP client.
|
||||
def set_soap_cookie(self, cookie):
|
||||
"""Set the specified vCenter session cookie in the SOAP header
|
||||
|
||||
:param cookie: cookie to set
|
||||
"""
|
||||
elem = element.Element('vcSessionCookie').setText(cookie)
|
||||
self._pbm_client.set_options(soapheaders=elem)
|
||||
self.client.set_options(soapheaders=elem)
|
||||
|
||||
@property
|
||||
def client(self):
|
||||
return self._pbm_client
|
||||
def retrieve_service_content(self):
|
||||
ref = vim_util.get_moref(service.SERVICE_INSTANCE, SERVICE_TYPE)
|
||||
return self.PbmRetrieveServiceContent(ref)
|
||||
|
||||
@property
|
||||
def service_content(self):
|
||||
if not self._pbm_service_content:
|
||||
si_moref = vim_util.get_moref(SERVICE_INSTANCE, SERVICE_TYPE)
|
||||
self._pbm_service_content = (
|
||||
self._pbm_client.service.PbmRetrieveServiceContent(si_moref))
|
||||
return self._pbm_service_content
|
||||
def __repr__(self):
|
||||
return "PBM Object"
|
||||
|
||||
def __str__(self):
|
||||
return "PBM Object"
|
||||
|
||||
|
||||
def get_all_profiles(session):
|
||||
|
246
oslo/vmware/service.py
Normal file
246
oslo/vmware/service.py
Normal file
@ -0,0 +1,246 @@
|
||||
# Copyright (c) 2014 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.
|
||||
|
||||
"""
|
||||
Common classes that provide access to vSphere services.
|
||||
"""
|
||||
|
||||
import httplib
|
||||
import logging
|
||||
import netaddr
|
||||
import urllib2
|
||||
|
||||
import six
|
||||
import suds
|
||||
|
||||
from oslo.vmware import exceptions
|
||||
from oslo.vmware.openstack.common.gettextutils import _
|
||||
from oslo.vmware.openstack.common.gettextutils import _LE
|
||||
from oslo.vmware import vim_util
|
||||
|
||||
|
||||
ADDRESS_IN_USE_ERROR = 'Address already in use'
|
||||
CONN_ABORT_ERROR = 'Software caused connection abort'
|
||||
RESP_NOT_XML_ERROR = 'Response is "text/html", not "text/xml"'
|
||||
|
||||
SERVICE_INSTANCE = 'ServiceInstance'
|
||||
|
||||
LOG = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ServiceMessagePlugin(suds.plugin.MessagePlugin):
|
||||
"""Suds plug-in handling some special cases while calling VI SDK."""
|
||||
|
||||
def add_attribute_for_value(self, node):
|
||||
"""Helper to handle AnyType.
|
||||
|
||||
Suds does not handle AnyType properly. But VI SDK requires type
|
||||
attribute to be set when AnyType is used.
|
||||
|
||||
:param node: XML value node
|
||||
"""
|
||||
if node.name == 'value':
|
||||
node.set('xsi:type', 'xsd:string')
|
||||
|
||||
def marshalled(self, context):
|
||||
"""Modifies the envelope document before it is sent.
|
||||
|
||||
This method provides the plug-in with the opportunity to prune empty
|
||||
nodes and fix nodes before sending it to the server.
|
||||
|
||||
:param context: send context
|
||||
"""
|
||||
# Suds builds the entire request object based on the WSDL schema.
|
||||
# VI SDK throws server errors if optional SOAP nodes are sent
|
||||
# without values; e.g., <test/> as opposed to <test>test</test>.
|
||||
context.envelope.prune()
|
||||
context.envelope.walk(self.add_attribute_for_value)
|
||||
|
||||
|
||||
class Service(object):
|
||||
"""Base class containing common functionality for invoking vSphere
|
||||
services
|
||||
"""
|
||||
|
||||
def __init__(self, wsdl_url=None, soap_url=None):
|
||||
self.wsdl_url = wsdl_url
|
||||
self.soap_url = soap_url
|
||||
LOG.debug("Creating suds client with soap_url='%s' and wsdl_url='%s'",
|
||||
self.soap_url, self.wsdl_url)
|
||||
self.client = suds.client.Client(self.wsdl_url,
|
||||
location=self.soap_url,
|
||||
plugins=[ServiceMessagePlugin()])
|
||||
self._service_content = None
|
||||
|
||||
@staticmethod
|
||||
def build_base_url(protocol, host, port):
|
||||
proto_str = '%s://' % protocol
|
||||
host_str = '[%s]' % host if netaddr.valid_ipv6(host) else host
|
||||
port_str = '' if port is None else ':%d' % port
|
||||
return proto_str + host_str + port_str
|
||||
|
||||
@staticmethod
|
||||
def _retrieve_properties_ex_fault_checker(response):
|
||||
"""Checks the RetrievePropertiesEx API response for errors.
|
||||
|
||||
Certain faults are sent in the SOAP body as a property of missingSet.
|
||||
This method raises VimFaultException when a fault is found in the
|
||||
response.
|
||||
|
||||
:param response: response from RetrievePropertiesEx API call
|
||||
:raises: VimFaultException
|
||||
"""
|
||||
# TODO(rgerganov) this method doesn't belong here because this fault
|
||||
# checking is specific to the Vim service. We should come up with
|
||||
# a new design that allows extensible fault checking and have the
|
||||
# service specific parts in the corresponding child classes
|
||||
|
||||
LOG.debug("Checking RetrievePropertiesEx API response for faults.")
|
||||
fault_list = []
|
||||
if not response:
|
||||
# This is the case when the session has timed out. ESX SOAP
|
||||
# server sends an empty RetrievePropertiesExResponse. Normally
|
||||
# missingSet in the response objects has the specifics about
|
||||
# the error, but that's not the case with a timed out idle
|
||||
# session. It is as bad as a terminated session for we cannot
|
||||
# use the session. Therefore setting fault to NotAuthenticated
|
||||
# fault.
|
||||
LOG.debug("RetrievePropertiesEx API response is empty; setting "
|
||||
"fault to %s.",
|
||||
exceptions.NOT_AUTHENTICATED)
|
||||
fault_list = [exceptions.NOT_AUTHENTICATED]
|
||||
else:
|
||||
for obj_cont in response.objects:
|
||||
if hasattr(obj_cont, 'missingSet'):
|
||||
for missing_elem in obj_cont.missingSet:
|
||||
fault_type = missing_elem.fault.fault.__class__
|
||||
fault_list.append(fault_type.__name__)
|
||||
if fault_list:
|
||||
LOG.error(_LE("Faults %s found in RetrievePropertiesEx API "
|
||||
"response."),
|
||||
fault_list)
|
||||
raise exceptions.VimFaultException(fault_list,
|
||||
_("Error occurred while calling"
|
||||
" RetrievePropertiesEx."))
|
||||
LOG.debug("No faults found in RetrievePropertiesEx API response.")
|
||||
|
||||
@property
|
||||
def service_content(self):
|
||||
if self._service_content is None:
|
||||
self._service_content = self.retrieve_service_content()
|
||||
return self._service_content
|
||||
|
||||
def get_http_cookie(self):
|
||||
"""Return the vCenter session cookie."""
|
||||
cookies = self.client.options.transport.cookiejar
|
||||
for cookie in cookies:
|
||||
if cookie.name.lower() == 'vmware_soap_session':
|
||||
return cookie.value
|
||||
|
||||
def __getattr__(self, attr_name):
|
||||
"""Returns the method to invoke API identified by param attr_name."""
|
||||
|
||||
def request_handler(managed_object, **kwargs):
|
||||
"""Handler for vSphere API calls.
|
||||
|
||||
Invokes the API and parses the response for fault checking and
|
||||
other errors.
|
||||
|
||||
:param managed_object: managed object reference argument of the
|
||||
API call
|
||||
:param kwargs: keyword arguments of the API call
|
||||
:returns: response of the API call
|
||||
:raises: VimException, VimFaultException, VimAttributeException,
|
||||
VimSessionOverLoadException, VimConnectionException
|
||||
"""
|
||||
try:
|
||||
if isinstance(managed_object, str):
|
||||
# For strings, use string value for value and type
|
||||
# of the managed object.
|
||||
managed_object = vim_util.get_moref(managed_object,
|
||||
managed_object)
|
||||
if managed_object is None:
|
||||
return
|
||||
request = getattr(self.client.service, attr_name)
|
||||
LOG.debug("Invoking %(attr_name)s on %(moref)s.",
|
||||
{'attr_name': attr_name,
|
||||
'moref': managed_object})
|
||||
response = request(managed_object, **kwargs)
|
||||
if (attr_name.lower() == 'retrievepropertiesex'):
|
||||
Service._retrieve_properties_ex_fault_checker(response)
|
||||
LOG.debug("Invocation of %(attr_name)s on %(moref)s "
|
||||
"completed successfully.",
|
||||
{'attr_name': attr_name,
|
||||
'moref': managed_object})
|
||||
return response
|
||||
except exceptions.VimFaultException:
|
||||
# Catch the VimFaultException that is raised by the fault
|
||||
# check of the SOAP response.
|
||||
raise
|
||||
|
||||
except suds.WebFault as excep:
|
||||
doc = excep.document
|
||||
fault_string = doc.childAtPath("/Envelope/Body/Fault/"
|
||||
"faultstring").getText()
|
||||
detail = doc.childAtPath('/Envelope/Body/Fault/detail')
|
||||
fault_list = []
|
||||
details = {}
|
||||
if detail:
|
||||
for fault in detail.getChildren():
|
||||
fault_list.append(fault.get("type"))
|
||||
for child in fault.getChildren():
|
||||
details[child.name] = child.getText()
|
||||
raise exceptions.VimFaultException(fault_list, fault_string,
|
||||
excep, details)
|
||||
|
||||
except AttributeError as excep:
|
||||
raise exceptions.VimAttributeException(
|
||||
_("No such SOAP method %s.") % attr_name, excep)
|
||||
|
||||
except (httplib.CannotSendRequest,
|
||||
httplib.ResponseNotReady,
|
||||
httplib.CannotSendHeader) as excep:
|
||||
raise exceptions.VimSessionOverLoadException(
|
||||
_("httplib error in %s.") % attr_name, excep)
|
||||
|
||||
except (urllib2.URLError, urllib2.HTTPError) as excep:
|
||||
raise exceptions.VimConnectionException(
|
||||
_("urllib2 error in %s.") % attr_name, excep)
|
||||
|
||||
except Exception as excep:
|
||||
# TODO(vbala) should catch specific exceptions and raise
|
||||
# appropriate VimExceptions.
|
||||
|
||||
# Socket errors which need special handling; some of these
|
||||
# might be caused by server API call overload.
|
||||
if (six.text_type(excep).find(ADDRESS_IN_USE_ERROR) != -1 or
|
||||
six.text_type(excep).find(CONN_ABORT_ERROR)) != -1:
|
||||
raise exceptions.VimSessionOverLoadException(
|
||||
_("Socket error in %s.") % attr_name, excep)
|
||||
# Type error which needs special handling; it might be caused
|
||||
# by server API call overload.
|
||||
elif six.text_type(excep).find(RESP_NOT_XML_ERROR) != -1:
|
||||
raise exceptions.VimSessionOverLoadException(
|
||||
_("Type error in %s.") % attr_name, excep)
|
||||
else:
|
||||
raise exceptions.VimException(
|
||||
_("Exception in %s.") % attr_name, excep)
|
||||
return request_handler
|
||||
|
||||
def __repr__(self):
|
||||
return "vSphere object"
|
||||
|
||||
def __str__(self):
|
||||
return "vSphere object"
|
@ -13,240 +13,34 @@
|
||||
# License for the specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
"""
|
||||
Classes for making VMware VI SOAP calls.
|
||||
"""
|
||||
|
||||
import httplib
|
||||
import logging
|
||||
import urllib2
|
||||
|
||||
import six
|
||||
import suds
|
||||
|
||||
from oslo.vmware import exceptions
|
||||
from oslo.vmware.openstack.common.gettextutils import _, _LE
|
||||
from oslo.vmware import vim_util
|
||||
from oslo.vmware import service
|
||||
|
||||
|
||||
ADDRESS_IN_USE_ERROR = 'Address already in use'
|
||||
CONN_ABORT_ERROR = 'Software caused connection abort'
|
||||
RESP_NOT_XML_ERROR = "Response is 'text/html', not 'text/xml'"
|
||||
|
||||
LOG = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class VimMessagePlugin(suds.plugin.MessagePlugin):
|
||||
"""Suds plug-in handling some special cases while calling VI SDK."""
|
||||
|
||||
def add_attribute_for_value(self, node):
|
||||
"""Helper to handle AnyType.
|
||||
|
||||
Suds does not handle AnyType properly. But VI SDK requires type
|
||||
attribute to be set when AnyType is used.
|
||||
|
||||
:param node: XML value node
|
||||
"""
|
||||
if node.name == 'value':
|
||||
node.set('xsi:type', 'xsd:string')
|
||||
|
||||
def marshalled(self, context):
|
||||
"""Modifies the envelope document before it is sent.
|
||||
|
||||
This method provides the plug-in with the opportunity to prune empty
|
||||
nodes and fix nodes before sending it to the server.
|
||||
|
||||
:param context: send context
|
||||
"""
|
||||
# Suds builds the entire request object based on the WSDL schema.
|
||||
# VI SDK throws server errors if optional SOAP nodes are sent
|
||||
# without values; e.g., <test/> as opposed to <test>test</test>.
|
||||
context.envelope.prune()
|
||||
context.envelope.walk(self.add_attribute_for_value)
|
||||
|
||||
|
||||
class Vim(object):
|
||||
"""VIM API Client."""
|
||||
class Vim(service.Service):
|
||||
"""Service class that provides access to the VIM API."""
|
||||
|
||||
def __init__(self, protocol='https', host='localhost', port=None,
|
||||
wsdl_loc=None):
|
||||
"""Create communication interfaces for initiating SOAP transactions.
|
||||
wsdl_url=None):
|
||||
"""Constructs a VIM service client object.
|
||||
|
||||
:param protocol: http or https
|
||||
:param host: server IP address or host name
|
||||
:param port: port for connection
|
||||
:param wsdl_loc: WSDL file location
|
||||
:param wsdl_url: VIM WSDL url
|
||||
:raises: VimException, VimFaultException, VimAttributeException,
|
||||
VimSessionOverLoadException, VimConnectionException
|
||||
"""
|
||||
if not wsdl_loc:
|
||||
wsdl_loc = Vim._get_wsdl_loc(protocol, host, port)
|
||||
self._wsdl_loc = wsdl_loc
|
||||
self._soap_url = vim_util.get_soap_url(protocol, host, port)
|
||||
self._client = suds.client.Client(wsdl_loc,
|
||||
location=self._soap_url,
|
||||
plugins=[VimMessagePlugin()])
|
||||
self._service_content = self.RetrieveServiceContent('ServiceInstance')
|
||||
base_url = service.Service.build_base_url(protocol, host, port)
|
||||
soap_url = base_url + '/sdk'
|
||||
if wsdl_url is None:
|
||||
wsdl_url = soap_url + '/vimService.wsdl'
|
||||
super(Vim, self).__init__(wsdl_url, soap_url)
|
||||
|
||||
@staticmethod
|
||||
def _get_wsdl_loc(protocol, host, port):
|
||||
"""Get the default WSDL file location hosted at the server.
|
||||
|
||||
:param protocol: http or https
|
||||
:param host: server IP address or host name
|
||||
:param port: port for connection
|
||||
:returns: default WSDL file location hosted at the server
|
||||
"""
|
||||
return vim_util.get_wsdl_url(protocol, host, port)
|
||||
|
||||
@property
|
||||
def wsdl_url(self):
|
||||
return self._wsdl_loc
|
||||
|
||||
@property
|
||||
def soap_url(self):
|
||||
return self._soap_url
|
||||
|
||||
@property
|
||||
def service_content(self):
|
||||
return self._service_content
|
||||
|
||||
@property
|
||||
def client(self):
|
||||
return self._client
|
||||
|
||||
@staticmethod
|
||||
def _retrieve_properties_ex_fault_checker(response):
|
||||
"""Checks the RetrievePropertiesEx API response for errors.
|
||||
|
||||
Certain faults are sent in the SOAP body as a property of missingSet.
|
||||
This method raises VimFaultException when a fault is found in the
|
||||
response.
|
||||
|
||||
:param response: response from RetrievePropertiesEx API call
|
||||
:raises: VimFaultException
|
||||
"""
|
||||
LOG.debug("Checking RetrievePropertiesEx API response for faults.")
|
||||
fault_list = []
|
||||
if not response:
|
||||
# This is the case when the session has timed out. ESX SOAP
|
||||
# server sends an empty RetrievePropertiesExResponse. Normally
|
||||
# missingSet in the response objects has the specifics about
|
||||
# the error, but that's not the case with a timed out idle
|
||||
# session. It is as bad as a terminated session for we cannot
|
||||
# use the session. Therefore setting fault to NotAuthenticated
|
||||
# fault.
|
||||
LOG.debug("RetrievePropertiesEx API response is empty; setting "
|
||||
"fault to %s.",
|
||||
exceptions.NOT_AUTHENTICATED)
|
||||
fault_list = [exceptions.NOT_AUTHENTICATED]
|
||||
else:
|
||||
for obj_cont in response.objects:
|
||||
if hasattr(obj_cont, 'missingSet'):
|
||||
for missing_elem in obj_cont.missingSet:
|
||||
fault_type = missing_elem.fault.fault.__class__
|
||||
fault_list.append(fault_type.__name__)
|
||||
if fault_list:
|
||||
LOG.error(_LE("Faults %s found in RetrievePropertiesEx API "
|
||||
"response."),
|
||||
fault_list)
|
||||
raise exceptions.VimFaultException(fault_list,
|
||||
_("Error occurred while calling"
|
||||
" RetrievePropertiesEx."))
|
||||
LOG.debug("No faults found in RetrievePropertiesEx API response.")
|
||||
|
||||
def __getattr__(self, attr_name):
|
||||
"""Returns the method to invoke API identified by param attr_name."""
|
||||
|
||||
def vim_request_handler(managed_object, **kwargs):
|
||||
"""Handler for VIM API calls.
|
||||
|
||||
Invokes the API and parses the response for fault checking and
|
||||
other errors.
|
||||
|
||||
:param managed_object: managed object reference argument of the
|
||||
API call
|
||||
:param kwargs: keyword arguments of the API call
|
||||
:returns: response of the API call
|
||||
:raises: VimException, VimFaultException, VimAttributeException,
|
||||
VimSessionOverLoadException, VimConnectionException
|
||||
"""
|
||||
try:
|
||||
if isinstance(managed_object, str):
|
||||
# For strings, use string value for value and type
|
||||
# of the managed object.
|
||||
managed_object = vim_util.get_moref(managed_object,
|
||||
managed_object)
|
||||
if managed_object is None:
|
||||
return
|
||||
request = getattr(self.client.service, attr_name)
|
||||
LOG.debug("Invoking %(attr_name)s on %(moref)s.",
|
||||
{'attr_name': attr_name,
|
||||
'moref': managed_object})
|
||||
response = request(managed_object, **kwargs)
|
||||
if (attr_name.lower() == 'retrievepropertiesex'):
|
||||
Vim._retrieve_properties_ex_fault_checker(response)
|
||||
LOG.debug("Invocation of %(attr_name)s on %(moref)s "
|
||||
"completed successfully.",
|
||||
{'attr_name': attr_name,
|
||||
'moref': managed_object})
|
||||
return response
|
||||
except exceptions.VimFaultException:
|
||||
# Catch the VimFaultException that is raised by the fault
|
||||
# check of the SOAP response.
|
||||
raise
|
||||
|
||||
except suds.WebFault as excep:
|
||||
doc = excep.document
|
||||
fault_string = doc.childAtPath("/Envelope/Body/Fault/"
|
||||
"faultstring").getText()
|
||||
detail = doc.childAtPath('/Envelope/Body/Fault/detail')
|
||||
fault_list = []
|
||||
details = {}
|
||||
if detail:
|
||||
for fault in detail.getChildren():
|
||||
fault_list.append(fault.get("type"))
|
||||
for child in fault.getChildren():
|
||||
details[child.name] = child.getText()
|
||||
raise exceptions.VimFaultException(fault_list, fault_string,
|
||||
excep, details)
|
||||
|
||||
except AttributeError as excep:
|
||||
raise exceptions.VimAttributeException(
|
||||
_("No such SOAP method %s.") % attr_name, excep)
|
||||
|
||||
except (httplib.CannotSendRequest,
|
||||
httplib.ResponseNotReady,
|
||||
httplib.CannotSendHeader) as excep:
|
||||
raise exceptions.VimSessionOverLoadException(
|
||||
_("httplib error in %s.") % attr_name, excep)
|
||||
|
||||
except (urllib2.URLError, urllib2.HTTPError) as excep:
|
||||
raise exceptions.VimConnectionException(
|
||||
_("urllib2 error in %s.") % attr_name, excep)
|
||||
|
||||
except Exception as excep:
|
||||
# TODO(vbala) should catch specific exceptions and raise
|
||||
# appropriate VimExceptions.
|
||||
|
||||
# Socket errors which need special handling; some of these
|
||||
# might be caused by server API call overload.
|
||||
if (six.text_type(excep).find(ADDRESS_IN_USE_ERROR) != -1 or
|
||||
six.text_type(excep).find(CONN_ABORT_ERROR)) != -1:
|
||||
raise exceptions.VimSessionOverLoadException(
|
||||
_("Socket error in %s.") % attr_name, excep)
|
||||
# Type error which needs special handling; it might be caused
|
||||
# by server API call overload.
|
||||
elif six.text_type(excep).find(RESP_NOT_XML_ERROR) != -1:
|
||||
raise exceptions.VimSessionOverLoadException(
|
||||
_("Type error in %s.") % attr_name, excep)
|
||||
else:
|
||||
raise exceptions.VimException(
|
||||
_("Exception in %s.") % attr_name, excep)
|
||||
return vim_request_handler
|
||||
def retrieve_service_content(self):
|
||||
return self.RetrieveServiceContent(service.SERVICE_INSTANCE)
|
||||
|
||||
def __repr__(self):
|
||||
return "VIM Object."
|
||||
return "VIM Object"
|
||||
|
||||
def __str__(self):
|
||||
return "VIM Object."
|
||||
return "VIM Object"
|
||||
|
@ -17,7 +17,6 @@
|
||||
The VMware API utility module.
|
||||
"""
|
||||
|
||||
import netaddr
|
||||
import suds
|
||||
|
||||
|
||||
@ -373,34 +372,3 @@ def get_object_property(vim, moref, property_name):
|
||||
if prop:
|
||||
prop_val = prop[0].val
|
||||
return prop_val
|
||||
|
||||
|
||||
def get_wsdl_url(protocol, host, port=None):
|
||||
"""Get the default WSDL file location hosted at the server.
|
||||
|
||||
:param protocol: http or https
|
||||
:param host: server IP address or host name
|
||||
:param port: port for connection
|
||||
:returns: default WSDL file location hosted at the server
|
||||
"""
|
||||
return get_soap_url(protocol, host, port) + "/vimService.wsdl"
|
||||
|
||||
|
||||
def get_soap_url(protocol, host, port=None, path='sdk'):
|
||||
"""Return ESX/VC server's SOAP service URL.
|
||||
|
||||
:param protocol: https or http
|
||||
:param host: server IP address or host name
|
||||
:param port: port for connection
|
||||
:param path: path part of the SOAP URL
|
||||
:returns: SOAP service URL
|
||||
"""
|
||||
if netaddr.valid_ipv6(host):
|
||||
if port is None:
|
||||
return '%s://[%s]/%s' % (protocol, host, path)
|
||||
else:
|
||||
return '%s://[%s]:%d/%s' % (protocol, host, port, path)
|
||||
if port is None:
|
||||
return '%s://%s/%s' % (protocol, host, path)
|
||||
else:
|
||||
return '%s://%s:%d/%s' % (protocol, host, port, path)
|
||||
|
@ -124,54 +124,34 @@ class VMwareAPISessionTest(base.TestCase):
|
||||
self.VimMock.assert_called_with(protocol=api_session._scheme,
|
||||
host=VMwareAPISessionTest.SERVER_IP,
|
||||
port=VMwareAPISessionTest.PORT,
|
||||
wsdl_loc=api_session._vim_wsdl_loc)
|
||||
wsdl_url=api_session._vim_wsdl_loc)
|
||||
|
||||
@mock.patch.object(pbm, 'PBMClient')
|
||||
def test_pbm(self, pbm_client_mock):
|
||||
@mock.patch.object(pbm, 'Pbm')
|
||||
def test_pbm(self, pbm_mock):
|
||||
api_session = self._create_api_session(True)
|
||||
api_session._pbm_wsdl_loc = mock.Mock()
|
||||
pbm = mock.Mock()
|
||||
pbm_client_mock.return_value = pbm
|
||||
vim_obj = api_session.vim
|
||||
cookie = mock.Mock()
|
||||
vim_obj.get_http_cookie.return_value = cookie
|
||||
api_session._pbm_wsdl_loc = mock.Mock()
|
||||
|
||||
pbm = mock.Mock()
|
||||
pbm_mock.return_value = pbm
|
||||
api_session._get_session_cookie = mock.Mock(return_value=cookie)
|
||||
|
||||
self.assertEqual(pbm, api_session.pbm)
|
||||
pbm.set_cookie.assert_called_once_with(cookie)
|
||||
|
||||
def test_get_session_cookie(self):
|
||||
api_session = self._create_api_session(False)
|
||||
vim_obj = api_session.vim
|
||||
|
||||
cookie_value = 'xyz'
|
||||
cookie = mock.Mock()
|
||||
cookie.name = 'vmware_soap_session'
|
||||
cookie.value = cookie_value
|
||||
vim_obj.client.options.transport.cookiejar = [cookie]
|
||||
|
||||
self.assertEqual(cookie_value, api_session._get_session_cookie())
|
||||
|
||||
def test_get_session_cookie_with_no_cookie(self):
|
||||
api_session = self._create_api_session(False)
|
||||
vim_obj = api_session.vim
|
||||
|
||||
cookie = mock.Mock()
|
||||
cookie.name = 'cookie'
|
||||
cookie.value = 'xyz'
|
||||
vim_obj.client.options.transport.cookiejar = [cookie]
|
||||
|
||||
self.assertIsNone(api_session._get_session_cookie())
|
||||
pbm.set_soap_cookie.assert_called_once_with(cookie)
|
||||
|
||||
def test_create_session(self):
|
||||
session = mock.Mock()
|
||||
session.key = "12345"
|
||||
api_session = self._create_api_session(False)
|
||||
cookie = mock.Mock()
|
||||
vim_obj = api_session.vim
|
||||
vim_obj.Login.return_value = session
|
||||
vim_obj.get_http_cookie.return_value = cookie
|
||||
|
||||
pbm = mock.Mock()
|
||||
api_session._pbm = pbm
|
||||
cookie = mock.Mock()
|
||||
api_session._get_session_cookie = mock.Mock(return_value=cookie)
|
||||
|
||||
api_session._create_session()
|
||||
session_manager = vim_obj.service_content.sessionManager
|
||||
@ -180,7 +160,7 @@ class VMwareAPISessionTest(base.TestCase):
|
||||
password=VMwareAPISessionTest.PASSWORD)
|
||||
self.assertFalse(vim_obj.TerminateSession.called)
|
||||
self.assertEqual(session.key, api_session._session_id)
|
||||
pbm.set_cookie.assert_called_once_with(cookie)
|
||||
pbm.set_soap_cookie.assert_called_once_with(cookie)
|
||||
|
||||
def test_create_session_with_existing_session(self):
|
||||
old_session_key = '12345'
|
||||
|
290
tests/test_service.py
Normal file
290
tests/test_service.py
Normal file
@ -0,0 +1,290 @@
|
||||
# Copyright (c) 2014 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.
|
||||
|
||||
import httplib
|
||||
import urllib2
|
||||
|
||||
import mock
|
||||
import suds
|
||||
|
||||
from oslo.vmware import exceptions
|
||||
from oslo.vmware import service
|
||||
from oslo.vmware import vim_util
|
||||
from tests import base
|
||||
|
||||
|
||||
class ServiceMessagePluginTest(base.TestCase):
|
||||
"""Test class for ServiceMessagePlugin."""
|
||||
|
||||
def test_add_attribute_for_value(self):
|
||||
node = mock.Mock()
|
||||
node.name = 'value'
|
||||
plugin = service.ServiceMessagePlugin()
|
||||
plugin.add_attribute_for_value(node)
|
||||
node.set.assert_called_once_with('xsi:type', 'xsd:string')
|
||||
|
||||
def test_marshalled(self):
|
||||
plugin = service.ServiceMessagePlugin()
|
||||
context = mock.Mock()
|
||||
plugin.marshalled(context)
|
||||
context.envelope.prune.assert_called_once_with()
|
||||
context.envelope.walk.assert_called_once_with(
|
||||
plugin.add_attribute_for_value)
|
||||
|
||||
|
||||
class ServiceTest(base.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
super(ServiceTest, self).setUp()
|
||||
patcher = mock.patch('suds.client.Client')
|
||||
self.addCleanup(patcher.stop)
|
||||
self.SudsClientMock = patcher.start()
|
||||
|
||||
def test_retrieve_properties_ex_fault_checker_with_empty_response(self):
|
||||
try:
|
||||
service.Service._retrieve_properties_ex_fault_checker(None)
|
||||
assert False
|
||||
except exceptions.VimFaultException as ex:
|
||||
self.assertEqual([exceptions.NOT_AUTHENTICATED],
|
||||
ex.fault_list)
|
||||
|
||||
def test_retrieve_properties_ex_fault_checker(self):
|
||||
fault_list = ['FileFault', 'VimFault']
|
||||
missing_set = []
|
||||
for fault in fault_list:
|
||||
missing_elem = mock.Mock()
|
||||
missing_elem.fault.fault.__class__.__name__ = fault
|
||||
missing_set.append(missing_elem)
|
||||
obj_cont = mock.Mock()
|
||||
obj_cont.missingSet = missing_set
|
||||
response = mock.Mock()
|
||||
response.objects = [obj_cont]
|
||||
|
||||
try:
|
||||
service.Service._retrieve_properties_ex_fault_checker(response)
|
||||
assert False
|
||||
except exceptions.VimFaultException as ex:
|
||||
self.assertEqual(fault_list, ex.fault_list)
|
||||
|
||||
def test_request_handler(self):
|
||||
managed_object = 'VirtualMachine'
|
||||
resp = mock.Mock()
|
||||
|
||||
def side_effect(mo, **kwargs):
|
||||
self.assertEqual(managed_object, mo._type)
|
||||
self.assertEqual(managed_object, mo.value)
|
||||
return resp
|
||||
|
||||
svc_obj = service.Service()
|
||||
attr_name = 'powerOn'
|
||||
service_mock = svc_obj.client.service
|
||||
setattr(service_mock, attr_name, side_effect)
|
||||
ret = svc_obj.powerOn(managed_object)
|
||||
self.assertEqual(resp, ret)
|
||||
|
||||
def test_request_handler_with_retrieve_properties_ex_fault(self):
|
||||
managed_object = 'Datacenter'
|
||||
|
||||
def side_effect(mo, **kwargs):
|
||||
self.assertEqual(managed_object, mo._type)
|
||||
self.assertEqual(managed_object, mo.value)
|
||||
return None
|
||||
|
||||
svc_obj = service.Service()
|
||||
attr_name = 'retrievePropertiesEx'
|
||||
service_mock = svc_obj.client.service
|
||||
setattr(service_mock, attr_name, side_effect)
|
||||
self.assertRaises(exceptions.VimFaultException,
|
||||
svc_obj.retrievePropertiesEx,
|
||||
managed_object)
|
||||
|
||||
def test_request_handler_with_web_fault(self):
|
||||
managed_object = 'VirtualMachine'
|
||||
fault_list = ['Fault']
|
||||
|
||||
def side_effect(mo, **kwargs):
|
||||
self.assertEqual(managed_object, mo._type)
|
||||
self.assertEqual(managed_object, mo.value)
|
||||
fault_string = mock.Mock()
|
||||
fault_string.getText.return_value = "MyFault"
|
||||
|
||||
fault_children = mock.Mock()
|
||||
fault_children.name = "name"
|
||||
fault_children.getText.return_value = "value"
|
||||
child = mock.Mock()
|
||||
child.get.return_value = fault_list[0]
|
||||
child.getChildren.return_value = [fault_children]
|
||||
detail = mock.Mock()
|
||||
detail.getChildren.return_value = [child]
|
||||
doc = mock.Mock()
|
||||
doc.childAtPath = mock.Mock(side_effect=[fault_string, detail])
|
||||
raise suds.WebFault(None, doc)
|
||||
|
||||
svc_obj = service.Service()
|
||||
attr_name = 'powerOn'
|
||||
service_mock = svc_obj.client.service
|
||||
setattr(service_mock, attr_name, side_effect)
|
||||
|
||||
try:
|
||||
svc_obj.powerOn(managed_object)
|
||||
except exceptions.VimFaultException as ex:
|
||||
self.assertEqual(fault_list, ex.fault_list)
|
||||
self.assertEqual({'name': 'value'}, ex.details)
|
||||
self.assertEqual("MyFault", ex.msg)
|
||||
|
||||
def test_request_handler_with_attribute_error(self):
|
||||
managed_object = 'VirtualMachine'
|
||||
svc_obj = service.Service()
|
||||
# no powerOn method in Service
|
||||
service_mock = mock.Mock(spec=service.Service)
|
||||
svc_obj.client.service = service_mock
|
||||
self.assertRaises(exceptions.VimAttributeException,
|
||||
svc_obj.powerOn,
|
||||
managed_object)
|
||||
|
||||
def test_request_handler_with_http_cannot_send_error(self):
|
||||
managed_object = 'VirtualMachine'
|
||||
|
||||
def side_effect(mo, **kwargs):
|
||||
self.assertEqual(managed_object, mo._type)
|
||||
self.assertEqual(managed_object, mo.value)
|
||||
raise httplib.CannotSendRequest()
|
||||
|
||||
svc_obj = service.Service()
|
||||
attr_name = 'powerOn'
|
||||
service_mock = svc_obj.client.service
|
||||
setattr(service_mock, attr_name, side_effect)
|
||||
self.assertRaises(exceptions.VimSessionOverLoadException,
|
||||
svc_obj.powerOn,
|
||||
managed_object)
|
||||
|
||||
def test_request_handler_with_http_response_not_ready_error(self):
|
||||
managed_object = 'VirtualMachine'
|
||||
|
||||
def side_effect(mo, **kwargs):
|
||||
self.assertEqual(managed_object, mo._type)
|
||||
self.assertEqual(managed_object, mo.value)
|
||||
raise httplib.ResponseNotReady()
|
||||
|
||||
svc_obj = service.Service()
|
||||
attr_name = 'powerOn'
|
||||
service_mock = svc_obj.client.service
|
||||
setattr(service_mock, attr_name, side_effect)
|
||||
self.assertRaises(exceptions.VimSessionOverLoadException,
|
||||
svc_obj.powerOn,
|
||||
managed_object)
|
||||
|
||||
def test_request_handler_with_http_cannot_send_header_error(self):
|
||||
managed_object = 'VirtualMachine'
|
||||
|
||||
def side_effect(mo, **kwargs):
|
||||
self.assertEqual(managed_object, mo._type)
|
||||
self.assertEqual(managed_object, mo.value)
|
||||
raise httplib.CannotSendHeader()
|
||||
|
||||
svc_obj = service.Service()
|
||||
attr_name = 'powerOn'
|
||||
service_mock = svc_obj.client.service
|
||||
setattr(service_mock, attr_name, side_effect)
|
||||
self.assertRaises(exceptions.VimSessionOverLoadException,
|
||||
svc_obj.powerOn,
|
||||
managed_object)
|
||||
|
||||
def test_request_handler_with_url_error(self):
|
||||
managed_object = 'VirtualMachine'
|
||||
|
||||
def side_effect(mo, **kwargs):
|
||||
self.assertEqual(managed_object, mo._type)
|
||||
self.assertEqual(managed_object, mo.value)
|
||||
raise urllib2.URLError(None)
|
||||
|
||||
svc_obj = service.Service()
|
||||
attr_name = 'powerOn'
|
||||
service_mock = svc_obj.client.service
|
||||
setattr(service_mock, attr_name, side_effect)
|
||||
self.assertRaises(exceptions.VimConnectionException,
|
||||
svc_obj.powerOn,
|
||||
managed_object)
|
||||
|
||||
def test_request_handler_with_http_error(self):
|
||||
managed_object = 'VirtualMachine'
|
||||
|
||||
def side_effect(mo, **kwargs):
|
||||
self.assertEqual(managed_object, mo._type)
|
||||
self.assertEqual(managed_object, mo.value)
|
||||
raise urllib2.HTTPError(None, None, None, None, None)
|
||||
|
||||
svc_obj = service.Service()
|
||||
attr_name = 'powerOn'
|
||||
service_mock = svc_obj.client.service
|
||||
setattr(service_mock, attr_name, side_effect)
|
||||
self.assertRaises(exceptions.VimConnectionException,
|
||||
svc_obj.powerOn,
|
||||
managed_object)
|
||||
|
||||
@mock.patch.object(vim_util, 'get_moref', return_value=None)
|
||||
def test_request_handler_no_value(self, mock_moref):
|
||||
managed_object = 'VirtualMachine'
|
||||
svc_obj = service.Service()
|
||||
ret = svc_obj.UnregisterVM(managed_object)
|
||||
self.assertIsNone(ret)
|
||||
|
||||
def _test_request_handler_with_exception(self, message, exception):
|
||||
managed_object = 'VirtualMachine'
|
||||
|
||||
def side_effect(mo, **kwargs):
|
||||
self.assertEqual(managed_object, mo._type)
|
||||
self.assertEqual(managed_object, mo.value)
|
||||
raise Exception(message)
|
||||
|
||||
svc_obj = service.Service()
|
||||
attr_name = 'powerOn'
|
||||
service_mock = svc_obj.client.service
|
||||
setattr(service_mock, attr_name, side_effect)
|
||||
self.assertRaises(exception, svc_obj.powerOn, managed_object)
|
||||
|
||||
def test_request_handler_with_address_in_use_error(self):
|
||||
self._test_request_handler_with_exception(
|
||||
service.ADDRESS_IN_USE_ERROR,
|
||||
exceptions.VimSessionOverLoadException)
|
||||
|
||||
def test_request_handler_with_conn_abort_error(self):
|
||||
self._test_request_handler_with_exception(
|
||||
service.CONN_ABORT_ERROR, exceptions.VimSessionOverLoadException)
|
||||
|
||||
def test_request_handler_with_resp_not_xml_error(self):
|
||||
self._test_request_handler_with_exception(
|
||||
service.RESP_NOT_XML_ERROR, exceptions.VimSessionOverLoadException)
|
||||
|
||||
def test_request_handler_with_generic_error(self):
|
||||
self._test_request_handler_with_exception(
|
||||
'GENERIC_ERROR', exceptions.VimException)
|
||||
|
||||
def test_get_session_cookie(self):
|
||||
svc_obj = service.Service()
|
||||
cookie_value = 'xyz'
|
||||
cookie = mock.Mock()
|
||||
cookie.name = 'vmware_soap_session'
|
||||
cookie.value = cookie_value
|
||||
svc_obj.client.options.transport.cookiejar = [cookie]
|
||||
self.assertEqual(cookie_value, svc_obj.get_http_cookie())
|
||||
|
||||
def test_get_session_cookie_with_no_cookie(self):
|
||||
svc_obj = service.Service()
|
||||
cookie = mock.Mock()
|
||||
cookie.name = 'cookie'
|
||||
cookie.value = 'xyz'
|
||||
svc_obj.client.options.transport.cookiejar = [cookie]
|
||||
self.assertIsNone(svc_obj.get_http_cookie())
|
@ -17,37 +17,13 @@
|
||||
Unit tests for classes to invoke VMware VI SOAP calls.
|
||||
"""
|
||||
|
||||
import httplib
|
||||
import urllib2
|
||||
|
||||
import mock
|
||||
import suds
|
||||
|
||||
from oslo.vmware import exceptions
|
||||
from oslo.vmware import vim
|
||||
from oslo.vmware import vim_util
|
||||
from tests import base
|
||||
|
||||
|
||||
class VimMessagePluginTest(base.TestCase):
|
||||
"""Test class for VimMessagePlugin."""
|
||||
|
||||
def test_add_attribute_for_value(self):
|
||||
node = mock.Mock()
|
||||
node.name = 'value'
|
||||
plugin = vim.VimMessagePlugin()
|
||||
plugin.add_attribute_for_value(node)
|
||||
node.set.assert_called_once_with('xsi:type', 'xsd:string')
|
||||
|
||||
def test_marshalled(self):
|
||||
plugin = vim.VimMessagePlugin()
|
||||
context = mock.Mock()
|
||||
plugin.marshalled(context)
|
||||
context.envelope.prune.assert_called_once_with()
|
||||
context.envelope.walk.assert_called_once_with(
|
||||
plugin.add_attribute_for_value)
|
||||
|
||||
|
||||
class VimTest(base.TestCase):
|
||||
"""Test class for Vim."""
|
||||
|
||||
@ -58,234 +34,16 @@ class VimTest(base.TestCase):
|
||||
self.SudsClientMock = patcher.start()
|
||||
|
||||
@mock.patch.object(vim.Vim, '__getattr__', autospec=True)
|
||||
def test_init(self, getattr_mock):
|
||||
def test_service_content(self, getattr_mock):
|
||||
getattr_ret = mock.Mock()
|
||||
getattr_mock.side_effect = lambda *args: getattr_ret
|
||||
vim_obj = vim.Vim()
|
||||
vim_obj.service_content
|
||||
getattr_mock.assert_called_once_with(vim_obj, 'RetrieveServiceContent')
|
||||
getattr_ret.assert_called_once_with('ServiceInstance')
|
||||
self.assertEqual(self.SudsClientMock.return_value, vim_obj.client)
|
||||
self.assertEqual(getattr_ret.return_value, vim_obj.service_content)
|
||||
|
||||
def test_retrieve_properties_ex_fault_checker_with_empty_response(self):
|
||||
try:
|
||||
vim.Vim._retrieve_properties_ex_fault_checker(None)
|
||||
assert False
|
||||
except exceptions.VimFaultException as ex:
|
||||
self.assertEqual([exceptions.NOT_AUTHENTICATED],
|
||||
ex.fault_list)
|
||||
|
||||
def test_retrieve_properties_ex_fault_checker(self):
|
||||
fault_list = ['FileFault', 'VimFault']
|
||||
missing_set = []
|
||||
for fault in fault_list:
|
||||
missing_elem = mock.Mock()
|
||||
missing_elem.fault.fault.__class__.__name__ = fault
|
||||
missing_set.append(missing_elem)
|
||||
obj_cont = mock.Mock()
|
||||
obj_cont.missingSet = missing_set
|
||||
response = mock.Mock()
|
||||
response.objects = [obj_cont]
|
||||
|
||||
try:
|
||||
vim.Vim._retrieve_properties_ex_fault_checker(response)
|
||||
assert False
|
||||
except exceptions.VimFaultException as ex:
|
||||
self.assertEqual(fault_list, ex.fault_list)
|
||||
|
||||
def test_vim_request_handler(self):
|
||||
managed_object = 'VirtualMachine'
|
||||
resp = mock.Mock()
|
||||
|
||||
def side_effect(mo, **kwargs):
|
||||
self.assertEqual(managed_object, mo._type)
|
||||
self.assertEqual(managed_object, mo.value)
|
||||
return resp
|
||||
|
||||
vim_obj = vim.Vim()
|
||||
attr_name = 'powerOn'
|
||||
service_mock = vim_obj._client.service
|
||||
setattr(service_mock, attr_name, side_effect)
|
||||
ret = vim_obj.powerOn(managed_object)
|
||||
self.assertEqual(resp, ret)
|
||||
|
||||
def test_vim_request_handler_with_retrieve_properties_ex_fault(self):
|
||||
managed_object = 'Datacenter'
|
||||
|
||||
def side_effect(mo, **kwargs):
|
||||
self.assertEqual(managed_object, mo._type)
|
||||
self.assertEqual(managed_object, mo.value)
|
||||
return None
|
||||
|
||||
vim_obj = vim.Vim()
|
||||
attr_name = 'retrievePropertiesEx'
|
||||
service_mock = vim_obj._client.service
|
||||
setattr(service_mock, attr_name, side_effect)
|
||||
self.assertRaises(exceptions.VimFaultException,
|
||||
vim_obj.retrievePropertiesEx,
|
||||
managed_object)
|
||||
|
||||
def test_vim_request_handler_with_web_fault(self):
|
||||
managed_object = 'VirtualMachine'
|
||||
fault_list = ['Fault']
|
||||
|
||||
def side_effect(mo, **kwargs):
|
||||
self.assertEqual(managed_object, mo._type)
|
||||
self.assertEqual(managed_object, mo.value)
|
||||
fault_string = mock.Mock()
|
||||
fault_string.getText.return_value = "MyFault"
|
||||
|
||||
fault_children = mock.Mock()
|
||||
fault_children.name = "name"
|
||||
fault_children.getText.return_value = "value"
|
||||
child = mock.Mock()
|
||||
child.get.return_value = fault_list[0]
|
||||
child.getChildren.return_value = [fault_children]
|
||||
detail = mock.Mock()
|
||||
detail.getChildren.return_value = [child]
|
||||
doc = mock.Mock()
|
||||
doc.childAtPath = mock.Mock(side_effect=[fault_string, detail])
|
||||
raise suds.WebFault(None, doc)
|
||||
|
||||
vim_obj = vim.Vim()
|
||||
attr_name = 'powerOn'
|
||||
service_mock = vim_obj._client.service
|
||||
setattr(service_mock, attr_name, side_effect)
|
||||
|
||||
try:
|
||||
vim_obj.powerOn(managed_object)
|
||||
except exceptions.VimFaultException as ex:
|
||||
self.assertEqual(fault_list, ex.fault_list)
|
||||
self.assertEqual({'name': 'value'}, ex.details)
|
||||
self.assertEqual("MyFault", ex.msg)
|
||||
|
||||
def test_vim_request_handler_with_attribute_error(self):
|
||||
managed_object = 'VirtualMachine'
|
||||
vim_obj = vim.Vim()
|
||||
# no powerOn method in Vim
|
||||
service_mock = mock.Mock(spec=vim.Vim)
|
||||
vim_obj._client.service = service_mock
|
||||
self.assertRaises(exceptions.VimAttributeException,
|
||||
vim_obj.powerOn,
|
||||
managed_object)
|
||||
|
||||
def test_vim_request_handler_with_http_cannot_send_error(self):
|
||||
managed_object = 'VirtualMachine'
|
||||
|
||||
def side_effect(mo, **kwargs):
|
||||
self.assertEqual(managed_object, mo._type)
|
||||
self.assertEqual(managed_object, mo.value)
|
||||
raise httplib.CannotSendRequest()
|
||||
|
||||
vim_obj = vim.Vim()
|
||||
attr_name = 'powerOn'
|
||||
service_mock = vim_obj._client.service
|
||||
setattr(service_mock, attr_name, side_effect)
|
||||
self.assertRaises(exceptions.VimSessionOverLoadException,
|
||||
vim_obj.powerOn,
|
||||
managed_object)
|
||||
|
||||
def test_vim_request_handler_with_http_response_not_ready_error(self):
|
||||
managed_object = 'VirtualMachine'
|
||||
|
||||
def side_effect(mo, **kwargs):
|
||||
self.assertEqual(managed_object, mo._type)
|
||||
self.assertEqual(managed_object, mo.value)
|
||||
raise httplib.ResponseNotReady()
|
||||
|
||||
vim_obj = vim.Vim()
|
||||
attr_name = 'powerOn'
|
||||
service_mock = vim_obj._client.service
|
||||
setattr(service_mock, attr_name, side_effect)
|
||||
self.assertRaises(exceptions.VimSessionOverLoadException,
|
||||
vim_obj.powerOn,
|
||||
managed_object)
|
||||
|
||||
def test_vim_request_handler_with_http_cannot_send_header_error(self):
|
||||
managed_object = 'VirtualMachine'
|
||||
|
||||
def side_effect(mo, **kwargs):
|
||||
self.assertEqual(managed_object, mo._type)
|
||||
self.assertEqual(managed_object, mo.value)
|
||||
raise httplib.CannotSendHeader()
|
||||
|
||||
vim_obj = vim.Vim()
|
||||
attr_name = 'powerOn'
|
||||
service_mock = vim_obj._client.service
|
||||
setattr(service_mock, attr_name, side_effect)
|
||||
self.assertRaises(exceptions.VimSessionOverLoadException,
|
||||
vim_obj.powerOn,
|
||||
managed_object)
|
||||
|
||||
def test_vim_request_handler_with_url_error(self):
|
||||
managed_object = 'VirtualMachine'
|
||||
|
||||
def side_effect(mo, **kwargs):
|
||||
self.assertEqual(managed_object, mo._type)
|
||||
self.assertEqual(managed_object, mo.value)
|
||||
raise urllib2.URLError(None)
|
||||
|
||||
vim_obj = vim.Vim()
|
||||
attr_name = 'powerOn'
|
||||
service_mock = vim_obj._client.service
|
||||
setattr(service_mock, attr_name, side_effect)
|
||||
self.assertRaises(exceptions.VimConnectionException,
|
||||
vim_obj.powerOn,
|
||||
managed_object)
|
||||
|
||||
def test_vim_request_handler_with_http_error(self):
|
||||
managed_object = 'VirtualMachine'
|
||||
|
||||
def side_effect(mo, **kwargs):
|
||||
self.assertEqual(managed_object, mo._type)
|
||||
self.assertEqual(managed_object, mo.value)
|
||||
raise urllib2.HTTPError(None, None, None, None, None)
|
||||
|
||||
vim_obj = vim.Vim()
|
||||
attr_name = 'powerOn'
|
||||
service_mock = vim_obj._client.service
|
||||
setattr(service_mock, attr_name, side_effect)
|
||||
self.assertRaises(exceptions.VimConnectionException,
|
||||
vim_obj.powerOn,
|
||||
managed_object)
|
||||
|
||||
@mock.patch.object(vim_util, 'get_moref', return_value=None)
|
||||
def test_vim_request_handler_no_value(self, mock_moref):
|
||||
managed_object = 'VirtualMachine'
|
||||
vim_obj = vim.Vim()
|
||||
ret = vim_obj.UnregisterVM(managed_object)
|
||||
self.assertIsNone(ret)
|
||||
|
||||
def _test_vim_request_handler_with_exception(self, message, exception):
|
||||
managed_object = 'VirtualMachine'
|
||||
|
||||
def side_effect(mo, **kwargs):
|
||||
self.assertEqual(managed_object, mo._type)
|
||||
self.assertEqual(managed_object, mo.value)
|
||||
raise Exception(message)
|
||||
|
||||
vim_obj = vim.Vim()
|
||||
attr_name = 'powerOn'
|
||||
service_mock = vim_obj._client.service
|
||||
setattr(service_mock, attr_name, side_effect)
|
||||
self.assertRaises(exception, vim_obj.powerOn, managed_object)
|
||||
|
||||
def test_vim_request_handler_with_address_in_use_error(self):
|
||||
self._test_vim_request_handler_with_exception(
|
||||
vim.ADDRESS_IN_USE_ERROR, exceptions.VimSessionOverLoadException)
|
||||
|
||||
def test_vim_request_handler_with_conn_abort_error(self):
|
||||
self._test_vim_request_handler_with_exception(
|
||||
vim.CONN_ABORT_ERROR, exceptions.VimSessionOverLoadException)
|
||||
|
||||
def test_vim_request_handler_with_resp_not_xml_error(self):
|
||||
self._test_vim_request_handler_with_exception(
|
||||
vim.RESP_NOT_XML_ERROR, exceptions.VimSessionOverLoadException)
|
||||
|
||||
def test_vim_request_handler_with_generic_error(self):
|
||||
self._test_vim_request_handler_with_exception(
|
||||
'GENERIC_ERROR', exceptions.VimException)
|
||||
|
||||
def test_exception_summary_exception_as_list(self):
|
||||
# assert that if a list is fed to the VimException object
|
||||
# that it will error.
|
||||
@ -340,3 +98,10 @@ class VimTest(base.TestCase):
|
||||
vim_obj.wsdl_url)
|
||||
self.assertEqual('https://[::1]:12345/sdk',
|
||||
vim_obj.soap_url)
|
||||
|
||||
def test_configure_with_wsdl_url_override(self):
|
||||
vim_obj = vim.Vim('https', 'www.example.com',
|
||||
wsdl_url='https://test.com/sdk/vimService.wsdl')
|
||||
self.assertEqual('https://test.com/sdk/vimService.wsdl',
|
||||
vim_obj.wsdl_url)
|
||||
self.assertEqual('https://www.example.com/sdk', vim_obj.soap_url)
|
||||
|
@ -292,18 +292,3 @@ class VimUtilTest(base.TestCase):
|
||||
self.assertEqual(prop.val, val)
|
||||
get_object_properties.assert_called_once_with(
|
||||
vim, moref, [property_name])
|
||||
|
||||
def test_configure_without_wsdl_loc_override(self):
|
||||
wsdl_url = vim_util.get_wsdl_url("https", "www.example.com")
|
||||
url = vim_util.get_soap_url("https", "www.example.com")
|
||||
self.assertEqual("https://www.example.com/sdk/vimService.wsdl",
|
||||
wsdl_url)
|
||||
self.assertEqual("https://www.example.com/sdk", url)
|
||||
|
||||
def test_configure_without_wsdl_loc_override_using_ipv6(self):
|
||||
# Same as above but with ipv6 based host ip
|
||||
wsdl_url = vim_util.get_wsdl_url("https", "::1")
|
||||
url = vim_util.get_soap_url("https", "::1")
|
||||
self.assertEqual("https://[::1]/sdk/vimService.wsdl",
|
||||
wsdl_url)
|
||||
self.assertEqual("https://[::1]/sdk", url)
|
||||
|
Loading…
x
Reference in New Issue
Block a user