예제 #1
0
    def request(self, method, path, **kwargs):
        path = '{}{}'.format(self.api_root, path)

        if self.credentials and self.credentials.is_expired():
            self._refresh_access_token()

        try:
            response = self.session.request(method, path, **kwargs)
        except requests.exceptions.SSLError as sslError:
            msg = 'Connection to {} failed: {}'.format(self.address, sslError)
            six.raise_from(ConnectionFailure(msg), None)
        except requests.exceptions.ConnectionError:
            raise ConnectionFailure('Connection to {} refused'.format(
                self.address))

        if 200 <= response.status_code < 300:
            return response

        exception_message = rest_pb2.RestExceptionMessage()
        try:
            exception_message.ParseFromString(response.content)
        except DecodeError:
            pass

        if response.status_code == 401:
            raise Unauthorized('401 Client Error: Unauthorized')
        elif response.status_code == 404:
            raise NotFound('404 Client Error: {}'.format(
                exception_message.msg))
        elif 400 <= response.status_code < 500:
            raise YamcsError('{} Client Error: {}'.format(
                response.status_code, exception_message.msg))
        raise YamcsError('{} Server Error: {}'.format(response.status_code,
                                                      exception_message.msg))
예제 #2
0
    def request(self, method, path, **kwargs):
        path = "{}{}".format(self.api_root, path)

        if self.credentials:
            self.credentials.before_request(self.session, self.auth_root)

        try:
            response = self.session.request(method, path, **kwargs)
        except requests.exceptions.SSLError as sslError:
            msg = "Connection to {} failed: {}".format(self.address, sslError)
            six.raise_from(ConnectionFailure(msg), None)
        except requests.exceptions.ConnectionError as e:
            raise ConnectionFailure("Connection to {} failed: {}".format(
                self.address, e))

        if 200 <= response.status_code < 300:
            return response

        exception_message = exception_pb2.ExceptionMessage()
        try:
            exception_message.ParseFromString(response.content)
        except DecodeError:
            pass

        if response.status_code == 401:
            raise Unauthorized("401 Client Error: Unauthorized")
        elif response.status_code == 404:
            raise NotFound("404 Client Error: {}".format(
                getattr(exception_message, "msg")))
        elif 400 <= response.status_code < 500:
            raise YamcsError("{} Client Error: {}".format(
                response.status_code, getattr(exception_message, "msg")))
        raise YamcsError("{} Server Error: {}".format(
            response.status_code, getattr(exception_message, "msg")))
예제 #3
0
    def request(self, method, path, **kwargs):
        path = f"{self.api_root}{path}"

        try:
            if self.credentials:
                self.credentials.before_request(self.session, self.auth_root)

            response = self.session.request(method, path, **kwargs)
        except requests.exceptions.SSLError as ssl_error:
            msg = f"Connection to {self.url} failed: {ssl_error}"
            raise ConnectionFailure(msg) from None
        except requests.exceptions.ConnectionError as e:
            # Requests gives us a horribly confusing error when a connection
            # is refused. Confirm and unwrap.
            if e.args and isinstance(e.args[0], urllib3.exceptions.MaxRetryError):
                # This is a string (which is still confusing ....)
                msg = e.args[0].args[0]
                if "refused" in msg:
                    msg = f"Connection to {self.url} failed: connection refused"
                    raise ConnectionFailure(msg) from None
                elif "not known" in msg:
                    msg = f"Connection to {self.url} failed: could not resolve hostname"
                    raise ConnectionFailure(msg) from None

            raise ConnectionFailure(f"Connection to {self.url} failed: {e}")

        if 200 <= response.status_code < 300:
            return response

        exception_message = exception_pb2.ExceptionMessage()
        try:
            exception_message.ParseFromString(response.content)
        except DecodeError:
            pass

        if response.status_code == 401:
            raise Unauthorized("401 Client Error: Unauthorized")
        elif response.status_code == 404:
            msg = getattr(exception_message, "msg")
            raise NotFound(f"404 Client Error: {msg}")
        elif 400 <= response.status_code < 500:
            msg = getattr(exception_message, "msg")
            raise YamcsError(f"{response.status_code} Client Error: {msg}")
        msg = getattr(exception_message, "msg")
        raise YamcsError(f"{response.status_code} Server Error: {msg}")
