我们从Python开源项目中,提取了以下13个代码示例,用于说明如何使用eventlet.timeout()。
def generate_request(self, verb, url, headers, post_data=None): try: # import pdb; pdb.set_trace() req = request.Request(url, data=post_data.encode("utf-8") if post_data is not None else None, headers=headers, method=verb) if self.proxy: req.set_proxy(self.proxy_config, urllib.parse.urlparse(url).scheme) response = request.urlopen(req, timeout=60, context=self.create_ctx()) else: response = request.urlopen(req, timeout=60, context=self.create_ctx()) self.status_code.append(int(response.code)) except error.HTTPError as e: self.status_code.append(int(e.code)) except error.URLError as e: self.sns_logger(status_codes={}, exception=str(e.reason), subject="Grizzly Error") except Exception: import traceback self.sns_logger(status_codes={}, exception=str(traceback.format_exc()), subject="Grizzly Error") print(('generic exception: ' + traceback.format_exc()))
def sanity_check(self, client, computed_requests): ''' This method checks that the sanity_check_url provides a 200 status code. If the sanity check fails, the application exists. ''' req = request.Request(client, headers=self.computed_requests["headers"][0]) response = request.urlopen(req, timeout=60, context=self.create_ctx()) if response.code != 200: self.sns_logger(status_codes={}, exception=str(response.code), subject="Grizzly Sanity Check Failed", url=client) raise else: self.sns_logger(status_codes={}, exception=str(response.code), subject="Grizzly Sanity Check Passed", url=client) print('Sanity check passed: 200 OK') return True
def shutdown(self, timeout=None): """ :return: """ with self._shutdown_lock: if hasattr(self, '_proc') and self._proc is not None: try: self._proc.kill() self._proc.wait() finally: del self._proc self._logger.info(u'PhantomJS terminated.') if self._stderr_reader is not None: self._stderr_reader.shutdown()
def _check_instance_build_time(self, context): """Ensure that instances are not stuck in build.""" timeout = CONF.instance_build_timeout if timeout == 0: return filters = {'vm_state': vm_states.BUILDING, 'host': self.host} building_insts = objects.InstanceList.get_by_filters(context, filters, expected_attrs=[], use_slave=True) for instance in building_insts: if timeutils.is_older_than(instance.created_at, timeout): self._set_instance_obj_error_state(context, instance) LOG.warning(_LW("Instance build timed out. Set to error " "state."), instance=instance)
def _wait(self, timeout=None): while not self._cond: self._ev.wait()
def wait(self, timeout=None): if timeout is None: self._wait() else: try: with Timeout(timeout): self._wait() except Timeout: pass return self._cond
def _on_signal(self, sig, frame): """""" self.shutdown(timeout=0) os._exit(0)
def _get_power_off_values(self, context, instance, clean_shutdown): """Get the timing configuration for powering down this instance.""" if clean_shutdown: timeout = compute_utils.get_value_from_system_metadata(instance, key='image_os_shutdown_timeout', type=int, default=CONF.shutdown_timeout) retry_interval = self.SHUTDOWN_RETRY_INTERVAL else: timeout = 0 retry_interval = 0 return timeout, retry_interval
def _power_off_instance(self, context, instance, clean_shutdown=True): """Power off an instance on this host.""" timeout, retry_interval = self._get_power_off_values(context, instance, clean_shutdown) self.driver.power_off(instance, timeout, retry_interval)
def _running_deleted_instances(self, context): """Returns a list of instances nova thinks is deleted, but the hypervisor thinks is still running. """ timeout = CONF.running_deleted_instance_timeout filters = {'deleted': True, 'soft_deleted': False, 'host': self.host} instances = self._get_instances_on_driver(context, filters) return [i for i in instances if self._deleted_old_enough(i, timeout)]
def wait_for_instance_event(self, instance, event_names, deadline=300, error_callback=None): """Plan to wait for some events, run some code, then wait. This context manager will first create plans to wait for the provided event_names, yield, and then wait for all the scheduled events to complete. Note that this uses an eventlet.timeout.Timeout to bound the operation, so callers should be prepared to catch that failure and handle that situation appropriately. If the event is not received by the specified timeout deadline, eventlet.timeout.Timeout is raised. If the event is received but did not have a 'completed' status, a NovaException is raised. If an error_callback is provided, instead of raising an exception as detailed above for the failure case, the callback will be called with the event_name and instance, and can return True to continue waiting for the rest of the events, False to stop processing, or raise an exception which will bubble up to the waiter. :param instance: The instance for which an event is expected :param event_names: A list of event names. Each element can be a string event name or tuple of strings to indicate (name, tag). :param deadline: Maximum number of seconds we should wait for all of the specified events to arrive. :param error_callback: A function to be called if an event arrives """ if error_callback is None: error_callback = self._default_error_callback events = {} for event_name in event_names: if isinstance(event_name, tuple): name, tag = event_name event_name = objects.InstanceExternalEvent.make_key( name, tag) try: events[event_name] = ( self._compute.instance_events.prepare_for_instance_event( instance, event_name)) except exception.NovaException: error_callback(event_name, instance) # NOTE(danms): Don't wait for any of the events. They # should all be canceled and fired immediately below, # but don't stick around if not. deadline = 0 yield with eventlet.timeout.Timeout(deadline): for event_name, event in events.items(): actual_event = event.wait() if actual_event.status == 'completed': continue decision = error_callback(event_name, instance) if decision is False: break