def free(host, port, timeout=float('Inf')): """ Wait for the specified port to become free (dropping or rejecting requests). Return when the port is free or raise a Timeout if timeout has elapsed. Timeout may be specified in seconds or as a timedelta. If timeout is None or ∞, the routine will run indefinitely. >>> free('localhost', find_available_local_port()) """ if not host: raise ValueError("Host values of '' or None are not allowed.") if isinstance(timeout, datetime.timedelta): timeout = timeout.total_seconds() if timeout is None: # treat None as infinite timeout timeout = float('Inf') watch = timing.Stopwatch() while total_seconds(watch.split()) < timeout: try: # Expect a free port, so use a small timeout Checker(timeout=0.1).assert_free(host, port) return except PortNotFree: # Politely wait. time.sleep(0.1) raise Timeout("Port {port} not free on {host}.".format(**locals()))
def __init__(self, db_uri=None): super().__init__() self.store = FeedparserDB.from_URI(db_uri) timer = timing.Stopwatch() self.update(self.store.get_seen_feeds()) log.info("Loaded feed history in %s", timer.split()) storage.SelectableStorage._finalizers.append(self.__finalize)
def run(cls, args): with timing.Stopwatch() as watch: all_swarms = _get_swarms(args) tmpl = "Loaded {n_swarms} swarms in {watch.elapsed}" msg = tmpl.format(n_swarms=len(all_swarms), watch=watch) print(msg) filtered_swarms = args.filter.matches(all_swarms) consume(map(print, sorted(filtered_swarms)))
def test_Stopwatch_timezone_change(monkeypatch): """ The stopwatch should provide a consistent duration even if the timezone changes. """ watch = timing.Stopwatch() with change('AEST-10AEDT-11,M10.5.0,M3.5.0', monkeypatch): assert abs(watch.split().total_seconds()) < 0.1
def test_Stopwatch_timezone_change(alt_tz): """ The stopwatch should provide a consistent duration even if the timezone changes. """ watch = timing.Stopwatch() with alt_tz: assert abs(watch.split().total_seconds()) < 0.1
def test_MongoDBReplicaSet_starts_quickly(): pytest.skip("Takes 20-30 seconds") sw = timing.Stopwatch() rs = service.MongoDBReplicaSet() rs.start() try: elapsed = sw.split() limit = datetime.timedelta(seconds=5) assert elapsed < limit finally: rs.stop()
def acquire(self): """ Attempt to acquire the lock every `delay` seconds until the lock is acquired or until `timeout` has expired. Raises FileLockTimeout if the timeout is exceeded. Errors opening the lock file (other than if it exists) are passed through. """ self.lock = retry_call( self._attempt, retries=float('inf'), trap=zc.lockfile.LockError, cleanup=functools.partial(self._check_timeout, timing.Stopwatch()), )
def _do_build(build, build_yaml): with timing.Stopwatch() as watch: # enter a temp folder with tmpdir(): try: _try_build(build, build_yaml) except Exception: logger.exception('Build failed') build.status = 'failed' # Don't raise, or we'll mask the real error try_get_compile_log(build, re_raise=False) raise finally: build.end_time = timezone.now() build.save() msg = "Completed build %s in %s" % (build, watch.elapsed) send_event(str(build), msg, tags=['build', 'success'])
def start(self): super(MongoDBReplicaSet, self).start() self.data_root = tempfile.mkdtemp() self.instances = list(map(self.start_instance, range(3))) # initialize the replica set self.instances[0].connect().admin.command('replSetInitiate', self.build_config()) # wait until the replica set is initialized get_repl_set_status = functools.partial( self.instances[0].connect().admin.command, 'replSetGetStatus', 1) errors = importlib.import_module('pymongo.errors') log.info('Waiting for replica set to initialize') watch = timing.Stopwatch() while watch.elapsed < datetime.timedelta(minutes=5): try: res = get_repl_set_status() if res.get('myState') != 1: continue except errors.OperationFailure: continue break else: raise RuntimeError("timeout waiting for replica set to start")
def occupied(host, port, timeout=float('Inf')): """ Wait for the specified port to become occupied (accepting requests). Return when the port is occupied or raise a Timeout if timeout has elapsed. Timeout may be specified in seconds or as a timedelta. If timeout is None or ∞, the routine will run indefinitely. >>> occupied('localhost', find_available_local_port(), .1) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... Timeout: Port ... not bound on localhost. """ if not host: raise ValueError("Host values of '' or None are not allowed.") if isinstance(timeout, datetime.timedelta): timeout = timeout.total_seconds() if timeout is None: # treat None as infinite timeout timeout = float('Inf') watch = timing.Stopwatch() while total_seconds(watch.split()) < timeout: try: Checker(timeout=.5).assert_free(host, port) # Politely wait time.sleep(0.1) except PortNotFree: # port is occupied return raise Timeout("Port {port} not bound on {host}.".format(**locals()))