Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
inputs = [
([], {'method': method, 'url': url}),
([method], {'url': url}),
([method, url], {}),
]
for args, kwargs in inputs:
# ensure a traced request works with these args
out = self.session.request(*args, **kwargs)
assert out.status_code == 200
# validation
spans = self.tracer.writer.pop()
assert len(spans) == 1
s = spans[0]
assert s.get_tag(http.METHOD) == 'GET'
assert s.get_tag(http.STATUS_CODE) == '200'
# with the proper tags
request = yield from self.client.request('GET', '/')
assert 200 == request.status
text = yield from request.text()
assert 'What\'s tracing?' == text
# the trace is created
traces = self.tracer.writer.pop_traces()
assert 1 == len(traces)
assert 1 == len(traces[0])
span = traces[0][0]
# with the right fields
assert 'aiohttp.request' == span.name
assert 'aiohttp-web' == span.service
assert 'web' == span.span_type
assert 'GET /' == span.resource
assert str(self.client.make_url('/')) == span.get_tag(http.URL)
assert 'GET' == span.get_tag('http.method')
assert '200' == span.get_tag('http.status_code')
assert 0 == span.error
self.assertEqual(span.span_type, 'http')
self.assertIsNone(span.service)
self.assertEqual(span.name, self.SPAN_NAME)
self.assertEqual(span.error, 0)
assert_dict_issuperset(
span.meta,
{
'http.method': 'GET',
'http.status_code': '200',
'http.url': URL_200,
}
)
if config.httplib.trace_query_string:
assert span.get_tag(http.QUERY_STRING) == query_string
else:
assert http.QUERY_STRING not in span.meta
)
],
)
async with httpx.AsyncClient(app=app) as client:
r = await client.get("http://testserver/", params={"foo": "bar"})
assert r.status_code == 200
assert r.text == "Hello, world!"
traces = tracer.writer.pop_traces()
assert len(traces) == 1
spans: List[Span] = traces[0]
assert len(spans) == 1
span = spans[0]
assert span.get_tag(http_ext.QUERY_STRING) == "foo=bar"
self.assertEqual(req_span.name, 'flask.request')
self.assertEqual(req_span.resource, 'GET /')
self.assertEqual(req_span.span_type, 'web')
self.assertEqual(req_span.error, 0)
self.assertIsNone(req_span.parent_id)
# Request tags
self.assertEqual(
set(['system.pid', 'flask.version', 'http.url', 'http.method',
'flask.endpoint', 'flask.url_rule', 'http.status_code']),
set(req_span.meta.keys()),
)
self.assertEqual(req_span.get_tag('flask.endpoint'), 'index')
self.assertEqual(req_span.get_tag('flask.url_rule'), '/')
self.assertEqual(req_span.get_tag('http.method'), 'GET')
self.assertEqual(req_span.get_tag(http.URL), 'http://localhost/')
self.assertEqual(req_span.get_tag('http.status_code'), '200')
# Handler span
handler_span = spans[4]
self.assertEqual(handler_span.service, 'test-flask')
self.assertEqual(handler_span.name, 'tests.contrib.flask_autopatch.test_flask_autopatch.index')
self.assertEqual(handler_span.resource, '/')
self.assertEqual(req_span.error, 0)
def test_worker_filter_request(self):
self.tracer.configure(settings={FILTERS_KEY: [FilterRequestsOnUrl(r'http://example\.com/health')]})
# spy the send() method
self.api = self.tracer.writer.api
self.api._put = mock.Mock(self.api._put, wraps=self.api._put)
span = self.tracer.trace('testing.filteredurl')
span.set_tag(http.URL, 'http://example.com/health')
span.finish()
span = self.tracer.trace('testing.nonfilteredurl')
span.set_tag(http.URL, 'http://example.com/api/resource')
span.finish()
self._wait_thread_flush()
# Only the second trace should have been sent
eq_(self.api._put.call_count, 1)
# check and retrieve the right call
endpoint, payload = self._get_endpoint_payload(self.api._put.call_args_list, '/v0.4/traces')
eq_(endpoint, '/v0.4/traces')
eq_(len(payload), 1)
eq_(payload[0][0]['name'], 'testing.nonfilteredurl')
# it should manage properly handlers with params
request = yield from self.client.request('GET', '/echo/team' + fqs)
assert 200 == request.status
text = yield from request.text()
assert 'Hello team' == text
# the trace is created
traces = self.tracer.writer.pop_traces()
assert 1 == len(traces)
assert 1 == len(traces[0])
span = traces[0][0]
# with the right fields
assert 'GET /echo/{name}' == span.resource
assert str(self.client.make_url('/echo/team')) == span.get_tag(http.URL)
assert '200' == span.get_tag('http.status_code')
if self.app[CONFIG_KEY].get('trace_query_string'):
assert query_string == span.get_tag(http.QUERY_STRING)
else:
assert http.QUERY_STRING not in span.meta
def process_trace(self, trace):
"""
When the filter is registered in the tracer, process_trace is called by
on each trace before it is sent to the agent, the returned value will
be fed to the next filter in the list. If process_trace returns None,
the whole trace is discarded.
"""
for span in trace:
if span.parent_id is None and span.get_tag(http.URL) is not None:
url = span.get_tag(http.URL)
for regexp in self._regexps:
if regexp.match(url):
return None
return trace
if method == 'GET':
span.set_tag(metadata.BODY, instance.serializer.dumps(body))
status = None
# set analytics sample rate
span.set_tag(
ANALYTICS_SAMPLE_RATE_KEY,
config.elasticsearch.get_analytics_sample_rate()
)
span = quantize(span)
try:
result = func(*args, **kwargs)
except elasticsearch.exceptions.TransportError as e:
span.set_tag(http.STATUS_CODE, getattr(e, 'status_code', 500))
raise
try:
# Optional metadata extraction with soft fail.
if isinstance(result, tuple) and len(result) == 2:
# elasticsearch<2.4; it returns both the status and the body
status, data = result
else:
# elasticsearch>=2.4; internal change for ``Transport.perform_request``
# that just returns the body
data = result
took = data.get('took')
if took:
span.set_metric(metadata.TOOK, int(took))
except Exception:
None,
None,
None,
)
)
parsed_uri = parse.urlparse(request_url)
hostname = parsed_uri.netloc
sanitized_url = sanitize_url_for_tag(request_url)
tracer = getattr(obj, "datadog_tracer", ddtrace.tracer)
if not tracer.enabled:
return func(*args, **kwargs)
with tracer.trace("urllib3.request", span_type=http.TYPE) as span:
span.service = _extract_service_name(span, hostname, config.urllib3["split_by_domain"])
# If distributed tracing is enabled, propagate the tracing headers to downstream services
if config.urllib3["distributed_tracing"]:
if request_headers is None:
request_headers = {}
kwargs["headers"] = request_headers
propagator = HTTPPropagator()
propagator.inject(span.context, request_headers)
store_request_headers(request_headers, span, config.urllib3)
span.set_tag(http.METHOD, request_method)
span.set_tag(http.URL, sanitized_url)
if config.urllib3["trace_query_string"]:
span.set_tag(http.QUERY_STRING, parsed_uri.query)