def test_update_progress_with_error(self): session = self._create_mock_session(True, 10) handle = rw_handles.VmdkWriteHandle(session, '10.1.2.3', 443, 'rp-1', 'folder-1', None, 100) session.invoke_api.side_effect = exceptions.VimException(None) self.assertRaises(exceptions.VimException, handle.update_progress)
def side_effect(*args, **kwargs): if connection.invoke_api.call_count == i + 1: msg = ('Failed test with args: %(args)s ' 'and kwargs: %(kwargs)s' % {'args': args, 'kwargs': kwargs}) raise vmware_exceptions.VimException(msg) return org_side_effect(*args, **kwargs)
def test_update_progress_with_error(self): session = self._create_mock_session(True, 10) handle = rw_handles.VmdkReadHandle(session, '10.1.2.3', 443, 'vm-1', '[ds] disk1.vmdk', 100) session.invoke_api.side_effect = exceptions.VimException(None) self.assertRaises(exceptions.VimException, handle.update_progress)
def test_close_with_error(self): session = self._create_mock_session() handle = rw_handles.VmdkReadHandle(session, '10.1.2.3', 443, 'vm-1', '[ds] disk1.vmdk', 100) session.invoke_api.side_effect = exceptions.VimException(None) self.assertRaises(exceptions.VimException, handle.close) self._resp.close.assert_called_once_with()
def test_update_progress_with_error(self): session = mock.Mock() handle = rw_handles.VmdkHandle(session, None, 'fake-url', None) handle._get_progress = mock.Mock(return_value=0) session.invoke_api.side_effect = exceptions.VimException(None) self.assertRaises(exceptions.VimException, handle.update_progress)
def _poll_lease(self, lease): """Poll the state of the given lease. When the lease is ready, the event (param done) is notified. In case of any error, appropriate exception is set in the event. :param lease: lease whose state is to be polled """ try: state = self.invoke_api(vim_util, 'get_object_property', self.vim, lease, 'state', skip_op_id=True) except exceptions.VimException: with excutils.save_and_reraise_exception(): LOG.exception( "Error occurred while checking " "state of lease: %s.", lease) else: if state == 'ready': LOG.debug("Lease: %s is ready.", lease) raise loopingcall.LoopingCallDone() elif state == 'initializing': LOG.debug("Lease: %s is initializing.", lease) elif state == 'error': LOG.debug("Invoking VIM API to read lease: %s error.", lease) error_msg = self._get_error_message(lease) excep_msg = _("Lease: %(lease)s is in error state. Details: " "%(error_msg)s.") % { 'lease': lease, 'error_msg': error_msg } LOG.error(excep_msg) raise exceptions.VimException(excep_msg) else: # unknown state excep_msg = _("Unknown state: %(state)s for lease: " "%(lease)s.") % { 'state': state, 'lease': lease } LOG.error(excep_msg) raise exceptions.VimException(excep_msg)
def test_wait_for_lease_ready_with_invoke_api_exception(self): api_session = self._create_api_session(True) api_session.invoke_api = mock.Mock( side_effect=exceptions.VimException(None)) lease = mock.Mock() self.assertRaises(exceptions.VimException, api_session.wait_for_lease_ready, lease) api_session.invoke_api.assert_called_once_with(vim_util, 'get_object_property', api_session.vim, lease, 'state')
def test_switch_port_blocked_state_failed(self): port = {'id': 'fake_port_id'} with mock.patch.object(self.controller, 'get_port_info') as get_port_info_mock: get_port_info_mock.side_effect = exceptions.PortNotFound(id='') self.controller.switch_port_blocked_state(port) self.connection.invoke_api.assert_not_called() get_port_info_mock.side_effect = vmware_exceptions.VimException() self.assertRaises(exceptions.VMWareDVSException, self.controller.switch_port_blocked_state, port)
def test_wait_for_task_with_invoke_api_exception(self): api_session = self._create_api_session(True) api_session.invoke_api = mock.Mock( side_effect=exceptions.VimException(None)) task = mock.Mock() with mock.patch.object(greenthread, 'sleep'): self.assertRaises(exceptions.VimException, api_session.wait_for_task, task) api_session.invoke_api.assert_called_once_with(vim_util, 'get_object_property', api_session.vim, task, 'info')
def _find_vmdk_url(self, lease_info, host, port): """Find the URL corresponding to a VMDK file in lease info.""" url = None for deviceUrl in lease_info.deviceUrl: if deviceUrl.disk: url = self._fix_esx_url(deviceUrl.url, host, port) break if not url: excep_msg = _("Could not retrieve VMDK URL from lease info.") LOG.error(excep_msg) raise exceptions.VimException(excep_msg) LOG.debug("Found VMDK URL: %s from lease info.", url) return url
def _create_read_connection(self, url, cookies=None, cacerts=False, ssl_thumbprint=None): LOG.debug("Opening URL: %s for reading.", url) try: conn = self._create_connection(url, 'GET', cacerts, ssl_thumbprint) vim_cookie = self._build_vim_cookie_header(cookies) conn.putheader('User-Agent', USER_AGENT) conn.putheader('Cookie', vim_cookie) conn.endheaders() return conn.getresponse() except Exception as excep: # TODO(vbala) We need to catch and raise specific exceptions # related to connection problems, invalid request and invalid # arguments. excep_msg = _("Error occurred while opening URL: %s for " "reading.") % url LOG.exception(excep_msg) raise exceptions.VimException(excep_msg, excep)
def read(self, chunk_size): """Read a chunk of data from the VMDK file. :param chunk_size: size of read chunk :returns: the data :raises: VimException """ try: data = self._file_handle.read(READ_CHUNKSIZE) self._bytes_read += len(data) return data except Exception as excep: # TODO(vbala) We need to catch and raise specific exceptions # related to connection problems, invalid request and invalid # arguments. excep_msg = _("Error occurred while reading data from" " %s.") % self._url LOG.exception(excep_msg) raise exceptions.VimException(excep_msg, excep)
def _create_read_connection(self, url, cookies=None, cacerts=False): LOG.debug("Opening URL: %s for reading.", url) try: headers = {'User-Agent': USER_AGENT} if cookies: headers.update( {'Cookie': self._build_vim_cookie_header(cookies)}) response = requests.get(url, headers=headers, stream=True, verify=cacerts) return response.raw except Exception as excep: # TODO(vbala) We need to catch and raise specific exceptions # related to connection problems, invalid request and invalid # arguments. excep_msg = _("Error occurred while opening URL: %s for " "reading.") % url LOG.exception(excep_msg) raise exceptions.VimException(excep_msg, excep)
def write(self, data): """Write data to the file. :param data: data to be written :raises: VimConnectionException, VimException """ try: self._file_handle.send(data) except requests.RequestException as excep: excep_msg = _("Connection error occurred while writing data to" " %s.") % self._url LOG.exception(excep_msg) raise exceptions.VimConnectionException(excep_msg, excep) except Exception as excep: # TODO(vbala) We need to catch and raise specific exceptions # related to connection problems, invalid request and invalid # arguments. excep_msg = _("Error occurred while writing data to" " %s.") % self._url LOG.exception(excep_msg) raise exceptions.VimException(excep_msg, excep)
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) response = request(managed_object, **kwargs) if (attr_name.lower() == 'retrievepropertiesex'): Service._retrieve_properties_ex_fault_checker(response) 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: fault_string = None if excep.fault: fault_string = excep.fault.faultstring doc = excep.document detail = None if doc is not None: detail = doc.childAtPath('/detail') if not detail: # NOTE(arnaud): this is needed with VC 5.1 detail = doc.childAtPath('/Envelope/Body/Fault/detail') fault_list = [] details = {} if detail: for fault in detail.getChildren(): fault_type = fault.get('type') if fault_type.endswith(exceptions.SECURITY_ERROR): fault_type = exceptions.NOT_AUTHENTICATED fault_list.append(fault_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 requests.RequestException as excep: raise exceptions.VimConnectionException( _("requests 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)
def func(*args, **kwargs): raise exceptions.VimException(None)
def test_exception_summary_string(self): e = exceptions.VimException(_("string"), ValueError("foo")) string = str(e) self.assertEqual("string\nCause: foo", string)
def test_select_datastore(self, filter_datastores, get_profile_id): # Test with no hosts. size_bytes = units.Ki req = {self._ds_sel.SIZE_BYTES: size_bytes} self._vops.get_hosts.return_value = mock.Mock(objects=[]) self.assertEqual((), self._ds_sel.select_datastore(req)) self._vops.get_hosts.assert_called_once_with() # Test with single host with no valid datastores. host_1 = self._create_host('host-1') self._vops.get_hosts.return_value = mock.Mock( objects=[mock.Mock(obj=host_1)]) self._vops.continue_retrieval.return_value = None self._vops.get_dss_rp.side_effect = exceptions.VimException('error') self.assertEqual((), self._ds_sel.select_datastore(req)) self._vops.get_dss_rp.assert_called_once_with(host_1) # Test with three hosts and vCenter connection problem while fetching # datastores for the second host. self._vops.get_dss_rp.reset_mock() host_2 = self._create_host('host-2') host_3 = self._create_host('host-3') self._vops.get_hosts.return_value = mock.Mock( objects=[mock.Mock(obj=host_1), mock.Mock(obj=host_2), mock.Mock(obj=host_3)]) self._vops.get_dss_rp.side_effect = [ exceptions.VimException('no valid datastores'), exceptions.VimConnectionException('connection error')] self.assertRaises(exceptions.VimConnectionException, self._ds_sel.select_datastore, req) get_dss_rp_exp_calls = [mock.call(host_1), mock.call(host_2)] self.assertEqual(get_dss_rp_exp_calls, self._vops.get_dss_rp.call_args_list) # Modify previous case to return datastores for second and third host, # where none of them meet the requirements which include a storage # profile and affinity requirements. aff_ds_types = [ds_sel.DatastoreType.VMFS] req[ds_sel.DatastoreSelector.HARD_AFFINITY_DS_TYPE] = aff_ds_types ds_1a = mock.sentinel.ds_1a anti_affinity_ds = [ds_1a] req[ds_sel.DatastoreSelector.HARD_ANTI_AFFINITY_DS] = anti_affinity_ds profile_name = mock.sentinel.profile_name req[ds_sel.DatastoreSelector.PROFILE_NAME] = profile_name profile_id = mock.sentinel.profile_id get_profile_id.return_value = profile_id ds_2a = mock.sentinel.ds_2a ds_2b = mock.sentinel.ds_2b ds_3a = mock.sentinel.ds_3a self._vops.get_dss_rp.reset_mock() rp_2 = mock.sentinel.rp_2 rp_3 = mock.sentinel.rp_3 self._vops.get_dss_rp.side_effect = [ exceptions.VimException('no valid datastores'), ([ds_2a, ds_2b], rp_2), ([ds_3a], rp_3)] filter_datastores.return_value = [] self.assertEqual((), self._ds_sel.select_datastore(req)) get_profile_id.assert_called_once_with(profile_name) get_dss_rp_exp_calls.append(mock.call(host_3)) self.assertEqual(get_dss_rp_exp_calls, self._vops.get_dss_rp.call_args_list) filter_datastores_exp_calls = [ mock.call([ds_2a, ds_2b], size_bytes, profile_id, anti_affinity_ds, aff_ds_types), mock.call([ds_3a], size_bytes, profile_id, anti_affinity_ds, aff_ds_types)] self.assertEqual(filter_datastores_exp_calls, filter_datastores.call_args_list) # Modify previous case to have a non-empty summary list after filtering # with preferred utilization threshold unset. self._vops.get_dss_rp.side_effect = [ exceptions.VimException('no valid datastores'), ([ds_2a, ds_2b], rp_2), ([ds_3a], rp_3)] summary_2b = self._create_summary(ds_2b, free_space=0.5 * units.Mi, capacity=units.Mi) filter_datastores.side_effect = [[summary_2b]] self._vops.get_connected_hosts.return_value = [host_1] self.assertEqual((host_2, rp_2, summary_2b), self._ds_sel.select_datastore(req)) # Modify previous case to have a preferred utilization threshold # satsified by one datastore. self._vops.get_dss_rp.side_effect = [ exceptions.VimException('no valid datastores'), ([ds_2a, ds_2b], rp_2), ([ds_3a], rp_3)] req[ds_sel.DatastoreSelector.PREF_UTIL_THRESH] = 0.4 summary_3a = self._create_summary(ds_3a, free_space=0.7 * units.Mi, capacity=units.Mi) filter_datastores.side_effect = [[summary_2b], [summary_3a]] self.assertEqual((host_3, rp_3, summary_3a), self._ds_sel.select_datastore(req)) # Modify previous case to have a preferred utilization threshold # which cannot be satisfied. self._vops.get_dss_rp.side_effect = [ exceptions.VimException('no valid datastores'), ([ds_2a, ds_2b], rp_2), ([ds_3a], rp_3)] filter_datastores.side_effect = [[summary_2b], [summary_3a]] req[ds_sel.DatastoreSelector.PREF_UTIL_THRESH] = 0.2 summary_2b.freeSpace = 0.75 * units.Mi self.assertEqual((host_2, rp_2, summary_2b), self._ds_sel.select_datastore(req)) # Clear side effects. self._vops.get_dss_rp.side_effect = None