Ejemplo n.º 1
0
    def wait_reports(self, num_reports, timeout=2.0):
        """Wait for a fixed number of reports to be received

        Args:
            num_reports (int): The number of reports to wait for
            timeout (float): The maximum number of seconds to wait without
                receiving another report.
        """

        if self._stream_queue is None:
            raise ExternalError(
                "You have to enable streaming before you can wait for reports")

        reports = []

        for i in range(0, num_reports):
            try:
                report = self._stream_queue.get(timeout=timeout)
                reports.append(report)
            except Empty:
                raise TimeoutExpiredError("Timeout waiting for a report",
                                          expected_number=num_reports,
                                          received_number=i,
                                          received_reports=reports)

        return reports
Ejemplo n.º 2
0
    def send_ping(self, timeout=10.0):
        """Send a ping message to keep connection alive and to verify
        if the server is still there."""

        self.ping(self.control_data)

        flag = self._pong_received.wait(timeout=timeout)
        if not flag:
            raise TimeoutExpiredError("Timeout waiting for pong response")

        self._pong_received.clear()
Ejemplo n.º 3
0
        async def _awaiter():
            background_work = {x.join() for x in self._work_queues}
            for event in self._events:
                if not event.is_set():
                    background_work.add(event.wait())

            _done, pending = await asyncio.wait(background_work,
                                                timeout=timeout)
            if len(pending) > 0:
                raise TimeoutExpiredError(
                    "Timeout waiting for event loop to become idle",
                    pending=pending)
Ejemplo n.º 4
0
    def wait_running(self, timeout=None):
        """Wait for the thread to pass control to its routine.

        Args:
            timeout (float): The maximum amount of time to wait
        """

        flag = self._running.wait(timeout)

        if flag is False:
            raise TimeoutExpiredError(
                "Timeout waiting for thread to start running")
Ejemplo n.º 5
0
    def start(self, timeout=5.0):
        """Synchronously connect to websocket server.

        Args:
            timeout (float): The maximum amount of time to wait for the
                connection to be established. Defaults to 5 seconds
        """

        try:
            self.connect()
        except Exception as exc:
            raise InternalError("Unable to connect to websockets host", reason=str(exc))

        flag = self._connected.wait(timeout=timeout)
        if not flag:
            raise TimeoutExpiredError("Conection attempt to host timed out")
Ejemplo n.º 6
0
    def stop(self, timeout=5.0):
        """Synchronously disconnect from websocket server.

        Args:
            timeout (float): The maximum amount of time to wait for the
                connection to be established. Defaults to 5 seconds
        """

        if not self.connected:
            return

        try:
            self.close()
        except Exception as exc:
            raise InternalError("Unable to disconnect from websockets host", reason=str(exc))

        flag = self._disconnection_finished.wait(timeout=timeout)
        if not flag:
            raise TimeoutExpiredError("Disconnection attempt from host timed out")
        self._disconnection_finished.clear()
Ejemplo n.º 7
0
    def wait_stopped(self, timeout=None, force=False):
        """Wait for the thread to stop.

        You must have previously called signal_stop or this function will hang.

        Args:
            timeout (float): The maximum time to wait for the thread to stop
                before raising a TimeoutExpiredError.  If force is True, TimeoutExpiredError
                is not raised and the thread is just marked as a daemon thread
                so that it does not block cleanly exiting the process.
            force (bool): If true and the thread does not exit in timeout seconds
                no error is raised since the thread is marked as daemon and will
                be killed when the process exits.
        """

        self.join(timeout)

        if self.is_alive() and force is False:
            raise TimeoutExpiredError(
                "Error waiting for background thread to exit", timeout=timeout)
Ejemplo n.º 8
0
    def stop_threadsafe(self):
        """Stop this task from another thread and wait for it to finish.

        This method must not be called from within the BackgroundEventLoop but
        will inject self.stop() into the event loop and block until it
        returns.

        Raises:
            TimeoutExpiredError: If the task does not stop in the given
                timeout specified in __init__()
        """

        if self.stopped:
            return

        try:
            self._loop.run_coroutine(self.stop())
        except asyncio.TimeoutError:
            raise TimeoutExpiredError(
                "Timeout stopping task {} with {} subtasks".format(
                    self.name, len(self.subtasks)))
Ejemplo n.º 9
0
    def wait(self, timeout=None):
        """Wait for this operation to finish.

        You can specify an optional timeout that defaults to no timeout if
        None is passed.  The result of the operation is returned from this
        method. If the operation raised an exception, it is reraised from this
        method.

        Args:
            timeout (float): The maximum number of seconds to wait before timing
                out.
        """

        flag = self._finished.wait(timeout=timeout)
        if flag is False:
            raise TimeoutExpiredError(
                "Timeout waiting for response to event loop operation")

        if self._exception is not None:
            self._raise_exception()

        return self._result
Ejemplo n.º 10
0
    def send_command(self, command, args, timeout=10.0):
        """Send a command and synchronously wait for a response.

        Args:
            command (string): The command name
            args (dict): Optional arguments
            timeout (float): The maximum time to wait for a response
        """

        msg = {x: y for x, y in viewitems(args)}
        msg['type'] = 'command'
        msg['operation'] = command
        msg['no_response'] = False

        with self._command_lock:
            self._response_received.clear()
            self.send_message(msg)

            flag = self._response_received.wait(timeout=timeout)
            if not flag:
                raise TimeoutExpiredError("Timeout waiting for response")

            self._response_received.clear()
            return self._last_response
Ejemplo n.º 11
0
    def wait_trace(self,
                   size,
                   timeout=None,
                   drop_before=False,
                   progress_callback=None):
        """Wait for a specific amount of tracing data to be received.

        This function is the equivalent of wait_reports for streaming data.
        It allows you to block until a specific amount of tracing data has
        been received.  The optional timeout parameter allows you to stop
        waiting if you never receive enough tracing data after a specific
        amount of time.

        Args:
            size (int): The number of bytes to wait for.
            timeout (float): The maximum number of seconds to wait for
                these bytes to be received.
            drop_before (bool): Truncate all data received until now
                before waiting for size bytes.
            progress_callback (callable): An optional progress callback that
                is called periodically with updates.  It should have the
                signature progress_callback(received_byte_count, total_byte_count)

        Returns:
            bytearray: The raw trace data obtained.
        """

        if drop_before:
            self._trace_data = bytearray()

        if progress_callback is None:
            progress_callback = lambda x, y: None

        if len(self._trace_data) >= size:
            progress_callback(size, size)

            data = self._trace_data[:size]
            self._trace_data = self._trace_data[size:]

            return data

        progress_callback(len(self._trace_data), size)

        start = time.time()
        while len(self._trace_data) < size:
            progress_callback(len(self._trace_data), size)
            self._accumulate_trace()

            time.sleep(0.1)
            now = time.time()

            if timeout is not None and ((now - start) > timeout):
                raise TimeoutExpiredError("Timeout waiting for tracing data",
                                          expected_size=size,
                                          received_size=len(self._trace_data),
                                          timeout=timeout)

        progress_callback(size, size)

        data = self._trace_data[:size]
        self._trace_data = self._trace_data[size:]

        return data