def get_object_properties_dict(vim, moref, properties_to_collect): """Get properties of the given managed object as a dict. :param vim: Vim object :param moref: managed object reference :param properties_to_collect: names of the managed object properties to be collected :returns: a dict of properties of the given managed object :raises: VimException, VimFaultException, VimAttributeException, VimSessionOverLoadException, VimConnectionException """ obj_contents = get_object_properties(vim, moref, properties_to_collect) if obj_contents is None: return {} property_dict = {} if hasattr(obj_contents[0], "propSet"): dynamic_properties = obj_contents[0].propSet if dynamic_properties: for prop in dynamic_properties: property_dict[prop.name] = prop.val # The object may have information useful for logging if hasattr(obj_contents[0], "missingSet"): for m in obj_contents[0].missingSet: LOG.warning( _LW("Unable to retrieve value for %(path)s " "Reason: %(reason)s"), {"path": m.path, "reason": m.fault.localizedMessage}, ) return property_dict
def _func(*args, **kwargs): 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.warning(_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 get_object_properties_dict(vim, moref, properties_to_collect): """Get properties of the given managed object as a dict. :param vim: Vim object :param moref: managed object reference :param properties_to_collect: names of the managed object properties to be collected :returns: a dict of properties of the given managed object :raises: VimException, VimFaultException, VimAttributeException, VimSessionOverLoadException, VimConnectionException """ obj_contents = get_object_properties(vim, moref, properties_to_collect) if obj_contents is None: return {} property_dict = {} if hasattr(obj_contents[0], 'propSet'): dynamic_properties = obj_contents[0].propSet if dynamic_properties: for prop in dynamic_properties: property_dict[prop.name] = prop.val # The object may have information useful for logging if hasattr(obj_contents[0], 'missingSet'): for m in obj_contents[0].missingSet: LOG.warning( _LW("Unable to retrieve value for %(path)s " "Reason: %(reason)s"), { 'path': m.path, 'reason': m.fault.localizedMessage }) return property_dict
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 _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): """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): """Close the file handle.""" try: self._file_handle.close() except Exception: LOG.warning(_LW("Error occurred while closing the file handle"), exc_info=True)
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 _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 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.warning(_LW("Error occurred while releasing the lease " "for %s."), self._url, exc_info=True) raise finally: super(VmdkReadHandle, self).close() LOG.debug("Closed VMDK read handle for %s.", self._url)
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) if clazz: raise clazz(six.text_type(excep), details=excep.details) raise except exceptions.VimConnectionException: with excutils.save_and_reraise_exception(): # Re-create the session during connection exception only # if the session has expired. Otherwise, it could be # a transient issue. if not self.is_current_session_active(): 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.warning(_LW("Error occurred while reading the HTTP response."), exc_info=True) super(FileWriteHandle, self).close()
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 _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 close(self): """Releases the lease and close the connection. :raises: VimAttributeException, VimSessionOverLoadException, VimConnectionException """ try: self._release_lease() except exceptions.VimException: LOG.warning(_LW("Error occurred while releasing the lease " "for %s."), self._url, exc_info=True) super(VmdkWriteHandle, self).close() LOG.debug("Closed VMDK write handle for %s.", self._url)
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 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.warning(_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 _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 only # if the session has expired. Otherwise, it could be # a transient issue. if not self.is_current_session_active(): 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 _print_deprecation_warning(clazz): LOG.warn(_LW("Exception %s is deprecated, it will be removed in the " "next release."), clazz.__name__)