def _func(*args, **kwargs): func_name = f.__name__ result = None try: if self._retry_count: LOG.debug("Invoking %(func_name)s; retry count is " "%(retry_count)d.", {'func_name': func_name, 'retry_count': self._retry_count}) result = f(*args, **kwargs) except self._exceptions: with excutils.save_and_reraise_exception() as ctxt: LOG.warn(_LW("Exception which is in the suggested list of " "exceptions occurred while invoking function:" " %s."), func_name, exc_info=True) if (self._max_retry_count != -1 and self._retry_count >= self._max_retry_count): LOG.error(_LE("Cannot retry upon suggested exception " "since retry count (%(retry_count)d) " "reached max retry count " "(%(max_retry_count)d)."), {'retry_count': self._retry_count, 'max_retry_count': self._max_retry_count}) else: ctxt.reraise = False self._retry_count += 1 self._sleep_time += self._inc_sleep_time return self._sleep_time raise loopingcall.LoopingCallDone(result)
def _inner(): if initial_delay: greenthread.sleep(initial_delay) try: while self._running: start = timeutils.utcnow() self.f(*self.args, **self.kw) end = timeutils.utcnow() if not self._running: break delay = interval - timeutils.delta_seconds(start, end) if delay <= 0: LOG.warn(_LW('task run outlasted interval by %s sec'), -delay) greenthread.sleep(delay if delay > 0 else 0) except LoopingCallDone as e: self.stop() done.send(e.retvalue) except Exception: LOG.exception(_LE('in fixed duration looping call')) done.send_exception(*sys.exc_info()) return else: done.send(True)
def close(self): """Releases the lease and close the connection. :raises: VimException, VimFaultException, VimAttributeException, VimSessionOverLoadException, VimConnectionException """ LOG.debug("Getting lease state for %s.", self._url) try: state = self._session.invoke_api(vim_util, 'get_object_property', self._session.vim, self._lease, 'state') LOG.debug("Lease for %(url)s is in state: %(state)s.", { 'url': self._url, 'state': state }) if state == 'ready': LOG.debug("Releasing lease for %s.", self._url) self._session.invoke_api(self._session.vim, 'HttpNfcLeaseComplete', self._lease) else: LOG.debug( "Lease for %(url)s is in state: %(state)s; no " "need to release.", { 'url': self._url, 'state': state }) except exceptions.VimException: LOG.warn(_LW("Error occurred while releasing the lease for %s."), self._url, exc_info=True) raise super(VmdkReadHandle, self).close() LOG.debug("Closed VMDK read handle for %s.", self._url)
def close(self): """Close the file handle.""" try: self._file_handle.close() except Exception: LOG.warn(_LW("Error occurred while closing the file handle"), exc_info=True)
def close(self): """Releases the lease and close the connection. :raises: VimException, VimFaultException, VimAttributeException, VimSessionOverLoadException, VimConnectionException """ LOG.debug("Getting lease state for %s.", self._url) try: state = self._session.invoke_api(vim_util, 'get_object_property', self._session.vim, self._lease, 'state') LOG.debug("Lease for %(url)s is in state: %(state)s.", {'url': self._url, 'state': state}) if state == 'ready': LOG.debug("Releasing lease for %s.", self._url) self._session.invoke_api(self._session.vim, 'HttpNfcLeaseComplete', self._lease) else: LOG.debug("Lease for %(url)s is in state: %(state)s; no " "need to release.", {'url': self._url, 'state': state}) except exceptions.VimException: LOG.warn(_LW("Error occurred while releasing the lease for %s."), self._url, exc_info=True) raise super(VmdkReadHandle, self).close() LOG.debug("Closed VMDK read handle for %s.", self._url)
def _func(*args, **kwargs): func_name = f.__name__ result = None try: if self._retry_count: LOG.debug( "Invoking %(func_name)s; retry count is " "%(retry_count)d.", { 'func_name': func_name, 'retry_count': self._retry_count }) result = f(*args, **kwargs) except self._exceptions: with excutils.save_and_reraise_exception() as ctxt: LOG.warn(_LW("Exception which is in the suggested list of " "exceptions occurred while invoking function:" " %s."), func_name, exc_info=True) if (self._max_retry_count != -1 and self._retry_count >= self._max_retry_count): LOG.error( _LE("Cannot retry upon suggested exception " "since retry count (%(retry_count)d) " "reached max retry count " "(%(max_retry_count)d)."), { 'retry_count': self._retry_count, 'max_retry_count': self._max_retry_count }) else: ctxt.reraise = False self._retry_count += 1 self._sleep_time += self._inc_sleep_time return self._sleep_time raise loopingcall.LoopingCallDone(result)
def _invoke_api(module, method, *args, **kwargs): try: api_method = getattr(module, method) return api_method(*args, **kwargs) except exceptions.VimFaultException as excep: # If this is due to an inactive session, we should re-create # the session and retry. if exceptions.NOT_AUTHENTICATED in excep.fault_list: # The NotAuthenticated fault is set by the fault checker # due to an empty response. An empty response could be a # valid response; for e.g., response for the query to # return the VMs in an ESX server which has no VMs in it. # Also, the server responds with an empty response in the # case of an inactive session. Therefore, we need a way to # differentiate between these two cases. if self._is_current_session_active(): LOG.debug( "Returning empty response for " "%(module)s.%(method)s invocation.", { 'module': module, 'method': method }) return [] else: # empty response is due to an inactive session excep_msg = ( _("Current session: %(session)s is inactive; " "re-creating the session while invoking " "method %(module)s.%(method)s.") % { 'session': _trunc_id(self._session_id), 'module': module, 'method': method }) LOG.warn(excep_msg, exc_info=True) self._create_session() raise exceptions.VimConnectionException( excep_msg, excep) else: # no need to retry for other VIM faults like # InvalidArgument # Raise specific exceptions here if possible if excep.fault_list: LOG.debug("Fault list: %s", excep.fault_list) fault = excep.fault_list[0] clazz = exceptions.get_fault_class(fault) raise clazz(unicode(excep), excep.details) raise except exceptions.VimConnectionException: with excutils.save_and_reraise_exception(): # Re-create the session during connection exception. LOG.warn(_LW("Re-creating session due to connection " "problems while invoking method " "%(module)s.%(method)s."), { 'module': module, 'method': method }, exc_info=True) self._create_session()
def close(self): """Get the response and close the connection.""" LOG.debug("Closing write handle for %s.", self._url) try: self.conn.getresponse() except Exception: LOG.warn(_LW("Error occurred while reading the HTTP response."), exc_info=True) super(FileWriteHandle, self).close()
def _invoke_api(module, method, *args, **kwargs): try: api_method = getattr(module, method) return api_method(*args, **kwargs) except exceptions.VimFaultException as excep: # If this is due to an inactive session, we should re-create # the session and retry. if exceptions.NOT_AUTHENTICATED in excep.fault_list: # The NotAuthenticated fault is set by the fault checker # due to an empty response. An empty response could be a # valid response; for e.g., response for the query to # return the VMs in an ESX server which has no VMs in it. # Also, the server responds with an empty response in the # case of an inactive session. Therefore, we need a way to # differentiate between these two cases. if self._is_current_session_active(): LOG.debug("Returning empty response for " "%(module)s.%(method)s invocation.", {'module': module, 'method': method}) return [] else: # empty response is due to an inactive session excep_msg = ( _("Current session: %(session)s is inactive; " "re-creating the session while invoking " "method %(module)s.%(method)s.") % {'session': _trunc_id(self._session_id), 'module': module, 'method': method}) LOG.warn(excep_msg, exc_info=True) self._create_session() raise exceptions.VimConnectionException(excep_msg, excep) else: # no need to retry for other VIM faults like # InvalidArgument # Raise specific exceptions here if possible if excep.fault_list: LOG.debug("Fault list: %s", excep.fault_list) fault = excep.fault_list[0] clazz = exceptions.get_fault_class(fault) raise clazz(six.text_type(excep), excep.details) raise except exceptions.VimConnectionException: with excutils.save_and_reraise_exception(): # Re-create the session during connection exception. LOG.warn(_LW("Re-creating session due to connection " "problems while invoking method " "%(module)s.%(method)s."), {'module': module, 'method': method}, exc_info=True) self._create_session()
def _get_error_message(self, lease): """Get error message associated with the given lease.""" try: return self.invoke_api(vim_util, 'get_object_property', self.vim, lease, 'error') except exceptions.VimException: LOG.warn(_LW("Error occurred while reading error message for " "lease: %s."), lease, exc_info=True) return "Unknown"
def get_pbm_wsdl_location(vc_version): """Return PBM WSDL file location corresponding to VC version. :param vc_version: a dot-separated version string. For example, "1.2". :return: the pbm wsdl file location. """ if not vc_version: return ver = vc_version.split(".") major_minor = ver[0] if len(ver) >= 2: major_minor = "%s.%s" % (major_minor, ver[1]) curr_dir = os.path.abspath(os.path.dirname(__file__)) pbm_service_wsdl = os.path.join(curr_dir, "wsdl", major_minor, "pbmService.wsdl") if not os.path.exists(pbm_service_wsdl): LOG.warn(_LW("PBM WSDL file %s not found."), pbm_service_wsdl) return pbm_wsdl = urlparse.urljoin("file:", urllib.pathname2url(pbm_service_wsdl)) LOG.debug("Using PBM WSDL location: %s.", pbm_wsdl) return pbm_wsdl
def _create_session(self): """Establish session with the server.""" session_manager = self.vim.service_content.sessionManager # Login and create new session with the server for making API calls. LOG.debug("Logging in with username = %s.", self._server_username) session = self.vim.Login(session_manager, userName=self._server_username, password=self._server_password) prev_session_id, self._session_id = self._session_id, session.key # We need to save the username in the session since we may need it # later to check active session. The SessionIsActive method requires # the username parameter to be exactly same as that in the session # object. We can't use the username used for login since the Login # method ignores the case. self._session_username = session.userName LOG.info( _LI("Successfully established new session; session ID is " "%s."), _trunc_id(self._session_id)) # Terminate the previous session (if exists) for preserving sessions # as there is a limit on the number of sessions we can have. if prev_session_id: try: LOG.info(_LI("Terminating the previous session with ID = %s"), _trunc_id(prev_session_id)) self.vim.TerminateSession(session_manager, sessionId=[prev_session_id]) except Exception: # This exception is something we can live with. It is # just an extra caution on our side. The session might # have been cleared already. We could have made a call to # SessionIsActive, but that is an overhead because we # anyway would have to call TerminateSession. LOG.warn(_LW("Error occurred while terminating the previous " "session with ID = %s."), _trunc_id(prev_session_id), exc_info=True) # Set PBM client cookie. if self._pbm is not None: self._pbm.set_soap_cookie(self._vim.get_http_cookie())
def _create_session(self): """Establish session with the server.""" session_manager = self.vim.service_content.sessionManager # Login and create new session with the server for making API calls. LOG.debug("Logging in with username = %s.", self._server_username) session = self.vim.Login(session_manager, userName=self._server_username, password=self._server_password) prev_session_id, self._session_id = self._session_id, session.key # We need to save the username in the session since we may need it # later to check active session. The SessionIsActive method requires # the username parameter to be exactly same as that in the session # object. We can't use the username used for login since the Login # method ignores the case. self._session_username = session.userName LOG.info(_LI("Successfully established new session; session ID is " "%s."), _trunc_id(self._session_id)) # Terminate the previous session (if exists) for preserving sessions # as there is a limit on the number of sessions we can have. if prev_session_id: try: LOG.info(_LI("Terminating the previous session with ID = %s"), _trunc_id(prev_session_id)) self.vim.TerminateSession(session_manager, sessionId=[prev_session_id]) except Exception: # This exception is something we can live with. It is # just an extra caution on our side. The session might # have been cleared already. We could have made a call to # SessionIsActive, but that is an overhead because we # anyway would have to call TerminateSession. LOG.warn(_LW("Error occurred while terminating the previous " "session with ID = %s."), _trunc_id(prev_session_id), exc_info=True) # Set PBM client cookie. if self._pbm is not None: self._pbm.set_soap_cookie(self._vim.get_http_cookie())
def _is_current_session_active(self): """Check if current session is active. :returns: True if the session is active; False otherwise """ LOG.debug("Checking if the current session: %s is active.", _trunc_id(self._session_id)) is_active = False try: is_active = self.vim.SessionIsActive( self.vim.service_content.sessionManager, sessionID=self._session_id, userName=self._session_username) except exceptions.VimException: LOG.warn(_LW("Error occurred while checking whether the " "current session: %s is active."), _trunc_id(self._session_id), exc_info=True) return is_active
def get_pbm_wsdl_location(vc_version): """Return PBM WSDL file location corresponding to VC version. :param vc_version: a dot-separated version string. For example, "1.2". :return: the pbm wsdl file location. """ if not vc_version: return ver = vc_version.split('.') major_minor = ver[0] if len(ver) >= 2: major_minor = '%s.%s' % (major_minor, ver[1]) curr_dir = os.path.abspath(os.path.dirname(__file__)) pbm_service_wsdl = os.path.join(curr_dir, 'wsdl', major_minor, 'pbmService.wsdl') if not os.path.exists(pbm_service_wsdl): LOG.warn(_LW("PBM WSDL file %s not found."), pbm_service_wsdl) return pbm_wsdl = urlparse.urljoin('file:', urllib.pathname2url(pbm_service_wsdl)) LOG.debug("Using PBM WSDL location: %s.", pbm_wsdl) return pbm_wsdl