Beispiel #1
0
def get_org_query_param(org, client, required_id=False):
    """
    Get required type of Org query parameter.

    :param str, Organization org: value provided as a parameter into API (optional)
    :param InfluxDBClient client: with default value for Org parameter
    :param bool required_id: true if the query param has to be a ID
    :return: request type of org query parameter or None
    """
    _org = client.org if org is None else org
    if 'Organization' in type(_org).__name__:
        _org = _org.id
    if required_id and _org and not _is_id(_org):
        try:
            organizations = client.organizations_api().find_organizations(
                org=_org)
            if len(organizations) < 1:
                from influxdb_client.client.exceptions import InfluxDBError
                message = f"The client cannot find organization with name: '{_org}' " \
                          "to determine their ID. Are you using token with sufficient permission?"
                raise InfluxDBError(response=None, message=message)
            return organizations[0].id
        except ApiException as e:
            if e.status == 404:
                from influxdb_client.client.exceptions import InfluxDBError
                message = f"The client cannot find organization with name: '{_org}' " \
                          "to determine their ID."
                raise InfluxDBError(response=None, message=message)
            raise e

    return _org
Beispiel #2
0
    def test_message_get_retry_after(self):
        response = HTTPResponse(reason="too many requests")
        response.headers.add('Retry-After', '63')

        influx_db_error = InfluxDBError(response=response)
        self.assertEqual("too many requests", str(influx_db_error))
        self.assertEqual("63", influx_db_error.retry_after)

        influx_db_error = InfluxDBError(response=HTTPResponse(
            reason="too many requests"))
        self.assertEqual("too many requests", str(influx_db_error))
        self.assertEqual(None, influx_db_error.retry_after)
Beispiel #3
0
    def increment(self,
                  method=None,
                  url=None,
                  response=None,
                  error=None,
                  _pool=None,
                  _stacktrace=None):
        """Return a new Retry object with incremented retry counters."""
        new_retry = super().increment(method, url, response, error, _pool,
                                      _stacktrace)

        if response is not None:
            parsed_error = InfluxDBError(response=response)
        elif error is not None:
            parsed_error = error
        else:
            parsed_error = f"Failed request to: {url}"

        message = f"The retriable error occurred during request. Reason: '{parsed_error}'."
        if isinstance(parsed_error, InfluxDBError):
            message += f" Retry in {parsed_error.retry_after}s."

        logger.warning(message)

        return new_retry
