def test_update_progress_with_error(self):
     session = self._create_mock_session(True, 10)
     handle = rw_handles.VmdkWriteHandle(session, '10.1.2.3',
                                         'rp-1', 'folder-1', None,
                                         100)
     session.invoke_api.side_effect = exceptions.VimException(None)
     self.assertRaises(exceptions.VimException, handle.update_progress)
 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)
Example #3
0
    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
        """
        LOG.debug("Invoking VIM API to read state of lease: %s.", lease)
        try:
            state = self.invoke_api(vim_util, 'get_object_property', self.vim,
                                    lease, 'state')
        except exceptions.VimException:
            with excutils.save_and_reraise_exception():
                LOG.exception(
                    _LE("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)
Example #4
0
 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,
                       lambda: 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')
Example #5
0
 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()
     self.assertRaises(exceptions.VimException,
                       lambda: api_session.wait_for_task(task))
     api_session.invoke_api.assert_called_once_with(vim_util,
                                                    'get_object_property',
                                                    api_session.vim, task,
                                                    'info')
Example #6
0
 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')
Example #7
0
 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
Example #8
0
 def _create_connection(self, session, url):
     LOG.debug(_("Opening URL: %s for reading."), url)
     try:
         cookies = session.vim.client.options.transport.cookiejar
         headers = {'User-Agent': USER_AGENT,
                    'Cookie': self._build_vim_cookie_header(cookies)}
         request = urllib2.Request(url, None, headers)
         conn = urllib2.urlopen(request)
         LOG.debug(_("URL: %s opened for reading."), url)
         return conn
     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)
Example #9
0
    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)
Example #10
0
    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 (socket.error, httplib.NotConnected) 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)
Example #11
0
        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)
                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
                detail = doc.childAtPath('/Envelope/Body/Fault/detail')
                fault_list = []
                if detail:
                    for child in detail.getChildren():
                        fault_list.append(child.get('type'))
                raise exceptions.VimFaultException(
                    fault_list,
                    _("Web fault in %s.") % attr_name, excep)

            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)
Example #12
0
        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_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 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)
Example #13
0
 def test_exception_summary_string(self):
     e = exceptions.VimException(_("string"), ValueError("foo"))
     string = str(e)
     self.assertEqual("string\nCause: foo", string)
Example #14
0
 def func(*args, **kwargs):
     raise exceptions.VimException(None)