예제 #4
0
    def request(self, method, path, **kwargs):
        path = "{}{}".format(self.api_root, path)

        if self.credentials:
            self.credentials.before_request(self.session, self.auth_root)

        try:
            response = self.session.request(method, path, **kwargs)
        except requests.exceptions.SSLError as sslError:
            msg = "Connection to {} failed: {}".format(self.address, sslError)
            raise ConnectionFailure(msg) from None
        except requests.exceptions.ConnectionError as e:
            # Requests gives us a horribly confusing error when a connection
            # is refused. Confirm and unwrap.
            if e.args and isinstance(e.args[0],
                                     urllib3.exceptions.MaxRetryError):
                # This is a string (which is still confusing ....)
                msg = e.args[0].args[0]
                if "refused" in msg:
                    msg = "Connection to {} failed: connection refused".format(
                        self.address)
                    raise ConnectionFailure(msg) from None

            raise ConnectionFailure("Connection to {} failed: {}".format(
                self.address, e))

        if 200 <= response.status_code < 300:
            return response

        exception_message = exception_pb2.ExceptionMessage()
        try:
            exception_message.ParseFromString(response.content)
        except DecodeError:
            pass

        if response.status_code == 401:
            raise Unauthorized("401 Client Error: Unauthorized")
        elif response.status_code == 404:
            raise NotFound("404 Client Error: {}".format(
                getattr(exception_message, "msg")))
        elif 400 <= response.status_code < 500:
            raise YamcsError("{} Client Error: {}".format(
                response.status_code, getattr(exception_message, "msg")))
        raise YamcsError("{} Server Error: {}".format(
            response.status_code, getattr(exception_message, "msg")))
예제 #5
0
    def _on_websocket_error(self, ws, error):
        logging.exception('WebSocket error')

        # Generate our own exception.
        # (the default message is misleading 'connection is already closed')
        if isinstance(error, websocket.WebSocketConnectionClosedException):
            error = ConnectionFailure('Connection closed')

        self._close_async(reason=error)
예제 #6
0
    def _on_websocket_error(self, ws, error):
        # Set to False to avoid printing some errors twice
        # (the ones that are generated during an initial connection)
        log_error = True

        # Generate custom exception.
        # (the default message is misleading 'connection is already closed')
        if isinstance(error, websocket.WebSocketConnectionClosedException):
            error = ConnectionFailure("Connection closed")
        elif isinstance(error, websocket.WebSocketAddressException):
            # No log because this error usually happens while blocking on an
            # initial connection, so prefer not to print it twice.
            log_error = False
            msg = f"Connection to {self.ctx.url} failed: could not resolve hostname"
            error = ConnectionFailure(msg)
        elif isinstance(error, ConnectionRefusedError):
            log_error = False
            msg = f"Connection to {self.ctx.url} failed: connection refused"
            error = ConnectionFailure(msg)

        if log_error:
            logger.error("WebSocket error: %s", error)

        self._close_async(reason=error)
예제 #7
0
    def get_auth_info(self):
        """
        Returns general authentication information. This operation
        does not require authenticating and is useful to test
        if a server requires authentication or not.

        :rtype: .AuthInfo
        """
        try:
            response = self.session.get(
                self.auth_root, headers={"Accept": "application/protobuf"})
            message = auth_pb2.AuthInfo()
            message.ParseFromString(response.content)
            return AuthInfo(message)
        except requests.exceptions.ConnectionError:
            raise ConnectionFailure("Connection to {} refused".format(
                self.address))