class InfluxDBClientAsync(_BaseClient):
    """InfluxDBClientAsync is client for InfluxDB v2."""

    def __init__(self, url, token: str = None, org: str = None, debug=None, timeout=10_000, enable_gzip=False,
                 **kwargs) -> None:
        """
        Initialize defaults.

        :param url: InfluxDB server API url (ex. http://localhost:8086).
        :param token: ``token`` to authenticate to the InfluxDB 2.x
        :param org: organization name (used as a default in Query, Write and Delete API)
        :param debug: enable verbose logging of http requests
        :param timeout: The maximal number of milliseconds for the whole HTTP request including
                        connection establishment, request sending and response reading.
                        It can also be a :class:`~aiohttp.ClientTimeout` which is directly pass to ``aiohttp``.
        :param enable_gzip: Enable Gzip compression for http requests. Currently, only the "Write" and "Query" endpoints
                            supports the Gzip compression.
        :key bool verify_ssl: Set this to false to skip verifying SSL certificate when calling API from https server.
        :key str ssl_ca_cert: Set this to customize the certificate file to verify the peer.
        :key str proxy: Set this to configure the http proxy to be used (ex. http://localhost:3128)
        :key str proxy_headers: A dictionary containing headers that will be sent to the proxy. Could be used for proxy
                                authentication.
        :key int connection_pool_maxsize: The total number of simultaneous connections.
                                          Defaults to "multiprocessing.cpu_count() * 5".
        :key bool auth_basic: Set this to true to enable basic authentication when talking to a InfluxDB 1.8.x that
                              does not use auth-enabled but is protected by a reverse proxy with basic authentication.
                              (defaults to false, don't set to true when talking to InfluxDB 2)
        :key str username: ``username`` to authenticate via username and password credentials to the InfluxDB 2.x
        :key str password: ``password`` to authenticate via username and password credentials to the InfluxDB 2.x
        :key bool allow_redirects: If set to ``False``, do not follow HTTP redirects. ``True`` by default.
        :key int max_redirects: Maximum number of HTTP redirects to follow. ``10`` by default.
        :key dict client_session_kwargs: Additional configuration arguments for :class:`~aiohttp.ClientSession`
        :key type client_session_type: Type of aiohttp client to use. Useful for third party wrappers like
                                       ``aiohttp-retry``. :class:`~aiohttp.ClientSession` by default.
        :key list[str] profilers: list of enabled Flux profilers
        """
        super().__init__(url=url, token=token, org=org, debug=debug, timeout=timeout, enable_gzip=enable_gzip,
                         http_client_logger="aiohttp.client", **kwargs)

        # compatibility with Python 3.6
        if sys.version_info[:2] >= (3, 7):
            from asyncio import get_running_loop
        else:
            from asyncio import _get_running_loop as get_running_loop

        # check present asynchronous context
        try:
            loop = get_running_loop()
            # compatibility with Python 3.6
            if loop is None:
                raise RuntimeError('no running event loop')
        except RuntimeError:
            from influxdb_client.client.exceptions import InfluxDBError
            message = "The async client should be initialised inside async coroutine " \
                      "otherwise there can be unexpected behaviour."
            raise InfluxDBError(response=None, message=message)

        from .._async.api_client import ApiClientAsync
        self.api_client = ApiClientAsync(configuration=self.conf, header_name=self.auth_header_name,
                                         header_value=self.auth_header_value, retries=self.retries, **kwargs)
    def increment(self,
                  method=None,
                  url=None,
                  response=None,
                  error=None,
                  _pool=None,
                  _stacktrace=None):
        """Return a new Retry object with incremented retry counters."""
        if self.retry_timeout < datetime.now():
            raise MaxRetryError(
                _pool, url, error or ResponseError("max_retry_time exceeded"))

        new_retry = super().increment(method, url, response, error, _pool,
                                      _stacktrace)

        if response is not None:
            parsed_error = InfluxDBError(response=response)
        elif error is not None:
            parsed_error = error
        else:
            parsed_error = f"Failed request to: {url}"

        message = f"The retriable error occurred during request. Reason: '{parsed_error}'."
        if isinstance(parsed_error, InfluxDBError):
            message += f" Retry in {parsed_error.retry_after}s."

        if self.retry_callback:
            self.retry_callback(parsed_error)

        logger.warning(message)

        return new_retry
Beispiel #6
0
    def test_message(self):

        response = HTTPResponse()
        response.headers.add('X-Platform-Error-Code', 'too many requests 1')
        self.assertEqual("too many requests 1",
                         str(InfluxDBError(response=response)))

        response = HTTPResponse()
        response.headers.add('X-Influx-Error', 'too many requests 2')
        self.assertEqual("too many requests 2",
                         str(InfluxDBError(response=response)))

        response = HTTPResponse()
        response.headers.add('X-InfluxDb-Error', 'too many requests 3')
        self.assertEqual("too many requests 3",
                         str(InfluxDBError(response=response)))

        response = HTTPResponse(
            body=
            '{"code":"too many requests","message":"org 04014de4ed590000 has exceeded limited_write plan limit"}'
        )
        response.headers.add('X-InfluxDb-Error', 'error 3')
        self.assertEqual(
            "org 04014de4ed590000 has exceeded limited_write plan limit",
            str(InfluxDBError(response=response)))

        response = HTTPResponse(
            body='org 04014de4ed590000 has exceeded limited_write plan limit')
        response.headers.add('X-InfluxDb-Error', 'error 3')
        self.assertEqual(
            "org 04014de4ed590000 has exceeded limited_write plan limit",
            str(InfluxDBError(response=response)))

        response = HTTPResponse(reason='too many requests 4')
        self.assertEqual("too many requests 4",
                         str(InfluxDBError(response=response)))
Beispiel #7
0
 def test_response(self):
     response = HTTPResponse()
     self.assertEqual(response, InfluxDBError(response=response).response)
Beispiel #8
0
 def test_no_response(self):
     influx_db_error = InfluxDBError(response=None)
     self.assertEqual("no response", str(influx_db_error))
     self.assertIsNone(influx_db_error.response)
     self.assertIsNone(influx_db_error.retry_after)