|
| 1 | +import requests |
| 2 | +import six |
| 3 | +import tenacity |
| 4 | + |
| 5 | +from ddtrace.context import Context |
| 6 | +from ddtrace.filters import TraceFilter |
| 7 | +from ddtrace.propagation.http import HTTPPropagator |
| 8 | + |
| 9 | + |
| 10 | +class Client(object): |
| 11 | + """HTTP Client for making requests to a local http server.""" |
| 12 | + |
| 13 | + def __init__(self, base_url): |
| 14 | + # type: (str) -> None |
| 15 | + self._base_url = base_url |
| 16 | + self._session = requests.Session() |
| 17 | + # Propagate traces with trace_id = 1 for the ping trace so we can filter them out. |
| 18 | + c, d = Context(trace_id=1, span_id=1), {} |
| 19 | + HTTPPropagator.inject(c, d) |
| 20 | + self._ignore_headers = d |
| 21 | + |
| 22 | + def _url(self, path): |
| 23 | + # type: (str) -> str |
| 24 | + return six.moves.urllib.parse.urljoin(self._base_url, path) |
| 25 | + |
| 26 | + def get(self, path, **kwargs): |
| 27 | + return self._session.get(self._url(path), **kwargs) |
| 28 | + |
| 29 | + def get_ignored(self, path, **kwargs): |
| 30 | + """Do a normal get request but signal that the trace should be filtered out. |
| 31 | +
|
| 32 | + The signal is a distributed trace id header with the value 1. |
| 33 | + """ |
| 34 | + headers = kwargs.get("headers", {}).copy() |
| 35 | + headers.update(self._ignore_headers) |
| 36 | + kwargs["headers"] = headers |
| 37 | + return self._session.get(self._url(path), **kwargs) |
| 38 | + |
| 39 | + def post(self, path, *args, **kwargs): |
| 40 | + return self._session.post(self._url(path), *args, **kwargs) |
| 41 | + |
| 42 | + def request(self, method, path, *args, **kwargs): |
| 43 | + return self._session.request(method, self._url(path), *args, **kwargs) |
| 44 | + |
| 45 | + def wait(self, path="/", max_tries=100, delay=0.1): |
| 46 | + # type: (str, int, float) -> None |
| 47 | + """Wait for the server to start by repeatedly http `get`ting `path` until a 200 is received.""" |
| 48 | + |
| 49 | + @tenacity.retry(stop=tenacity.stop_after_attempt(max_tries), wait=tenacity.wait_fixed(delay)) |
| 50 | + def ping(): |
| 51 | + r = self.get_ignored(path) |
| 52 | + assert r.status_code == 200 |
| 53 | + |
| 54 | + ping() |
| 55 | + |
| 56 | + |
| 57 | +class PingFilter(TraceFilter): |
| 58 | + def process_trace(self, trace): |
| 59 | + # Filter out all traces with trace_id = 1 |
| 60 | + # This is done to prevent certain traces from being included in snapshots and |
| 61 | + # accomplished by propagating an http trace id of 1 with the request to the webserver. |
| 62 | + return None if trace and trace[0].trace_id == 1 else trace |
0 commit comments