Exemple #1
0
    def get_config(self, current_version=None, keys=None):
        """
        Gets configuration from a remote APM Server

        :param current_version: version of the current configuration
        :param keys: a JSON-serializable dict to identify this instance, e.g.
                {
                    "service": {
                        "name": "foo",
                        "environment": "bar"
                    }
                }
        :return: a three-tuple of new version, config dictionary and validity in seconds.
                 Any element of the tuple can be None.
        """
        url = self._config_url
        data = json_encoder.dumps(keys).encode("utf-8")
        headers = self._headers.copy()
        headers.update(self.auth_headers)
        max_age = 300
        if current_version:
            headers["If-None-Match"] = current_version
        try:
            response = self.http.urlopen("POST",
                                         url,
                                         body=data,
                                         headers=headers,
                                         timeout=self._timeout,
                                         preload_content=False)
        except (urllib3.exceptions.RequestError,
                urllib3.exceptions.HTTPError) as e:
            logger.debug("HTTP error while fetching remote config: %s",
                         compat.text_type(e))
            return current_version, None, max_age
        body = response.read()
        if "Cache-Control" in response.headers:
            try:
                max_age = int(
                    next(
                        re.finditer(
                            r"max-age=(\d+)",
                            response.headers["Cache-Control"])).groups()[0])
            except StopIteration:
                logger.debug("Could not parse Cache-Control header: %s",
                             response.headers["Cache-Control"])
        if response.status == 304:
            # config is unchanged, return
            logger.debug("Configuration unchanged")
            return current_version, None, max_age
        elif response.status >= 400:
            return None, None, max_age

        if not body:
            logger.debug(
                "APM Server answered with empty body and status code %s",
                response.status)
            return current_version, None, max_age

        return response.headers.get("Etag"), json_encoder.loads(
            body.decode("utf-8")), max_age
Exemple #2
0
def test_datetime():
    res = datetime.datetime(day=1,
                            month=1,
                            year=2011,
                            hour=1,
                            minute=1,
                            second=1)
    assert json.dumps(res) == '"2011-01-01T01:01:01.000000Z"'
Exemple #3
0
 def test_datetime(self):
     res = datetime.datetime(day=1,
                             month=1,
                             year=2011,
                             hour=1,
                             minute=1,
                             second=1)
     self.assertEquals(json.dumps(res), '"2011-01-01T01:01:01.000000Z"')
    def call(self, module, method, wrapped, instance, args, kwargs):
        args_len = len(args)
        http_method = args[0] if args_len else kwargs.get("method")
        http_path = args[1] if args_len > 1 else kwargs.get("url")
        params = args[2] if args_len > 2 else kwargs.get("params")
        body = params.pop(BODY_REF_NAME, None) if params else None

        api_method = params.pop(API_METHOD_KEY_NAME, None) if params else None

        signature = "ES %s %s" % (http_method, http_path)
        context = {"db": {"type": "elasticsearch"}}
        if api_method in self.query_methods:
            query = []
            # using both q AND body is allowed in some API endpoints / ES versions,
            # but not in others. We simply capture both if they are there so the
            # user can see it.
            if params and "q" in params:
                # 'q' is already encoded to a byte string at this point
                # we assume utf8, which is the default
                query.append("q=" +
                             params["q"].decode("utf-8", errors="replace"))
            if isinstance(body, dict) and "query" in body:
                query.append(json.dumps(body["query"]))
            context["db"]["statement"] = "\n\n".join(query)
        elif api_method == "Elasticsearch.update":
            if isinstance(body, dict) and "script" in body:
                # only get the `script` field from the body
                context["db"]["statement"] = json.dumps(
                    {"script": body["script"]})
        # TODO: add instance.base_url to context once we agreed on a format
        with elasticapm.capture_span(signature,
                                     "db.elasticsearch",
                                     extra=context,
                                     skip_frames=2,
                                     leaf=True):
            return wrapped(*args, **kwargs)
    def get_config(self, current_version=None, keys=None):
        url = self._config_url
        data = json_encoder.dumps(keys).encode("utf-8")
        headers = self._headers.copy()
        max_age = 300
        if current_version:
            headers["If-None-Match"] = current_version
        try:
            response = self.http.urlopen("POST",
                                         url,
                                         body=data,
                                         headers=headers,
                                         timeout=self._timeout,
                                         preload_content=False)
        except (urllib3.exceptions.RequestError,
                urllib3.exceptions.HTTPError) as e:
            logger.debug("HTTP error while fetching remote config: %s",
                         compat.text_type(e))
            return current_version, None, max_age
        body = response.read()
        if "Cache-Control" in response.headers:
            try:
                max_age = int(
                    next(
                        re.finditer(
                            r"max-age=(\d+)",
                            response.headers["Cache-Control"])).groups()[0])
            except StopIteration:
                logger.debug("Could not parse Cache-Control header: %s",
                             response["Cache-Control"])
        if response.status == 304:
            # config is unchanged, return
            logger.debug("Configuration unchanged")
            return current_version, None, max_age
        elif response.status >= 400:
            return None, None, max_age

        return response.headers.get("Etag"), json_encoder.loads(
            body.decode("utf-8")), max_age
 def encode(self, data):
     """
     Serializes ``data`` into a raw string.
     """
     return zlib.compress(json.dumps(data).encode('utf8'))
Exemple #7
0
def test_bytes():
    if compat.PY2:
        res = bytes("foobar")
    else:
        res = bytes("foobar", encoding="ascii")
    assert json.dumps(res) == '"foobar"'
Exemple #8
0
def test_frozenset():
    res = frozenset(["foo", "bar"])
    assert json.dumps(res) in ('["foo", "bar"]', '["bar", "foo"]')
Exemple #9
0
def test_uuid():
    res = uuid.uuid4()
    assert json.dumps(res) == '"%s"' % res.hex
def test_bytes():
    if compat.PY2:
        res = bytes('foobar')
    else:
        res = bytes('foobar', encoding='ascii')
    assert json.dumps(res) == '"foobar"'
def test_set():
    res = set(['foo', 'bar'])
    assert json.dumps(res) in ('["foo", "bar"]', '["bar", "foo"]')
Exemple #12
0
def test_unsupported():
    res = object()
    assert json.dumps(res).startswith('"<object object at')
Exemple #13
0
def test_decimal():
    res = decimal.Decimal("1.0")
    assert json.dumps(res) == "1.0"
Exemple #14
0
 def test_bytes(self):
     if six.PY2:
         res = bytes('foobar')
     else:
         res = bytes('foobar', encoding='ascii')
     self.assertEqual(json.dumps(res), '"foobar"')
Exemple #15
0
 def test_frozenset(self):
     res = frozenset(['foo', 'bar'])
     self.assertIn(json.dumps(res), ('["foo", "bar"]', '["bar", "foo"]'))
Exemple #16
0
 def test_uuid(self):
     res = uuid.uuid4()
     self.assertEquals(json.dumps(res), '"%s"' % res.hex)