|
| 1 | +import urllib |
| 2 | +from aiohttp import web |
| 3 | +from guillotina.utils import get_dotted_name |
| 4 | +from multidict import CIMultiDictProxy |
| 5 | +from opentelemetry import context, trace |
| 6 | +from opentelemetry.instrumentation.aiohttp_server.package import _instruments |
| 7 | +from opentelemetry.instrumentation.instrumentor import BaseInstrumentor |
| 8 | +from opentelemetry.instrumentation.utils import http_status_to_status_code |
| 9 | +from opentelemetry.propagate import extract |
| 10 | +from opentelemetry.propagators.textmap import Getter |
| 11 | +from opentelemetry.semconv.trace import SpanAttributes |
| 12 | +from opentelemetry.trace.status import Status, StatusCode |
| 13 | +from opentelemetry.util.http import get_excluded_urls |
| 14 | +from opentelemetry.util.http import remove_url_credentials |
| 15 | + |
| 16 | +from typing import Tuple |
| 17 | + |
| 18 | + |
| 19 | +_SUPPRESS_HTTP_INSTRUMENTATION_KEY = "suppress_http_instrumentation" |
| 20 | + |
| 21 | +tracer = trace.get_tracer(__name__) |
| 22 | +_excluded_urls = get_excluded_urls("FLASK") |
| 23 | + |
| 24 | + |
| 25 | +def get_default_span_details(request: web.Request) -> Tuple[str, dict]: |
| 26 | + """Default implementation for get_default_span_details |
| 27 | + Args: |
| 28 | + scope: the asgi scope dictionary |
| 29 | + Returns: |
| 30 | + a tuple of the span name, and any attributes to attach to the span. |
| 31 | + """ |
| 32 | + span_name = request.path.strip() or f"HTTP {request.method}" |
| 33 | + return span_name, {} |
| 34 | + |
| 35 | + |
| 36 | +def _get_view_func(request) -> str: |
| 37 | + """TODO: is this only working for guillotina?""" |
| 38 | + try: |
| 39 | + return get_dotted_name(request.found_view) |
| 40 | + except AttributeError: |
| 41 | + return "unknown" |
| 42 | + |
| 43 | + |
| 44 | +def collect_request_attributes(request: web.Request): |
| 45 | + """Collects HTTP request attributes from the ASGI scope and returns a |
| 46 | + dictionary to be used as span creation attributes.""" |
| 47 | + |
| 48 | + server_host, port, http_url = ( |
| 49 | + request.url.host, |
| 50 | + request.url.port, |
| 51 | + str(request.url), |
| 52 | + ) |
| 53 | + query_string = request.query_string |
| 54 | + if query_string and http_url: |
| 55 | + if isinstance(query_string, bytes): |
| 56 | + query_string = query_string.decode("utf8") |
| 57 | + http_url += "?" + urllib.parse.unquote(query_string) |
| 58 | + |
| 59 | + result = { |
| 60 | + SpanAttributes.HTTP_SCHEME: request.scheme, |
| 61 | + SpanAttributes.HTTP_HOST: server_host, |
| 62 | + SpanAttributes.NET_HOST_PORT: port, |
| 63 | + SpanAttributes.HTTP_ROUTE: _get_view_func(request), |
| 64 | + SpanAttributes.HTTP_FLAVOR: f"{request.version.major}.{request.version.minor}", |
| 65 | + SpanAttributes.HTTP_TARGET: request.path, |
| 66 | + SpanAttributes.HTTP_URL: remove_url_credentials(http_url), |
| 67 | + } |
| 68 | + |
| 69 | + http_method = request.method |
| 70 | + if http_method: |
| 71 | + result[SpanAttributes.HTTP_METHOD] = http_method |
| 72 | + |
| 73 | + http_host_value_list = ( |
| 74 | + [request.host] if type(request.host) != list else request.host |
| 75 | + ) |
| 76 | + if http_host_value_list: |
| 77 | + result[SpanAttributes.HTTP_SERVER_NAME] = ",".join( |
| 78 | + http_host_value_list |
| 79 | + ) |
| 80 | + http_user_agent = request.headers.get("user-agent") |
| 81 | + if http_user_agent: |
| 82 | + result[SpanAttributes.HTTP_USER_AGENT] = http_user_agent |
| 83 | + |
| 84 | + # remove None values |
| 85 | + result = {k: v for k, v in result.items() if v is not None} |
| 86 | + |
| 87 | + return result |
| 88 | + |
| 89 | + |
| 90 | +def set_status_code(span, status_code): |
| 91 | + """Adds HTTP response attributes to span using the status_code argument.""" |
| 92 | + if not span.is_recording(): |
| 93 | + return |
| 94 | + try: |
| 95 | + status_code = int(status_code) |
| 96 | + except ValueError: |
| 97 | + span.set_status( |
| 98 | + Status( |
| 99 | + StatusCode.ERROR, |
| 100 | + "Non-integer HTTP status: " + repr(status_code), |
| 101 | + ) |
| 102 | + ) |
| 103 | + else: |
| 104 | + span.set_attribute(SpanAttributes.HTTP_STATUS_CODE, status_code) |
| 105 | + span.set_status( |
| 106 | + Status(http_status_to_status_code(status_code, server_span=True)) |
| 107 | + ) |
| 108 | + |
| 109 | + |
| 110 | +class AiohttpGetter(Getter): |
| 111 | + """Extract current trace from headers""" |
| 112 | + |
| 113 | + def get(self, carrier, key: str): |
| 114 | + """Getter implementation to retrieve a HTTP header value from the ASGI |
| 115 | + scope. |
| 116 | +
|
| 117 | + Args: |
| 118 | + carrier: ASGI scope object |
| 119 | + key: header name in scope |
| 120 | + Returns: |
| 121 | + A list with a single string with the header value if it exists, |
| 122 | + else None. |
| 123 | + """ |
| 124 | + headers: CIMultiDictProxy = carrier.headers |
| 125 | + if not headers: |
| 126 | + return None |
| 127 | + return headers.getall(key, None) |
| 128 | + |
| 129 | + def keys(self, carrier: dict): |
| 130 | + return list(carrier.keys()) |
| 131 | + |
| 132 | + |
| 133 | +getter = AiohttpGetter() |
| 134 | + |
| 135 | + |
| 136 | +@web.middleware |
| 137 | +async def middleware(request, handler): |
| 138 | + """Middleware for aiohttp implementing tracing logic""" |
| 139 | + if ( |
| 140 | + context.get_value("suppress_instrumentation") |
| 141 | + or context.get_value(_SUPPRESS_HTTP_INSTRUMENTATION_KEY) |
| 142 | + or not _excluded_urls.url_disabled(request.url) |
| 143 | + ): |
| 144 | + return await handler(request) |
| 145 | + |
| 146 | + token = context.attach(extract(request, getter=getter)) |
| 147 | + span_name, additional_attributes = get_default_span_details(request) |
| 148 | + |
| 149 | + with tracer.start_as_current_span( |
| 150 | + span_name, |
| 151 | + kind=trace.SpanKind.SERVER, |
| 152 | + ) as span: |
| 153 | + if span.is_recording(): |
| 154 | + attributes = collect_request_attributes(request) |
| 155 | + attributes.update(additional_attributes) |
| 156 | + for key, value in attributes.items(): |
| 157 | + span.set_attribute(key, value) |
| 158 | + try: |
| 159 | + resp = await handler(request) |
| 160 | + set_status_code(span, resp.status) |
| 161 | + finally: |
| 162 | + context.detach(token) |
| 163 | + return resp |
| 164 | + |
| 165 | + |
| 166 | +class _InstrumentedApplication(web.Application): |
| 167 | + """Insert tracing middleware""" |
| 168 | + |
| 169 | + def __init__(self, *args, **kwargs): |
| 170 | + middlewares = kwargs.pop("middlewares", []) |
| 171 | + middlewares.insert(0, middleware) |
| 172 | + kwargs["middlewares"] = middlewares |
| 173 | + super().__init__(*args, **kwargs) |
| 174 | + |
| 175 | + |
| 176 | +class AioHttpInstrumentor(BaseInstrumentor): |
| 177 | + # pylint: disable=protected-access,attribute-defined-outside-init |
| 178 | + """An instrumentor for aiohttp.web.Application |
| 179 | +
|
| 180 | + See `BaseInstrumentor` |
| 181 | + """ |
| 182 | + |
| 183 | + def _instrument(self, **kwargs): |
| 184 | + self._original_app = web.Application |
| 185 | + setattr(web, "Application", _InstrumentedApplication) |
| 186 | + |
| 187 | + def _uninstrument(self, **kwargs): |
| 188 | + setattr(web, "Application", self._original_app) |
| 189 | + |
| 190 | + def instrumentation_dependencies(self): |
| 191 | + return _instruments |
0 commit comments