repo
stringclasses
856 values
pull_number
int64
3
127k
instance_id
stringlengths
12
58
issue_numbers
sequencelengths
1
5
base_commit
stringlengths
40
40
patch
stringlengths
67
1.54M
test_patch
stringlengths
0
107M
problem_statement
stringlengths
3
307k
hints_text
stringlengths
0
908k
created_at
timestamp[s]
open-telemetry/opentelemetry-python-contrib
421
open-telemetry__opentelemetry-python-contrib-421
[ "274" ]
3e1a9fa0c218b408eede012f3ef93f22bbb728eb
diff --git a/exporter/opentelemetry-exporter-datadog/src/opentelemetry/exporter/datadog/exporter.py b/exporter/opentelemetry-exporter-datadog/src/opentelemetry/exporter/datadog/exporter.py --- a/exporter/opentelemetry-exporter-datadog/src/opentelemetry/exporter/datadog/exporter.py +++ b/exporter/opentelemetry-exporter-datadog/src/opentelemetry/exporter/datadog/exporter.py @@ -63,7 +63,7 @@ class DatadogSpanExporter(SpanExporter): service: The service name to be used for the application or use ``DD_SERVICE`` environment variable env: Set the application’s environment or use ``DD_ENV`` environment variable version: Set the application’s version or use ``DD_VERSION`` environment variable - tags: A list of default tags to be added to every span or use ``DD_TAGS`` environment variable + tags: A list (formatted as a comma-separated string) of default tags to be added to every span or use ``DD_TAGS`` environment variable """ def __init__(
exporter-datadog: docstring does not match arguments The docstring here: https://github.com/open-telemetry/opentelemetry-python-contrib/blob/master/exporter/opentelemetry-exporter-datadog/src/opentelemetry/exporter/datadog/exporter.py#L68 says it expects a list, but what it really expects is a string containing a comma-separated list of tags. Do I fix the docstring, do I change the code code to accept a real list ,or do I change the code to accept *either* a list or the current string? I'm also working on #154 and would really prefer both objects accept the same parameters if possible.. but this is just odd, and IMHO not very pythonic. What do we prefer for things like this? (I'm happy to do the work, again, since I'm already working on related stuff)
@alertedsnake I would simply change the docstring to reflect the actual code. This issue was marked stale due to lack of activity. It will be closed in 30 days.
2021-04-07T02:58:01
open-telemetry/opentelemetry-python-contrib
424
open-telemetry__opentelemetry-python-contrib-424
[ "409" ]
e7d26a4c2dfc05b587d92fb5e64c99447bd05f65
diff --git a/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py b/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py --- a/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py @@ -186,21 +186,26 @@ class OpenTelemetryMiddleware: Args: wsgi: The WSGI application callable to forward requests to. - name_callback: Callback which calculates a generic span name for an - incoming HTTP request based on the PEP3333 WSGI environ. - Optional: Defaults to get_default_span_name. + request_hook: Optional callback which is called with the server span and WSGI + environ object for every incoming request. + response_hook: Optional callback which is called with the server span, + WSGI environ, status_code and response_headers for every + incoming request. """ - def __init__(self, wsgi, name_callback=get_default_span_name): + def __init__(self, wsgi, request_hook=None, response_hook=None): self.wsgi = wsgi self.tracer = trace.get_tracer(__name__, __version__) - self.name_callback = name_callback + self.request_hook = request_hook + self.response_hook = response_hook @staticmethod - def _create_start_response(span, start_response): + def _create_start_response(span, start_response, response_hook): @functools.wraps(start_response) def _start_response(status, response_headers, *args, **kwargs): add_response_attributes(span, status, response_headers) + if response_hook: + response_hook(status, response_headers) return start_response(status, response_headers, *args, **kwargs) return _start_response @@ -214,18 +219,24 @@ def __call__(self, environ, start_response): """ token = context.attach(extract(environ, getter=wsgi_getter)) - span_name = self.name_callback(environ) span = self.tracer.start_span( - span_name, + get_default_span_name(environ), kind=trace.SpanKind.SERVER, attributes=collect_request_attributes(environ), ) + if self.request_hook: + self.request_hook(span, environ) + + response_hook = self.response_hook + if response_hook: + response_hook = functools.partial(response_hook, span, environ) + try: with trace.use_span(span): start_response = self._create_start_response( - span, start_response + span, start_response, response_hook ) iterable = self.wsgi(environ, start_response) return _end_span_after_iterating(
diff --git a/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py b/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py --- a/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py +++ b/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py @@ -81,7 +81,13 @@ def error_wsgi_unhandled(environ, start_response): class TestWsgiApplication(WsgiTestBase): def validate_response( - self, response, error=None, span_name="HTTP GET", http_method="GET" + self, + response, + error=None, + span_name="HTTP GET", + http_method="GET", + span_attributes=None, + response_headers=None, ): while True: try: @@ -90,10 +96,12 @@ def validate_response( except StopIteration: break + expected_headers = [("Content-Type", "text/plain")] + if response_headers: + expected_headers.extend(response_headers) + self.assertEqual(self.status, "200 OK") - self.assertEqual( - self.response_headers, [("Content-Type", "text/plain")] - ) + self.assertEqual(self.response_headers, expected_headers) if error: self.assertIs(self.exc_info[0], error) self.assertIsInstance(self.exc_info[1], error) @@ -114,6 +122,7 @@ def validate_response( "http.url": "http://127.0.0.1/", "http.status_code": 200, } + expected_attributes.update(span_attributes or {}) if http_method is not None: expected_attributes["http.method"] = http_method self.assertEqual(span_list[0].attributes, expected_attributes) @@ -123,6 +132,30 @@ def test_basic_wsgi_call(self): response = app(self.environ, self.start_response) self.validate_response(response) + def test_hooks(self): + hook_headers = ( + "hook_attr", + "hello otel", + ) + + def request_hook(span, environ): + span.update_name("name from hook") + + def response_hook(span, environ, status_code, response_headers): + span.set_attribute("hook_attr", "hello world") + response_headers.append(hook_headers) + + app = otel_wsgi.OpenTelemetryMiddleware( + simple_wsgi, request_hook, response_hook + ) + response = app(self.environ, self.start_response) + self.validate_response( + response, + span_name="name from hook", + span_attributes={"hook_attr": "hello world"}, + response_headers=(hook_headers,), + ) + def test_wsgi_not_recording(self): mock_tracer = mock.Mock() mock_span = mock.Mock() @@ -176,20 +209,6 @@ def test_wsgi_internal_error(self): span_list[0].status.status_code, StatusCode.ERROR, ) - def test_override_span_name(self): - """Test that span_names can be overwritten by our callback function.""" - span_name = "Dymaxion" - - def get_predefined_span_name(scope): - # pylint: disable=unused-argument - return span_name - - app = otel_wsgi.OpenTelemetryMiddleware( - simple_wsgi, name_callback=get_predefined_span_name - ) - response = app(self.environ, self.start_response) - self.validate_response(response, span_name=span_name) - def test_default_span_name_missing_request_method(self): """Test that default span_names with missing request method.""" self.environ.pop("REQUEST_METHOD")
[WSGI] Replace span name callback with request and response hooks WSGI instrumentation accepts a span name callback which should be replaced with more generic request/response callbacks (hooks). Details: https://github.com/open-telemetry/opentelemetry-python-contrib/issues/408
2021-04-08T04:13:18
open-telemetry/opentelemetry-python-contrib
426
open-telemetry__opentelemetry-python-contrib-426
[ "132" ]
0fcb60d2ad139f78a52edd85b1cc4e32f2e962d0
diff --git a/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py b/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py --- a/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py @@ -33,6 +33,43 @@ def get(self): app = tornado.web.Application([(r"/", Handler)]) app.listen(8080) tornado.ioloop.IOLoop.current().start() + +Hooks +******* + +Tornado instrumentation supports extending tracing behaviour with the help of hooks. +It's ``instrument()`` method accepts three optional functions that get called back with the +created span and some other contextual information. Example: + +.. code-block:: python + + # will be called for each incoming request to Tornado + # web server. `handler` is an instance of + # `tornado.web.RequestHandler`. + def server_request_hook(span, handler): + pass + + # will be called just before sending out a request with + # `tornado.httpclient.AsyncHTTPClient.fetch`. + # `request` is an instance of ``tornado.httpclient.HTTPRequest`. + def client_request_hook(span, request): + pass + + # will be called after a outgoing request made with + # `tornado.httpclient.AsyncHTTPClient.fetch` finishes. + # `response`` is an instance of ``Future[tornado.httpclient.HTTPResponse]`. + def client_resposne_hook(span, future): + pass + + # apply tornado instrumentation with hooks + TornadoInstrumentor().instrument( + server_request_hook=server_request_hook, + client_request_hook=client_request_hook, + client_response_hook=client_resposne_hook + ) + +API +--- """ @@ -96,9 +133,13 @@ def _instrument(self, **kwargs): tracer_provider = kwargs.get("tracer_provider") tracer = trace.get_tracer(__name__, __version__, tracer_provider) + client_request_hook = kwargs.get("client_request_hook", None) + client_response_hook = kwargs.get("client_response_hook", None) + server_request_hook = kwargs.get("server_request_hook", None) + def handler_init(init, handler, args, kwargs): cls = handler.__class__ - if patch_handler_class(tracer, cls): + if patch_handler_class(tracer, cls, server_request_hook): self.patched_handlers.append(cls) return init(*args, **kwargs) @@ -108,7 +149,9 @@ def handler_init(init, handler, args, kwargs): wrap_function_wrapper( "tornado.httpclient", "AsyncHTTPClient.fetch", - partial(fetch_async, tracer), + partial( + fetch_async, tracer, client_request_hook, client_response_hook + ), ) def _uninstrument(self, **kwargs): @@ -119,12 +162,12 @@ def _uninstrument(self, **kwargs): self.patched_handlers = [] -def patch_handler_class(tracer, cls): +def patch_handler_class(tracer, cls, request_hook=None): if getattr(cls, _OTEL_PATCHED_KEY, False): return False setattr(cls, _OTEL_PATCHED_KEY, True) - _wrap(cls, "prepare", partial(_prepare, tracer)) + _wrap(cls, "prepare", partial(_prepare, tracer, request_hook)) _wrap(cls, "on_finish", partial(_on_finish, tracer)) _wrap(cls, "log_exception", partial(_log_exception, tracer)) return True @@ -146,12 +189,14 @@ def _wrap(cls, method_name, wrapper): wrapt.apply_patch(cls, method_name, wrapper) -def _prepare(tracer, func, handler, args, kwargs): +def _prepare(tracer, request_hook, func, handler, args, kwargs): start_time = _time_ns() request = handler.request if _excluded_urls.url_disabled(request.uri): return func(*args, **kwargs) - _start_span(tracer, handler, start_time) + ctx = _start_span(tracer, handler, start_time) + if request_hook: + request_hook(ctx.span, handler) return func(*args, **kwargs) diff --git a/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/client.py b/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/client.py --- a/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/client.py +++ b/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/client.py @@ -39,7 +39,7 @@ def _normalize_request(args, kwargs): return (new_args, new_kwargs) -def fetch_async(tracer, func, _, args, kwargs): +def fetch_async(tracer, request_hook, response_hook, func, _, args, kwargs): start_time = _time_ns() # Return immediately if no args were provided (error) @@ -55,6 +55,8 @@ def fetch_async(tracer, func, _, args, kwargs): span = tracer.start_span( request.method, kind=trace.SpanKind.CLIENT, start_time=start_time, ) + if request_hook: + request_hook(span, request) if span.is_recording(): attributes = { @@ -68,12 +70,16 @@ def fetch_async(tracer, func, _, args, kwargs): inject(request.headers) future = func(*args, **kwargs) future.add_done_callback( - functools.partial(_finish_tracing_callback, span=span) + functools.partial( + _finish_tracing_callback, + span=span, + response_hook=response_hook, + ) ) return future -def _finish_tracing_callback(future, span): +def _finish_tracing_callback(future, span, response_hook): status_code = None description = None exc = future.exception() @@ -92,4 +98,6 @@ def _finish_tracing_callback(future, span): description=description, ) ) + if response_hook: + response_hook(span, future) span.end()
diff --git a/instrumentation/opentelemetry-instrumentation-tornado/tests/test_instrumentation.py b/instrumentation/opentelemetry-instrumentation-tornado/tests/test_instrumentation.py --- a/instrumentation/opentelemetry-instrumentation-tornado/tests/test_instrumentation.py +++ b/instrumentation/opentelemetry-instrumentation-tornado/tests/test_instrumentation.py @@ -42,7 +42,11 @@ def get_app(self): return app def setUp(self): - TornadoInstrumentor().instrument() + TornadoInstrumentor().instrument( + server_request_hook=getattr(self, "server_request_hook", None), + client_request_hook=getattr(self, "client_request_hook", None), + client_response_hook=getattr(self, "client_response_hook", None), + ) super().setUp() # pylint: disable=protected-access self.env_patch = patch.dict( @@ -367,6 +371,59 @@ def test_traced_attrs(self): self.memory_exporter.clear() +class TornadoHookTest(TornadoTest): + _client_request_hook = None + _client_response_hook = None + _server_request_hook = None + + def client_request_hook(self, span, handler): + if self._client_request_hook is not None: + self._client_request_hook(span, handler) + + def client_response_hook(self, span, handler): + if self._client_response_hook is not None: + self._client_response_hook(span, handler) + + def server_request_hook(self, span, handler): + if self._server_request_hook is not None: + self._server_request_hook(span, handler) + + def test_hooks(self): + def server_request_hook(span, handler): + span.update_name("name from server hook") + handler.set_header("hello", "world") + + def client_request_hook(span, request): + span.update_name("name from client hook") + + def client_response_hook(span, request): + span.set_attribute("attr-from-hook", "value") + + self._server_request_hook = server_request_hook + self._client_request_hook = client_request_hook + self._client_response_hook = client_response_hook + + response = self.fetch("/") + self.assertEqual(response.headers.get("hello"), "world") + + spans = self.sorted_spans(self.memory_exporter.get_finished_spans()) + self.assertEqual(len(spans), 3) + server_span = spans[1] + self.assertEqual(server_span.kind, SpanKind.SERVER) + self.assertEqual(server_span.name, "name from server hook") + self.assert_span_has_attributes(server_span, {"uri": "/"}) + self.memory_exporter.clear() + + client_span = spans[2] + self.assertEqual(client_span.kind, SpanKind.CLIENT) + self.assertEqual(client_span.name, "name from client hook") + self.assert_span_has_attributes( + client_span, {"attr-from-hook": "value"} + ) + + self.memory_exporter.clear() + + class TestTornadoUninstrument(TornadoTest): def test_uninstrument(self): response = self.fetch("/")
Add request and response hooks to tornado instrumentation Accept a request and response hook functions in `TornadoInstrumentor().instrument`. Details: https://github.com/open-telemetry/opentelemetry-python-contrib/issues/408
2021-04-08T10:20:03
open-telemetry/opentelemetry-python-contrib
459
open-telemetry__opentelemetry-python-contrib-459
[ "244" ]
b1d6c90d7002b0b7e3f89025152c4d6e95ffa910
diff --git a/exporter/opentelemetry-exporter-datadog/src/opentelemetry/exporter/datadog/constants.py b/exporter/opentelemetry-exporter-datadog/src/opentelemetry/exporter/datadog/constants.py --- a/exporter/opentelemetry-exporter-datadog/src/opentelemetry/exporter/datadog/constants.py +++ b/exporter/opentelemetry-exporter-datadog/src/opentelemetry/exporter/datadog/constants.py @@ -7,3 +7,10 @@ ENV_KEY = "env" VERSION_KEY = "version" SERVICE_NAME_TAG = "service.name" +EVENT_NAME_EXCEPTION = "exception" +EXCEPTION_TYPE_ATTR_KEY = "exception.type" +EXCEPTION_MSG_ATTR_KEY = "exception.message" +EXCEPTION_STACK_ATTR_KEY = "exception.stacktrace" +DD_ERROR_TYPE_TAG_KEY = "error.type" +DD_ERROR_MSG_TAG_KEY = "error.msg" +DD_ERROR_STACK_TAG_KEY = "error.stack" diff --git a/exporter/opentelemetry-exporter-datadog/src/opentelemetry/exporter/datadog/exporter.py b/exporter/opentelemetry-exporter-datadog/src/opentelemetry/exporter/datadog/exporter.py --- a/exporter/opentelemetry-exporter-datadog/src/opentelemetry/exporter/datadog/exporter.py +++ b/exporter/opentelemetry-exporter-datadog/src/opentelemetry/exporter/datadog/exporter.py @@ -22,8 +22,15 @@ import opentelemetry.trace as trace_api from opentelemetry.exporter.datadog.constants import ( + DD_ERROR_MSG_TAG_KEY, + DD_ERROR_STACK_TAG_KEY, + DD_ERROR_TYPE_TAG_KEY, DD_ORIGIN, ENV_KEY, + EVENT_NAME_EXCEPTION, + EXCEPTION_MSG_ATTR_KEY, + EXCEPTION_STACK_ATTR_KEY, + EXCEPTION_TYPE_ATTR_KEY, SAMPLE_RATE_METRIC_KEY, SERVICE_NAME_TAG, VERSION_KEY, @@ -145,11 +152,12 @@ def _translate_to_datadog(self, spans): if not span.status.is_ok: datadog_span.error = 1 - if span.status.description: - exc_type, exc_val = _get_exc_info(span) - # no mapping for error.stack since traceback not recorded - datadog_span.set_tag("error.msg", exc_val) - datadog_span.set_tag("error.type", exc_type) + # loop over events and look for exception events, extract info. + # https://github.com/open-telemetry/opentelemetry-python/blob/71e3a7a192c0fc8a7503fac967ada36a74b79e58/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py#L810-L819 + if span.events: + _extract_tags_from_exception_events( + span.events, datadog_span + ) # combine resource attributes and span attributes, don't modify existing span attributes combined_span_tags = {} @@ -178,7 +186,7 @@ def _translate_to_datadog(self, spans): if sampling_rate is not None: datadog_span.set_metric(SAMPLE_RATE_METRIC_KEY, sampling_rate) - # span events and span links are not supported + # span events and span links are not supported except for extracting exception event context datadog_spans.append(datadog_span) @@ -318,3 +326,17 @@ def _extract_tags_from_resource(resource): else: tags[attribute_key] = attribute_value return [tags, service_name] + + +def _extract_tags_from_exception_events(events, datadog_span): + """Parse error tags from exception events, error.msg error.type + and error.stack have special significance within datadog""" + for event in events: + if event.name is not None and event.name == EVENT_NAME_EXCEPTION: + for key, value in event.attributes.items(): + if key == EXCEPTION_TYPE_ATTR_KEY: + datadog_span.set_tag(DD_ERROR_TYPE_TAG_KEY, value) + elif key == EXCEPTION_MSG_ATTR_KEY: + datadog_span.set_tag(DD_ERROR_MSG_TAG_KEY, value) + elif key == EXCEPTION_STACK_ATTR_KEY: + datadog_span.set_tag(DD_ERROR_STACK_TAG_KEY, value)
diff --git a/exporter/opentelemetry-exporter-datadog/tests/test_datadog_exporter.py b/exporter/opentelemetry-exporter-datadog/tests/test_datadog_exporter.py --- a/exporter/opentelemetry-exporter-datadog/tests/test_datadog_exporter.py +++ b/exporter/opentelemetry-exporter-datadog/tests/test_datadog_exporter.py @@ -388,6 +388,7 @@ def test_errors(self): self.assertEqual(span["error"], 1) self.assertEqual(span["meta"]["error.msg"], "bar") self.assertEqual(span["meta"]["error.type"], "ValueError") + self.assertTrue(span["meta"]["error.stack"] is not None) def test_shutdown(self): span_names = ["xxx", "bar", "foo"]
Datadog exporter shouldn't parse span description to determine if there was an exception The Datadog exporter currently [parses the status description](https://github.com/open-telemetry/opentelemetry-python-contrib/blob/master/exporter/opentelemetry-exporter-datadog/src/opentelemetry/exporter/datadog/exporter.py#L252) to determine if an exception was raised, yet [the specification](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/api.md#record-exception) requires these to be recorded as events (and [the python code already does this](https://github.com/open-telemetry/opentelemetry-python/blob/master/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py#L690-L715)), so the Datadog exporter should read this data from the event list instead of hoping the description is properly formatted. The current code does say that [span events are not supported ](https://github.com/open-telemetry/opentelemetry-python-contrib/blob/master/exporter/opentelemetry-exporter-datadog/src/opentelemetry/exporter/datadog/exporter.py#L252), and while that would suggest that *reporting* events are not supported, we could certainly parse them for this data. I'll probably tackle this, I'm already working on #154. Also mentioned in #236, where I worked around the current behavior.
//cc @majorgreys Thanks for reporting this @alertedsnake! Your suggestion makes sense. If you end up tackling this, just give a heads up here and I'll check in before giving it a go myself. @owais @majorgreys can you assign this to me? I'll try to address this and bring in line with spec compliane , sorry for the delay @ericmustin thanks! I got bogged down trying to fix #262 that I haven't had a chance to look at this one. @alertedsnake no worries, only one of us gets time during their day job to do this 🙃 . May ask for a review as my python is quite rusty, will ping on PR @ericmustin assigned!
2021-04-19T20:47:54
open-telemetry/opentelemetry-python-contrib
469
open-telemetry__opentelemetry-python-contrib-469
[ "460" ]
fe4e2d44c56cb8ca67b7374bac331873f712cb03
diff --git a/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/engine.py b/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/engine.py --- a/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/engine.py +++ b/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/engine.py @@ -13,7 +13,6 @@ # limitations under the License. from threading import local -from weakref import WeakKeyDictionary from sqlalchemy.event import listen # pylint: disable=no-name-in-module @@ -60,7 +59,7 @@ def __init__(self, tracer, engine): self.tracer = tracer self.engine = engine self.vendor = _normalize_vendor(engine.name) - self.cursor_mapping = WeakKeyDictionary() + self.cursor_mapping = {} self.local = local() listen(engine, "before_cursor_execute", self._before_cur_exec) @@ -116,6 +115,7 @@ def _after_cur_exec(self, conn, cursor, statement, *args): return span.end() + self._cleanup(cursor) def _handle_error(self, context): span = self.current_thread_span @@ -129,6 +129,13 @@ def _handle_error(self, context): ) finally: span.end() + self._cleanup(context.cursor) + + def _cleanup(self, cursor): + try: + del self.cursor_mapping[cursor] + except KeyError: + pass def _get_attributes_from_url(url):
diff --git a/tests/opentelemetry-docker-tests/tests/check_availability.py b/tests/opentelemetry-docker-tests/tests/check_availability.py --- a/tests/opentelemetry-docker-tests/tests/check_availability.py +++ b/tests/opentelemetry-docker-tests/tests/check_availability.py @@ -18,6 +18,7 @@ import mysql.connector import psycopg2 import pymongo +import pyodbc import redis MONGODB_COLLECTION_NAME = "test" @@ -36,6 +37,11 @@ POSTGRES_USER = os.getenv("POSTGRESQL_USER", "testuser") REDIS_HOST = os.getenv("REDIS_HOST", "localhost") REDIS_PORT = int(os.getenv("REDIS_PORT ", "6379")) +MSSQL_DB_NAME = os.getenv("MSSQL_DB_NAME", "opentelemetry-tests") +MSSQL_HOST = os.getenv("MSSQL_HOST", "localhost") +MSSQL_PORT = int(os.getenv("MSSQL_PORT", "1433")) +MSSQL_USER = os.getenv("MSSQL_USER", "sa") +MSSQL_PASSWORD = os.getenv("MSSQL_PASSWORD", "yourStrong(!)Password") RETRY_COUNT = 8 RETRY_INTERVAL = 5 # Seconds @@ -104,12 +110,23 @@ def check_redis_connection(): connection.hgetall("*") +@retryable +def check_mssql_connection(): + connection = pyodbc.connect( + f"DRIVER={{ODBC Driver 17 for SQL Server}};SERVER={MSSQL_HOST}," + f"{MSSQL_PORT};DATABASE={MSSQL_DB_NAME};UID={MSSQL_USER};" + f"PWD={MSSQL_PASSWORD}" + ) + connection.close() + + def check_docker_services_availability(): # Check if Docker services accept connections check_pymongo_connection() check_mysql_connection() check_postgres_connection() check_redis_connection() + check_mssql_connection() check_docker_services_availability() diff --git a/tests/opentelemetry-docker-tests/tests/docker-compose.yml b/tests/opentelemetry-docker-tests/tests/docker-compose.yml --- a/tests/opentelemetry-docker-tests/tests/docker-compose.yml +++ b/tests/opentelemetry-docker-tests/tests/docker-compose.yml @@ -39,3 +39,11 @@ services: - "16686:16686" - "14268:14268" - "9411:9411" + otmssql: + image: mcr.microsoft.com/mssql/server:2017-latest + ports: + - "1433:1433" + environment: + ACCEPT_EULA: "Y" + SA_PASSWORD: "yourStrong(!)Password" + command: /bin/sh -c "sleep 10s && /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P yourStrong\(!\)Password -d master -Q 'CREATE DATABASE [opentelemetry-tests]' & /opt/mssql/bin/sqlservr" \ No newline at end of file diff --git a/tests/opentelemetry-docker-tests/tests/sqlalchemy_tests/test_mssql.py b/tests/opentelemetry-docker-tests/tests/sqlalchemy_tests/test_mssql.py new file mode 100644 --- /dev/null +++ b/tests/opentelemetry-docker-tests/tests/sqlalchemy_tests/test_mssql.py @@ -0,0 +1,107 @@ +# Copyright The OpenTelemetry Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import unittest + +import pytest +from sqlalchemy.exc import ProgrammingError + +from opentelemetry import trace +from opentelemetry.semconv.trace import SpanAttributes + +from .mixins import Player, SQLAlchemyTestMixin + +MSSQL_CONFIG = { + "host": "127.0.0.1", + "port": int(os.getenv("TEST_MSSQL_PORT", "1433")), + "user": os.getenv("TEST_MSSQL_USER", "sa"), + "password": os.getenv("TEST_MSSQL_PASSWORD", "yourStrong(!)Password"), + "database": os.getenv("TEST_MSSQL_DATABASE", "opentelemetry-tests"), + "driver": os.getenv("TEST_MSSQL_DRIVER", "ODBC+Driver+17+for+SQL+Server"), +} + + +class MssqlConnectorTestCase(SQLAlchemyTestMixin): + """TestCase for pyodbc engine""" + + __test__ = True + + VENDOR = "mssql" + SQL_DB = "opentelemetry-tests" + ENGINE_ARGS = { + "url": "mssql+pyodbc://%(user)s:%(password)s@%(host)s:%(port)s/%(database)s?driver=%(driver)s" + % MSSQL_CONFIG + } + + def check_meta(self, span): + # check database connection tags + self.assertEqual( + span.attributes.get(SpanAttributes.NET_PEER_NAME), + MSSQL_CONFIG["host"], + ) + self.assertEqual( + span.attributes.get(SpanAttributes.NET_PEER_PORT), + MSSQL_CONFIG["port"], + ) + self.assertEqual( + span.attributes.get(SpanAttributes.DB_NAME), + MSSQL_CONFIG["database"], + ) + self.assertEqual( + span.attributes.get(SpanAttributes.DB_USER), MSSQL_CONFIG["user"] + ) + + def test_engine_execute_errors(self): + # ensures that SQL errors are reported + with pytest.raises(ProgrammingError): + with self.connection() as conn: + conn.execute("SELECT * FROM a_wrong_table").fetchall() + + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 1) + span = spans[0] + # span fields + self.assertEqual(span.name, "SELECT opentelemetry-tests") + self.assertEqual( + span.attributes.get(SpanAttributes.DB_STATEMENT), + "SELECT * FROM a_wrong_table", + ) + self.assertEqual( + span.attributes.get(SpanAttributes.DB_NAME), self.SQL_DB + ) + self.check_meta(span) + self.assertTrue(span.end_time - span.start_time > 0) + # check the error + self.assertIs( + span.status.status_code, trace.StatusCode.ERROR, + ) + self.assertIn("a_wrong_table", span.status.description) + + def test_orm_insert(self): + # ensures that the ORM session is traced + wayne = Player(id=1, name="wayne") + self.session.add(wayne) + self.session.commit() + + spans = self.memory_exporter.get_finished_spans() + # identity insert on before the insert, insert, and identity insert off after the insert + self.assertEqual(len(spans), 3) + span = spans[1] + self._check_span(span, "INSERT") + self.assertIn( + "INSERT INTO players", + span.attributes.get(SpanAttributes.DB_STATEMENT), + ) + self.check_meta(span)
sqlalchemy: TypeError: cannot create weak reference to 'pyodbc.Cursor' object **Describe your environment** See the repo provided below for a simple reproduction environment. I was using Python 3.8.8 when running it locally. **Steps to reproduce** Provided a reproduction repo: https://github.com/jomasti/opentelemetry-instrumentation-sqlalchemy-pyodbc-bug **What is the expected behavior?** I expected the query to work successfully when the engine is instrumented. The code in the repo above works fine with 0.18b1. **What is the actual behavior?** Ran into `TypeError: cannot create weak reference to 'pyodbc.Cursor' object`. **Additional context** #315 appears to be the culprit.
2021-04-26T03:57:21
open-telemetry/opentelemetry-python-contrib
472
open-telemetry__opentelemetry-python-contrib-472
[ "471" ]
45c94e765d2ade0ea12b700faf10dfde419e32a9
diff --git a/propagator/opentelemetry-propagator-ot-trace/src/opentelemetry/propagators/ot_trace/__init__.py b/propagator/opentelemetry-propagator-ot-trace/src/opentelemetry/propagators/ot_trace/__init__.py --- a/propagator/opentelemetry-propagator-ot-trace/src/opentelemetry/propagators/ot_trace/__init__.py +++ b/propagator/opentelemetry-propagator-ot-trace/src/opentelemetry/propagators/ot_trace/__init__.py @@ -85,7 +85,7 @@ def extract( trace_id=int(traceid, 16), span_id=int(spanid, 16), is_remote=True, - trace_flags=traceflags, + trace_flags=TraceFlags(traceflags), ) ), context,
diff --git a/propagator/opentelemetry-propagator-ot-trace/tests/test_ot_trace_propagator.py b/propagator/opentelemetry-propagator-ot-trace/tests/test_ot_trace_propagator.py --- a/propagator/opentelemetry-propagator-ot-trace/tests/test_ot_trace_propagator.py +++ b/propagator/opentelemetry-propagator-ot-trace/tests/test_ot_trace_propagator.py @@ -248,6 +248,9 @@ def test_extract_trace_id_span_id_sampled_true(self): self.assertEqual(hex(span_context.span_id)[2:], "e457b5a2e4d86bd1") self.assertTrue(span_context.is_remote) self.assertEqual(span_context.trace_flags, TraceFlags.SAMPLED) + self.assertIsInstance( + get_current_span().get_span_context().trace_flags, TraceFlags + ) def test_extract_trace_id_span_id_sampled_false(self): """Test valid trace_id, span_id and sampled false""" @@ -268,6 +271,9 @@ def test_extract_trace_id_span_id_sampled_false(self): self.assertEqual(hex(span_context.span_id)[2:], "e457b5a2e4d86bd1") self.assertTrue(span_context.is_remote) self.assertEqual(span_context.trace_flags, TraceFlags.DEFAULT) + self.assertIsInstance( + get_current_span().get_span_context().trace_flags, TraceFlags + ) def test_extract_malformed_trace_id(self): """Test extraction with malformed trace_id"""
OpenTracing propagator does not use a TraceFlags object I set up a client and server that propagated spans using the OpenTracing propagator. The server side reported this error: ``` [2021-04-26 16:41:13,377] ERROR in app: Exception on /ping [GET] Traceback (most recent call last): File "/home/ocelotl/virtual_environments/LS-22507/lib/python3.8/site-packages/flask/app.py", line 2447, in wsgi_app response = self.full_dispatch_request() File "/home/ocelotl/virtual_environments/LS-22507/lib/python3.8/site-packages/flask/app.py", line 1952, in full_dispatch_request rv = self.handle_user_exception(e) File "/home/ocelotl/virtual_environments/LS-22507/lib/python3.8/site-packages/flask/app.py", line 1821, in handle_user_exception reraise(exc_type, exc_value, tb) File "/home/ocelotl/virtual_environments/LS-22507/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise raise value File "/home/ocelotl/virtual_environments/LS-22507/lib/python3.8/site-packages/flask/app.py", line 1950, in full_dispatch_request rv = self.dispatch_request() File "/home/ocelotl/virtual_environments/LS-22507/lib/python3.8/site-packages/flask/app.py", line 1936, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "server.py", line 53, in ping with tracer.start_as_current_span( File "/home/ocelotl/.pyenv/versions/3.8.3/lib/python3.8/contextlib.py", line 113, in __enter__ return next(self.gen) File "/home/ocelotl/github/ocelotl/opentelemetry-python/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py", line 863, in start_as_current_span span = self.start_span( File "/home/ocelotl/github/ocelotl/opentelemetry-python/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py", line 917, in start_span sampling_result = self.sampler.should_sample( File "/home/ocelotl/github/ocelotl/opentelemetry-python/opentelemetry-sdk/src/opentelemetry/sdk/trace/sampling.py", line 326, in should_sample if parent_span_context.trace_flags.sampled: AttributeError: 'int' object has no attribute 'sampled' ``` This happens because when instantiating a context during propagation with the OpenTracing propagator, a `TracFlags` object is not used for the trace flags.
2021-04-26T22:45:41
open-telemetry/opentelemetry-python-contrib
478
open-telemetry__opentelemetry-python-contrib-478
[ "427" ]
f4a2b615ed0b9a26a3535d5c74a2d45050f1a79c
diff --git a/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py b/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py --- a/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py @@ -233,8 +233,10 @@ async def wrapped_send(message): if send_span.is_recording(): if message["type"] == "http.response.start": status_code = message["status"] + set_status_code(span, status_code) set_status_code(send_span, status_code) elif message["type"] == "websocket.send": + set_status_code(span, 200) set_status_code(send_span, 200) send_span.set_attribute("type", message["type"]) await send(message)
diff --git a/instrumentation/opentelemetry-instrumentation-asgi/tests/test_asgi_middleware.py b/instrumentation/opentelemetry-instrumentation-asgi/tests/test_asgi_middleware.py --- a/instrumentation/opentelemetry-instrumentation-asgi/tests/test_asgi_middleware.py +++ b/instrumentation/opentelemetry-instrumentation-asgi/tests/test_asgi_middleware.py @@ -146,6 +146,7 @@ def validate_outputs(self, outputs, error=None, modifiers=None): SpanAttributes.HTTP_URL: "http://127.0.0.1/", SpanAttributes.NET_PEER_IP: "127.0.0.1", SpanAttributes.NET_PEER_PORT: 32767, + SpanAttributes.HTTP_STATUS_CODE: 200, }, }, ] @@ -303,15 +304,57 @@ def test_websocket(self): span_list = self.memory_exporter.get_finished_spans() self.assertEqual(len(span_list), 6) expected = [ - "/ asgi.websocket.receive", - "/ asgi.websocket.send", - "/ asgi.websocket.receive", - "/ asgi.websocket.send", - "/ asgi.websocket.receive", - "/ asgi", + { + "name": "/ asgi.websocket.receive", + "kind": trace_api.SpanKind.INTERNAL, + "attributes": {"type": "websocket.connect"}, + }, + { + "name": "/ asgi.websocket.send", + "kind": trace_api.SpanKind.INTERNAL, + "attributes": {"type": "websocket.accept"}, + }, + { + "name": "/ asgi.websocket.receive", + "kind": trace_api.SpanKind.INTERNAL, + "attributes": { + "type": "websocket.receive", + SpanAttributes.HTTP_STATUS_CODE: 200, + }, + }, + { + "name": "/ asgi.websocket.send", + "kind": trace_api.SpanKind.INTERNAL, + "attributes": { + "type": "websocket.send", + SpanAttributes.HTTP_STATUS_CODE: 200, + }, + }, + { + "name": "/ asgi.websocket.receive", + "kind": trace_api.SpanKind.INTERNAL, + "attributes": {"type": "websocket.disconnect"}, + }, + { + "name": "/ asgi", + "kind": trace_api.SpanKind.SERVER, + "attributes": { + SpanAttributes.HTTP_SCHEME: self.scope["scheme"], + SpanAttributes.NET_HOST_PORT: self.scope["server"][1], + SpanAttributes.HTTP_HOST: self.scope["server"][0], + SpanAttributes.HTTP_FLAVOR: self.scope["http_version"], + SpanAttributes.HTTP_TARGET: self.scope["path"], + SpanAttributes.HTTP_URL: f'{self.scope["scheme"]}://{self.scope["server"][0]}{self.scope["path"]}', + SpanAttributes.NET_PEER_IP: self.scope["client"][0], + SpanAttributes.NET_PEER_PORT: self.scope["client"][1], + SpanAttributes.HTTP_STATUS_CODE: 200, + }, + }, ] - actual = [span.name for span in span_list] - self.assertListEqual(actual, expected) + for span, expected in zip(span_list, expected): + self.assertEqual(span.name, expected["name"]) + self.assertEqual(span.kind, expected["kind"]) + self.assertDictEqual(dict(span.attributes), expected["attributes"]) def test_lifespan(self): self.scope["type"] = "lifespan"
FastAPI Instrumentor not populating attributes required for Azure exporter **Describe your environment** **Package Version - azure-monitor-opentelemetry-exporter = {version = "^1.0.0-beta.3", allow-prereleases = true} opentelemetry-instrumentation-fastapi = "^0.19b0" Operating System - macOS Mojave v10.14.6** **Python Version - v3.9.0** **Steps to reproduce** When using the azure-monitor-opentelemetry-exporter in conjunction with opentelemetry-instrumentation-fastapi the response code is not populated by the exporter, raised this issue with Azure monitor team and was redirected here; > Looking at the output, it seems like the spans are missing some attributes. This is probably an issue in the opentelemetry-instrumentation-asgi, could you file an issue here for this problem specifically? Basically, the exporter sees if http.status_code is populated in the span attributes to populate response_Code in app insights. Since the attribute is not there, this is why you are seeing 0s. Normally, it is up to the instrumentation to populate this. [Azure monitor issue#17839](https://github.com/Azure/azure-sdk-for-python/issues/17839) Spans obtained from console exporter: - one for successful - 201 request - one for failed - 422 request - one on exit [json.zip](https://github.com/open-telemetry/opentelemetry-python-contrib/files/6281056/json.zip) Screen grab from Azure App Insights indication reponse code as 0: ![image](https://user-images.githubusercontent.com/43657587/114087357-6bae9380-9879-11eb-98db-3d3b1a0c1055.png) **What is the expected behavior?** Compatibility with Azure monitor exporter **Additional context** Detailed context for this issue [Azure monitor issue#17839](https://github.com/Azure/azure-sdk-for-python/issues/17839) Please let me know in case of additional info required. Thanks.
2021-04-28T05:21:47
open-telemetry/opentelemetry-python-contrib
499
open-telemetry__opentelemetry-python-contrib-499
[ "495" ]
5b125b196a967b9e6021c8ff304a36994863a4e3
diff --git a/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py b/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py --- a/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py @@ -213,8 +213,9 @@ def _prepare(tracer, request_hook, func, handler, args, kwargs): def _on_finish(tracer, func, handler, args, kwargs): + response = func(*args, **kwargs) _finish_span(tracer, handler) - return func(*args, **kwargs) + return response def _log_exception(tracer, func, handler, args, kwargs):
diff --git a/instrumentation/opentelemetry-instrumentation-tornado/tests/test_instrumentation.py b/instrumentation/opentelemetry-instrumentation-tornado/tests/test_instrumentation.py --- a/instrumentation/opentelemetry-instrumentation-tornado/tests/test_instrumentation.py +++ b/instrumentation/opentelemetry-instrumentation-tornado/tests/test_instrumentation.py @@ -347,6 +347,54 @@ def test_dynamic_handler(self): }, ) + def test_handler_on_finish(self): + + response = self.fetch("/on_finish") + self.assertEqual(response.code, 200) + + spans = self.sorted_spans(self.memory_exporter.get_finished_spans()) + self.assertEqual(len(spans), 3) + auditor, server, client = spans + + self.assertEqual(server.name, "FinishedHandler.get") + self.assertTrue(server.parent.is_remote) + self.assertNotEqual(server.parent, client.context) + self.assertEqual(server.parent.span_id, client.context.span_id) + self.assertEqual(server.context.trace_id, client.context.trace_id) + self.assertEqual(server.kind, SpanKind.SERVER) + self.assert_span_has_attributes( + server, + { + SpanAttributes.HTTP_METHOD: "GET", + SpanAttributes.HTTP_SCHEME: "http", + SpanAttributes.HTTP_HOST: "127.0.0.1:" + + str(self.get_http_port()), + SpanAttributes.HTTP_TARGET: "/on_finish", + SpanAttributes.NET_PEER_IP: "127.0.0.1", + SpanAttributes.HTTP_STATUS_CODE: 200, + }, + ) + + self.assertEqual(client.name, "GET") + self.assertFalse(client.context.is_remote) + self.assertIsNone(client.parent) + self.assertEqual(client.kind, SpanKind.CLIENT) + self.assert_span_has_attributes( + client, + { + SpanAttributes.HTTP_URL: self.get_url("/on_finish"), + SpanAttributes.HTTP_METHOD: "GET", + SpanAttributes.HTTP_STATUS_CODE: 200, + }, + ) + + self.assertEqual(auditor.name, "audit_task") + self.assertFalse(auditor.context.is_remote) + self.assertEqual(auditor.parent.span_id, server.context.span_id) + self.assertEqual(auditor.context.trace_id, client.context.trace_id) + + self.assertEqual(auditor.kind, SpanKind.INTERNAL) + def test_exclude_lists(self): def test_excluded(path): self.fetch(path) diff --git a/instrumentation/opentelemetry-instrumentation-tornado/tests/tornado_test_app.py b/instrumentation/opentelemetry-instrumentation-tornado/tests/tornado_test_app.py --- a/instrumentation/opentelemetry-instrumentation-tornado/tests/tornado_test_app.py +++ b/instrumentation/opentelemetry-instrumentation-tornado/tests/tornado_test_app.py @@ -1,4 +1,5 @@ # pylint: disable=W0223,R0201 +import time import tornado.web from tornado import gen @@ -79,6 +80,16 @@ def get(self): self.set_status(202) +class FinishedHandler(tornado.web.RequestHandler): + def on_finish(self): + with self.application.tracer.start_as_current_span("audit_task"): + time.sleep(0.05) + + def get(self): + self.write("Test can finish") + self.set_status(200) + + class HealthCheckHandler(tornado.web.RequestHandler): def get(self): self.set_status(200) @@ -91,6 +102,7 @@ def make_app(tracer): (r"/error", BadHandler), (r"/cor", CoroutineHandler), (r"/async", AsyncHandler), + (r"/on_finish", FinishedHandler), (r"/healthz", HealthCheckHandler), (r"/ping", HealthCheckHandler), ]
Tornado instrumentation closes spans before on_finish is completed. Ideally all trace spans in a request response cycle should be contained in one span. However because the tornado instrumentation library closes the span before calling the on_finish method. Orphaned spans from any instrumented code in on_finish method are created. Looking at the [code](https://github.com/open-telemetry/opentelemetry-python-contrib/blob/main/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py#L210-L212) a reordering would fix this situation. **Describe your environment** Python 3.8.5 requirements.txt tornado==6.0.3 #tracing opentelemetry-api==1.1.0 opentelemetry-sdk==1.1.0 opentelemetry-exporter-zipkin-json opentelemetry-instrumentation opentelemetry-instrumentation-dbapi opentelemetry-instrumentation-tornado opentelemetry-exporter-gcp-trace==1.0.0rc0 **Steps to reproduce** Run the attached app below: ` import tornado.ioloop import tornado.web from opentelemetry import trace from opentelemetry.trace import SpanKind from opentelemetry import trace from opentelemetry.exporter.cloud_trace import CloudTraceSpanExporter from opentelemetry.exporter.zipkin.json import ZipkinExporter from opentelemetry.sdk.resources import SERVICE_NAME, Resource from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import ( ConsoleSpanExporter, BatchSpanProcessor ) from opentelemetry.instrumentation.tornado import TornadoInstrumentor class MainHandler(tornado.web.RequestHandler): def on_finish(self) -> None: with trace.get_tracer(__name__).start_as_current_span("On finish test", kind=SpanKind.CLIENT) as span: print("Testing on finish span") super(MainHandler, self).on_finish() def get(self): self.write("Hello, world") def init_tracing(is_deployment): resource = Resource.create(attributes={SERVICE_NAME: "Profile Service"}) tracer_provider = TracerProvider(resource=resource) trace.set_tracer_provider(tracer_provider) if is_deployment: span_exporter = CloudTraceSpanExporter() else: # span_exporter = ZipkinExporter() span_exporter = ConsoleSpanExporter() span_processor = BatchSpanProcessor(span_exporter=span_exporter) trace.get_tracer_provider().add_span_processor(span_processor) TornadoInstrumentor().instrument() def make_app(): return tornado.web.Application([ (r"/", MainHandler), ]) if __name__ == "__main__": init_tracing(is_deployment=False) app = make_app() app.listen(8888) tornado.ioloop.IOLoop.current().start() ` **What is the expected behavior?** All traces in a request cycle should be contained in one span. However because the tornado instrumentation library closes the span before calling the on_finish method. This causes an orphaned span to be created. **What is the actual behavior?** Tornado instrumentation library should possibly run on_finish method before closing the main trace span **Additional context** I looked at the code and saw the affected part is [here ](https://github.com/open-telemetry/opentelemetry-python-contrib/blob/main/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py#L210-L212). Is there any reason to close the span before the parent on_finish method can be run?
2021-05-16T08:45:18
open-telemetry/opentelemetry-python-contrib
523
open-telemetry__opentelemetry-python-contrib-523
[ "519" ]
7cae4d3001c13ec348a2be9efe7b50a717860b3d
diff --git a/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py b/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py --- a/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py @@ -13,7 +13,7 @@ # limitations under the License. """ This library provides a WSGI middleware that can be used on any WSGI framework -(such as Django / Flask) to track requests timing through OpenTelemetry. +(such as Django / Flask / Web.py) to track requests timing through OpenTelemetry. Usage (Flask) ------------- @@ -50,6 +50,35 @@ def hello(): application = get_wsgi_application() application = OpenTelemetryMiddleware(application) +Usage (Web.py) +-------------- + +.. code-block:: python + + import web + from opentelemetry.instrumentation.wsgi import OpenTelemetryMiddleware + from cheroot import wsgi + + urls = ('/', 'index') + + + class index: + + def GET(self): + return "Hello, world!" + + + if __name__ == "__main__": + app = web.application(urls, globals()) + func = app.wsgifunc() + + func = OpenTelemetryMiddleware(func) + + server = wsgi.WSGIServer( + ("localhost", 5100), func, server_name="localhost" + ) + server.start() + API --- """
Compatible with web.py? Is it possible to use opentelemetry-insrumentation-wsgi with web.py framework? If yes, some examples would be appreciated.
Does this help https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/wsgi/wsgi.html?
2021-06-01T16:31:00
open-telemetry/opentelemetry-python-contrib
530
open-telemetry__opentelemetry-python-contrib-530
[ "529" ]
9c834f088150e208d4fbd189477ed3bca5d106a3
diff --git a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/dependencies.py b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/dependencies.py --- a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/dependencies.py +++ b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/dependencies.py @@ -1,12 +1,16 @@ +from logging import getLogger from typing import Collection, Optional from pkg_resources import ( Distribution, DistributionNotFound, + RequirementParseError, VersionConflict, get_distribution, ) +logger = getLogger(__file__) + class DependencyConflict: required: str = None @@ -25,12 +29,19 @@ def __str__(self): def get_dist_dependency_conflicts( dist: Distribution, ) -> Optional[DependencyConflict]: - deps = [ - dep - for dep in dist.requires(("instruments",)) - if dep not in dist.requires() - ] - return get_dependency_conflicts(deps) + main_deps = dist.requires() + instrumentation_deps = [] + for dep in dist.requires(("instruments",)): + if dep not in main_deps: + # we set marker to none so string representation of the dependency looks like + # requests ~= 1.0 + # instead of + # requests ~= 1.0; extra = "instruments" + # which does not work with `get_distribution()` + dep.marker = None + instrumentation_deps.append(str(dep)) + + return get_dependency_conflicts(instrumentation_deps) def get_dependency_conflicts( @@ -38,9 +49,16 @@ def get_dependency_conflicts( ) -> Optional[DependencyConflict]: for dep in deps: try: - get_distribution(str(dep)) + get_distribution(dep) except VersionConflict as exc: return DependencyConflict(dep, exc.dist) except DistributionNotFound: return DependencyConflict(dep) + except RequirementParseError as exc: + logger.warning( + 'error parsing dependency, reporting as a conflict: "%s" - %s', + dep, + exc, + ) + return DependencyConflict(dep) return None
diff --git a/opentelemetry-instrumentation/tests/test_dependencies.py b/opentelemetry-instrumentation/tests/test_dependencies.py --- a/opentelemetry-instrumentation/tests/test_dependencies.py +++ b/opentelemetry-instrumentation/tests/test_dependencies.py @@ -14,11 +14,13 @@ # pylint: disable=protected-access +import pkg_resources import pytest from opentelemetry.instrumentation.dependencies import ( DependencyConflict, get_dependency_conflicts, + get_dist_dependency_conflicts, ) from opentelemetry.test.test_base import TestBase @@ -37,7 +39,6 @@ def test_get_dependency_conflicts_not_installed(self): conflict = get_dependency_conflicts(["this-package-does-not-exist"]) self.assertTrue(conflict is not None) self.assertTrue(isinstance(conflict, DependencyConflict)) - print(conflict) self.assertEqual( str(conflict), 'DependencyConflict: requested: "this-package-does-not-exist" but found: "None"', @@ -47,10 +48,32 @@ def test_get_dependency_conflicts_mismatched_version(self): conflict = get_dependency_conflicts(["pytest == 5000"]) self.assertTrue(conflict is not None) self.assertTrue(isinstance(conflict, DependencyConflict)) - print(conflict) self.assertEqual( str(conflict), 'DependencyConflict: requested: "pytest == 5000" but found: "pytest {0}"'.format( pytest.__version__ ), ) + + def test_get_dist_dependency_conflicts(self): + def mock_requires(extras=()): + if "instruments" in extras: + return [ + pkg_resources.Requirement( + 'test-pkg ~= 1.0; extra == "instruments"' + ) + ] + return [] + + dist = pkg_resources.Distribution( + project_name="test-instrumentation", version="1.0" + ) + dist.requires = mock_requires + + conflict = get_dist_dependency_conflicts(dist) + self.assertTrue(conflict is not None) + self.assertTrue(isinstance(conflict, DependencyConflict)) + self.assertEqual( + str(conflict), + 'DependencyConflict: requested: "test-pkg~=1.0" but found: "None"', + )
opentelemetry-instrument command fails if incompatible instrumentation is found If an instrumentation is installed for a library that is not found in the environment, the instrument command raises the following exception: ``` ❯ opentelemetry-instrument python main.py Instrumenting of flask failed Traceback (most recent call last): File "/Users/olone/playground/splunk-otel-py/venv/lib/python3.8/site-packages/opentelemetry/instrumentation/auto_instrumentation/sitecustomize.py", line 71, in _load_instrumentors conflict = get_dist_dependency_conflicts(entry_point.dist) File "/Users/olone/playground/splunk-otel-py/venv/lib/python3.8/site-packages/opentelemetry/instrumentation/dependencies.py", line 33, in get_dist_dependency_conflicts return get_dependency_conflicts(deps) File "/Users/olone/playground/splunk-otel-py/venv/lib/python3.8/site-packages/opentelemetry/instrumentation/dependencies.py", line 41, in get_dependency_conflicts get_distribution(str(dep)) File "/Users/olone/playground/splunk-otel-py/venv/lib/python3.8/site-packages/pkg_resources/__init__.py", line 482, in get_distribution dist = get_provider(dist) File "/Users/olone/playground/splunk-otel-py/venv/lib/python3.8/site-packages/pkg_resources/__init__.py", line 358, in get_provider return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0] IndexError: list index out of range Failed to auto initialize opentelemetry Traceback (most recent call last): File "/Users/olone/playground/splunk-otel-py/venv/lib/python3.8/site-packages/opentelemetry/instrumentation/auto_instrumentation/sitecustomize.py", line 111, in initialize _load_instrumentors(distro) File "/Users/olone/playground/splunk-otel-py/venv/lib/python3.8/site-packages/opentelemetry/instrumentation/auto_instrumentation/sitecustomize.py", line 85, in _load_instrumentors raise exc File "/Users/olone/playground/splunk-otel-py/venv/lib/python3.8/site-packages/opentelemetry/instrumentation/auto_instrumentation/sitecustomize.py", line 71, in _load_instrumentors conflict = get_dist_dependency_conflicts(entry_point.dist) File "/Users/olone/playground/splunk-otel-py/venv/lib/python3.8/site-packages/opentelemetry/instrumentation/dependencies.py", line 33, in get_dist_dependency_conflicts return get_dependency_conflicts(deps) File "/Users/olone/playground/splunk-otel-py/venv/lib/python3.8/site-packages/opentelemetry/instrumentation/dependencies.py", line 41, in get_dependency_conflicts get_distribution(str(dep)) File "/Users/olone/playground/splunk-otel-py/venv/lib/python3.8/site-packages/pkg_resources/__init__.py", line 482, in get_distribution dist = get_provider(dist) File "/Users/olone/playground/splunk-otel-py/venv/lib/python3.8/site-packages/pkg_resources/__init__.py", line 358, in get_provider return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0] IndexError: list index out of range ``` bootstrap command does not install any instrumentations for libraries that are not present in the environment so this would only happen if someone manually installed an instrumentation package for a library they're not using. So this is not a deal breaker and doesn't require an immediate hotfix. That said, this IS a bug as the intended behavior of instrument command is to silently ignore such instrumentations.
2021-06-02T17:56:18
open-telemetry/opentelemetry-python-contrib
537
open-telemetry__opentelemetry-python-contrib-537
[ "532" ]
9695bcfed37d7ce99a40d5ce4b23668d25a5192f
diff --git a/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py b/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py --- a/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py @@ -118,7 +118,7 @@ def collect_request_attributes(environ): } host_port = environ.get("SERVER_PORT") - if host_port is not None: + if host_port is not None and not host_port == "": result.update({SpanAttributes.NET_HOST_PORT: int(host_port)}) setifnotnone(result, SpanAttributes.HTTP_HOST, environ.get("HTTP_HOST"))
Problem with using domain socket as bind address **Describe your environment** The OT-wsgi library throws error if domain socket is used for the bind address. **Steps to reproduce** Here is a test program: ``` import web from time import sleep from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import ( ConsoleSpanExporter, SimpleSpanProcessor, ) from opentelemetry.instrumentation.wsgi import OpenTelemetryMiddleware from cheroot import wsgi trace.set_tracer_provider(TracerProvider()) trace.get_tracer_provider().add_span_processor( SimpleSpanProcessor(ConsoleSpanExporter()) ) #tracer = trace.get_tracer(__name__) urls = ( '/', 'index' ) class index: def GET(self): return "Hello, world!" if __name__ == "__main__": app = web.application(urls, globals()) func = app.wsgifunc() func = OpenTelemetryMiddleware(func) server = wsgi.WSGIServer("/tmp/lr.sock", func, server_name="localhost") server.start() ``` invocation: ``` (base) kamalh-mbp:~ kamalh$ echo -ne 'GET / HTTP/1.1\r\nHost: test.com\r\n\r\n' | nc -U /tmp/lr.sock HTTP/1.1 500 Internal Server Error Content-Length: 0 Content-Type: text/plain ``` Error from the program ``` (base) kamalh-mbp:opentelemetry kamalh$ python3 wsgi-lr.py Overriding of current TracerProvider is not allowed ValueError("invalid literal for int() with base 10: ''") Traceback (most recent call last): File "/Users/kamalh/miniconda3/lib/python3.7/site-packages/cheroot/server.py", line 1287, in communicate req.respond() File "/Users/kamalh/miniconda3/lib/python3.7/site-packages/cheroot/server.py", line 1077, in respond self.server.gateway(self).respond() File "/Users/kamalh/miniconda3/lib/python3.7/site-packages/cheroot/wsgi.py", line 140, in respond response = self.req.server.wsgi_app(self.env, self.start_response) File "/Users/kamalh/miniconda3/lib/python3.7/site-packages/opentelemetry/instrumentation/wsgi/__init__.py", line 229, in __call__ attributes=collect_request_attributes(environ), File "/Users/kamalh/miniconda3/lib/python3.7/site-packages/opentelemetry/instrumentation/wsgi/__init__.py", line 122, in collect_request_attributes result.update({SpanAttributes.NET_HOST_PORT: int(host_port)}) ValueError: invalid literal for int() with base 10: '' ``` **What is the expected behavior?** Expect to see the server returning normally as in TCP sockets. **What is the actual behavior?** Error message. Please see the paste above. **Additional context** Add any other context about the problem here.
2021-06-07T16:57:20
open-telemetry/opentelemetry-python-contrib
543
open-telemetry__opentelemetry-python-contrib-543
[ "541" ]
e12917401f5ca6af8737378a99b00da2b1987d5c
diff --git a/instrumentation/opentelemetry-instrumentation-psycopg2/src/opentelemetry/instrumentation/psycopg2/package.py b/instrumentation/opentelemetry-instrumentation-psycopg2/src/opentelemetry/instrumentation/psycopg2/package.py --- a/instrumentation/opentelemetry-instrumentation-psycopg2/src/opentelemetry/instrumentation/psycopg2/package.py +++ b/instrumentation/opentelemetry-instrumentation-psycopg2/src/opentelemetry/instrumentation/psycopg2/package.py @@ -13,4 +13,4 @@ # limitations under the License. -_instruments = ("psycopg2-binary >= 2.7.3.1",) +_instruments = ("psycopg2 >= 2.7.3.1",) diff --git a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py --- a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py +++ b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py @@ -80,8 +80,8 @@ "library": "mysql-connector-python ~= 8.0", "instrumentation": "opentelemetry-instrumentation-mysql==0.23.dev0", }, - "psycopg2-binary": { - "library": "psycopg2-binary >= 2.7.3.1", + "psycopg2": { + "library": "psycopg2 >= 2.7.3.1", "instrumentation": "opentelemetry-instrumentation-psycopg2==0.23.dev0", }, "pymemcache": {
psycopg2-binary dependency conflict **Describe your environment** ``` > pip freeze | grep psyco opentelemetry-instrumentation-psycopg2==0.22b0 psycopg2==2.8.6 ``` **Steps to reproduce** Install `psycopg2` instead of `psycopg2-binary` **What is the expected behavior?** No error message popping up **What is the actual behavior?** The instrumentation library will throw this error for every run. ``` DependencyConflict: requested: "psycopg2-binary >= 2.7.3.1" but found: "None" ``` **Additional context** The instrumentation actually works as expected for `psycopg2`. So, the package instrumented should be both `psycopg2-binary` and `psycopg`
`psycopg-binary` is not recommended for production usage. It should not be used as a dependency in general. It is more of a workaround for local setups.
2021-06-15T06:23:39
open-telemetry/opentelemetry-python-contrib
566
open-telemetry__opentelemetry-python-contrib-566
[ "565" ]
b2802ddd212d9e4dd62ccfc2189489b9f9e6e31f
diff --git a/sdk-extension/opentelemetry-sdk-extension-aws/src/opentelemetry/sdk/extension/aws/trace/propagation/aws_xray_format.py b/sdk-extension/opentelemetry-sdk-extension-aws/src/opentelemetry/sdk/extension/aws/trace/propagation/aws_xray_format.py --- a/sdk-extension/opentelemetry-sdk-extension-aws/src/opentelemetry/sdk/extension/aws/trace/propagation/aws_xray_format.py +++ b/sdk-extension/opentelemetry-sdk-extension-aws/src/opentelemetry/sdk/extension/aws/trace/propagation/aws_xray_format.py @@ -31,7 +31,7 @@ :: - export OTEL_PROPAGATORS = aws_xray + export OTEL_PROPAGATORS = xray Or by setting this propagator in your instrumented application:
AWS X-Ray propagator should be registered with xray environment variable In the spec, we have a definition for the environment variable as `xray` https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/sdk-environment-variables.md#general-sdk-configuration Currently python uses `aws_xray`
/cc @NathanielRN
2021-07-05T17:46:56
open-telemetry/opentelemetry-python-contrib
583
open-telemetry__opentelemetry-python-contrib-583
[ "582" ]
2ee2cf3cb54c7e9704567894636bcc1cfff702e6
diff --git a/scripts/eachdist.py b/scripts/eachdist.py --- a/scripts/eachdist.py +++ b/scripts/eachdist.py @@ -11,6 +11,7 @@ from datetime import datetime from inspect import cleandoc from itertools import chain +from os.path import basename from pathlib import Path, PurePath DEFAULT_ALLSEP = " " @@ -631,9 +632,7 @@ def update_dependencies(targets, version, packages): if str(pkg) == "all": continue print(pkg) - package_name = str(pkg).split("/", maxsplit=1)[-1] - # Windows uses backslashes - package_name = str(pkg).split("\\", maxsplit=1)[-1] + package_name = basename(pkg) print(package_name) update_files(
Fix eachdist.py `scripts/eachdist.py` is ignoring certain packages because it tries to get the package name by splitting with `split("/", maxsplit=1)`. This fails for a regular package path: ```python In [1]: "/a/b/c/d".split("/", maxsplit=1) Out[1]: ['', 'a/b/c/d'] ``` This script also tries to split at a different character if the operating system is Windows. Both problems can be fixed by using [`basename`](https://docs.python.org/3/library/os.path.html#os.path.basename) which is OS-portable: ```python In [1]: from os.path import basename In [2]: basename("/a/b/c/d") Out[2]: 'd' ```
2021-07-14T04:31:49
open-telemetry/opentelemetry-python-contrib
656
open-telemetry__opentelemetry-python-contrib-656
[ "649" ]
704f1d9cfdd59f84162885bfc611f416ba37f0c7
diff --git a/sdk-extension/opentelemetry-sdk-extension-aws/src/opentelemetry/sdk/extension/aws/trace/propagation/aws_xray_format.py b/sdk-extension/opentelemetry-sdk-extension-aws/src/opentelemetry/sdk/extension/aws/trace/propagation/aws_xray_format.py --- a/sdk-extension/opentelemetry-sdk-extension-aws/src/opentelemetry/sdk/extension/aws/trace/propagation/aws_xray_format.py +++ b/sdk-extension/opentelemetry-sdk-extension-aws/src/opentelemetry/sdk/extension/aws/trace/propagation/aws_xray_format.py @@ -18,9 +18,17 @@ The **AWS X-Ray Propagator** provides a propagator that when used, adds a `trace header`_ to outgoing traces that is compatible with the AWS X-Ray backend service. -This allows the trace context to be propagated when a trace span multiple AWS +This allows the trace context to be propagated when a trace spans multiple AWS services. +The same propagator setup is used to extract a context sent by external systems +so that child span have the correct parent context. + +**NOTE**: Because the parent context parsed from the ``X-Amzn-Trace-Id`` header +assumes the context is _not_ sampled by default, users should make sure to add +``Sampled=1`` to their ``X-Amzn-Trace-Id`` headers so that the child spans are +sampled. + Usage -----
Providing Parent in X-Amzn-Trace-Id results in no spans being exported There's a good chance this is user error. If so, I'd appreciate a pointer to the relevant doc. **Describe your environment** - Python 3.9 - fastapi==0.65.3 - opentelemetry-api==1.4.1 - opentelemetry-exporter-otlp==1.4.1 - opentelemetry-exporter-otlp-proto-grpc==1.4.1 - opentelemetry-instrumentation==0.23b2 - opentelemetry-instrumentation-asgi==0.23b2 - opentelemetry-instrumentation-fastapi==0.23b2 - opentelemetry-proto==1.4.1 - opentelemetry-sdk==1.4.1 - opentelemetry-sdk-extension-aws==0.23b2 - opentelemetry-semantic-conventions==0.23b2 - opentelemetry-util-http==0.23b2 **Steps to reproduce** Using this sample application: ``` import fastapi import uvicorn from opentelemetry import propagate, trace from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor from opentelemetry.sdk.extension.aws.trace import AwsXRayIdGenerator from opentelemetry.sdk.extension.aws.trace.propagation.aws_xray_format import AwsXRayFormat from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor app = fastapi.FastAPI() @app.get("/foo") async def foo(): return {"message": "foo"} # Setup AWS X-Ray Propagator propagate.set_global_textmap(AwsXRayFormat()) # Setup Tracer otlp_exporter = OTLPSpanExporter() span_processor = BatchSpanProcessor(otlp_exporter) tracer_provider = TracerProvider(id_generator=AwsXRayIdGenerator()) tracer_provider.add_span_processor(span_processor) trace.set_tracer_provider(tracer_provider) FastAPIInstrumentor.instrument_app(app) uvicorn.run(app) ``` Calling: `curl 'http://localhost:8000/foo'` produces a span that is exported by my collector to X-Ray. Calling: `curl 'http://localhost:8000/foo' -H 'X-Amzn-Trace-Id: Root=1-612fa749-271fa48e4c544863a13425d5;Parent=86153bfee2237b3b'` does not export a span. **What is the expected behavior?** My frontend application is producing requests with `X-Amzn-Trace-Id` in the format above. The frontend is separately sending X-Ray data. I'm expecting the trace ID generated by the frontend to be the root of the of the server segment so I can correlate the frontend activity and the backend activity. **What is the actual behavior?** When providing the header from the frontend, no span is generated by the backend. The frontend succeeds in generating spans that I see in the X-Ray console. No backend segments are seen. **Additional context** Unsure if #445 is related. It's the only thing that I could find in the issues that might be.
FYI @NathanielRN I continued playing with this last night and was able to get this to work by adding `;Sampled=1` to the header. My team is exploring moving from using the aws xray sdk to opentelemetry. The behavior of our stack in the past was to not provide `Sampled` from our frontend (we get a small number of requests, so just sample all). The defaults from our instrumentation libraries and the xray sdk seem to use that as a signal to sample. I'd refine my bug report, as - Not providing `Sampled` should result in the span being recorded (equivalent of `Sampled=1`) - The behavior in the absence of `Sampled` should be consistent for `Parent` supplied or not. Thanks for providing this additional context @andrew-matteson ! It's very helpful 😄 > Not providing `Sampled` should result in the span being recorded (equivalent of `Sampled=1`) I looks like you are correct, if `Sampled=` is **not** provided, the trace is assumed to **not** be sampled by the `AwsXrayFormat` propagator when it extracts the context from the header: https://github.com/open-telemetry/opentelemetry-python-contrib/blob/6f96577989698b9d7834abee2d172d47b24bebae/sdk-extension/opentelemetry-sdk-extension-aws/src/opentelemetry/sdk/extension/aws/trace/propagation/aws_xray_format.py#L154-L158 This behavior is consistent with what is done in other languages such as in the [OTel Java AWS X-Ray Propagator](https://github.com/open-telemetry/opentelemetry-java/blob/29cc44ed08dba28a65fa7d9f0c6824f38c51f6f2/extensions/aws/src/main/java/io/opentelemetry/extension/aws/AwsXrayPropagator.java#L172-L181) or in [OTel JS AWS X-Ray Propagator](https://github.com/open-telemetry/opentelemetry-js-contrib/blob/5fb3313b60a8d74af9ba8bacd260818545e4a1db/propagators/opentelemetry-propagator-aws-xray/src/AWSXRayPropagator.ts#L91-L103). Your use case makes sense, however I'm not sure if sampling by default is what most users would want. Maybe we can make documentation about this better in the meantime. > The behavior in the absence of `Sampled` should be consistent for `Parent` supplied or not. I think based on your configuration, the behavior you saw was expected. In your code you are using `TracerProvider` without a custom `Sampler`, that means you get [the default](https://github.com/open-telemetry/opentelemetry-python/blob/main/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py#L1048) `Sampler`: ```python class TracerProvider(trace_api.TracerProvider): """See `opentelemetry.trace.TracerProvider`.""" def __init__( self, sampler: sampling.Sampler = _TRACE_SAMPLER, ``` The default `Sampler` is the `parentbased_alwayson` [sampler](https://github.com/open-telemetry/opentelemetry-python/blob/c1e8a51b752f8d71e3910f122f355b49bfc7dbfa/opentelemetry-sdk/src/opentelemetry/sdk/trace/sampling.py#L384): ```python def _get_from_env_or_default() -> Sampler: trace_sampler = os.getenv( OTEL_TRACES_SAMPLER, "parentbased_always_on" ).lower() ``` which [will always sample](https://github.com/open-telemetry/opentelemetry-python/blob/c1e8a51b752f8d71e3910f122f355b49bfc7dbfa/opentelemetry-sdk/src/opentelemetry/sdk/trace/sampling.py#L357-L358) _unless the Parent is present to say otherwise_: ```python DEFAULT_ON = ParentBased(ALWAYS_ON) """Sampler that respects its parent span's sampling decision, but otherwise always samples.""" ``` So in your 2nd case, when you add the Parent header, your `TracerProvider` chooses to respect the Parent. Maybe if you want the trace to be `Sampled` without setting `Sampled=1` explicitly we could make the `AwsXrayFormat` propagator read from the currently configured `TraceProvider`'s `Sampler` to make the default sampling decision (instead of assuming `sampled = false`. But to unblock you for now I would suggest using `Sampled=1` 🙂 Please let me know if that makes sense! @NathanielRN Thank you! Makes complete sense. I'm unblocked at this point. Your doc suggestion sounds like the way to go.
2021-09-02T20:21:53
open-telemetry/opentelemetry-python-contrib
695
open-telemetry__opentelemetry-python-contrib-695
[ "694" ]
354bdc42d9e3d071a60737c47c7b1e17f77e8425
diff --git a/instrumentation/opentelemetry-instrumentation-celery/src/opentelemetry/instrumentation/celery/utils.py b/instrumentation/opentelemetry-instrumentation-celery/src/opentelemetry/instrumentation/celery/utils.py --- a/instrumentation/opentelemetry-instrumentation-celery/src/opentelemetry/instrumentation/celery/utils.py +++ b/instrumentation/opentelemetry-instrumentation-celery/src/opentelemetry/instrumentation/celery/utils.py @@ -131,7 +131,7 @@ def attach_span(task, task_id, span, is_publish=False): """ span_dict = getattr(task, CTX_KEY, None) if span_dict is None: - span_dict = dict() + span_dict = {} setattr(task, CTX_KEY, span_dict) span_dict[(task_id, is_publish)] = span diff --git a/instrumentation/opentelemetry-instrumentation-sklearn/src/opentelemetry/instrumentation/sklearn/__init__.py b/instrumentation/opentelemetry-instrumentation-sklearn/src/opentelemetry/instrumentation/sklearn/__init__.py --- a/instrumentation/opentelemetry-instrumentation-sklearn/src/opentelemetry/instrumentation/sklearn/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-sklearn/src/opentelemetry/instrumentation/sklearn/__init__.py @@ -194,7 +194,7 @@ def get_base_estimators(packages: List[str]) -> Dict[str, Type[BaseEstimator]]: A dictionary of qualnames and classes inheriting from ``BaseEstimator``. """ - klasses = dict() + klasses = {} for package_name in packages: lib = import_module(package_name) package_dir = os.path.dirname(lib.__file__)
Use {} instead of dict()
2021-09-21T18:31:53
open-telemetry/opentelemetry-python-contrib
705
open-telemetry__opentelemetry-python-contrib-705
[ "704" ]
4046fdb0a26d957604f41f304c8a6e3d817668bb
diff --git a/instrumentation/opentelemetry-instrumentation-elasticsearch/src/opentelemetry/instrumentation/elasticsearch/__init__.py b/instrumentation/opentelemetry-instrumentation-elasticsearch/src/opentelemetry/instrumentation/elasticsearch/__init__.py --- a/instrumentation/opentelemetry-instrumentation-elasticsearch/src/opentelemetry/instrumentation/elasticsearch/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-elasticsearch/src/opentelemetry/instrumentation/elasticsearch/__init__.py @@ -81,6 +81,7 @@ def response_hook(span, response): es.get(index='my-index', doc_type='my-type', id=1) """ +import re from logging import getLogger from os import environ from typing import Collection @@ -107,7 +108,7 @@ def response_hook(span, response): "took", ] -_DEFALT_OP_NAME = "request" +_DEFAULT_OP_NAME = "request" class ElasticsearchInstrumentor(BaseInstrumentor): @@ -146,6 +147,9 @@ def _uninstrument(self, **kwargs): unwrap(elasticsearch.Transport, "perform_request") +_regex_doc_url = re.compile(r"/_doc/([^/]+)") + + def _wrap_perform_request( tracer, span_name_prefix, request_hook=None, response_hook=None ): @@ -161,7 +165,24 @@ def wrapper(wrapped, _, args, kwargs): len(args), ) - op_name = span_name_prefix + (url or method or _DEFALT_OP_NAME) + op_name = span_name_prefix + (url or method or _DEFAULT_OP_NAME) + doc_id = None + if url: + # TODO: This regex-based solution avoids creating an unbounded number of span names, but should be replaced by instrumenting individual Elasticsearch methods instead of Transport.perform_request() + # A limitation of the regex is that only the '_doc' mapping type is supported. Mapping types are deprecated since Elasticsearch 7 + # https://github.com/open-telemetry/opentelemetry-python-contrib/issues/708 + match = _regex_doc_url.search(url) + if match is not None: + # Remove the full document ID from the URL + doc_span = match.span() + op_name = ( + span_name_prefix + + url[: doc_span[0]] + + "/_doc/:id" + + url[doc_span[1] :] + ) + # Put the document ID in attributes + doc_id = match.group(1) params = kwargs.get("params", {}) body = kwargs.get("body", None) @@ -184,6 +205,8 @@ def wrapper(wrapped, _, args, kwargs): attributes[SpanAttributes.DB_STATEMENT] = str(body) if params: attributes["elasticsearch.params"] = str(params) + if doc_id: + attributes["elasticsearch.id"] = doc_id for key, value in attributes.items(): span.set_attribute(key, value)
diff --git a/instrumentation/opentelemetry-instrumentation-elasticsearch/tests/test_elasticsearch.py b/instrumentation/opentelemetry-instrumentation-elasticsearch/tests/test_elasticsearch.py --- a/instrumentation/opentelemetry-instrumentation-elasticsearch/tests/test_elasticsearch.py +++ b/instrumentation/opentelemetry-instrumentation-elasticsearch/tests/test_elasticsearch.py @@ -64,7 +64,7 @@ def test_instrumentor(self, request_mock): request_mock.return_value = (1, {}, {}) es = Elasticsearch() - es.index(index="sw", doc_type="people", id=1, body={"name": "adam"}) + es.index(index="sw", doc_type="_doc", id=1, body={"name": "adam"}) spans_list = self.get_finished_spans() self.assertEqual(len(spans_list), 1) @@ -79,7 +79,7 @@ def test_instrumentor(self, request_mock): # check that no spans are generated after uninstrument ElasticsearchInstrumentor().uninstrument() - es.index(index="sw", doc_type="people", id=1, body={"name": "adam"}) + es.index(index="sw", doc_type="_doc", id=1, body={"name": "adam"}) spans_list = self.get_finished_spans() self.assertEqual(len(spans_list), 1) @@ -119,7 +119,7 @@ def test_prefix_env(self, request_mock): def _test_prefix(self, prefix): es = Elasticsearch() - es.index(index="sw", doc_type="people", id=1, body={"name": "adam"}) + es.index(index="sw", doc_type="_doc", id=1, body={"name": "adam"}) spans_list = self.get_finished_spans() self.assertEqual(len(spans_list), 1) @@ -133,11 +133,12 @@ def test_result_values(self, request_mock): '{"found": false, "timed_out": true, "took": 7}', ) es = Elasticsearch() - es.get(index="test-index", doc_type="tweet", id=1) + es.get(index="test-index", doc_type="_doc", id=1) spans = self.get_finished_spans() self.assertEqual(1, len(spans)) + self.assertEqual(spans[0].name, "Elasticsearch/test-index/_doc/:id") self.assertEqual("False", spans[0].attributes["elasticsearch.found"]) self.assertEqual( "True", spans[0].attributes["elasticsearch.timed_out"] @@ -159,7 +160,7 @@ def test_trace_error_not_found(self, request_mock): def _test_trace_error(self, code, exc): es = Elasticsearch() try: - es.get(index="test-index", doc_type="tweet", id=1) + es.get(index="test-index", doc_type="_doc", id=1) except Exception: # pylint: disable=broad-except pass @@ -176,15 +177,13 @@ def test_parent(self, request_mock): request_mock.return_value = (1, {}, {}) es = Elasticsearch() with self.tracer.start_as_current_span("parent"): - es.index( - index="sw", doc_type="people", id=1, body={"name": "adam"} - ) + es.index(index="sw", doc_type="_doc", id=1, body={"name": "adam"}) spans = self.get_finished_spans() self.assertEqual(len(spans), 2) parent = spans.by_name("parent") - child = spans.by_name("Elasticsearch/sw/people/1") + child = spans.by_name("Elasticsearch/sw/_doc/:id") self.assertIsNotNone(child.parent) self.assertEqual(child.parent.span_id, parent.context.span_id) @@ -198,13 +197,13 @@ def test_multithread(self, request_mock): # 3. Check the spans got different parents, and are in the expected order. def target1(parent_span): with trace.use_span(parent_span): - es.get(index="test-index", doc_type="tweet", id=1) + es.get(index="test-index", doc_type="_doc", id=1) ev.set() ev.wait() def target2(): ev.wait() - es.get(index="test-index", doc_type="tweet", id=2) + es.get(index="test-index", doc_type="_doc", id=2) ev.set() with self.tracer.start_as_current_span("parent") as span: @@ -220,8 +219,8 @@ def target2(): self.assertEqual(3, len(spans)) s1 = spans.by_name("parent") - s2 = spans.by_name("Elasticsearch/test-index/tweet/1") - s3 = spans.by_name("Elasticsearch/test-index/tweet/2") + s2 = spans.by_attr("elasticsearch.id", "1") + s3 = spans.by_attr("elasticsearch.id", "2") self.assertIsNotNone(s2.parent) self.assertEqual(s2.parent.span_id, s1.context.span_id) @@ -343,10 +342,9 @@ def request_hook(span, method, url, kwargs): ) es = Elasticsearch() index = "test-index" - doc_type = "tweet" doc_id = 1 kwargs = {"params": {"test": True}} - es.get(index=index, doc_type=doc_type, id=doc_id, **kwargs) + es.get(index=index, doc_type="_doc", id=doc_id, **kwargs) spans = self.get_finished_spans() @@ -355,7 +353,7 @@ def request_hook(span, method, url, kwargs): "GET", spans[0].attributes[request_hook_method_attribute] ) self.assertEqual( - f"/{index}/{doc_type}/{doc_id}", + f"/{index}/_doc/{doc_id}", spans[0].attributes[request_hook_url_attribute], ) self.assertEqual( @@ -390,7 +388,7 @@ def response_hook(span, response): "hits": [ { "_index": "test-index", - "_type": "tweet", + "_type": "_doc", "_id": "1", "_score": 0.18232156, "_source": {"name": "tester"}, @@ -405,7 +403,7 @@ def response_hook(span, response): json.dumps(response_payload), ) es = Elasticsearch() - es.get(index="test-index", doc_type="tweet", id=1) + es.get(index="test-index", doc_type="_doc", id=1) spans = self.get_finished_spans()
elasticsearch instrumentation creates too many span names, with unique document IDs. **Describe your environment** Using `opentelemetry-instrumentation-elasticsearch` `0.24b0` with `elasticsearch` `7.14.1` **Steps to reproduce** Perform some `index()` and/or `delete()` calls with `id` parameter set **What is the expected behavior?** The number of span names created is reasonable and finite **What is the actual behavior?** An unbounded number of span names get created, containing the unique document names. This makes it hard to search through operations, for example in Jaeger: ![screenshot](https://user-images.githubusercontent.com/426784/135645077-dde57682-5398-4e47-92d3-bf6e0eddb5ea.png) The `datamart.test.xxxx` parts are the Elasticsearch document IDs. **Additional context** I have a patch for this incoming.
2021-10-01T15:26:47
open-telemetry/opentelemetry-python-contrib
736
open-telemetry__opentelemetry-python-contrib-736
[ "687" ]
face2a3272b2ccda4c1692bbffa238f9b2cd6efb
diff --git a/instrumentation/opentelemetry-instrumentation-pymongo/src/opentelemetry/instrumentation/pymongo/__init__.py b/instrumentation/opentelemetry-instrumentation-pymongo/src/opentelemetry/instrumentation/pymongo/__init__.py --- a/instrumentation/opentelemetry-instrumentation-pymongo/src/opentelemetry/instrumentation/pymongo/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-pymongo/src/opentelemetry/instrumentation/pymongo/__init__.py @@ -41,9 +41,11 @@ from pymongo import monitoring +from opentelemetry import context from opentelemetry.instrumentation.instrumentor import BaseInstrumentor from opentelemetry.instrumentation.pymongo.package import _instruments from opentelemetry.instrumentation.pymongo.version import __version__ +from opentelemetry.instrumentation.utils import _SUPPRESS_INSTRUMENTATION_KEY from opentelemetry.semconv.trace import DbSystemValues, SpanAttributes from opentelemetry.trace import SpanKind, get_tracer from opentelemetry.trace.status import Status, StatusCode @@ -57,7 +59,9 @@ def __init__(self, tracer): def started(self, event: monitoring.CommandStartedEvent): """ Method to handle a pymongo CommandStartedEvent """ - if not self.is_enabled: + if not self.is_enabled or context.get_value( + _SUPPRESS_INSTRUMENTATION_KEY + ): return command = event.command.get(event.command_name, "") name = event.command_name @@ -92,7 +96,9 @@ def started(self, event: monitoring.CommandStartedEvent): def succeeded(self, event: monitoring.CommandSucceededEvent): """ Method to handle a pymongo CommandSucceededEvent """ - if not self.is_enabled: + if not self.is_enabled or context.get_value( + _SUPPRESS_INSTRUMENTATION_KEY + ): return span = self._pop_span(event) if span is None: @@ -101,7 +107,9 @@ def succeeded(self, event: monitoring.CommandSucceededEvent): def failed(self, event: monitoring.CommandFailedEvent): """ Method to handle a pymongo CommandFailedEvent """ - if not self.is_enabled: + if not self.is_enabled or context.get_value( + _SUPPRESS_INSTRUMENTATION_KEY + ): return span = self._pop_span(event) if span is None:
diff --git a/instrumentation/opentelemetry-instrumentation-pymongo/tests/test_pymongo.py b/instrumentation/opentelemetry-instrumentation-pymongo/tests/test_pymongo.py --- a/instrumentation/opentelemetry-instrumentation-pymongo/tests/test_pymongo.py +++ b/instrumentation/opentelemetry-instrumentation-pymongo/tests/test_pymongo.py @@ -14,11 +14,13 @@ from unittest import mock +from opentelemetry import context from opentelemetry import trace as trace_api from opentelemetry.instrumentation.pymongo import ( CommandTracer, PymongoInstrumentor, ) +from opentelemetry.instrumentation.utils import _SUPPRESS_INSTRUMENTATION_KEY from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.test.test_base import TestBase @@ -90,6 +92,31 @@ def test_not_recording(self): self.assertFalse(mock_span.set_attribute.called) self.assertFalse(mock_span.set_status.called) + def test_suppression_key(self): + mock_tracer = mock.Mock() + mock_span = mock.Mock() + mock_span.is_recording.return_value = True + mock_tracer.start_span.return_value = mock_span + mock_event = MockEvent({}) + mock_event.command.get = mock.Mock() + mock_event.command.get.return_value = "dummy" + + token = context.attach( + context.set_value(_SUPPRESS_INSTRUMENTATION_KEY, True) + ) + + try: + command_tracer = CommandTracer(mock_tracer) + command_tracer.started(event=mock_event) + command_tracer.succeeded(event=mock_event) + finally: + context.detach(token) + + # if suppression key is set, CommandTracer methods return immediately, so command.get is not invoked. + self.assertFalse( + mock_event.command.get.called # pylint: disable=no-member + ) + def test_failed(self): mock_event = MockEvent({}) command_tracer = CommandTracer(self.tracer)
opentelemetry-instrumentation-pymongo is not checking suppress_information **Describe your environment** - Python 3.9 - opentelemetry-instrumentation-pymongo==0.23b2 **Steps to reproduce** A method polls our database waiting for success. We've tried to add suppression for this because we get many 10s of segments for this polling, but spans still get generated. ``` ctx = set_value("suppress_instrumentation", True) with tracer.start_as_current_span("polling", ctx): tt = time.time() while timeout is None or float(timeout) > time.time() - tt: status = cls.status(job_id) if not status.is_pending(): return await asyncio.sleep(increment) ``` Invoking `cls.status(job_id)` does a mongo query to determine status. **What is the expected behavior?** I expect that the mongo query triggered by the status call doesn't generate a span. **What is the actual behavior?** many 10s of spans are included in the output of the instrumentation. **Additional context** There's a possibility I'm invoking the code wrong here (I'm new to OpenTelemetry), but the implementation for PyMongo doesn't reference the suppression key like other libraries.
2021-10-13T16:18:47
open-telemetry/opentelemetry-python-contrib
782
open-telemetry__opentelemetry-python-contrib-782
[ "771" ]
e6dff7e5d115cfb882b7760a21adff52f0c9f343
diff --git a/exporter/opentelemetry-exporter-richconsole/src/opentelemetry/exporter/richconsole/__init__.py b/exporter/opentelemetry-exporter-richconsole/src/opentelemetry/exporter/richconsole/__init__.py --- a/exporter/opentelemetry-exporter-richconsole/src/opentelemetry/exporter/richconsole/__init__.py +++ b/exporter/opentelemetry-exporter-richconsole/src/opentelemetry/exporter/richconsole/__init__.py @@ -36,13 +36,13 @@ from opentelemetry import trace from opentelemetry.sdk.trace.export import BatchSpanProcessor - from opentelemetry.exporter.richconsole import RichConsoleExporter + from opentelemetry.exporter.richconsole import RichConsoleSpanExporter from opentelemetry.sdk.trace import TracerProvider trace.set_tracer_provider(TracerProvider()) tracer = trace.get_tracer(__name__) - tracer.add_span_processor(BatchSpanProcessor(RichConsoleExporter())) + tracer.add_span_processor(BatchSpanProcessor(RichConsoleSpanExporter())) API @@ -155,18 +155,19 @@ def export(self, spans: typing.Sequence[ReadableSpan]) -> SpanExportResult: _child_to_tree(child, span) for span in spans: - if span.parent and span.parent.span_id not in parents: - child = tree.add( + if span.parent and span.parent.span_id in parents: + child = parents[span.parent.span_id].add( label=Text.from_markup( f"[blue][{_ns_to_time(span.start_time)}][/blue] [bold]{span.name}[/bold], span {opentelemetry.trace.format_span_id(span.context.span_id)}" ) ) else: - child = parents[span.parent.span_id].add( + child = tree.add( label=Text.from_markup( f"[blue][{_ns_to_time(span.start_time)}][/blue] [bold]{span.name}[/bold], span {opentelemetry.trace.format_span_id(span.context.span_id)}" ) ) + parents[span.context.span_id] = child _child_to_tree(child, span)
diff --git a/exporter/opentelemetry-exporter-richconsole/tests/__init__.py b/exporter/opentelemetry-exporter-richconsole/tests/__init__.py new file mode 100644 diff --git a/exporter/opentelemetry-exporter-richconsole/tests/test_rich_exporter.py b/exporter/opentelemetry-exporter-richconsole/tests/test_rich_exporter.py new file mode 100644 --- /dev/null +++ b/exporter/opentelemetry-exporter-richconsole/tests/test_rich_exporter.py @@ -0,0 +1,47 @@ +# Copyright The OpenTelemetry Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pytest + +from opentelemetry.exporter.richconsole import RichConsoleSpanExporter +from opentelemetry.sdk import trace +from opentelemetry.sdk.trace.export import BatchSpanProcessor + + [email protected](name="span_processor") +def fixture_span_processor(): + exporter = RichConsoleSpanExporter() + span_processor = BatchSpanProcessor(exporter) + + yield span_processor + + span_processor.shutdown() + + [email protected](name="tracer_provider") +def fixture_tracer_provider(span_processor): + tracer_provider = trace.TracerProvider() + tracer_provider.add_span_processor(span_processor) + + yield tracer_provider + + +def test_span_exporter(tracer_provider, span_processor, capsys): + tracer = tracer_provider.get_tracer(__name__) + span = tracer.start_span("test_span") + span.set_attribute("key", "V4LuE") + span.end() + span_processor.force_flush() + captured = capsys.readouterr() + assert "V4LuE" in captured.out
Bug in RichConsoleSpanExporter **Describe your environment** Python 3.9.7, Snippet from `pipenv graph`: ``` opentelemetry-exporter-richconsole==0.25b2 - opentelemetry-api [required: ~=1.3, installed: 1.10a0] - opentelemetry-sdk [required: ~=1.3, installed: 1.10a0] - opentelemetry-api [required: ==1.10a0, installed: 1.10a0] - opentelemetry-semantic-conventions [required: ==0.25b2, installed: 0.25b2] - rich [required: >=10.0.0, installed: 10.12.0] - colorama [required: >=0.4.0,<0.5.0, installed: 0.4.4] - commonmark [required: >=0.9.0,<0.10.0, installed: 0.9.1] - pygments [required: >=2.6.0,<3.0.0, installed: 2.10.0] ``` **Steps to reproduce** Given this code: ``` from opentelemetry import trace from opentelemetry.sdk.resources import SERVICE_NAME, Resource from opentelemetry.exporter.richconsole import RichConsoleSpanExporter from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor from opentelemetry.sdk.trace.export import ConsoleSpanExporter APP_SERVICE_NAME = "fastapi-goofing" trace.set_tracer_provider( TracerProvider( resource=Resource.create({SERVICE_NAME: APP_SERVICE_NAME}) ) ) rich_console_exporter = RichConsoleSpanExporter( service_name=APP_SERVICE_NAME, ) console_exporter = ConsoleSpanExporter( service_name=APP_SERVICE_NAME ) trace.get_tracer_provider().add_span_processor( BatchSpanProcessor(rich_console_exporter) #BatchSpanProcessor(console_exporter) ) tracer = trace.get_tracer(__name__) with tracer.start_as_current_span("foo"): with tracer.start_as_current_span("bar"): with tracer.start_as_current_span("baz"): print("Hello world from OpenTelemetry Python!") ``` The `RichConsoleSpanExporter` throws this error: ``` Exception while exporting Span batch. Traceback (most recent call last): File "/home/trond/Documents/projects/fastapi-goofring/.venv/lib/python3.9/site-packages/opentelemetry/sdk/trace/export/__init__.py", line 331, in _export_batch self.span_exporter.export(self.spans_list[:idx]) # type: ignore File "/home/trond/Documents/projects/fastapi-goofring/.venv/lib/python3.9/site-packages/opentelemetry/exporter/richconsole/__init__.py", line 166, in export child = parents[span.parent.span_id].add( AttributeError: 'NoneType' object has no attribute 'span_id' ``` If I replace the Rich exporter with the regular Console exporter, everything runs nicely without problems **What is the expected behavior?** Code runs without exceptions **What is the actual behavior?** Exception is thrown **Additional context**
@tonybaloney fyi > @tonybaloney fyi Thanks for the report. Will fix today
2021-10-26T22:19:32
open-telemetry/opentelemetry-python-contrib
792
open-telemetry__opentelemetry-python-contrib-792
[ "791" ]
671aea32f9bbf53ace776c17ef2a80424d730fbb
diff --git a/instrumentation/opentelemetry-instrumentation-pymysql/src/opentelemetry/instrumentation/pymysql/package.py b/instrumentation/opentelemetry-instrumentation-pymysql/src/opentelemetry/instrumentation/pymysql/package.py --- a/instrumentation/opentelemetry-instrumentation-pymysql/src/opentelemetry/instrumentation/pymysql/package.py +++ b/instrumentation/opentelemetry-instrumentation-pymysql/src/opentelemetry/instrumentation/pymysql/package.py @@ -13,4 +13,4 @@ # limitations under the License. -_instruments = ("PyMySQL ~= 0.10.1",) +_instruments = ("PyMySQL < 2",) diff --git a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py --- a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py +++ b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py @@ -97,7 +97,7 @@ "instrumentation": "opentelemetry-instrumentation-pymongo==0.25b2", }, "PyMySQL": { - "library": "PyMySQL ~= 0.10.1", + "library": "PyMySQL < 2", "instrumentation": "opentelemetry-instrumentation-pymysql==0.25b2", }, "pyramid": {
Add support for PyMySQL v1.x series pymysql instrumentation does not work with 1.x series as it lists <1.0 as the compatible versions. I've tested the instrumentatoin with a simple application that uses PyMySQL 1.0 and it seems to work. We should update the instrumentation to support <2.0. original issue: https://github.com/open-telemetry/opentelemetry-python/issues/2259
2021-11-03T15:55:39
open-telemetry/opentelemetry-python-contrib
797
open-telemetry__opentelemetry-python-contrib-797
[ "796" ]
d4ad8f57be9387aa030dc3e1ea5797173c19afca
diff --git a/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py b/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py --- a/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py @@ -160,7 +160,7 @@ def collect_request_attributes(scope): if query_string and http_url: if isinstance(query_string, bytes): query_string = query_string.decode("utf8") - http_url = http_url + ("?" + urllib.parse.unquote(query_string)) + http_url += "?" + urllib.parse.unquote(query_string) result = { SpanAttributes.HTTP_SCHEME: scope.get("scheme"),
Increase the usage of augmented assignment statements This issue corresponds with [this one](https://github.com/open-telemetry/opentelemetry-python/issues/2258).
2021-11-09T13:41:57
open-telemetry/opentelemetry-python-contrib
817
open-telemetry__opentelemetry-python-contrib-817
[ "803" ]
26aa17f8e93c43e80a204cde14d6bac680918c27
diff --git a/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py b/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py --- a/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py @@ -103,11 +103,14 @@ def client_response_hook(span: Span, message: dict): from opentelemetry import context, trace from opentelemetry.instrumentation.asgi.version import __version__ # noqa +from opentelemetry.instrumentation.propagators import ( + get_global_response_propagator, +) from opentelemetry.instrumentation.utils import http_status_to_status_code from opentelemetry.propagate import extract -from opentelemetry.propagators.textmap import Getter +from opentelemetry.propagators.textmap import Getter, Setter from opentelemetry.semconv.trace import SpanAttributes -from opentelemetry.trace import Span +from opentelemetry.trace import Span, set_span_in_context from opentelemetry.trace.status import Status, StatusCode from opentelemetry.util.http import remove_url_credentials @@ -152,6 +155,30 @@ def keys(self, carrier: dict) -> typing.List[str]: asgi_getter = ASGIGetter() +class ASGISetter(Setter): + def set( + self, carrier: dict, key: str, value: str + ) -> None: # pylint: disable=no-self-use + """Sets response header values on an ASGI scope according to `the spec <https://asgi.readthedocs.io/en/latest/specs/www.html#response-start-send-event>`_. + + Args: + carrier: ASGI scope object + key: response header name to set + value: response header value + Returns: + None + """ + headers = carrier.get("headers") + if not headers: + headers = [] + carrier["headers"] = headers + + headers.append([key.lower().encode(), value.encode()]) + + +asgi_setter = ASGISetter() + + def collect_request_attributes(scope): """Collects HTTP request attributes from the ASGI scope and returns a dictionary to be used as span creation attributes.""" @@ -295,54 +322,84 @@ async def __call__(self, scope, receive, send): return await self.app(scope, receive, send) token = context.attach(extract(scope, getter=asgi_getter)) - span_name, additional_attributes = self.default_span_details(scope) + server_span_name, additional_attributes = self.default_span_details( + scope + ) try: with self.tracer.start_as_current_span( - span_name, + server_span_name, kind=trace.SpanKind.SERVER, - ) as span: - if span.is_recording(): + ) as server_span: + if server_span.is_recording(): attributes = collect_request_attributes(scope) attributes.update(additional_attributes) for key, value in attributes.items(): - span.set_attribute(key, value) + server_span.set_attribute(key, value) if callable(self.server_request_hook): - self.server_request_hook(span, scope) - - @wraps(receive) - async def wrapped_receive(): - with self.tracer.start_as_current_span( - " ".join((span_name, scope["type"], "receive")) - ) as receive_span: - if callable(self.client_request_hook): - self.client_request_hook(receive_span, scope) - message = await receive() - if receive_span.is_recording(): - if message["type"] == "websocket.receive": - set_status_code(receive_span, 200) - receive_span.set_attribute("type", message["type"]) - return message - - @wraps(send) - async def wrapped_send(message): - with self.tracer.start_as_current_span( - " ".join((span_name, scope["type"], "send")) - ) as send_span: - if callable(self.client_response_hook): - self.client_response_hook(send_span, message) - if send_span.is_recording(): - if message["type"] == "http.response.start": - status_code = message["status"] - set_status_code(span, status_code) - set_status_code(send_span, status_code) - elif message["type"] == "websocket.send": - set_status_code(span, 200) - set_status_code(send_span, 200) - send_span.set_attribute("type", message["type"]) - await send(message) - - await self.app(scope, wrapped_receive, wrapped_send) + self.server_request_hook(server_span, scope) + + otel_receive = self._get_otel_receive( + server_span_name, scope, receive + ) + + otel_send = self._get_otel_send( + server_span, + server_span_name, + scope, + send, + ) + + await self.app(scope, otel_receive, otel_send) finally: context.detach(token) + + def _get_otel_receive(self, server_span_name, scope, receive): + @wraps(receive) + async def otel_receive(): + with self.tracer.start_as_current_span( + " ".join((server_span_name, scope["type"], "receive")) + ) as receive_span: + if callable(self.client_request_hook): + self.client_request_hook(receive_span, scope) + message = await receive() + if receive_span.is_recording(): + if message["type"] == "websocket.receive": + set_status_code(receive_span, 200) + receive_span.set_attribute("type", message["type"]) + return message + + return otel_receive + + def _get_otel_send(self, server_span, server_span_name, scope, send): + @wraps(send) + async def otel_send(message): + with self.tracer.start_as_current_span( + " ".join((server_span_name, scope["type"], "send")) + ) as send_span: + if callable(self.client_response_hook): + self.client_response_hook(send_span, message) + if send_span.is_recording(): + if message["type"] == "http.response.start": + status_code = message["status"] + set_status_code(server_span, status_code) + set_status_code(send_span, status_code) + elif message["type"] == "websocket.send": + set_status_code(server_span, 200) + set_status_code(send_span, 200) + send_span.set_attribute("type", message["type"]) + + propagator = get_global_response_propagator() + if propagator: + propagator.inject( + message, + context=set_span_in_context( + server_span, trace.context_api.Context() + ), + setter=asgi_setter, + ) + + await send(message) + + return otel_send
diff --git a/instrumentation/opentelemetry-instrumentation-asgi/tests/test_asgi_middleware.py b/instrumentation/opentelemetry-instrumentation-asgi/tests/test_asgi_middleware.py --- a/instrumentation/opentelemetry-instrumentation-asgi/tests/test_asgi_middleware.py +++ b/instrumentation/opentelemetry-instrumentation-asgi/tests/test_asgi_middleware.py @@ -18,6 +18,11 @@ import opentelemetry.instrumentation.asgi as otel_asgi from opentelemetry import trace as trace_api +from opentelemetry.instrumentation.propagators import ( + TraceResponsePropagator, + get_global_response_propagator, + set_global_response_propagator, +) from opentelemetry.sdk import resources from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.test.asgitestutil import ( @@ -25,6 +30,7 @@ setup_testing_defaults, ) from opentelemetry.test.test_base import TestBase +from opentelemetry.trace import format_span_id, format_trace_id async def http_app(scope, receive, send): @@ -287,6 +293,38 @@ def update_expected_user_agent(expected): outputs = self.get_all_output() self.validate_outputs(outputs, modifiers=[update_expected_user_agent]) + def test_traceresponse_header(self): + """Test a traceresponse header is sent when a global propagator is set.""" + + orig = get_global_response_propagator() + set_global_response_propagator(TraceResponsePropagator()) + + app = otel_asgi.OpenTelemetryMiddleware(simple_asgi) + self.seed_app(app) + self.send_default_request() + + span = self.memory_exporter.get_finished_spans()[-1] + self.assertEqual(trace_api.SpanKind.SERVER, span.kind) + + response_start, response_body, *_ = self.get_all_output() + self.assertEqual(response_body["body"], b"*") + self.assertEqual(response_start["status"], 200) + + traceresponse = "00-{0}-{1}-01".format( + format_trace_id(span.get_span_context().trace_id), + format_span_id(span.get_span_context().span_id), + ) + self.assertListEqual( + response_start["headers"], + [ + [b"Content-Type", b"text/plain"], + [b"traceresponse", f"{traceresponse}".encode()], + [b"access-control-expose-headers", b"traceresponse"], + ], + ) + + set_global_response_propagator(orig) + def test_websocket(self): self.scope = { "type": "websocket", @@ -359,6 +397,46 @@ def test_websocket(self): self.assertEqual(span.kind, expected["kind"]) self.assertDictEqual(dict(span.attributes), expected["attributes"]) + def test_websocket_traceresponse_header(self): + """Test a traceresponse header is set for websocket messages""" + + orig = get_global_response_propagator() + set_global_response_propagator(TraceResponsePropagator()) + + self.scope = { + "type": "websocket", + "http_version": "1.1", + "scheme": "ws", + "path": "/", + "query_string": b"", + "headers": [], + "client": ("127.0.0.1", 32767), + "server": ("127.0.0.1", 80), + } + app = otel_asgi.OpenTelemetryMiddleware(simple_asgi) + self.seed_app(app) + self.send_input({"type": "websocket.connect"}) + self.send_input({"type": "websocket.receive", "text": "ping"}) + self.send_input({"type": "websocket.disconnect"}) + _, socket_send, *_ = self.get_all_output() + + span = self.memory_exporter.get_finished_spans()[-1] + self.assertEqual(trace_api.SpanKind.SERVER, span.kind) + + traceresponse = "00-{0}-{1}-01".format( + format_trace_id(span.get_span_context().trace_id), + format_span_id(span.get_span_context().span_id), + ) + self.assertListEqual( + socket_send["headers"], + [ + [b"traceresponse", f"{traceresponse}".encode()], + [b"access-control-expose-headers", b"traceresponse"], + ], + ) + + set_global_response_propagator(orig) + def test_lifespan(self): self.scope["type"] = "lifespan" app = otel_asgi.OpenTelemetryMiddleware(simple_asgi)
Add traceresponse header support for ASGI applications (Starlette, FastAPI) This was added to a lot of HTTP frameworks in #436 but it looks like FastAPI and Starlette missed the cut. Could have been there was not support for those frameworks just yet.
2021-11-28T05:12:47
open-telemetry/opentelemetry-python-contrib
823
open-telemetry__opentelemetry-python-contrib-823
[ "820", "820" ]
e69030e94bd5b8d5d21b40e59b124d105de8542a
diff --git a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/utils.py b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/utils.py --- a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/utils.py +++ b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/utils.py @@ -49,6 +49,9 @@ def http_status_to_status_code( status (int): HTTP status code """ # See: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#status + if not isinstance(status, int): + return StatusCode.UNSET + if status < 100: return StatusCode.ERROR if status <= 299:
diff --git a/opentelemetry-instrumentation/tests/test_utils.py b/opentelemetry-instrumentation/tests/test_utils.py --- a/opentelemetry-instrumentation/tests/test_utils.py +++ b/opentelemetry-instrumentation/tests/test_utils.py @@ -56,6 +56,12 @@ def test_http_status_to_status_code(self): actual = http_status_to_status_code(int(status_code)) self.assertEqual(actual, expected, status_code) + def test_http_status_to_status_code_none(self): + for status_code, expected in ((None, StatusCode.UNSET),): + with self.subTest(status_code=status_code): + actual = http_status_to_status_code(status_code) + self.assertEqual(actual, expected, status_code) + def test_http_status_to_status_code_redirect(self): for status_code, expected in ( (HTTPStatus.MULTIPLE_CHOICES, StatusCode.ERROR),
urllib instrumentation fails for local file access When reading local files the status code is not specified and is None. This isn't handled by the instrumentation and causes an exception. https://github.com/open-telemetry/opentelemetry-python-contrib/blob/444e0a13127304d3a04ccd44445b2e6caed3f770/instrumentation/opentelemetry-instrumentation-urllib/src/opentelemetry/instrumentation/urllib/__init__.py#L212-L217 urllib instrumentation fails for local file access When reading local files the status code is not specified and is None. This isn't handled by the instrumentation and causes an exception. https://github.com/open-telemetry/opentelemetry-python-contrib/blob/444e0a13127304d3a04ccd44445b2e6caed3f770/instrumentation/opentelemetry-instrumentation-urllib/src/opentelemetry/instrumentation/urllib/__init__.py#L212-L217
Thanks for reporting this. Could you please share the exception traceback and a reproducible code example? Traceback: ``` Traceback (most recent call last): File "/opt/foo/lib/python3.7/site-packages/swagger_spec_validator/common.py", line 36, in wrapper return method(*args, **kwargs) File "/opt/foo/lib/python3.7/site-packages/swagger_spec_validator/validator20.py", line 195, in validate_json schema, schema_path = read_resource_file(schema_path) File "/opt/foo/lib/python3.7/site-packages/swagger_spec_validator/common.py", line 63, in read_resource_file return read_file(schema_path), schema_path File "/opt/foo/lib/python3.7/site-packages/swagger_spec_validator/common.py", line 57, in read_file return read_url(get_uri_from_file_path(file_path)) File "/opt/foo/lib/python3.7/site-packages/swagger_spec_validator/common.py", line 67, in read_url with contextlib.closing(urlopen(url, timeout=timeout)) as fh: File "/usr/lib/python3.7/urllib/request.py", line 222, in urlopen return opener.open(url, data, timeout) File "/opt/foo/lib/python3.7/site-packages/opentelemetry/instrumentation/urllib/__init__.py", line 163, in instrumented_open opener, request_, call_wrapped, get_or_create_headers File "/opt/foo/lib/python3.7/site-packages/opentelemetry/instrumentation/urllib/__init__.py", line 217, in _instrumented_open_call span.set_status(Status(http_status_to_status_code(code_))) File "/opt/foo/lib/python3.7/site-packages/opentelemetry/instrumentation/utils.py", line 49, in http_status_to_status_code if status < 100: TypeError: '<' not supported between instances of 'NoneType' and 'int' ``` It's not minimal, but reproduction is as easy as specifying a local file as the schema for https://github.com/Yelp/swagger_spec_validator. Is "returning a non-int status code' a common thing amongst instrumentations? If not, maybe we should treat this as a special use case and address it only for urlib. Thanks for reporting this. Could you please share the exception traceback and a reproducible code example? Traceback: ``` Traceback (most recent call last): File "/opt/foo/lib/python3.7/site-packages/swagger_spec_validator/common.py", line 36, in wrapper return method(*args, **kwargs) File "/opt/foo/lib/python3.7/site-packages/swagger_spec_validator/validator20.py", line 195, in validate_json schema, schema_path = read_resource_file(schema_path) File "/opt/foo/lib/python3.7/site-packages/swagger_spec_validator/common.py", line 63, in read_resource_file return read_file(schema_path), schema_path File "/opt/foo/lib/python3.7/site-packages/swagger_spec_validator/common.py", line 57, in read_file return read_url(get_uri_from_file_path(file_path)) File "/opt/foo/lib/python3.7/site-packages/swagger_spec_validator/common.py", line 67, in read_url with contextlib.closing(urlopen(url, timeout=timeout)) as fh: File "/usr/lib/python3.7/urllib/request.py", line 222, in urlopen return opener.open(url, data, timeout) File "/opt/foo/lib/python3.7/site-packages/opentelemetry/instrumentation/urllib/__init__.py", line 163, in instrumented_open opener, request_, call_wrapped, get_or_create_headers File "/opt/foo/lib/python3.7/site-packages/opentelemetry/instrumentation/urllib/__init__.py", line 217, in _instrumented_open_call span.set_status(Status(http_status_to_status_code(code_))) File "/opt/foo/lib/python3.7/site-packages/opentelemetry/instrumentation/utils.py", line 49, in http_status_to_status_code if status < 100: TypeError: '<' not supported between instances of 'NoneType' and 'int' ``` It's not minimal, but reproduction is as easy as specifying a local file as the schema for https://github.com/Yelp/swagger_spec_validator. Is "returning a non-int status code' a common thing amongst instrumentations? If not, maybe we should treat this as a special use case and address it only for urlib.
2021-12-03T18:18:11
open-telemetry/opentelemetry-python-contrib
828
open-telemetry__opentelemetry-python-contrib-828
[ "446" ]
0786aa49adb3fe9b0f7fdd31c69511d48d3b413e
diff --git a/instrumentation/opentelemetry-instrumentation-flask/src/opentelemetry/instrumentation/flask/__init__.py b/instrumentation/opentelemetry-instrumentation-flask/src/opentelemetry/instrumentation/flask/__init__.py --- a/instrumentation/opentelemetry-instrumentation-flask/src/opentelemetry/instrumentation/flask/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-flask/src/opentelemetry/instrumentation/flask/__init__.py @@ -176,15 +176,24 @@ def _before_request(): return flask_request_environ = flask.request.environ span_name = get_default_span_name() - token = context.attach( - extract(flask_request_environ, getter=otel_wsgi.wsgi_getter) - ) + + token = ctx = span_kind = None + + if trace.get_current_span() is trace.INVALID_SPAN: + ctx = extract(flask_request_environ, getter=otel_wsgi.wsgi_getter) + token = context.attach(ctx) + span_kind = trace.SpanKind.SERVER + else: + ctx = context.get_current() + span_kind = trace.SpanKind.INTERNAL span = tracer.start_span( span_name, - kind=trace.SpanKind.SERVER, + ctx, + kind=span_kind, start_time=flask_request_environ.get(_ENVIRON_STARTTIME_KEY), ) + if request_hook: request_hook(span, flask_request_environ) @@ -229,7 +238,9 @@ def _teardown_request(exc): activation.__exit__( type(exc), exc, getattr(exc, "__traceback__", None) ) - context.detach(flask.request.environ.get(_ENVIRON_TOKEN)) + + if flask.request.environ.get(_ENVIRON_TOKEN, None): + context.detach(flask.request.environ.get(_ENVIRON_TOKEN)) return _teardown_request
diff --git a/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py b/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py --- a/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py +++ b/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py @@ -23,6 +23,7 @@ get_global_response_propagator, set_global_response_propagator, ) +from opentelemetry.instrumentation.wsgi import OpenTelemetryMiddleware from opentelemetry.sdk.resources import Resource from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.test.test_base import TestBase @@ -413,3 +414,31 @@ def test_custom_span_name(self): span_list[0].resource.attributes["service.name"], "flask-api-no-app", ) + + +class TestProgrammaticWrappedWithOtherFramework( + InstrumentationTest, TestBase, WsgiTestBase +): + def setUp(self): + super().setUp() + + self.app = Flask(__name__) + self.app.wsgi_app = OpenTelemetryMiddleware(self.app.wsgi_app) + FlaskInstrumentor().instrument_app(self.app) + self._common_initialization() + + def tearDown(self) -> None: + super().tearDown() + with self.disable_logging(): + FlaskInstrumentor().uninstrument_app(self.app) + + def test_mark_span_internal_in_presence_of_span_from_other_framework(self): + resp = self.client.get("/hello/123") + self.assertEqual(200, resp.status_code) + resp.get_data() + span_list = self.memory_exporter.get_finished_spans() + self.assertEqual(trace.SpanKind.INTERNAL, span_list[0].kind) + self.assertEqual(trace.SpanKind.SERVER, span_list[1].kind) + self.assertEqual( + span_list[0].parent.span_id, span_list[1].context.span_id + )
Flask: Conditionally create SERVER spans Part of #445
@owais I would like to work on this issue as a beginner. Kindly let me know if it's okay to pick this issue or not 🙂 Hi @pravarag. Yes, you can pick it up but be warned that it might sound simpler than it is. We've had at least one other person attempt this only to find out it was more complicated than it looked :) I don't want to discourage you but just trying to set the expectations. I've removed "good first issue" label from this ticket as it was a bit misleading I think. All things considered, this is not a hard or complex issue but definitely not a byte-sized, beginner friendly problem either. Happy to assign it to you. Thanks @owais , if possible could you please help me in finding a beginner friendly issue to work on 🙂 , I'll be happy to take that. https://github.com/open-telemetry/opentelemetry-python-contrib/labels/good%20first%20issue https://github.com/open-telemetry/opentelemetry-python/labels/good%20first%20issue @pravarag ^ Hi @owais I would like to work on this as my first issue! Can you assign this issue to me? Would really appreciate any help in getting started with the same. Done
2021-12-08T06:57:51
open-telemetry/opentelemetry-python-contrib
847
open-telemetry__opentelemetry-python-contrib-847
[ "846" ]
b32be746e4a2d5ff2cd2bb8ebe5731197d395800
diff --git a/instrumentation/opentelemetry-instrumentation-celery/src/opentelemetry/instrumentation/celery/utils.py b/instrumentation/opentelemetry-instrumentation-celery/src/opentelemetry/instrumentation/celery/utils.py --- a/instrumentation/opentelemetry-instrumentation-celery/src/opentelemetry/instrumentation/celery/utils.py +++ b/instrumentation/opentelemetry-instrumentation-celery/src/opentelemetry/instrumentation/celery/utils.py @@ -61,8 +61,11 @@ def set_attributes_from_context(span, context): # Skip `timelimit` if it is not set (it's default/unset value is a # tuple or a list of `None` values - if key == "timelimit" and value in [(None, None), [None, None]]: - continue + if key == "timelimit": + if value in [(None, None), [None, None]]: + continue + if None in value: + value = ["" if tl is None else tl for tl in value] # Skip `retries` if it's value is `0` if key == "retries" and value == 0:
diff --git a/instrumentation/opentelemetry-instrumentation-celery/tests/test_utils.py b/instrumentation/opentelemetry-instrumentation-celery/tests/test_utils.py --- a/instrumentation/opentelemetry-instrumentation-celery/tests/test_utils.py +++ b/instrumentation/opentelemetry-instrumentation-celery/tests/test_utils.py @@ -96,6 +96,46 @@ def test_set_attributes_not_recording(self): self.assertFalse(mock_span.set_attribute.called) self.assertFalse(mock_span.set_status.called) + def test_set_attributes_partial_timelimit_hard_limit(self): + # it should extract only relevant keys + context = { + "correlation_id": "44b7f305", + "delivery_info": {"eager": True}, + "eta": "soon", + "expires": "later", + "hostname": "localhost", + "id": "44b7f305", + "reply_to": "44b7f305", + "retries": 4, + "timelimit": ("now", None), + "custom_meta": "custom_value", + "routing_key": "celery", + } + span = trace._Span("name", mock.Mock(spec=trace_api.SpanContext)) + utils.set_attributes_from_context(span, context) + self.assertEqual(span.attributes.get("celery.timelimit"), ("now", "")) + + def test_set_attributes_partial_timelimit_soft_limit(self): + # it should extract only relevant keys + context = { + "correlation_id": "44b7f305", + "delivery_info": {"eager": True}, + "eta": "soon", + "expires": "later", + "hostname": "localhost", + "id": "44b7f305", + "reply_to": "44b7f305", + "retries": 4, + "timelimit": (None, "later"), + "custom_meta": "custom_value", + "routing_key": "celery", + } + span = trace._Span("name", mock.Mock(spec=trace_api.SpanContext)) + utils.set_attributes_from_context(span, context) + self.assertEqual( + span.attributes.get("celery.timelimit"), ("", "later") + ) + def test_set_attributes_from_context_empty_keys(self): # it should not extract empty keys context = {
Partial celery task time limit is not support Python 3.8 **Steps to reproduce** - Create celery task with only one of the time limit soft/hard Or use this test to reproduce: `instrumentation/opentelemetry-instrumentation-celery/tests/test_utils.py` ```python def test_set_attributes_partial_timelimit_hard_limit(self): context = { "correlation_id": "44b7f305", "delivery_info": {"eager": True}, "eta": "soon", "expires": "later", "hostname": "localhost", "id": "44b7f305", "reply_to": "44b7f305", "retries": 4, "timelimit": ("now", None), "custom_meta": "custom_value", "routing_key": "celery", } span = trace._Span("name", mock.Mock(spec=trace_api.SpanContext)) utils.set_attributes_from_context(span, context) self.assertEqual(span.attributes.get("celery.timelimit"), ("now", "")) ``` **What is the expected behavior?** The time limit that was specify should be instrumented **What is the actual behavior?** Exception is raised and no time limit is instrumented ``` [__init__.py:_translate_attributes:164] _translate_key_values(key, value) exception.trace.1 [exporter.py:_translate_key_values:126] return KeyValue(key=key, value=_translate_value(value)) exception.trace.2 [ exporter.py:_translate_value:104] array_value=ArrayValue(values=[_translate_value(v) for v in value]) exception.trace.3 [ exporter.py:<listcomp>:104] array_value=ArrayValue(values=[_translate_value(v) for v in value]) exception.trace.4 [ exporter.py:_translate_value:119] "Invalid type {} of value {}".format(type(value), value) ```
2022-01-09T08:47:12
open-telemetry/opentelemetry-python-contrib
857
open-telemetry__opentelemetry-python-contrib-857
[ "848" ]
895800fa1dd03c2dee6a23bd87999f6f19c80a51
diff --git a/instrumentation/opentelemetry-instrumentation-aiohttp-client/src/opentelemetry/instrumentation/aiohttp_client/__init__.py b/instrumentation/opentelemetry-instrumentation-aiohttp-client/src/opentelemetry/instrumentation/aiohttp_client/__init__.py --- a/instrumentation/opentelemetry-instrumentation-aiohttp-client/src/opentelemetry/instrumentation/aiohttp_client/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-aiohttp-client/src/opentelemetry/instrumentation/aiohttp_client/__init__.py @@ -23,10 +23,7 @@ .. code:: python import aiohttp - from opentelemetry.instrumentation.aiohttp_client import ( - create_trace_config, - url_path_span_name - ) + from opentelemetry.instrumentation.aiohttp_client import create_trace_config import yarl def strip_query_params(url: yarl.URL) -> str: @@ -35,8 +32,6 @@ def strip_query_params(url: yarl.URL) -> str: async with aiohttp.ClientSession(trace_configs=[create_trace_config( # Remove all query params from the URL attribute on the span. url_filter=strip_query_params, - # Use the URL's path as the span name. - span_name=url_path_span_name )]) as session: async with session.get(url) as response: await response.text() @@ -127,21 +122,6 @@ def response_hook(span: Span, params: typing.Union[ ] -def url_path_span_name(params: aiohttp.TraceRequestStartParams) -> str: - """Extract a span name from the request URL path. - - A simple callable to extract the path portion of the requested URL - for use as the span name. - - :param aiohttp.TraceRequestStartParams params: Parameters describing - the traced request. - - :return: The URL path. - :rtype: str - """ - return params.url.path - - def create_trace_config( url_filter: _UrlFilterT = None, request_hook: _RequestHookT = None,
diff --git a/instrumentation/opentelemetry-instrumentation-aiohttp-client/tests/test_aiohttp_client_integration.py b/instrumentation/opentelemetry-instrumentation-aiohttp-client/tests/test_aiohttp_client_integration.py --- a/instrumentation/opentelemetry-instrumentation-aiohttp-client/tests/test_aiohttp_client_integration.py +++ b/instrumentation/opentelemetry-instrumentation-aiohttp-client/tests/test_aiohttp_client_integration.py @@ -71,20 +71,6 @@ def assert_spans(self, spans): spans, ) - def test_url_path_span_name(self): - for url, expected in ( - ( - yarl.URL("http://hostname.local:1234/some/path?query=params"), - "/some/path", - ), - (yarl.URL("http://hostname.local:1234"), "/"), - ): - with self.subTest(url=url): - params = aiohttp.TraceRequestStartParams("METHOD", url, {}) - actual = aiohttp_client.url_path_span_name(params) - self.assertEqual(actual, expected) - self.assertIsInstance(actual, str) - @staticmethod def _http_request( trace_config,
aiohttp instrumentation: Function create_trace_config has no span_name argument. ## Docs usage example Ref: https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/aiohttp_client/aiohttp_client.html#usage ```python import aiohttp from opentelemetry.instrumentation.aiohttp_client import ( create_trace_config, url_path_span_name ) import yarl def strip_query_params(url: yarl.URL) -> str: return str(url.with_query(None)) async with aiohttp.ClientSession(trace_configs=[create_trace_config( # Remove all query params from the URL attribute on the span. url_filter=strip_query_params, # Use the URL's path as the span name. span_name=url_path_span_name )]) as session: async with session.get(url) as response: await response.text() ``` ## Bug Function `create_trace_config` has no `span_name` argument. ```python def create_trace_config( url_filter: _UrlFilterT = None, request_hook: _RequestHookT = None, response_hook: _ResponseHookT = None, tracer_provider: TracerProvider = None, ) -> aiohttp.TraceConfig: ... ```
Also looks weird that current solution starts span with name `f"HTTP {http_method}"` and then prompts to change it through `request_hook` callback https://github.com/open-telemetry/opentelemetry-python-contrib/blob/d01efe5c5023110447de1741107e53b009b5886e/instrumentation/opentelemetry-instrumentation-aiohttp-client/src/opentelemetry/instrumentation/aiohttp_client/__init__.py#L200-L210 It would be nice to add `span_name` (as it described in the docs). ```python def create_trace_config( ... span_name: Optional[str] = None, ) -> aiohttp.TraceConfig: ... request_span_name = f"HTTP {http_method}" if span_name is None else span_name ``` Proposed patch looks good to me. Happy to merge a PR if one is sent :)
2022-01-11T15:12:47
open-telemetry/opentelemetry-python-contrib
867
open-telemetry__opentelemetry-python-contrib-867
[ "447" ]
dd72d94615a66105a5275efac08f1fd5c89c54b2
diff --git a/instrumentation/opentelemetry-instrumentation-falcon/src/opentelemetry/instrumentation/falcon/__init__.py b/instrumentation/opentelemetry-instrumentation-falcon/src/opentelemetry/instrumentation/falcon/__init__.py --- a/instrumentation/opentelemetry-instrumentation-falcon/src/opentelemetry/instrumentation/falcon/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-falcon/src/opentelemetry/instrumentation/falcon/__init__.py @@ -107,10 +107,10 @@ def response_hook(span, req, resp): get_global_response_propagator, ) from opentelemetry.instrumentation.utils import ( + _start_internal_or_server_span, extract_attributes_from_object, http_status_to_status_code, ) -from opentelemetry.propagate import extract from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.trace.status import Status from opentelemetry.util._time import _time_ns @@ -195,12 +195,14 @@ def __call__(self, env, start_response): start_time = _time_ns() - token = context.attach(extract(env, getter=otel_wsgi.wsgi_getter)) - span = self._tracer.start_span( - otel_wsgi.get_default_span_name(env), - kind=trace.SpanKind.SERVER, + span, token = _start_internal_or_server_span( + tracer=self._tracer, + span_name=otel_wsgi.get_default_span_name(env), start_time=start_time, + context_carrier=env, + context_getter=otel_wsgi.wsgi_getter, ) + if span.is_recording(): attributes = otel_wsgi.collect_request_attributes(env) for key, value in attributes.items(): @@ -216,7 +218,8 @@ def _start_response(status, response_headers, *args, **kwargs): status, response_headers, *args, **kwargs ) activation.__exit__(None, None, None) - context.detach(token) + if token is not None: + context.detach(token) return response try: @@ -227,7 +230,8 @@ def _start_response(status, response_headers, *args, **kwargs): exc, getattr(exc, "__traceback__", None), ) - context.detach(token) + if token is not None: + context.detach(token) raise diff --git a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/utils.py b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/utils.py --- a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/utils.py +++ b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/utils.py @@ -16,9 +16,12 @@ from wrapt import ObjectProxy +from opentelemetry import context, trace + # pylint: disable=unused-import # pylint: disable=E0611 from opentelemetry.context import _SUPPRESS_INSTRUMENTATION_KEY # noqa: F401 +from opentelemetry.propagate import extract from opentelemetry.trace import StatusCode @@ -67,3 +70,39 @@ def unwrap(obj, attr: str): func = getattr(obj, attr, None) if func and isinstance(func, ObjectProxy) and hasattr(func, "__wrapped__"): setattr(obj, attr, func.__wrapped__) + + +def _start_internal_or_server_span( + tracer, span_name, start_time, context_carrier, context_getter +): + """Returns internal or server span along with the token which can be used by caller to reset context + + + Args: + tracer : tracer in use by given instrumentation library + name (string): name of the span + start_time : start time of the span + context_carrier : object which contains values that are + used to construct a Context. This object + must be paired with an appropriate getter + which understands how to extract a value from it. + context_getter : an object which contains a get function that can retrieve zero + or more values from the carrier and a keys function that can get all the keys + from carrier. + """ + + token = ctx = span_kind = None + if trace.get_current_span() is trace.INVALID_SPAN: + ctx = extract(context_carrier, getter=context_getter) + token = context.attach(ctx) + span_kind = trace.SpanKind.SERVER + else: + ctx = context.get_current() + span_kind = trace.SpanKind.INTERNAL + span = tracer.start_span( + name=span_name, + context=ctx, + kind=span_kind, + start_time=start_time, + ) + return span, token
diff --git a/instrumentation/opentelemetry-instrumentation-falcon/tests/test_falcon.py b/instrumentation/opentelemetry-instrumentation-falcon/tests/test_falcon.py --- a/instrumentation/opentelemetry-instrumentation-falcon/tests/test_falcon.py +++ b/instrumentation/opentelemetry-instrumentation-falcon/tests/test_falcon.py @@ -16,6 +16,7 @@ from falcon import testing +from opentelemetry import trace from opentelemetry.instrumentation.falcon import FalconInstrumentor from opentelemetry.instrumentation.propagators import ( TraceResponsePropagator, @@ -264,3 +265,18 @@ def test_hooks(self): self.assertEqual( span.attributes["request_hook_attr"], "value from hook" ) + + +class TestFalconInstrumentationWrappedWithOtherFramework(TestFalconBase): + def test_mark_span_internal_in_presence_of_span_from_other_framework(self): + tracer = trace.get_tracer(__name__) + with tracer.start_as_current_span( + "test", kind=trace.SpanKind.SERVER + ) as parent_span: + self.client().simulate_request(method="GET", path="/hello") + span = self.memory_exporter.get_finished_spans()[0] + assert span.status.is_ok + self.assertEqual(trace.SpanKind.INTERNAL, span.kind) + self.assertEqual( + span.parent.span_id, parent_span.get_span_context().span_id + )
Falcon: Conditionally create SERVER spans Part of #445
@ashu658 ^ @owais Can you assign this issue to me?
2022-01-18T10:48:49
open-telemetry/opentelemetry-python-contrib
890
open-telemetry__opentelemetry-python-contrib-890
[ "810" ]
0431d7b62f4cf363fceb1f3f722339b975f46d6b
diff --git a/instrumentation/opentelemetry-instrumentation-logging/src/opentelemetry/instrumentation/logging/__init__.py b/instrumentation/opentelemetry-instrumentation-logging/src/opentelemetry/instrumentation/logging/__init__.py --- a/instrumentation/opentelemetry-instrumentation-logging/src/opentelemetry/instrumentation/logging/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-logging/src/opentelemetry/instrumentation/logging/__init__.py @@ -76,20 +76,29 @@ def instrumentation_dependencies(self) -> Collection[str]: return _instruments def _instrument(self, **kwargs): - service_name = "" - provider = kwargs.get("tracer_provider", None) or get_tracer_provider() - resource = provider.resource if provider else None - if resource: - service_name = resource.attributes.get("service.name") + provider = kwargs.get("tracer_provider", None) or get_tracer_provider() old_factory = logging.getLogRecordFactory() LoggingInstrumentor._old_factory = old_factory + service_name = None + def record_factory(*args, **kwargs): record = old_factory(*args, **kwargs) record.otelSpanID = "0" record.otelTraceID = "0" + + nonlocal service_name + if service_name is None: + resource = getattr(provider, "resource", None) + if resource: + service_name = ( + resource.attributes.get("service.name") or "" + ) + else: + service_name = "" + record.otelServiceName = service_name span = get_current_span()
diff --git a/instrumentation/opentelemetry-instrumentation-logging/tests/test_logging.py b/instrumentation/opentelemetry-instrumentation-logging/tests/test_logging.py --- a/instrumentation/opentelemetry-instrumentation-logging/tests/test_logging.py +++ b/instrumentation/opentelemetry-instrumentation-logging/tests/test_logging.py @@ -13,6 +13,7 @@ # limitations under the License. import logging +from typing import Optional from unittest import mock import pytest @@ -22,7 +23,45 @@ LoggingInstrumentor, ) from opentelemetry.test.test_base import TestBase -from opentelemetry.trace import get_tracer +from opentelemetry.trace import ProxyTracer, get_tracer + + +class FakeTracerProvider: + def get_tracer( # pylint: disable=no-self-use + self, + instrumenting_module_name: str, + instrumenting_library_version: Optional[str] = None, + schema_url: Optional[str] = None, + ) -> ProxyTracer: + return ProxyTracer( + instrumenting_module_name, + instrumenting_library_version, + schema_url, + ) + + +class TestLoggingInstrumentorProxyTracerProvider(TestBase): + @pytest.fixture(autouse=True) + def inject_fixtures(self, caplog): + self.caplog = caplog # pylint: disable=attribute-defined-outside-init + + def setUp(self): + super().setUp() + LoggingInstrumentor().instrument(tracer_provider=FakeTracerProvider()) + + def tearDown(self): + super().tearDown() + LoggingInstrumentor().uninstrument() + + def test_trace_context_injection(self): + with self.caplog.at_level(level=logging.INFO): + logger = logging.getLogger("test logger") + logger.info("hello") + self.assertEqual(len(self.caplog.records), 1) + record = self.caplog.records[0] + self.assertEqual(record.otelSpanID, "0") + self.assertEqual(record.otelTraceID, "0") + self.assertEqual(record.otelServiceName, "") class TestLoggingInstrumentor(TestBase):
error with logging instrumentation - AttributeError: 'ProxyTracerProvider' object has no attribute 'resource' **Describe your environment** LoggingInstrumentor().instrument() is throwing an error ``` Traceback (most recent call last): File "manage.py", line 30, in <module> main() File "manage.py", line 14, in main LoggingInstrumentor().instrument(set_logging_format=True) File "/home/vamsikrishnam/otel/lib/python3.8/site-packages/opentelemetry/instrumentation/instrumentor.py", line 109, in instrument result = self._instrument( # pylint: disable=assignment-from-no-return File "/home/vamsikrishnam/otel/lib/python3.8/site-packages/opentelemetry/instrumentation/logging/__init__.py", line 81, in _instrument resource = provider.resource if provider else None AttributeError: 'ProxyTracerProvider' object has no attribute 'resource' ``` **Steps to reproduce** Below packages installed and trying to instrument with below two lines: > LoggingInstrumentor().instrument(set_logging_format=True) > DjangoInstrumentor().instrument() ``` (otel) vamsikrishnam@NHHYDL-00217:~/django$ pip list | grep opentele opentelemetry-api 1.7.1 opentelemetry-exporter-otlp 1.7.1 opentelemetry-exporter-otlp-proto-grpc 1.7.1 opentelemetry-exporter-otlp-proto-http 1.7.1 opentelemetry-instrumentation 0.26b1 opentelemetry-instrumentation-django 0.26b1 opentelemetry-instrumentation-logging 0.26b1 opentelemetry-instrumentation-wsgi 0.26b1 opentelemetry-propagator-b3 1.7.1 opentelemetry-proto 1.7.1 opentelemetry-sdk 1.7.1 opentelemetry-semantic-conventions 0.26b1 opentelemetry-util-http 0.26b1 ``` **What is the expected behavior?** What did you expect to see? logging should be instrumented properly. **What is the actual behavior?** What did you see instead? logging should be instrumented properly and populate the otelTraceID and otelSpanID in the logs. **Additional context** Add any other context about the problem here. $ python3 --version Python 3.8.10 manage.py: ``` #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys import logging from opentelemetry.instrumentation.django import DjangoInstrumentor from opentelemetry.instrumentation.logging import LoggingInstrumentor def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_project.settings') logging.basicConfig(level = logging.DEBUG) LoggingInstrumentor().instrument(set_logging_format=True) DjangoInstrumentor().instrument() # LoggingInstrumentor().instrument(set_logging_format=True,log_level=logging.DEBUG) try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() ```
You need to set up the SDK and tracing pipeline before you can use any instrumentors. Please refer to this: https://opentelemetry-python.readthedocs.io/en/latest/getting-started.html ``` provider = TracerProvider() processor = BatchSpanProcessor(ConsoleSpanExporter()) provider.add_span_processor(processor) trace.set_tracer_provider(provider) ``` > You need to set up the SDK and tracing pipeline before you can use any instrumentors. Please refer to this: https://opentelemetry-python.readthedocs.io/en/latest/getting-started.html This is right, but we should not fail like this (with an attribute error) if SDK or tracing has not yet been set. We shouldn't. I meant to bring it up in weekly SIG this Thursday. @owais I'm seeing a similar thing in #821, I believe that I've set things up properly, if I use the ConsoleSpanExporter then I get the traces output to the CLI, but as soon as I switch to OTLPHTTP my TraceID's are *always* `0` in the logs. Could there be a bigger issue here? @proffalken Is your issue related to this issue's topic? As well, have you looked at the [explanation](https://github.com/open-telemetry/opentelemetry-python-contrib/issues/821#issuecomment-988220469) for the linked issue? Perhaps it may solve your use case. @lzchen - apologies, I'd forgotten that I'd commented here, the linked issue resolved my particular problem. > > You need to set up the SDK and tracing pipeline before you can use any instrumentors. Please refer to this: https://opentelemetry-python.readthedocs.io/en/latest/getting-started.html > > This is right, but we should not fail like this (with an attribute error) if SDK or tracing has not yet been set. Imo, the instrumentation shouldn't make any assumptions about the SDK at all since it does not define a dependency to it. Furtheremore, there might be 3rd party SDKs in the wild that might handle things like resources differently. Hello all, QQ related to the same topic. Is the logging instrumentation supposed to work with the auto-instrumentation? I'm asking because when I use the `opentelemetry-instrument` in my sample I get this exact same error. Just checking if maybe I'm doing something wrong, or if that's a limitation. I have this sample with the logging instrumentation commented out, just in case someone wants to reproduce the issue. https://github.com/julianocosta89/microservices-demo/tree/main/src/emailservice
2022-02-01T13:06:26
open-telemetry/opentelemetry-python-contrib
895
open-telemetry__opentelemetry-python-contrib-895
[ "894" ]
22cc215c6cf1adddca6fa04d7d68b45bbe5b6bf3
diff --git a/instrumentation/opentelemetry-instrumentation-falcon/src/opentelemetry/instrumentation/falcon/__init__.py b/instrumentation/opentelemetry-instrumentation-falcon/src/opentelemetry/instrumentation/falcon/__init__.py --- a/instrumentation/opentelemetry-instrumentation-falcon/src/opentelemetry/instrumentation/falcon/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-falcon/src/opentelemetry/instrumentation/falcon/__init__.py @@ -90,7 +90,6 @@ def response_hook(span, req, resp): --- """ -from functools import partial from logging import getLogger from sys import exc_info from typing import Collection @@ -135,48 +134,32 @@ def response_hook(span, req, resp): _instrument_app = "API" -class FalconInstrumentor(BaseInstrumentor): - # pylint: disable=protected-access,attribute-defined-outside-init - """An instrumentor for falcon.API - - See `BaseInstrumentor` - """ - - def instrumentation_dependencies(self) -> Collection[str]: - return _instruments - - def _instrument(self, **kwargs): - self._original_falcon_api = getattr(falcon, _instrument_app) - setattr( - falcon, _instrument_app, partial(_InstrumentedFalconAPI, **kwargs) - ) - - def _uninstrument(self, **kwargs): - setattr(falcon, _instrument_app, self._original_falcon_api) - - class _InstrumentedFalconAPI(getattr(falcon, _instrument_app)): def __init__(self, *args, **kwargs): + otel_opts = kwargs.pop("_otel_opts", {}) + # inject trace middleware middlewares = kwargs.pop("middleware", []) - tracer_provider = kwargs.pop("tracer_provider", None) + tracer_provider = otel_opts.pop("tracer_provider", None) if not isinstance(middlewares, (list, tuple)): middlewares = [middlewares] - self._tracer = trace.get_tracer(__name__, __version__, tracer_provider) + self._otel_tracer = trace.get_tracer( + __name__, __version__, tracer_provider + ) trace_middleware = _TraceMiddleware( - self._tracer, - kwargs.pop( + self._otel_tracer, + otel_opts.pop( "traced_request_attributes", get_traced_request_attrs("FALCON") ), - kwargs.pop("request_hook", None), - kwargs.pop("response_hook", None), + otel_opts.pop("request_hook", None), + otel_opts.pop("response_hook", None), ) middlewares.insert(0, trace_middleware) kwargs["middleware"] = middlewares - self._excluded_urls = get_excluded_urls("FALCON") + self._otel_excluded_urls = get_excluded_urls("FALCON") super().__init__(*args, **kwargs) def _handle_exception( @@ -190,13 +173,13 @@ def _handle_exception( def __call__(self, env, start_response): # pylint: disable=E1101 - if self._excluded_urls.url_disabled(env.get("PATH_INFO", "/")): + if self._otel_excluded_urls.url_disabled(env.get("PATH_INFO", "/")): return super().__call__(env, start_response) start_time = _time_ns() span, token = _start_internal_or_server_span( - tracer=self._tracer, + tracer=self._otel_tracer, span_name=otel_wsgi.get_default_span_name(env), start_time=start_time, context_carrier=env, @@ -321,3 +304,27 @@ def process_response( if self._response_hook: self._response_hook(span, req, resp) + + +class FalconInstrumentor(BaseInstrumentor): + # pylint: disable=protected-access,attribute-defined-outside-init + """An instrumentor for falcon.API + + See `BaseInstrumentor` + """ + + def instrumentation_dependencies(self) -> Collection[str]: + return _instruments + + def _instrument(self, **opts): + self._original_falcon_api = getattr(falcon, _instrument_app) + + class FalconAPI(_InstrumentedFalconAPI): + def __init__(self, *args, **kwargs): + kwargs["_otel_opts"] = opts + super().__init__(*args, **kwargs) + + setattr(falcon, _instrument_app, FalconAPI) + + def _uninstrument(self, **kwargs): + setattr(falcon, _instrument_app, self._original_falcon_api)
Using opentelemetry-instrument breaks Sentry SDK **Describe your environment** * Python 3.6.8 * Centos 7 * Supervisord * Sentry_sdk 1.4.3 * Environment Variables Set: ** OTEL_SERVICE_NAME=testthing ** SENTRY_URL=<secure sentry url> **Steps to reproduce** Using the below proof of concept python script: ``` import os import sentry_sdk print('about to run') if os.environ.get('SENTRY_URL', None): # pragma: unreachable sentry_sdk.init(os.environ['SENTRY_URL']) print('sentry run') ``` When the script is executed as `python3 proof.py` the output is: ``` about to run sentry run ``` Though when executing `opentelemetry-instrument python3 proof.py` the result is: ``` You are using Python 3.6. This version does not support timestamps with nanosecond precision and the OpenTelemetry SDK will use millisecond precision instead. Please refer to PEP 564 for more information. Please upgrade to Python 3.7 or newer to use nanosecond precision. about to run Traceback (most recent call last): File "proof.py", line 7, in <module> sentry_sdk.init(os.environ['SENTRY_URL']) File "/usr/local/lib/python3.6/site-packages/sentry_sdk/hub.py", line 105, in _init client = Client(*args, **kwargs) # type: ignore File "/usr/local/lib/python3.6/site-packages/sentry_sdk/client.py", line 86, in __init__ self._init_impl() File "/usr/local/lib/python3.6/site-packages/sentry_sdk/client.py", line 124, in _init_impl "auto_enabling_integrations" File "/usr/local/lib/python3.6/site-packages/sentry_sdk/integrations/__init__.py", line 120, in setup_integrations type(integration).setup_once() File "/usr/local/lib/python3.6/site-packages/sentry_sdk/integrations/falcon.py", line 113, in setup_once _patch_handle_exception() File "/usr/local/lib/python3.6/site-packages/sentry_sdk/integrations/falcon.py", line 139, in _patch_handle_exception original_handle_exception = falcon.API._handle_exception AttributeError: 'functools.partial' object has no attribute '_handle_exception' ``` **What is the expected behavior?** Ideally sentry should execute without errors and provide the following response from the sample script: ``` about to run sentry run ``` **What is the actual behavior?** Recieved the error: ``` You are using Python 3.6. This version does not support timestamps with nanosecond precision and the OpenTelemetry SDK will use millisecond precision instead. Please refer to PEP 564 for more information. Please upgrade to Python 3.7 or newer to use nanosecond precision. about to run Traceback (most recent call last): File "proof.py", line 7, in <module> sentry_sdk.init(os.environ['SENTRY_URL']) File "/usr/local/lib/python3.6/site-packages/sentry_sdk/hub.py", line 105, in _init client = Client(*args, **kwargs) # type: ignore File "/usr/local/lib/python3.6/site-packages/sentry_sdk/client.py", line 86, in __init__ self._init_impl() File "/usr/local/lib/python3.6/site-packages/sentry_sdk/client.py", line 124, in _init_impl "auto_enabling_integrations" File "/usr/local/lib/python3.6/site-packages/sentry_sdk/integrations/__init__.py", line 120, in setup_integrations type(integration).setup_once() File "/usr/local/lib/python3.6/site-packages/sentry_sdk/integrations/falcon.py", line 113, in setup_once _patch_handle_exception() File "/usr/local/lib/python3.6/site-packages/sentry_sdk/integrations/falcon.py", line 139, in _patch_handle_exception original_handle_exception = falcon.API._handle_exception AttributeError: 'functools.partial' object has no attribute '_handle_exception' ```
Looks like an issue with Falcon. Which version of Falcon are you using? Please share output of `pip freeze` aiocontextvars==0.2.2 apispec==5.1.1 ari==0.1.3 backoff==1.10.0 boto3==1.20.46 botocore==1.23.46 certifi==2021.10.8 charset-normalizer==2.0.11 contextvars==2.4 dataclasses==0.8 datadog==0.42.0 Deprecated==1.2.13 dnspython==2.1.0 falcon==2.0.0 googleapis-common-protos==1.54.0 grpcio==1.43.0 idna==3.3 immutables==0.16 inflection==0.5.1 Jinja2==3.0.3 jmespath==0.10.0 MarkupSafe==2.0.1 marshmallow==3.14.1 opentelemetry-api==1.9.1 opentelemetry-exporter-jaeger-thrift==1.9.1 opentelemetry-exporter-otlp-proto-grpc==1.9.1 opentelemetry-instrumentation==0.28b1 opentelemetry-instrumentation-aws-lambda==0.28b1 opentelemetry-instrumentation-dbapi==0.28b1 opentelemetry-instrumentation-falcon==0.28b1 opentelemetry-instrumentation-grpc==0.28b1 opentelemetry-instrumentation-logging==0.28b1 opentelemetry-instrumentation-redis==0.28b1 opentelemetry-instrumentation-requests==0.28b1 opentelemetry-instrumentation-sqlite3==0.28b1 opentelemetry-instrumentation-urllib==0.28b1 opentelemetry-instrumentation-urllib3==0.28b1 opentelemetry-instrumentation-wsgi==0.28b1 opentelemetry-propagator-aws-xray==1.0.1 opentelemetry-propagator-b3==1.9.1 opentelemetry-proto==1.9.1 opentelemetry-sdk==1.9.1 opentelemetry-semantic-conventions==0.28b1 opentelemetry-util-http==0.28b1 panoramisk==1.4 protobuf==3.19.4 PyJWT==2.3.0 python-dateutil==2.8.2 PyYAML==6.0 redis==3.5.3 requests==2.27.1 s3transfer==0.5.0 sentry-sdk==1.4.3 six==1.16.0 splunk-opentelemetry==1.4.1 supervisor==4.2.2 swaggerpy==0.2.1 thrift==0.15.0 typing_extensions==4.0.1 urllib3==1.26.8 uWSGI==2.0.20 websocket-client==1.2.3 wrapt==1.13.3 I should mention that the application in question doesn't use Falcon, there is a second application that runs on the same instance that does though, and that is executed using `uwsgi` which runs without any issues and pushes telemetry data. The issue is here: https://github.com/open-telemetry/opentelemetry-python-contrib/blob/main/instrumentation/opentelemetry-instrumentation-falcon/src/opentelemetry/instrumentation/falcon/__init__.py#L151 We wrap the Falcon API class into a partial function so when it is initialized, it receives some default params. This does not break the public Falcon API as it remains a callable but it breaks Sentry because Sentry also seems to patch Falcon and assumes certain knowledge about Falcon internals. I think we can change our implementation so instead of using a partial we use an actual class and pass in the kwargs some other way. As a side note, using a virtual environment (which is the fix we are going for in the interim) should solve this problem as if you are using falcon you would likely be running your application via uwsgi which seems to not suffer this issue
2022-02-03T01:21:25
open-telemetry/opentelemetry-python-contrib
923
open-telemetry__opentelemetry-python-contrib-923
[ "632" ]
d54b61e6872a2f6773054d3d825b9781cdfc872c
diff --git a/exporter/opentelemetry-exporter-richconsole/setup.py b/exporter/opentelemetry-exporter-richconsole/setup.py --- a/exporter/opentelemetry-exporter-richconsole/setup.py +++ b/exporter/opentelemetry-exporter-richconsole/setup.py @@ -21,7 +21,7 @@ BASE_DIR, "src", "opentelemetry", "exporter", "richconsole", "version.py" ) PACKAGE_INFO = {} -with open(VERSION_FILENAME) as f: +with open(VERSION_FILENAME, encoding="utf-8") as f: exec(f.read(), PACKAGE_INFO) setuptools.setup(version=PACKAGE_INFO["__version__"]) diff --git a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/utils.py b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/utils.py --- a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/utils.py +++ b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/utils.py @@ -131,6 +131,7 @@ def _generate_sql_comment(**meta): # Sort the keywords to ensure that caching works and that testing is # deterministic. It eases visual inspection as well. + # pylint: disable=consider-using-f-string return ( " /*" + _KEY_VALUE_DELIMITER.join(
diff --git a/instrumentation/opentelemetry-instrumentation-aiopg/tests/test_aiopg_integration.py b/instrumentation/opentelemetry-instrumentation-aiopg/tests/test_aiopg_integration.py --- a/instrumentation/opentelemetry-instrumentation-aiopg/tests/test_aiopg_integration.py +++ b/instrumentation/opentelemetry-instrumentation-aiopg/tests/test_aiopg_integration.py @@ -507,6 +507,7 @@ def __init__(self, database, server_port, server_host, user): self.server_host = server_host self.user = user + # pylint: disable=no-self-use async def release(self, conn): return conn @@ -542,11 +543,11 @@ def __init__(self, database, server_port, server_host, user): database, server_port, server_host, user ) - # pylint: disable=no-self-use def cursor(self): coro = self._cursor() return _ContextManager(coro) # pylint: disable=no-value-for-parameter + # pylint: disable=no-self-use async def _cursor(self): return MockCursor() @@ -585,6 +586,7 @@ async def __aenter__(self): class AiopgPoolMock: + # pylint: disable=no-self-use async def release(self, conn): return conn @@ -592,6 +594,7 @@ def acquire(self): coro = self._acquire() return _PoolAcquireContextManager(coro, self) + # pylint: disable=no-self-use async def _acquire(self): return AiopgConnectionMock() diff --git a/instrumentation/opentelemetry-instrumentation-asgi/tests/test_asgi_middleware.py b/instrumentation/opentelemetry-instrumentation-asgi/tests/test_asgi_middleware.py --- a/instrumentation/opentelemetry-instrumentation-asgi/tests/test_asgi_middleware.py +++ b/instrumentation/opentelemetry-instrumentation-asgi/tests/test_asgi_middleware.py @@ -310,10 +310,10 @@ def test_traceresponse_header(self): self.assertEqual(response_body["body"], b"*") self.assertEqual(response_start["status"], 200) - traceresponse = "00-{0}-{1}-01".format( - format_trace_id(span.get_span_context().trace_id), - format_span_id(span.get_span_context().span_id), - ) + trace_id = format_trace_id(span.get_span_context().trace_id) + span_id = format_span_id(span.get_span_context().span_id) + traceresponse = f"00-{trace_id}-{span_id}-01" + self.assertListEqual( response_start["headers"], [ @@ -423,10 +423,10 @@ def test_websocket_traceresponse_header(self): span = self.memory_exporter.get_finished_spans()[-1] self.assertEqual(trace_api.SpanKind.SERVER, span.kind) - traceresponse = "00-{0}-{1}-01".format( - format_trace_id(span.get_span_context().trace_id), - format_span_id(span.get_span_context().span_id), - ) + trace_id = format_trace_id(span.get_span_context().trace_id) + span_id = format_span_id(span.get_span_context().span_id) + traceresponse = f"00-{trace_id}-{span_id}-01" + self.assertListEqual( socket_send["headers"], [ diff --git a/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware_asgi.py b/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware_asgi.py --- a/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware_asgi.py +++ b/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware_asgi.py @@ -368,12 +368,11 @@ async def test_trace_response_headers(self): response["Access-Control-Expose-Headers"], "traceresponse", ) + trace_id = format_trace_id(span.get_span_context().trace_id) + span_id = format_span_id(span.get_span_context().span_id) self.assertEqual( response["traceresponse"], - "00-{}-{}-01".format( - format_trace_id(span.get_span_context().trace_id), - format_span_id(span.get_span_context().span_id), - ), + f"00-{trace_id}-{span_id}-01", ) self.memory_exporter.clear() diff --git a/instrumentation/opentelemetry-instrumentation-pymemcache/tests/test_pymemcache.py b/instrumentation/opentelemetry-instrumentation-pymemcache/tests/test_pymemcache.py --- a/instrumentation/opentelemetry-instrumentation-pymemcache/tests/test_pymemcache.py +++ b/instrumentation/opentelemetry-instrumentation-pymemcache/tests/test_pymemcache.py @@ -106,7 +106,7 @@ def test_set_not_recording(self): def test_get_many_none_found(self): client = self.make_client([b"END\r\n"]) result = client.get_many([b"key1", b"key2"]) - assert result == {} + assert not result spans = self.memory_exporter.get_finished_spans() @@ -116,7 +116,7 @@ def test_get_multi_none_found(self): client = self.make_client([b"END\r\n"]) # alias for get_many result = client.get_multi([b"key1", b"key2"]) - assert result == {} + assert not result spans = self.memory_exporter.get_finished_spans()
Upgrade pylint to 2.11.0 Proposing we keep up with pylint and upgrade to 2.11.0. The following needs to be done to clean up the code: - [x] #692 - [ ] #684 - [x] #694 - [x] #688 - [x] #690
There's an open issue regarding this here https://github.com/PyCQA/pylint/issues/4972
2022-02-15T17:28:40
open-telemetry/opentelemetry-python-contrib
935
open-telemetry__opentelemetry-python-contrib-935
[ "907" ]
dbc3073bd2bde92e7d50148ca21723b63db1893a
diff --git a/instrumentation/opentelemetry-instrumentation-pymemcache/src/opentelemetry/instrumentation/pymemcache/package.py b/instrumentation/opentelemetry-instrumentation-pymemcache/src/opentelemetry/instrumentation/pymemcache/package.py --- a/instrumentation/opentelemetry-instrumentation-pymemcache/src/opentelemetry/instrumentation/pymemcache/package.py +++ b/instrumentation/opentelemetry-instrumentation-pymemcache/src/opentelemetry/instrumentation/pymemcache/package.py @@ -13,4 +13,4 @@ # limitations under the License. -_instruments = ("pymemcache ~= 1.3",) +_instruments = ("pymemcache >= 1.3.5, < 4",) diff --git a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py --- a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py +++ b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py @@ -93,7 +93,7 @@ "instrumentation": "opentelemetry-instrumentation-psycopg2==0.29b0", }, "pymemcache": { - "library": "pymemcache ~= 1.3", + "library": "pymemcache >= 1.3.5, < 4", "instrumentation": "opentelemetry-instrumentation-pymemcache==0.29b0", }, "pymongo": {
diff --git a/instrumentation/opentelemetry-instrumentation-pymemcache/tests/test_pymemcache.py b/instrumentation/opentelemetry-instrumentation-pymemcache/tests/test_pymemcache.py --- a/instrumentation/opentelemetry-instrumentation-pymemcache/tests/test_pymemcache.py +++ b/instrumentation/opentelemetry-instrumentation-pymemcache/tests/test_pymemcache.py @@ -14,6 +14,8 @@ from unittest import mock import pymemcache +from packaging import version as get_package_version +from pymemcache import __version__ as pymemcache_package_version from pymemcache.exceptions import ( MemcacheClientError, MemcacheIllegalInputError, @@ -33,6 +35,22 @@ TEST_HOST = "localhost" TEST_PORT = 117711 +pymemcache_version = get_package_version.parse(pymemcache_package_version) + +# In pymemcache versions greater than 2, set_multi, set_many and delete_multi +# now use a batched call +# https://github.com/pinterest/pymemcache/blob/master/ChangeLog.rst#new-in-version-200 # noqa +pymemcache_version_lt_2 = pymemcache_version < get_package_version.parse( + "2.0.0" +) + +# In pymemcache versions greater than 3.4.1, the stats command no +# longer sends trailing whitespace in the command +# https://github.com/pinterest/pymemcache/blob/master/ChangeLog.rst#new-in-version-342 # noqa +pymemcache_version_gt_341 = pymemcache_version > get_package_version.parse( + "3.4.1" +) + class PymemcacheClientTestCase( TestBase @@ -126,11 +144,16 @@ def test_set_multi_success(self): client = self.make_client([b"STORED\r\n"]) # Alias for set_many, a convienance function that calls set for every key result = client.set_multi({b"key": b"value"}, noreply=False) - self.assertTrue(result) - spans = self.memory_exporter.get_finished_spans() - self.check_spans(spans, 2, ["set key", "set_multi key"]) + # In pymemcache versions greater than 2, set_multi now uses a batched call + # https://github.com/pinterest/pymemcache/blob/master/ChangeLog.rst#new-in-version-200 # noqa + if pymemcache_version_lt_2: + self.assertTrue(result) + self.check_spans(spans, 2, ["set key", "set_multi key"]) + else: + assert len(result) == 0 + self.check_spans(spans, 1, ["set_multi key"]) def test_delete_not_found(self): client = self.make_client([b"NOT_FOUND\r\n"]) @@ -191,19 +214,30 @@ def test_delete_many_found(self): spans = self.memory_exporter.get_finished_spans() - self.check_spans( - spans, 3, ["add key", "delete key", "delete_many key"] - ) + # In pymemcache versions greater than 2, delete_many now uses a batched call + # https://github.com/pinterest/pymemcache/blob/master/ChangeLog.rst#new-in-version-200 # noqa + if pymemcache_version_lt_2: + self.check_spans( + spans, 3, ["add key", "delete key", "delete_many key"] + ) + else: + self.check_spans(spans, 2, ["add key", "delete_many key"]) def test_set_many_success(self): client = self.make_client([b"STORED\r\n"]) # a convienance function that calls set for every key result = client.set_many({b"key": b"value"}, noreply=False) - self.assertTrue(result) spans = self.memory_exporter.get_finished_spans() - self.check_spans(spans, 2, ["set key", "set_many key"]) + # In pymemcache versions greater than 2, set_many now uses a batched call + # https://github.com/pinterest/pymemcache/blob/master/ChangeLog.rst#new-in-version-200 # noqa + if pymemcache_version_lt_2: + self.assertTrue(result) + self.check_spans(spans, 2, ["set key", "set_many key"]) + else: + assert len(result) == 0 + self.check_spans(spans, 1, ["set_many key"]) def test_set_get(self): client = self.make_client( @@ -243,7 +277,7 @@ def test_prepend_stored(self): def test_cas_stored(self): client = self.make_client([b"STORED\r\n"]) - result = client.cas(b"key", b"value", b"cas", noreply=False) + result = client.cas(b"key", b"value", b"1", noreply=False) self.assertTrue(result) spans = self.memory_exporter.get_finished_spans() @@ -252,7 +286,7 @@ def test_cas_stored(self): def test_cas_exists(self): client = self.make_client([b"EXISTS\r\n"]) - result = client.cas(b"key", b"value", b"cas", noreply=False) + result = client.cas(b"key", b"value", b"1", noreply=False) assert result is False spans = self.memory_exporter.get_finished_spans() @@ -261,7 +295,7 @@ def test_cas_exists(self): def test_cas_not_found(self): client = self.make_client([b"NOT_FOUND\r\n"]) - result = client.cas(b"key", b"value", b"cas", noreply=False) + result = client.cas(b"key", b"value", b"1", noreply=False) assert result is None spans = self.memory_exporter.get_finished_spans() @@ -445,7 +479,14 @@ def test_version_success(self): def test_stats(self): client = self.make_client([b"STAT fake_stats 1\r\n", b"END\r\n"]) result = client.stats() - assert client.sock.send_bufs == [b"stats \r\n"] + + # In pymemcache versions greater than 3.4.1, the stats command no + # longer sends trailing whitespace in the command + # https://github.com/pinterest/pymemcache/blob/master/ChangeLog.rst#new-in-version-342 # noqa + if pymemcache_version_gt_341: + assert client.sock.send_bufs == [b"stats\r\n"] + else: + assert client.sock.send_bufs == [b"stats \r\n"] assert result == {b"fake_stats": 1} spans = self.memory_exporter.get_finished_spans() @@ -544,5 +585,4 @@ def test_delete_many_found(self): self.assertTrue(result) spans = self.memory_exporter.get_finished_spans() - self.check_spans(spans, 2, ["add key", "delete key"])
Support for pymemcache 2.x and 3.x The `pymemcache` integration is currently locked to version 1.x. Current version is ~=3.5. https://github.com/open-telemetry/opentelemetry-python-contrib/blob/0b9e96dae0bfcafa1e0b28dc695e3697fbcf2864/instrumentation/opentelemetry-instrumentation-pymemcache/src/opentelemetry/instrumentation/pymemcache/package.py#L16
duplicate of #842
2022-03-01T16:45:10
open-telemetry/opentelemetry-python-contrib
950
open-telemetry__opentelemetry-python-contrib-950
[ "915" ]
5539d1f35aefaf8597a6f81160ea4362a5770428
diff --git a/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py b/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py --- a/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py @@ -129,7 +129,15 @@ def client_resposne_hook(span, future): from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.trace.status import Status, StatusCode from opentelemetry.util._time import _time_ns -from opentelemetry.util.http import get_excluded_urls, get_traced_request_attrs +from opentelemetry.util.http import ( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST, + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE, + get_custom_headers, + get_excluded_urls, + get_traced_request_attrs, + normalise_request_header_name, + normalise_response_header_name, +) from .client import fetch_async # pylint: disable=E0401 @@ -141,7 +149,6 @@ def client_resposne_hook(span, future): _excluded_urls = get_excluded_urls("TORNADO") _traced_request_attrs = get_traced_request_attrs("TORNADO") - response_propagation_setter = FuncSetter(tornado.web.RequestHandler.add_header) @@ -257,6 +264,32 @@ def _log_exception(tracer, func, handler, args, kwargs): return func(*args, **kwargs) +def _add_custom_request_headers(span, request_headers): + custom_request_headers_name = get_custom_headers( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST + ) + attributes = {} + for header_name in custom_request_headers_name: + header_values = request_headers.get(header_name) + if header_values: + key = normalise_request_header_name(header_name.lower()) + attributes[key] = [header_values] + span.set_attributes(attributes) + + +def _add_custom_response_headers(span, response_headers): + custom_response_headers_name = get_custom_headers( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE + ) + attributes = {} + for header_name in custom_response_headers_name: + header_values = response_headers.get(header_name) + if header_values: + key = normalise_response_header_name(header_name.lower()) + attributes[key] = [header_values] + span.set_attributes(attributes) + + def _get_attributes_from_request(request): attrs = { SpanAttributes.HTTP_METHOD: request.method, @@ -307,6 +340,8 @@ def _start_span(tracer, handler, start_time) -> _TraceContext: for key, value in attributes.items(): span.set_attribute(key, value) span.set_attribute("tornado.handler", _get_full_handler_name(handler)) + if span.kind == trace.SpanKind.SERVER: + _add_custom_request_headers(span, handler.request.headers) activation = trace.use_span(span, end_on_exit=True) activation.__enter__() # pylint: disable=E1101 @@ -360,6 +395,8 @@ def _finish_span(tracer, handler, error=None): description=otel_status_description, ) ) + if ctx.span.kind == trace.SpanKind.SERVER: + _add_custom_response_headers(ctx.span, handler._headers) ctx.activation.__exit__(*finish_args) # pylint: disable=E1101 if ctx.token:
diff --git a/instrumentation/opentelemetry-instrumentation-tornado/tests/test_instrumentation.py b/instrumentation/opentelemetry-instrumentation-tornado/tests/test_instrumentation.py --- a/instrumentation/opentelemetry-instrumentation-tornado/tests/test_instrumentation.py +++ b/instrumentation/opentelemetry-instrumentation-tornado/tests/test_instrumentation.py @@ -32,7 +32,12 @@ from opentelemetry.test.test_base import TestBase from opentelemetry.test.wsgitestutil import WsgiTestBase from opentelemetry.trace import SpanKind -from opentelemetry.util.http import get_excluded_urls, get_traced_request_attrs +from opentelemetry.util.http import ( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST, + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE, + get_excluded_urls, + get_traced_request_attrs, +) from .tornado_test_app import ( AsyncHandler, @@ -604,3 +609,122 @@ def test_mark_span_internal_in_presence_of_another_span(self): self.assertEqual( test_span.context.span_id, tornado_handler_span.parent.span_id ) + + +class TestTornadoCustomRequestResponseHeadersAddedWithServerSpan(TornadoTest): + @patch.dict( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3" + }, + ) + def test_custom_request_headers_added_in_server_span(self): + headers = { + "Custom-Test-Header-1": "Test Value 1", + "Custom-Test-Header-2": "TestValue2,TestValue3", + } + response = self.fetch("/", headers=headers) + self.assertEqual(response.code, 201) + _, tornado_span, _ = self.sorted_spans( + self.memory_exporter.get_finished_spans() + ) + expected = { + "http.request.header.custom_test_header_1": ("Test Value 1",), + "http.request.header.custom_test_header_2": ( + "TestValue2,TestValue3", + ), + } + self.assertEqual(tornado_span.kind, trace.SpanKind.SERVER) + self.assertSpanHasAttributes(tornado_span, expected) + + @patch.dict( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "content-type,content-length,my-custom-header,invalid-header" + }, + ) + def test_custom_response_headers_added_in_server_span(self): + response = self.fetch("/test_custom_response_headers") + self.assertEqual(response.code, 200) + tornado_span, _ = self.sorted_spans( + self.memory_exporter.get_finished_spans() + ) + expected = { + "http.response.header.content_type": ( + "text/plain; charset=utf-8", + ), + "http.response.header.content_length": ("0",), + "http.response.header.my_custom_header": ( + "my-custom-value-1,my-custom-header-2", + ), + } + self.assertEqual(tornado_span.kind, trace.SpanKind.SERVER) + self.assertSpanHasAttributes(tornado_span, expected) + + +class TestTornadoCustomRequestResponseHeadersNotAddedWithInternalSpan( + TornadoTest +): + def get_app(self): + tracer = trace.get_tracer(__name__) + app = make_app(tracer) + + def middleware(request): + """Wraps the request with a server span""" + with tracer.start_as_current_span( + "test", kind=trace.SpanKind.SERVER + ): + app(request) + + return middleware + + @patch.dict( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3" + }, + ) + def test_custom_request_headers_not_added_in_internal_span(self): + headers = { + "Custom-Test-Header-1": "Test Value 1", + "Custom-Test-Header-2": "TestValue2,TestValue3", + } + response = self.fetch("/", headers=headers) + self.assertEqual(response.code, 201) + _, tornado_span, _, _ = self.sorted_spans( + self.memory_exporter.get_finished_spans() + ) + not_expected = { + "http.request.header.custom_test_header_1": ("Test Value 1",), + "http.request.header.custom_test_header_2": ( + "TestValue2,TestValue3", + ), + } + self.assertEqual(tornado_span.kind, trace.SpanKind.INTERNAL) + for key, _ in not_expected.items(): + self.assertNotIn(key, tornado_span.attributes) + + @patch.dict( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "content-type,content-length,my-custom-header,invalid-header" + }, + ) + def test_custom_response_headers_not_added_in_internal_span(self): + response = self.fetch("/test_custom_response_headers") + self.assertEqual(response.code, 200) + tornado_span, _, _ = self.sorted_spans( + self.memory_exporter.get_finished_spans() + ) + not_expected = { + "http.response.header.content_type": ( + "text/plain; charset=utf-8", + ), + "http.response.header.content_length": ("0",), + "http.response.header.my_custom_header": ( + "my-custom-value-1,my-custom-header-2", + ), + } + self.assertEqual(tornado_span.kind, trace.SpanKind.INTERNAL) + for key, _ in not_expected.items(): + self.assertNotIn(key, tornado_span.attributes) diff --git a/instrumentation/opentelemetry-instrumentation-tornado/tests/tornado_test_app.py b/instrumentation/opentelemetry-instrumentation-tornado/tests/tornado_test_app.py --- a/instrumentation/opentelemetry-instrumentation-tornado/tests/tornado_test_app.py +++ b/instrumentation/opentelemetry-instrumentation-tornado/tests/tornado_test_app.py @@ -95,6 +95,16 @@ def get(self): self.set_status(200) +class CustomResponseHeaderHandler(tornado.web.RequestHandler): + def get(self): + self.set_header("content-type", "text/plain; charset=utf-8") + self.set_header("content-length", "0") + self.set_header( + "my-custom-header", "my-custom-value-1,my-custom-header-2" + ) + self.set_status(200) + + def make_app(tracer): app = tornado.web.Application( [ @@ -105,6 +115,7 @@ def make_app(tracer): (r"/on_finish", FinishedHandler), (r"/healthz", HealthCheckHandler), (r"/ping", HealthCheckHandler), + (r"/test_custom_response_headers", CustomResponseHeaderHandler), ] ) app.tracer = tracer
Tornado: Capture request/response headers as span attributes part of #906
2022-03-08T10:33:25
open-telemetry/opentelemetry-python-contrib
952
open-telemetry__opentelemetry-python-contrib-952
[ "911" ]
dbb35a29465bcaf84380715c356726718724859b
diff --git a/instrumentation/opentelemetry-instrumentation-flask/src/opentelemetry/instrumentation/flask/__init__.py b/instrumentation/opentelemetry-instrumentation-flask/src/opentelemetry/instrumentation/flask/__init__.py --- a/instrumentation/opentelemetry-instrumentation-flask/src/opentelemetry/instrumentation/flask/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-flask/src/opentelemetry/instrumentation/flask/__init__.py @@ -153,6 +153,10 @@ def _start_response(status, response_headers, *args, **kwargs): otel_wsgi.add_response_attributes( span, status, response_headers ) + if span.kind == trace.SpanKind.SERVER: + otel_wsgi.add_custom_response_headers( + span, response_headers + ) else: _logger.warning( "Flask environ's OpenTelemetry span " @@ -200,6 +204,10 @@ def _before_request(): ] = flask.request.url_rule.rule for key, value in attributes.items(): span.set_attribute(key, value) + if span.kind == trace.SpanKind.SERVER: + otel_wsgi.add_custom_request_headers( + span, flask_request_environ + ) activation = trace.use_span(span, end_on_exit=True) activation.__enter__() # pylint: disable=E1101
diff --git a/instrumentation/opentelemetry-instrumentation-flask/tests/base_test.py b/instrumentation/opentelemetry-instrumentation-flask/tests/base_test.py --- a/instrumentation/opentelemetry-instrumentation-flask/tests/base_test.py +++ b/instrumentation/opentelemetry-instrumentation-flask/tests/base_test.py @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +from flask import Response from werkzeug.test import Client from werkzeug.wrappers import BaseResponse @@ -23,6 +24,16 @@ def _hello_endpoint(helloid): raise ValueError(":-(") return "Hello: " + str(helloid) + @staticmethod + def _custom_response_headers(): + resp = Response("test response") + resp.headers["content-type"] = "text/plain; charset=utf-8" + resp.headers["content-length"] = "13" + resp.headers[ + "my-custom-header" + ] = "my-custom-value-1,my-custom-header-2" + return resp + def _common_initialization(self): def excluded_endpoint(): return "excluded" @@ -35,6 +46,9 @@ def excluded2_endpoint(): self.app.route("/excluded/<int:helloid>")(self._hello_endpoint) self.app.route("/excluded")(excluded_endpoint) self.app.route("/excluded2")(excluded2_endpoint) + self.app.route("/test_custom_response_headers")( + self._custom_response_headers + ) # pylint: disable=attribute-defined-outside-init self.client = Client(self.app, BaseResponse) diff --git a/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py b/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py --- a/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py +++ b/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py @@ -442,3 +442,101 @@ def test_mark_span_internal_in_presence_of_span_from_other_framework(self): self.assertEqual( span_list[0].parent.span_id, span_list[1].context.span_id ) + + +class TestCustomRequestResponseHeaders( + InstrumentationTest, TestBase, WsgiTestBase +): + def setUp(self): + super().setUp() + + self.env_patch = patch.dict( + "os.environ", + { + "OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST": "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3", + "OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE": "content-type,content-length,my-custom-header,invalid-header", + }, + ) + self.env_patch.start() + self.app = Flask(__name__) + FlaskInstrumentor().instrument_app(self.app) + + self._common_initialization() + + def tearDown(self): + super().tearDown() + self.env_patch.stop() + with self.disable_logging(): + FlaskInstrumentor().uninstrument_app(self.app) + + def test_custom_request_header_added_in_server_span(self): + headers = { + "Custom-Test-Header-1": "Test Value 1", + "Custom-Test-Header-2": "TestValue2,TestValue3", + } + resp = self.client.get("/hello/123", headers=headers) + self.assertEqual(200, resp.status_code) + span = self.memory_exporter.get_finished_spans()[0] + expected = { + "http.request.header.custom_test_header_1": ("Test Value 1",), + "http.request.header.custom_test_header_2": ( + "TestValue2,TestValue3", + ), + } + self.assertEqual(span.kind, trace.SpanKind.SERVER) + self.assertSpanHasAttributes(span, expected) + + def test_custom_request_header_not_added_in_internal_span(self): + tracer = trace.get_tracer(__name__) + with tracer.start_as_current_span("test", kind=trace.SpanKind.SERVER): + headers = { + "Custom-Test-Header-1": "Test Value 1", + "Custom-Test-Header-2": "TestValue2,TestValue3", + } + resp = self.client.get("/hello/123", headers=headers) + self.assertEqual(200, resp.status_code) + span = self.memory_exporter.get_finished_spans()[0] + not_expected = { + "http.request.header.custom_test_header_1": ("Test Value 1",), + "http.request.header.custom_test_header_2": ( + "TestValue2,TestValue3", + ), + } + self.assertEqual(span.kind, trace.SpanKind.INTERNAL) + for key, _ in not_expected.items(): + self.assertNotIn(key, span.attributes) + + def test_custom_response_header_added_in_server_span(self): + resp = self.client.get("/test_custom_response_headers") + self.assertEqual(resp.status_code, 200) + span = self.memory_exporter.get_finished_spans()[0] + expected = { + "http.response.header.content_type": ( + "text/plain; charset=utf-8", + ), + "http.response.header.content_length": ("13",), + "http.response.header.my_custom_header": ( + "my-custom-value-1,my-custom-header-2", + ), + } + self.assertEqual(span.kind, trace.SpanKind.SERVER) + self.assertSpanHasAttributes(span, expected) + + def test_custom_response_header_not_added_in_internal_span(self): + tracer = trace.get_tracer(__name__) + with tracer.start_as_current_span("test", kind=trace.SpanKind.SERVER): + resp = self.client.get("/test_custom_response_headers") + self.assertEqual(resp.status_code, 200) + span = self.memory_exporter.get_finished_spans()[0] + not_expected = { + "http.response.header.content_type": ( + "text/plain; charset=utf-8", + ), + "http.response.header.content_length": ("13",), + "http.response.header.my_custom_header": ( + "my-custom-value-1,my-custom-header-2", + ), + } + self.assertEqual(span.kind, trace.SpanKind.INTERNAL) + for key, _ in not_expected.items(): + self.assertNotIn(key, span.attributes)
Flask: Capture request/response headers as span attributes part of #906
please assign this issue to me.
2022-03-09T10:36:14
open-telemetry/opentelemetry-python-contrib
957
open-telemetry__opentelemetry-python-contrib-957
[ "956" ]
1bf9e0c51f800574acfff6e722dc586fe310bd01
diff --git a/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py b/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py --- a/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py @@ -313,7 +313,7 @@ def _create_start_response(span, start_response, response_hook): @functools.wraps(start_response) def _start_response(status, response_headers, *args, **kwargs): add_response_attributes(span, status, response_headers) - if span.kind == trace.SpanKind.SERVER: + if span.is_recording() and span.kind == trace.SpanKind.SERVER: add_custom_response_headers(span, response_headers) if response_hook: response_hook(status, response_headers) @@ -336,7 +336,7 @@ def __call__(self, environ, start_response): context_getter=wsgi_getter, attributes=collect_request_attributes(environ), ) - if span.kind == trace.SpanKind.SERVER: + if span.is_recording() and span.kind == trace.SpanKind.SERVER: add_custom_request_headers(span, environ) if self.request_hook:
diff --git a/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py b/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py --- a/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py +++ b/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py @@ -475,6 +475,29 @@ def iterate_response(self, response): except StopIteration: break + @mock.patch.dict( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3", + }, + ) + def test_custom_request_headers_non_recording_span(self): + try: + tracer_provider = trace_api.NoOpTracerProvider() + self.environ.update( + { + "HTTP_CUSTOM_TEST_HEADER_1": "Test Value 2", + "HTTP_CUSTOM_TEST_HEADER_2": "TestValue2,TestValue3", + } + ) + app = otel_wsgi.OpenTelemetryMiddleware( + simple_wsgi, tracer_provider=tracer_provider + ) + response = app(self.environ, self.start_response) + self.iterate_response(response) + except Exception as exc: # pylint: disable=W0703 + self.fail(f"Exception raised with NonRecordingSpan {exc}") + @mock.patch.dict( "os.environ", {
NonRecordingSpan causes errors in wsgi The following error arises from the `tracecontext` integration tests in the core repo: ``` Traceback (most recent call last): File "/Users/alex.ianchici/workspace/opentelemetry-python/.tox/tracecontext/lib/python3.9/site-packages/flask/app.py", line 2464, in __call__ return self.wsgi_app(environ, start_response) File "/Users/alex.ianchici/workspace/opentelemetry-python/.tox/tracecontext/src/opentelemetry-instrumentation-wsgi/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py", line 339, in __call__ if span.kind == trace.SpanKind.SERVER: AttributeError: 'NonRecordingSpan' object has no attribute 'kind' ``` It appears the problem came from this change: https://github.com/open-telemetry/opentelemetry-python-contrib/commit/2f5bbc416ab33f4856e1990a5e5682fcedc90f5f
2022-03-10T17:01:58
open-telemetry/opentelemetry-python-contrib
1,001
open-telemetry__opentelemetry-python-contrib-1001
[ "888" ]
b1bf8d4a5470facb6e63f33ff57a144b20e2a319
diff --git a/instrumentation/opentelemetry-instrumentation-pyramid/src/opentelemetry/instrumentation/pyramid/callbacks.py b/instrumentation/opentelemetry-instrumentation-pyramid/src/opentelemetry/instrumentation/pyramid/callbacks.py --- a/instrumentation/opentelemetry-instrumentation-pyramid/src/opentelemetry/instrumentation/pyramid/callbacks.py +++ b/instrumentation/opentelemetry-instrumentation-pyramid/src/opentelemetry/instrumentation/pyramid/callbacks.py @@ -137,16 +137,23 @@ def trace_tween(request): request.environ[_ENVIRON_ENABLED_KEY] = True request.environ[_ENVIRON_STARTTIME_KEY] = _time_ns() + response = None + status = None + try: response = handler(request) - response_or_exception = response except HTTPException as exc: # If the exception is a pyramid HTTPException, # that's still valuable information that isn't necessarily # a 500. For instance, HTTPFound is a 302. # As described in docs, Pyramid exceptions are all valid # response types - response_or_exception = exc + response = exc + raise + except BaseException: + # In the case that a non-HTTPException is bubbled up we + # should infer a internal server error and raise + status = "500 InternalServerError" raise finally: span = request.environ.get(_ENVIRON_SPAN_KEY) @@ -158,23 +165,26 @@ def trace_tween(request): "PyramidInstrumentor().instrument_config(config) is called" ) elif enabled: - otel_wsgi.add_response_attributes( - span, - response_or_exception.status, - response_or_exception.headerlist, - ) + status = getattr(response, "status", status) + + if status is not None: + otel_wsgi.add_response_attributes( + span, + status, + getattr(response, "headerList", None), + ) propagator = get_global_response_propagator() - if propagator: + if propagator and hasattr(response, "headers"): propagator.inject(response.headers) activation = request.environ.get(_ENVIRON_ACTIVATION_KEY) - if isinstance(response_or_exception, HTTPException): + if isinstance(response, HTTPException): activation.__exit__( - type(response_or_exception), - response_or_exception, - getattr(response_or_exception, "__traceback__", None), + type(response), + response, + getattr(response, "__traceback__", None), ) else: activation.__exit__(None, None, None)
diff --git a/instrumentation/opentelemetry-instrumentation-pyramid/tests/pyramid_base_test.py b/instrumentation/opentelemetry-instrumentation-pyramid/tests/pyramid_base_test.py --- a/instrumentation/opentelemetry-instrumentation-pyramid/tests/pyramid_base_test.py +++ b/instrumentation/opentelemetry-instrumentation-pyramid/tests/pyramid_base_test.py @@ -24,6 +24,8 @@ def _hello_endpoint(request): helloid = int(request.matchdict["helloid"]) if helloid == 500: raise exc.HTTPInternalServerError() + if helloid == 900: + raise NotImplementedError() return Response("Hello: " + str(helloid)) def _common_initialization(self, config): diff --git a/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_programmatic.py b/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_programmatic.py --- a/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_programmatic.py +++ b/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_programmatic.py @@ -167,6 +167,24 @@ def test_internal_error(self): self.assertEqual(span_list[0].kind, trace.SpanKind.SERVER) self.assertEqual(span_list[0].attributes, expected_attrs) + def test_internal_exception(self): + expected_attrs = expected_attributes( + { + SpanAttributes.HTTP_TARGET: "/hello/900", + SpanAttributes.HTTP_ROUTE: "/hello/{helloid}", + SpanAttributes.HTTP_STATUS_CODE: 500, + } + ) + with self.assertRaises(NotImplementedError): + resp = self.client.get("/hello/900") + resp.close() + + span_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(span_list), 1) + self.assertEqual(span_list[0].name, "/hello/{helloid}") + self.assertEqual(span_list[0].kind, trace.SpanKind.SERVER) + self.assertEqual(span_list[0].attributes, expected_attrs) + def test_tween_list(self): tween_list = "opentelemetry.instrumentation.pyramid.trace_tween_factory\npyramid.tweens.excview_tween_factory" config = Configurator(settings={"pyramid.tweens": tween_list})
Pyramid tween only handles HTTPException **Describe your environment** Seeing this exhibited in Pyramid 1.10 and as far back as Pyramid 1.7. **Steps to reproduce** Raise a non-HTTPException. **What is the expected behavior?** Tweens should process normally. **What is the actual behavior?** An error for use of `response_or_exception` before assignment is raised. **Additional context** The problem exists here https://github.com/open-telemetry/opentelemetry-python-contrib/blob/main/instrumentation/opentelemetry-instrumentation-pyramid/src/opentelemetry/instrumentation/pyramid/callbacks.py#L146-L157. It seems there should be an additional exception case for `BaseException` to initialize `response_or_exception`.
Proposed fix makes sense. PRs welcome :)
2022-03-15T19:49:07
open-telemetry/opentelemetry-python-contrib
1,003
open-telemetry__opentelemetry-python-contrib-1003
[ "912" ]
e861b93362126f5c701982efcf43c5d2e99f2f50
diff --git a/instrumentation/opentelemetry-instrumentation-falcon/src/opentelemetry/instrumentation/falcon/__init__.py b/instrumentation/opentelemetry-instrumentation-falcon/src/opentelemetry/instrumentation/falcon/__init__.py --- a/instrumentation/opentelemetry-instrumentation-falcon/src/opentelemetry/instrumentation/falcon/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-falcon/src/opentelemetry/instrumentation/falcon/__init__.py @@ -190,6 +190,8 @@ def __call__(self, env, start_response): attributes = otel_wsgi.collect_request_attributes(env) for key, value in attributes.items(): span.set_attribute(key, value) + if span.is_recording() and span.kind == trace.SpanKind.SERVER: + otel_wsgi.add_custom_request_headers(span, env) activation = trace.use_span(span, end_on_exit=True) activation.__enter__() @@ -295,6 +297,10 @@ def process_response( description=reason, ) ) + if span.is_recording() and span.kind == trace.SpanKind.SERVER: + otel_wsgi.add_custom_response_headers( + span, resp.headers.items() + ) except ValueError: pass
diff --git a/instrumentation/opentelemetry-instrumentation-falcon/tests/app.py b/instrumentation/opentelemetry-instrumentation-falcon/tests/app.py --- a/instrumentation/opentelemetry-instrumentation-falcon/tests/app.py +++ b/instrumentation/opentelemetry-instrumentation-falcon/tests/app.py @@ -33,6 +33,18 @@ def on_get(self, req, resp): print(non_existent_var) # noqa +class CustomResponseHeaderResource: + def on_get(self, _, resp): + # pylint: disable=no-member + resp.status = falcon.HTTP_201 + resp.set_header("content-type", "text/plain; charset=utf-8") + resp.set_header("content-length", "0") + resp.set_header( + "my-custom-header", "my-custom-value-1,my-custom-header-2" + ) + resp.set_header("dont-capture-me", "test-value") + + def make_app(): if hasattr(falcon, "App"): # Falcon 3 @@ -43,4 +55,7 @@ def make_app(): app.add_route("/hello", HelloWorldResource()) app.add_route("/ping", HelloWorldResource()) app.add_route("/error", ErrorResource()) + app.add_route( + "/test_custom_response_headers", CustomResponseHeaderResource() + ) return app diff --git a/instrumentation/opentelemetry-instrumentation-falcon/tests/test_falcon.py b/instrumentation/opentelemetry-instrumentation-falcon/tests/test_falcon.py --- a/instrumentation/opentelemetry-instrumentation-falcon/tests/test_falcon.py +++ b/instrumentation/opentelemetry-instrumentation-falcon/tests/test_falcon.py @@ -28,6 +28,10 @@ from opentelemetry.test.test_base import TestBase from opentelemetry.test.wsgitestutil import WsgiTestBase from opentelemetry.trace import StatusCode +from opentelemetry.util.http import ( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST, + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE, +) from .app import make_app @@ -280,3 +284,105 @@ def test_mark_span_internal_in_presence_of_span_from_other_framework(self): self.assertEqual( span.parent.span_id, parent_span.get_span_context().span_id ) + + [email protected]( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,invalid-header", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "content-type,content-length,my-custom-header,invalid-header", + }, +) +class TestCustomRequestResponseHeaders(TestFalconBase): + def test_custom_request_header_added_in_server_span(self): + headers = { + "Custom-Test-Header-1": "Test Value 1", + "Custom-Test-Header-2": "TestValue2,TestValue3", + "Custom-Test-Header-3": "TestValue4", + } + self.client().simulate_request( + method="GET", path="/hello", headers=headers + ) + span = self.memory_exporter.get_finished_spans()[0] + assert span.status.is_ok + + expected = { + "http.request.header.custom_test_header_1": ("Test Value 1",), + "http.request.header.custom_test_header_2": ( + "TestValue2,TestValue3", + ), + } + not_expected = { + "http.request.header.custom_test_header_3": ("TestValue4",), + } + + self.assertEqual(span.kind, trace.SpanKind.SERVER) + self.assertSpanHasAttributes(span, expected) + for key, _ in not_expected.items(): + self.assertNotIn(key, span.attributes) + + def test_custom_request_header_not_added_in_internal_span(self): + tracer = trace.get_tracer(__name__) + with tracer.start_as_current_span("test", kind=trace.SpanKind.SERVER): + headers = { + "Custom-Test-Header-1": "Test Value 1", + "Custom-Test-Header-2": "TestValue2,TestValue3", + } + self.client().simulate_request( + method="GET", path="/hello", headers=headers + ) + span = self.memory_exporter.get_finished_spans()[0] + assert span.status.is_ok + not_expected = { + "http.request.header.custom_test_header_1": ("Test Value 1",), + "http.request.header.custom_test_header_2": ( + "TestValue2,TestValue3", + ), + } + self.assertEqual(span.kind, trace.SpanKind.INTERNAL) + for key, _ in not_expected.items(): + self.assertNotIn(key, span.attributes) + + def test_custom_response_header_added_in_server_span(self): + self.client().simulate_request( + method="GET", path="/test_custom_response_headers" + ) + span = self.memory_exporter.get_finished_spans()[0] + assert span.status.is_ok + expected = { + "http.response.header.content_type": ( + "text/plain; charset=utf-8", + ), + "http.response.header.content_length": ("0",), + "http.response.header.my_custom_header": ( + "my-custom-value-1,my-custom-header-2", + ), + } + not_expected = { + "http.response.header.dont_capture_me": ("test-value",) + } + self.assertEqual(span.kind, trace.SpanKind.SERVER) + self.assertSpanHasAttributes(span, expected) + for key, _ in not_expected.items(): + self.assertNotIn(key, span.attributes) + + def test_custom_response_header_not_added_in_internal_span(self): + tracer = trace.get_tracer(__name__) + with tracer.start_as_current_span("test", kind=trace.SpanKind.SERVER): + self.client().simulate_request( + method="GET", path="/test_custom_response_headers" + ) + span = self.memory_exporter.get_finished_spans()[0] + assert span.status.is_ok + not_expected = { + "http.response.header.content_type": ( + "text/plain; charset=utf-8", + ), + "http.response.header.content_length": ("0",), + "http.response.header.my_custom_header": ( + "my-custom-value-1,my-custom-header-2", + ), + } + self.assertEqual(span.kind, trace.SpanKind.INTERNAL) + for key, _ in not_expected.items(): + self.assertNotIn(key, span.attributes)
Falcon: Capture request/response headers as span attributes part of #906
Please assign this issue to me.
2022-03-17T07:05:28
open-telemetry/opentelemetry-python-contrib
1,014
open-telemetry__opentelemetry-python-contrib-1014
[ "938" ]
7deea055ddf71c10f5fa7c709f0c6445679c1b3c
diff --git a/instrumentation/opentelemetry-instrumentation-urllib/src/opentelemetry/instrumentation/urllib/__init__.py b/instrumentation/opentelemetry-instrumentation-urllib/src/opentelemetry/instrumentation/urllib/__init__.py --- a/instrumentation/opentelemetry-instrumentation-urllib/src/opentelemetry/instrumentation/urllib/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-urllib/src/opentelemetry/instrumentation/urllib/__init__.py @@ -184,14 +184,11 @@ def _instrumented_open_call( } with tracer.start_as_current_span( - span_name, kind=SpanKind.CLIENT + span_name, kind=SpanKind.CLIENT, attributes=labels ) as span: exception = None if callable(request_hook): request_hook(span, request) - if span.is_recording(): - span.set_attribute(SpanAttributes.HTTP_METHOD, method) - span.set_attribute(SpanAttributes.HTTP_URL, url) headers = get_or_create_headers() inject(headers)
opentelemetry-instrumentation-urllib
Hi I want to take this up
2022-03-21T06:40:49
open-telemetry/opentelemetry-python-contrib
1,018
open-telemetry__opentelemetry-python-contrib-1018
[ "947" ]
8727bc3374ea1a1c4dc3ff5736ae48d742ce7bc0
diff --git a/instrumentation/opentelemetry-instrumentation-elasticsearch/src/opentelemetry/instrumentation/elasticsearch/__init__.py b/instrumentation/opentelemetry-instrumentation-elasticsearch/src/opentelemetry/instrumentation/elasticsearch/__init__.py --- a/instrumentation/opentelemetry-instrumentation-elasticsearch/src/opentelemetry/instrumentation/elasticsearch/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-elasticsearch/src/opentelemetry/instrumentation/elasticsearch/__init__.py @@ -150,11 +150,14 @@ def _uninstrument(self, **kwargs): _regex_doc_url = re.compile(r"/_doc/([^/]+)") +# search api https://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html +_regex_search_url = re.compile(r"/([^/]+)/_search[/]?") + def _wrap_perform_request( tracer, span_name_prefix, request_hook=None, response_hook=None ): - # pylint: disable=R0912 + # pylint: disable=R0912,R0914 def wrapper(wrapped, _, args, kwargs): method = url = None try: @@ -167,7 +170,10 @@ def wrapper(wrapped, _, args, kwargs): ) op_name = span_name_prefix + (url or method or _DEFAULT_OP_NAME) + doc_id = None + search_target = None + if url: # TODO: This regex-based solution avoids creating an unbounded number of span names, but should be replaced by instrumenting individual Elasticsearch methods instead of Transport.perform_request() # A limitation of the regex is that only the '_doc' mapping type is supported. Mapping types are deprecated since Elasticsearch 7 @@ -184,6 +190,11 @@ def wrapper(wrapped, _, args, kwargs): ) # Put the document ID in attributes doc_id = match.group(1) + match = _regex_search_url.search(url) + if match is not None: + op_name = span_name_prefix + "/<target>/_search" + search_target = match.group(1) + params = kwargs.get("params", {}) body = kwargs.get("body", None) @@ -209,6 +220,8 @@ def wrapper(wrapped, _, args, kwargs): attributes["elasticsearch.params"] = str(params) if doc_id: attributes["elasticsearch.id"] = doc_id + if search_target: + attributes["elasticsearch.target"] = search_target for key, value in attributes.items(): span.set_attribute(key, value)
diff --git a/instrumentation/opentelemetry-instrumentation-elasticsearch/tests/test_elasticsearch.py b/instrumentation/opentelemetry-instrumentation-elasticsearch/tests/test_elasticsearch.py --- a/instrumentation/opentelemetry-instrumentation-elasticsearch/tests/test_elasticsearch.py +++ b/instrumentation/opentelemetry-instrumentation-elasticsearch/tests/test_elasticsearch.py @@ -237,7 +237,7 @@ def test_dsl_search(self, request_mock): spans = self.get_finished_spans() span = spans[0] self.assertEqual(1, len(spans)) - self.assertEqual(span.name, "Elasticsearch/test-index/_search") + self.assertEqual(span.name, "Elasticsearch/<target>/_search") self.assertIsNotNone(span.end_time) self.assertEqual( span.attributes, @@ -245,6 +245,7 @@ def test_dsl_search(self, request_mock): SpanAttributes.DB_SYSTEM: "elasticsearch", "elasticsearch.url": "/test-index/_search", "elasticsearch.method": helpers.dsl_search_method, + "elasticsearch.target": "test-index", SpanAttributes.DB_STATEMENT: str( { "query": {
elasticsearch span_name not correctly **Steps to reproduce** Describe exactly how to reproduce the error. Include a code sample if applicable. **What is the expected behavior?** Our index is created on a rolling basis Therefore, we will use a specific time to query the index when querying, and when the plugin generates span_name, it will bring the unified index, so that span_name cannot be described as an operation. As follows ``` Elasticsearch/bkfta_action_20220228_read,bkfta_action_20220301_read,bkfta_action_20220302_read,bkfta_action_20220303_read,bkfta_action_20220304_read,bkfta_action_20220305_read,bkfta_action_20220306_read,bkfta_action_20220307_read/_search ``` **What is the actual behavior?** span_name shuld be ``` Elasticsearch/{index_name}/_search ``` **Additional context** Add any other context about the problem here.
2022-03-22T11:28:02
open-telemetry/opentelemetry-python-contrib
1,022
open-telemetry__opentelemetry-python-contrib-1022
[ "914" ]
d76066893b541a97f92c5c084dc38ac5c205bdd5
diff --git a/instrumentation/opentelemetry-instrumentation-pyramid/src/opentelemetry/instrumentation/pyramid/__init__.py b/instrumentation/opentelemetry-instrumentation-pyramid/src/opentelemetry/instrumentation/pyramid/__init__.py --- a/instrumentation/opentelemetry-instrumentation-pyramid/src/opentelemetry/instrumentation/pyramid/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-pyramid/src/opentelemetry/instrumentation/pyramid/__init__.py @@ -90,6 +90,57 @@ will exclude requests such as ``https://site/client/123/info`` and ``https://site/xyz/healthcheck``. +Capture HTTP request and response headers +***************************************** +You can configure the agent to capture predefined HTTP headers as span attributes, according to the `semantic convention <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers>`_. + +Request headers +*************** +To capture predefined HTTP request headers as span attributes, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST`` +to a comma-separated list of HTTP header names. + +For example, + +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="content-type,custom_request_header" + +will extract ``content-type`` and ``custom_request_header`` from request headers and add them as span attributes. + +It is recommended that you should give the correct names of the headers to be captured in the environment variable. +Request header names in pyramid are case insensitive and - characters are replaced by _. So, giving header name as ``CUStom_Header`` in environment variable will be able capture header with name ``custom-header``. + +The name of the added span attribute will follow the format ``http.request.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ). +The value of the attribute will be single item list containing all the header values. + +Example of the added span attribute, +``http.request.header.custom_request_header = ["<value1>,<value2>"]`` + +Response headers +**************** +To capture predefined HTTP response headers as span attributes, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`` +to a comma-separated list of HTTP header names. + +For example, + +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="content-type,custom_response_header" + +will extract ``content-type`` and ``custom_response_header`` from response headers and add them as span attributes. + +It is recommended that you should give the correct names of the headers to be captured in the environment variable. +Response header names captured in pyramid are case insensitive. So, giving header name as ``CUStomHeader`` in environment variable will be able capture header with name ``customheader``. + +The name of the added span attribute will follow the format ``http.response.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ). +The value of the attribute will be single item list containing all the header values. + +Example of the added span attribute, +``http.response.header.custom_response_header = ["<value1>,<value2>"]`` + +Note: + Environment variable names to caputre http headers are still experimental, and thus are subject to change. + API --- """ diff --git a/instrumentation/opentelemetry-instrumentation-pyramid/src/opentelemetry/instrumentation/pyramid/callbacks.py b/instrumentation/opentelemetry-instrumentation-pyramid/src/opentelemetry/instrumentation/pyramid/callbacks.py --- a/instrumentation/opentelemetry-instrumentation-pyramid/src/opentelemetry/instrumentation/pyramid/callbacks.py +++ b/instrumentation/opentelemetry-instrumentation-pyramid/src/opentelemetry/instrumentation/pyramid/callbacks.py @@ -104,6 +104,8 @@ def _before_traversal(event): ] = request.matched_route.pattern for key, value in attributes.items(): span.set_attribute(key, value) + if span.kind == trace.SpanKind.SERVER: + otel_wsgi.add_custom_request_headers(span, request_environ) activation = trace.use_span(span, end_on_exit=True) activation.__enter__() # pylint: disable=E1101 @@ -127,6 +129,7 @@ def disabled_tween(request): return disabled_tween # make a request tracing function + # pylint: disable=too-many-branches def trace_tween(request): # pylint: disable=E1101 if _excluded_urls.url_disabled(request.url): @@ -171,7 +174,12 @@ def trace_tween(request): otel_wsgi.add_response_attributes( span, status, - getattr(response, "headerList", None), + getattr(response, "headerlist", None), + ) + + if span.is_recording() and span.kind == trace.SpanKind.SERVER: + otel_wsgi.add_custom_response_headers( + span, getattr(response, "headerlist", None) ) propagator = get_global_response_propagator()
diff --git a/instrumentation/opentelemetry-instrumentation-pyramid/tests/pyramid_base_test.py b/instrumentation/opentelemetry-instrumentation-pyramid/tests/pyramid_base_test.py --- a/instrumentation/opentelemetry-instrumentation-pyramid/tests/pyramid_base_test.py +++ b/instrumentation/opentelemetry-instrumentation-pyramid/tests/pyramid_base_test.py @@ -28,6 +28,16 @@ def _hello_endpoint(request): raise NotImplementedError() return Response("Hello: " + str(helloid)) + @staticmethod + def _custom_response_header_endpoint(request): + headers = { + "content-type": "text/plain; charset=utf-8", + "content-length": "7", + "my-custom-header": "my-custom-value-1,my-custom-header-2", + "dont-capture-me": "test-value", + } + return Response("Testing", headers=headers) + def _common_initialization(self, config): # pylint: disable=unused-argument def excluded_endpoint(request): @@ -45,6 +55,13 @@ def excluded2_endpoint(request): config.add_view(excluded_endpoint, route_name="excluded") config.add_route("excluded2", "/excluded_noarg2") config.add_view(excluded2_endpoint, route_name="excluded2") + config.add_route( + "custom_response_headers", "/test_custom_response_headers" + ) + config.add_view( + self._custom_response_header_endpoint, + route_name="custom_response_headers", + ) # pylint: disable=attribute-defined-outside-init self.client = Client(config.make_wsgi_app(), BaseResponse) diff --git a/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_automatic.py b/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_automatic.py --- a/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_automatic.py +++ b/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_automatic.py @@ -12,12 +12,20 @@ # See the License for the specific language governing permissions and # limitations under the License. +from unittest.mock import patch + from pyramid.config import Configurator +from opentelemetry import trace from opentelemetry.instrumentation.pyramid import PyramidInstrumentor +from opentelemetry.test.globals_test import reset_trace_globals from opentelemetry.test.test_base import TestBase from opentelemetry.test.wsgitestutil import WsgiTestBase from opentelemetry.trace import SpanKind +from opentelemetry.util.http import ( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST, + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE, +) # pylint: disable=import-error from .pyramid_base_test import InstrumentationTest @@ -109,3 +117,146 @@ def test_with_existing_span(self): parent_span.get_span_context().span_id, span_list[0].parent.span_id, ) + + +class TestCustomRequestResponseHeaders( + InstrumentationTest, TestBase, WsgiTestBase +): + def setUp(self): + super().setUp() + PyramidInstrumentor().instrument() + self.config = Configurator() + self._common_initialization(self.config) + self.env_patch = patch.dict( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,invalid-header", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "content-type,content-length,my-custom-header,invalid-header", + }, + ) + self.env_patch.start() + + def tearDown(self) -> None: + super().tearDown() + self.env_patch.stop() + with self.disable_logging(): + PyramidInstrumentor().uninstrument() + + def test_custom_request_header_added_in_server_span(self): + headers = { + "Custom-Test-Header-1": "Test Value 1", + "Custom-Test-Header-2": "TestValue2,TestValue3", + "Custom-Test-Header-3": "TestValue4", + } + resp = self.client.get("/hello/123", headers=headers) + self.assertEqual(200, resp.status_code) + span = self.memory_exporter.get_finished_spans()[0] + expected = { + "http.request.header.custom_test_header_1": ("Test Value 1",), + "http.request.header.custom_test_header_2": ( + "TestValue2,TestValue3", + ), + } + not_expected = { + "http.request.header.custom_test_header_3": ("TestValue4",), + } + self.assertEqual(span.kind, SpanKind.SERVER) + self.assertSpanHasAttributes(span, expected) + for key, _ in not_expected.items(): + self.assertNotIn(key, span.attributes) + + def test_custom_request_header_not_added_in_internal_span(self): + tracer = trace.get_tracer(__name__) + with tracer.start_as_current_span("test", kind=SpanKind.SERVER): + headers = { + "Custom-Test-Header-1": "Test Value 1", + "Custom-Test-Header-2": "TestValue2,TestValue3", + } + resp = self.client.get("/hello/123", headers=headers) + self.assertEqual(200, resp.status_code) + span = self.memory_exporter.get_finished_spans()[0] + not_expected = { + "http.request.header.custom_test_header_1": ("Test Value 1",), + "http.request.header.custom_test_header_2": ( + "TestValue2,TestValue3", + ), + } + self.assertEqual(span.kind, SpanKind.INTERNAL) + for key, _ in not_expected.items(): + self.assertNotIn(key, span.attributes) + + def test_custom_response_header_added_in_server_span(self): + resp = self.client.get("/test_custom_response_headers") + self.assertEqual(200, resp.status_code) + span = self.memory_exporter.get_finished_spans()[0] + expected = { + "http.response.header.content_type": ( + "text/plain; charset=utf-8", + ), + "http.response.header.content_length": ("7",), + "http.response.header.my_custom_header": ( + "my-custom-value-1,my-custom-header-2", + ), + } + not_expected = { + "http.response.header.dont_capture_me": ("test-value",) + } + self.assertEqual(span.kind, SpanKind.SERVER) + self.assertSpanHasAttributes(span, expected) + for key, _ in not_expected.items(): + self.assertNotIn(key, span.attributes) + + def test_custom_response_header_not_added_in_internal_span(self): + tracer = trace.get_tracer(__name__) + with tracer.start_as_current_span("test", kind=SpanKind.SERVER): + resp = self.client.get("/test_custom_response_headers") + self.assertEqual(200, resp.status_code) + span = self.memory_exporter.get_finished_spans()[0] + not_expected = { + "http.response.header.content_type": ( + "text/plain; charset=utf-8", + ), + "http.response.header.content_length": ("7",), + "http.response.header.my_custom_header": ( + "my-custom-value-1,my-custom-header-2", + ), + } + self.assertEqual(span.kind, SpanKind.INTERNAL) + for key, _ in not_expected.items(): + self.assertNotIn(key, span.attributes) + + +class TestCustomHeadersNonRecordingSpan( + InstrumentationTest, TestBase, WsgiTestBase +): + def setUp(self): + super().setUp() + # This is done because set_tracer_provider cannot override the + # current tracer provider. + reset_trace_globals() + tracer_provider = trace.NoOpTracerProvider() + trace.set_tracer_provider(tracer_provider) + PyramidInstrumentor().instrument() + self.config = Configurator() + self._common_initialization(self.config) + self.env_patch = patch.dict( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,invalid-header", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "content-type,content-length,my-custom-header,invalid-header", + }, + ) + self.env_patch.start() + + def tearDown(self) -> None: + super().tearDown() + self.env_patch.stop() + with self.disable_logging(): + PyramidInstrumentor().uninstrument() + + def test_custom_header_non_recording_span(self): + try: + resp = self.client.get("/hello/123") + self.assertEqual(200, resp.status_code) + except Exception as exc: # pylint: disable=W0703 + self.fail(f"Exception raised with NonRecordingSpan {exc}")
Pyramid: Capture request/response headers as span attributes part of #906
2022-03-29T06:18:33
open-telemetry/opentelemetry-python-contrib
1,024
open-telemetry__opentelemetry-python-contrib-1024
[ "913" ]
36ba621226641e7069d32aa13a6fa2346066d8ea
diff --git a/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/__init__.py b/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/__init__.py --- a/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/__init__.py @@ -76,6 +76,52 @@ def response_hook(span, request, response): Django Request object: https://docs.djangoproject.com/en/3.1/ref/request-response/#httprequest-objects Django Response object: https://docs.djangoproject.com/en/3.1/ref/request-response/#httpresponse-objects +Capture HTTP request and response headers +***************************************** +You can configure the agent to capture predefined HTTP headers as span attributes, according to the `semantic convention <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers>`_. + +Request headers +*************** +To capture predefined HTTP request headers as span attributes, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST`` +to a comma-separated list of HTTP header names. + +For example, +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="content_type,custom_request_header" + +will extract content_type and custom_request_header from request headers and add them as span attributes. + +It is recommended that you should give the correct names of the headers to be captured in the environment variable. +Request header names in django are case insensitive. So, giving header name as ``CUStom_Header`` in environment variable will be able capture header with name ``custom-header``. + +The name of the added span attribute will follow the format ``http.request.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ). +The value of the attribute will be single item list containing all the header values. + +Example of the added span attribute, +``http.request.header.custom_request_header = ["<value1>,<value2>"]`` + +Response headers +**************** +To capture predefined HTTP response headers as span attributes, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`` +to a comma-separated list of HTTP header names. + +For example, +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="content_type,custom_response_header" + +will extract content_type and custom_response_header from response headers and add them as span attributes. + +It is recommended that you should give the correct names of the headers to be captured in the environment variable. +Response header names captured in django are case insensitive. So, giving header name as ``CUStomHeader`` in environment variable will be able capture header with name ``customheader``. + +The name of the added span attribute will follow the format ``http.response.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ). +The value of the attribute will be single item list containing all the header values. + +Example of the added span attribute, +``http.response.header.custom_response_header = ["<value1>,<value2>"]`` + API --- """ diff --git a/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/middleware.py b/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/middleware.py --- a/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/middleware.py +++ b/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/middleware.py @@ -28,13 +28,19 @@ _start_internal_or_server_span, extract_attributes_from_object, ) +from opentelemetry.instrumentation.wsgi import ( + add_custom_request_headers as wsgi_add_custom_request_headers, +) +from opentelemetry.instrumentation.wsgi import ( + add_custom_response_headers as wsgi_add_custom_response_headers, +) from opentelemetry.instrumentation.wsgi import add_response_attributes from opentelemetry.instrumentation.wsgi import ( collect_request_attributes as wsgi_collect_request_attributes, ) from opentelemetry.instrumentation.wsgi import wsgi_getter from opentelemetry.semconv.trace import SpanAttributes -from opentelemetry.trace import Span, use_span +from opentelemetry.trace import Span, SpanKind, use_span from opentelemetry.util.http import get_excluded_urls, get_traced_request_attrs try: @@ -77,7 +83,13 @@ def __call__(self, request): # try/except block exclusive for optional ASGI imports. try: - from opentelemetry.instrumentation.asgi import asgi_getter + from opentelemetry.instrumentation.asgi import asgi_getter, asgi_setter + from opentelemetry.instrumentation.asgi import ( + collect_custom_request_headers_attributes as asgi_collect_custom_request_attributes, + ) + from opentelemetry.instrumentation.asgi import ( + collect_custom_response_headers_attributes as asgi_collect_custom_response_attributes, + ) from opentelemetry.instrumentation.asgi import ( collect_request_attributes as asgi_collect_request_attributes, ) @@ -213,6 +225,13 @@ def process_request(self, request): self._traced_request_attrs, attributes, ) + if span.is_recording() and span.kind == SpanKind.SERVER: + attributes.update( + asgi_collect_custom_request_attributes(carrier) + ) + else: + if span.is_recording() and span.kind == SpanKind.SERVER: + wsgi_add_custom_request_headers(span, carrier) for key, value in attributes.items(): span.set_attribute(key, value) @@ -257,6 +276,7 @@ def process_exception(self, request, exception): if self._environ_activation_key in request.META.keys(): request.META[self._environ_exception_key] = exception + # pylint: disable=too-many-branches def process_response(self, request, response): if self._excluded_urls.url_disabled(request.build_absolute_uri("?")): return response @@ -271,12 +291,25 @@ def process_response(self, request, response): if activation and span: if is_asgi_request: set_status_code(span, response.status_code) + + if span.is_recording() and span.kind == SpanKind.SERVER: + custom_headers = {} + for key, value in response.items(): + asgi_setter.set(custom_headers, key, value) + + custom_res_attributes = ( + asgi_collect_custom_response_attributes(custom_headers) + ) + for key, value in custom_res_attributes.items(): + span.set_attribute(key, value) else: add_response_attributes( span, f"{response.status_code} {response.reason_phrase}", response.items(), ) + if span.is_recording() and span.kind == SpanKind.SERVER: + wsgi_add_custom_response_headers(span, response.items()) propagator = get_global_response_propagator() if propagator:
diff --git a/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware.py b/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware.py --- a/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware.py +++ b/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware.py @@ -43,7 +43,12 @@ format_span_id, format_trace_id, ) -from opentelemetry.util.http import get_excluded_urls, get_traced_request_attrs +from opentelemetry.util.http import ( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST, + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE, + get_excluded_urls, + get_traced_request_attrs, +) # pylint: disable=import-error from .views import ( @@ -51,6 +56,7 @@ excluded, excluded_noarg, excluded_noarg2, + response_with_custom_header, route_span_name, traced, traced_template, @@ -67,6 +73,7 @@ urlpatterns = [ re_path(r"^traced/", traced), + re_path(r"^traced_custom_header/", response_with_custom_header), re_path(r"^route/(?P<year>[0-9]{4})/template/$", traced_template), re_path(r"^error/", error), re_path(r"^excluded_arg/", excluded), @@ -451,3 +458,107 @@ def test_django_with_wsgi_instrumented(self): parent_span.get_span_context().span_id, span_list[0].parent.span_id, ) + + +class TestMiddlewareWsgiWithCustomHeaders(TestBase, WsgiTestBase): + @classmethod + def setUpClass(cls): + conf.settings.configure(ROOT_URLCONF=modules[__name__]) + super().setUpClass() + + def setUp(self): + super().setUp() + setup_test_environment() + tracer_provider, exporter = self.create_tracer_provider() + self.exporter = exporter + _django_instrumentor.instrument(tracer_provider=tracer_provider) + self.env_patch = patch.dict( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3", + }, + ) + self.env_patch.start() + + def tearDown(self): + super().tearDown() + self.env_patch.stop() + teardown_test_environment() + _django_instrumentor.uninstrument() + + @classmethod + def tearDownClass(cls): + super().tearDownClass() + conf.settings = conf.LazySettings() + + def test_http_custom_request_headers_in_span_attributes(self): + expected = { + "http.request.header.custom_test_header_1": ( + "test-header-value-1", + ), + "http.request.header.custom_test_header_2": ( + "test-header-value-2", + ), + } + Client( + HTTP_CUSTOM_TEST_HEADER_1="test-header-value-1", + HTTP_CUSTOM_TEST_HEADER_2="test-header-value-2", + ).get("/traced/") + spans = self.exporter.get_finished_spans() + self.assertEqual(len(spans), 1) + + span = spans[0] + self.assertEqual(span.kind, SpanKind.SERVER) + self.assertSpanHasAttributes(span, expected) + self.memory_exporter.clear() + + def test_http_custom_request_headers_not_in_span_attributes(self): + not_expected = { + "http.request.header.custom_test_header_2": ( + "test-header-value-2", + ), + } + Client(HTTP_CUSTOM_TEST_HEADER_1="test-header-value-1").get("/traced/") + spans = self.exporter.get_finished_spans() + self.assertEqual(len(spans), 1) + + span = spans[0] + self.assertEqual(span.kind, SpanKind.SERVER) + for key, _ in not_expected.items(): + self.assertNotIn(key, span.attributes) + self.memory_exporter.clear() + + def test_http_custom_response_headers_in_span_attributes(self): + expected = { + "http.response.header.custom_test_header_1": ( + "test-header-value-1", + ), + "http.response.header.custom_test_header_2": ( + "test-header-value-2", + ), + } + Client().get("/traced_custom_header/") + spans = self.exporter.get_finished_spans() + self.assertEqual(len(spans), 1) + + span = spans[0] + self.assertEqual(span.kind, SpanKind.SERVER) + self.assertSpanHasAttributes(span, expected) + self.memory_exporter.clear() + + def test_http_custom_response_headers_not_in_span_attributes(self): + not_expected = { + "http.response.header.custom_test_header_3": ( + "test-header-value-3", + ), + } + Client().get("/traced_custom_header/") + spans = self.exporter.get_finished_spans() + self.assertEqual(len(spans), 1) + + span = spans[0] + self.assertEqual(span.kind, SpanKind.SERVER) + for key, _ in not_expected.items(): + self.assertNotIn(key, span.attributes) + self.memory_exporter.clear() diff --git a/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware_asgi.py b/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware_asgi.py --- a/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware_asgi.py +++ b/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware_asgi.py @@ -42,7 +42,12 @@ format_span_id, format_trace_id, ) -from opentelemetry.util.http import get_excluded_urls, get_traced_request_attrs +from opentelemetry.util.http import ( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST, + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE, + get_excluded_urls, + get_traced_request_attrs, +) # pylint: disable=import-error from .views import ( @@ -53,6 +58,7 @@ async_route_span_name, async_traced, async_traced_template, + async_with_custom_header, ) DJANGO_2_0 = VERSION >= (2, 0) @@ -65,6 +71,7 @@ urlpatterns = [ re_path(r"^traced/", async_traced), + re_path(r"^traced_custom_header/", async_with_custom_header), re_path(r"^route/(?P<year>[0-9]{4})/template/$", async_traced_template), re_path(r"^error/", async_error), re_path(r"^excluded_arg/", async_excluded), @@ -415,3 +422,116 @@ async def test_tracer_provider_traced(self): self.assertEqual( span.resource.attributes["resource-key"], "resource-value" ) + + +class TestMiddlewareAsgiWithCustomHeaders(SimpleTestCase, TestBase): + @classmethod + def setUpClass(cls): + conf.settings.configure(ROOT_URLCONF=modules[__name__]) + super().setUpClass() + + def setUp(self): + super().setUp() + setup_test_environment() + + tracer_provider, exporter = self.create_tracer_provider() + self.exporter = exporter + _django_instrumentor.instrument(tracer_provider=tracer_provider) + self.env_patch = patch.dict( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3", + }, + ) + self.env_patch.start() + + def tearDown(self): + super().tearDown() + self.env_patch.stop() + teardown_test_environment() + _django_instrumentor.uninstrument() + + @classmethod + def tearDownClass(cls): + super().tearDownClass() + conf.settings = conf.LazySettings() + + async def test_http_custom_request_headers_in_span_attributes(self): + expected = { + "http.request.header.custom_test_header_1": ( + "test-header-value-1", + ), + "http.request.header.custom_test_header_2": ( + "test-header-value-2", + ), + } + await self.async_client.get( + "/traced/", + **{ + "custom-test-header-1": "test-header-value-1", + "custom-test-header-2": "test-header-value-2", + }, + ) + spans = self.exporter.get_finished_spans() + self.assertEqual(len(spans), 1) + + span = spans[0] + self.assertEqual(span.kind, SpanKind.SERVER) + self.assertSpanHasAttributes(span, expected) + self.memory_exporter.clear() + + async def test_http_custom_request_headers_not_in_span_attributes(self): + not_expected = { + "http.request.header.custom_test_header_2": ( + "test-header-value-2", + ), + } + await self.async_client.get( + "/traced/", + **{ + "custom-test-header-1": "test-header-value-1", + }, + ) + spans = self.exporter.get_finished_spans() + self.assertEqual(len(spans), 1) + + span = spans[0] + self.assertEqual(span.kind, SpanKind.SERVER) + for key, _ in not_expected.items(): + self.assertNotIn(key, span.attributes) + self.memory_exporter.clear() + + async def test_http_custom_response_headers_in_span_attributes(self): + expected = { + "http.response.header.custom_test_header_1": ( + "test-header-value-1", + ), + "http.response.header.custom_test_header_2": ( + "test-header-value-2", + ), + } + await self.async_client.get("/traced_custom_header/") + spans = self.exporter.get_finished_spans() + self.assertEqual(len(spans), 1) + + span = spans[0] + self.assertEqual(span.kind, SpanKind.SERVER) + self.assertSpanHasAttributes(span, expected) + self.memory_exporter.clear() + + async def test_http_custom_response_headers_not_in_span_attributes(self): + not_expected = { + "http.response.header.custom_test_header_3": ( + "test-header-value-3", + ), + } + await self.async_client.get("/traced_custom_header/") + spans = self.exporter.get_finished_spans() + self.assertEqual(len(spans), 1) + + span = spans[0] + self.assertEqual(span.kind, SpanKind.SERVER) + for key, _ in not_expected.items(): + self.assertNotIn(key, span.attributes) + self.memory_exporter.clear() diff --git a/instrumentation/opentelemetry-instrumentation-django/tests/views.py b/instrumentation/opentelemetry-instrumentation-django/tests/views.py --- a/instrumentation/opentelemetry-instrumentation-django/tests/views.py +++ b/instrumentation/opentelemetry-instrumentation-django/tests/views.py @@ -31,6 +31,13 @@ def route_span_name( return HttpResponse() +def response_with_custom_header(request): + response = HttpResponse() + response["custom-test-header-1"] = "test-header-value-1" + response["custom-test-header-2"] = "test-header-value-2" + return response + + async def async_traced(request): # pylint: disable=unused-argument return HttpResponse() @@ -61,3 +68,10 @@ async def async_route_span_name( request, *args, **kwargs ): # pylint: disable=unused-argument return HttpResponse() + + +async def async_with_custom_header(request): + response = HttpResponse() + response.headers["custom-test-header-1"] = "test-header-value-1" + response.headers["custom-test-header-2"] = "test-header-value-2" + return response
Django: Capture request/response headers as span attributes part of #906
Please assign this issue to me
2022-03-31T13:28:01
open-telemetry/opentelemetry-python-contrib
1,032
open-telemetry__opentelemetry-python-contrib-1032
[ "916" ]
0fdc3c165671b865d1a48ba356db78f21932c881
diff --git a/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py b/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py --- a/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py @@ -91,6 +91,57 @@ def client_response_hook(span: Span, message: dict): OpenTelemetryMiddleware().(application, server_request_hook=server_request_hook, client_request_hook=client_request_hook, client_response_hook=client_response_hook) +Capture HTTP request and response headers +***************************************** +You can configure the agent to capture predefined HTTP headers as span attributes, according to the `semantic convention <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers>`_. + +Request headers +*************** +To capture predefined HTTP request headers as span attributes, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST`` +to a comma-separated list of HTTP header names. + +For example, + +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="content-type,custom_request_header" + +will extract ``content-type`` and ``custom_request_header`` from request headers and add them as span attributes. + +It is recommended that you should give the correct names of the headers to be captured in the environment variable. +Request header names in ASGI are case insensitive. So, giving header name as ``CUStom-Header`` in environment variable will be able capture header with name ``custom-header``. + +The name of the added span attribute will follow the format ``http.request.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ). +The value of the attribute will be single item list containing all the header values. + +Example of the added span attribute, +``http.request.header.custom_request_header = ["<value1>,<value2>"]`` + +Response headers +**************** +To capture predefined HTTP response headers as span attributes, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`` +to a comma-separated list of HTTP header names. + +For example, + +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="content-type,custom_response_header" + +will extract ``content-type`` and ``custom_response_header`` from response headers and add them as span attributes. + +It is recommended that you should give the correct names of the headers to be captured in the environment variable. +Response header names captured in ASGI are case insensitive. So, giving header name as ``CUStomHeader`` in environment variable will be able capture header with name ``customheader``. + +The name of the added span attribute will follow the format ``http.response.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ). +The value of the attribute will be single item list containing all the header values. + +Example of the added span attribute, +``http.response.header.custom_response_header = ["<value1>,<value2>"]`` + +Note: + Environment variable names to caputre http headers are still experimental, and thus are subject to change. + API --- """ diff --git a/instrumentation/opentelemetry-instrumentation-fastapi/src/opentelemetry/instrumentation/fastapi/__init__.py b/instrumentation/opentelemetry-instrumentation-fastapi/src/opentelemetry/instrumentation/fastapi/__init__.py --- a/instrumentation/opentelemetry-instrumentation-fastapi/src/opentelemetry/instrumentation/fastapi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-fastapi/src/opentelemetry/instrumentation/fastapi/__init__.py @@ -74,6 +74,58 @@ def client_response_hook(span: Span, message: dict): FastAPIInstrumentor().instrument(server_request_hook=server_request_hook, client_request_hook=client_request_hook, client_response_hook=client_response_hook) + +Capture HTTP request and response headers +***************************************** +You can configure the agent to capture predefined HTTP headers as span attributes, according to the `semantic convention <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers>`_. + +Request headers +*************** +To capture predefined HTTP request headers as span attributes, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST`` +to a comma-separated list of HTTP header names. + +For example, + +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="content-type,custom_request_header" + +will extract ``content-type`` and ``custom_request_header`` from request headers and add them as span attributes. + +It is recommended that you should give the correct names of the headers to be captured in the environment variable. +Request header names in FastAPI are case insensitive. So, giving header name as ``CUStom-Header`` in environment variable will be able capture header with name ``custom-header``. + +The name of the added span attribute will follow the format ``http.request.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ). +The value of the attribute will be single item list containing all the header values. + +Example of the added span attribute, +``http.request.header.custom_request_header = ["<value1>,<value2>"]`` + +Response headers +**************** +To capture predefined HTTP response headers as span attributes, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`` +to a comma-separated list of HTTP header names. + +For example, + +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="content-type,custom_response_header" + +will extract ``content-type`` and ``custom_response_header`` from response headers and add them as span attributes. + +It is recommended that you should give the correct names of the headers to be captured in the environment variable. +Response header names captured in FastAPI are case insensitive. So, giving header name as ``CUStomHeader`` in environment variable will be able capture header with name ``customheader``. + +The name of the added span attribute will follow the format ``http.response.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ). +The value of the attribute will be single item list containing all the header values. + +Example of the added span attribute, +``http.response.header.custom_response_header = ["<value1>,<value2>"]`` + +Note: + Environment variable names to caputre http headers are still experimental, and thus are subject to change. + API --- """
diff --git a/instrumentation/opentelemetry-instrumentation-fastapi/tests/test_fastapi_instrumentation.py b/instrumentation/opentelemetry-instrumentation-fastapi/tests/test_fastapi_instrumentation.py --- a/instrumentation/opentelemetry-instrumentation-fastapi/tests/test_fastapi_instrumentation.py +++ b/instrumentation/opentelemetry-instrumentation-fastapi/tests/test_fastapi_instrumentation.py @@ -16,6 +16,7 @@ from unittest.mock import patch import fastapi +from fastapi.responses import JSONResponse from fastapi.testclient import TestClient import opentelemetry.instrumentation.fastapi as otel_fastapi @@ -23,8 +24,13 @@ from opentelemetry.instrumentation.asgi import OpenTelemetryMiddleware from opentelemetry.sdk.resources import Resource from opentelemetry.semconv.trace import SpanAttributes +from opentelemetry.test.globals_test import reset_trace_globals from opentelemetry.test.test_base import TestBase -from opentelemetry.util.http import get_excluded_urls +from opentelemetry.util.http import ( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST, + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE, + get_excluded_urls, +) class TestFastAPIManualInstrumentation(TestBase): @@ -375,3 +381,314 @@ def test_mark_span_internal_in_presence_of_span_from_other_framework(self): self.assertEqual( parent_span.context.span_id, span_list[3].context.span_id ) + + +class TestHTTPAppWithCustomHeaders(TestBase): + def setUp(self): + super().setUp() + self.env_patch = patch.dict( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3", + }, + ) + self.env_patch.start() + self.app = self._create_app() + otel_fastapi.FastAPIInstrumentor().instrument_app(self.app) + self.client = TestClient(self.app) + + def tearDown(self) -> None: + super().tearDown() + self.env_patch.stop() + with self.disable_logging(): + otel_fastapi.FastAPIInstrumentor().uninstrument_app(self.app) + + @staticmethod + def _create_app(): + app = fastapi.FastAPI() + + @app.get("/foobar") + async def _(): + headers = { + "custom-test-header-1": "test-header-value-1", + "custom-test-header-2": "test-header-value-2", + } + content = {"message": "hello world"} + return JSONResponse(content=content, headers=headers) + + return app + + def test_http_custom_request_headers_in_span_attributes(self): + expected = { + "http.request.header.custom_test_header_1": ( + "test-header-value-1", + ), + "http.request.header.custom_test_header_2": ( + "test-header-value-2", + ), + } + resp = self.client.get( + "/foobar", + headers={ + "custom-test-header-1": "test-header-value-1", + "custom-test-header-2": "test-header-value-2", + }, + ) + self.assertEqual(200, resp.status_code) + span_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(span_list), 3) + + server_span = [ + span for span in span_list if span.kind == trace.SpanKind.SERVER + ][0] + + self.assertSpanHasAttributes(server_span, expected) + + def test_http_custom_request_headers_not_in_span_attributes(self): + not_expected = { + "http.request.header.custom_test_header_3": ( + "test-header-value-3", + ), + } + resp = self.client.get( + "/foobar", + headers={ + "custom-test-header-1": "test-header-value-1", + "custom-test-header-2": "test-header-value-2", + }, + ) + self.assertEqual(200, resp.status_code) + span_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(span_list), 3) + + server_span = [ + span for span in span_list if span.kind == trace.SpanKind.SERVER + ][0] + + for key, _ in not_expected.items(): + self.assertNotIn(key, server_span.attributes) + + def test_http_custom_response_headers_in_span_attributes(self): + expected = { + "http.response.header.custom_test_header_1": ( + "test-header-value-1", + ), + "http.response.header.custom_test_header_2": ( + "test-header-value-2", + ), + } + resp = self.client.get("/foobar") + self.assertEqual(200, resp.status_code) + span_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(span_list), 3) + + server_span = [ + span for span in span_list if span.kind == trace.SpanKind.SERVER + ][0] + self.assertSpanHasAttributes(server_span, expected) + + def test_http_custom_response_headers_not_in_span_attributes(self): + not_expected = { + "http.reponse.header.custom_test_header_3": ( + "test-header-value-3", + ), + } + resp = self.client.get("/foobar") + self.assertEqual(200, resp.status_code) + span_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(span_list), 3) + + server_span = [ + span for span in span_list if span.kind == trace.SpanKind.SERVER + ][0] + + for key, _ in not_expected.items(): + self.assertNotIn(key, server_span.attributes) + + +class TestWebSocketAppWithCustomHeaders(TestBase): + def setUp(self): + super().setUp() + self.env_patch = patch.dict( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3", + }, + ) + self.env_patch.start() + self.app = self._create_app() + otel_fastapi.FastAPIInstrumentor().instrument_app(self.app) + self.client = TestClient(self.app) + + def tearDown(self) -> None: + super().tearDown() + self.env_patch.stop() + with self.disable_logging(): + otel_fastapi.FastAPIInstrumentor().uninstrument_app(self.app) + + @staticmethod + def _create_app(): + app = fastapi.FastAPI() + + @app.websocket("/foobar_web") + async def _(websocket: fastapi.WebSocket): + message = await websocket.receive() + if message.get("type") == "websocket.connect": + await websocket.send( + { + "type": "websocket.accept", + "headers": [ + (b"custom-test-header-1", b"test-header-value-1"), + (b"custom-test-header-2", b"test-header-value-2"), + ], + } + ) + await websocket.send_json({"message": "hello world"}) + await websocket.close() + if message.get("type") == "websocket.disconnect": + pass + + return app + + def test_web_socket_custom_request_headers_in_span_attributes(self): + expected = { + "http.request.header.custom_test_header_1": ( + "test-header-value-1", + ), + "http.request.header.custom_test_header_2": ( + "test-header-value-2", + ), + } + + with self.client.websocket_connect( + "/foobar_web", + headers={ + "custom-test-header-1": "test-header-value-1", + "custom-test-header-2": "test-header-value-2", + }, + ) as websocket: + data = websocket.receive_json() + self.assertEqual(data, {"message": "hello world"}) + + span_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(span_list), 5) + + server_span = [ + span for span in span_list if span.kind == trace.SpanKind.SERVER + ][0] + + self.assertSpanHasAttributes(server_span, expected) + + def test_web_socket_custom_request_headers_not_in_span_attributes(self): + not_expected = { + "http.request.header.custom_test_header_3": ( + "test-header-value-3", + ), + } + + with self.client.websocket_connect( + "/foobar_web", + headers={ + "custom-test-header-1": "test-header-value-1", + "custom-test-header-2": "test-header-value-2", + }, + ) as websocket: + data = websocket.receive_json() + self.assertEqual(data, {"message": "hello world"}) + + span_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(span_list), 5) + + server_span = [ + span for span in span_list if span.kind == trace.SpanKind.SERVER + ][0] + + for key, _ in not_expected.items(): + self.assertNotIn(key, server_span.attributes) + + def test_web_socket_custom_response_headers_in_span_attributes(self): + expected = { + "http.response.header.custom_test_header_1": ( + "test-header-value-1", + ), + "http.response.header.custom_test_header_2": ( + "test-header-value-2", + ), + } + + with self.client.websocket_connect("/foobar_web") as websocket: + data = websocket.receive_json() + self.assertEqual(data, {"message": "hello world"}) + + span_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(span_list), 5) + + server_span = [ + span for span in span_list if span.kind == trace.SpanKind.SERVER + ][0] + + self.assertSpanHasAttributes(server_span, expected) + + def test_web_socket_custom_response_headers_not_in_span_attributes(self): + not_expected = { + "http.reponse.header.custom_test_header_3": ( + "test-header-value-3", + ), + } + + with self.client.websocket_connect("/foobar_web") as websocket: + data = websocket.receive_json() + self.assertEqual(data, {"message": "hello world"}) + + span_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(span_list), 5) + + server_span = [ + span for span in span_list if span.kind == trace.SpanKind.SERVER + ][0] + + for key, _ in not_expected.items(): + self.assertNotIn(key, server_span.attributes) + + +class TestNonRecordingSpanWithCustomHeaders(TestBase): + def setUp(self): + super().setUp() + self.env_patch = patch.dict( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3", + }, + ) + self.env_patch.start() + self.app = fastapi.FastAPI() + + @self.app.get("/foobar") + async def _(): + return {"message": "hello world"} + + reset_trace_globals() + tracer_provider = trace.NoOpTracerProvider() + trace.set_tracer_provider(tracer_provider=tracer_provider) + + self._instrumentor = otel_fastapi.FastAPIInstrumentor() + self._instrumentor.instrument_app(self.app) + self.client = TestClient(self.app) + + def tearDown(self) -> None: + super().tearDown() + with self.disable_logging(): + self._instrumentor.uninstrument_app(self.app) + + def test_custom_header_not_present_in_non_recording_span(self): + resp = self.client.get( + "/foobar", + headers={ + "custom-test-header-1": "test-header-value-1", + }, + ) + self.assertEqual(200, resp.status_code) + span_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(span_list), 0)
FastAPI: Capture request/response headers as span attributes part of #906
Hi @owais Can you assign this to me? Hi @owais I guess by mistake you have assigned this to @ashu658 instead of me. Can you please assign it to me?
2022-04-06T06:42:39
open-telemetry/opentelemetry-python-contrib
1,046
open-telemetry__opentelemetry-python-contrib-1046
[ "917" ]
3ca7e7a5a3c026961fc9331306359794ddeaec21
diff --git a/instrumentation/opentelemetry-instrumentation-fastapi/src/opentelemetry/instrumentation/fastapi/__init__.py b/instrumentation/opentelemetry-instrumentation-fastapi/src/opentelemetry/instrumentation/fastapi/__init__.py --- a/instrumentation/opentelemetry-instrumentation-fastapi/src/opentelemetry/instrumentation/fastapi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-fastapi/src/opentelemetry/instrumentation/fastapi/__init__.py @@ -74,7 +74,6 @@ def client_response_hook(span: Span, message: dict): FastAPIInstrumentor().instrument(server_request_hook=server_request_hook, client_request_hook=client_request_hook, client_response_hook=client_response_hook) - Capture HTTP request and response headers ***************************************** You can configure the agent to capture predefined HTTP headers as span attributes, according to the `semantic convention <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers>`_. @@ -93,7 +92,7 @@ def client_response_hook(span: Span, message: dict): will extract ``content-type`` and ``custom_request_header`` from request headers and add them as span attributes. It is recommended that you should give the correct names of the headers to be captured in the environment variable. -Request header names in FastAPI are case insensitive. So, giving header name as ``CUStom-Header`` in environment variable will be able capture header with name ``custom-header``. +Request header names in fastapi are case insensitive. So, giving header name as ``CUStom-Header`` in environment variable will be able capture header with name ``custom-header``. The name of the added span attribute will follow the format ``http.request.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ). The value of the attribute will be single item list containing all the header values. @@ -115,7 +114,7 @@ def client_response_hook(span: Span, message: dict): will extract ``content-type`` and ``custom_response_header`` from response headers and add them as span attributes. It is recommended that you should give the correct names of the headers to be captured in the environment variable. -Response header names captured in FastAPI are case insensitive. So, giving header name as ``CUStomHeader`` in environment variable will be able capture header with name ``customheader``. +Response header names captured in fastapi are case insensitive. So, giving header name as ``CUStomHeader`` in environment variable will be able capture header with name ``customheader``. The name of the added span attribute will follow the format ``http.response.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ). The value of the attribute will be single item list containing all the header values. diff --git a/instrumentation/opentelemetry-instrumentation-starlette/src/opentelemetry/instrumentation/starlette/__init__.py b/instrumentation/opentelemetry-instrumentation-starlette/src/opentelemetry/instrumentation/starlette/__init__.py --- a/instrumentation/opentelemetry-instrumentation-starlette/src/opentelemetry/instrumentation/starlette/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-starlette/src/opentelemetry/instrumentation/starlette/__init__.py @@ -68,6 +68,57 @@ def client_response_hook(span: Span, message: dict): StarletteInstrumentor().instrument(server_request_hook=server_request_hook, client_request_hook=client_request_hook, client_response_hook=client_response_hook) +Capture HTTP request and response headers +***************************************** +You can configure the agent to capture predefined HTTP headers as span attributes, according to the `semantic convention <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers>`_. + +Request headers +*************** +To capture predefined HTTP request headers as span attributes, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST`` +to a comma-separated list of HTTP header names. + +For example, + +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="content-type,custom_request_header" + +will extract ``content-type`` and ``custom_request_header`` from request headers and add them as span attributes. + +It is recommended that you should give the correct names of the headers to be captured in the environment variable. +Request header names in starlette are case insensitive. So, giving header name as ``CUStom-Header`` in environment variable will be able capture header with name ``custom-header``. + +The name of the added span attribute will follow the format ``http.request.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ). +The value of the attribute will be single item list containing all the header values. + +Example of the added span attribute, +``http.request.header.custom_request_header = ["<value1>,<value2>"]`` + +Response headers +**************** +To capture predefined HTTP response headers as span attributes, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`` +to a comma-separated list of HTTP header names. + +For example, + +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="content-type,custom_response_header" + +will extract ``content-type`` and ``custom_response_header`` from response headers and add them as span attributes. + +It is recommended that you should give the correct names of the headers to be captured in the environment variable. +Response header names captured in starlette are case insensitive. So, giving header name as ``CUStomHeader`` in environment variable will be able capture header with name ``customheader``. + +The name of the added span attribute will follow the format ``http.response.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ). +The value of the attribute will be single item list containing all the header values. + +Example of the added span attribute, +``http.response.header.custom_response_header = ["<value1>,<value2>"]`` + +Note: + Environment variable names to caputre http headers are still experimental, and thus are subject to change. + API --- """
diff --git a/instrumentation/opentelemetry-instrumentation-starlette/tests/test_starlette_instrumentation.py b/instrumentation/opentelemetry-instrumentation-starlette/tests/test_starlette_instrumentation.py --- a/instrumentation/opentelemetry-instrumentation-starlette/tests/test_starlette_instrumentation.py +++ b/instrumentation/opentelemetry-instrumentation-starlette/tests/test_starlette_instrumentation.py @@ -19,13 +19,24 @@ from starlette.responses import PlainTextResponse from starlette.routing import Route from starlette.testclient import TestClient +from starlette.websockets import WebSocket import opentelemetry.instrumentation.starlette as otel_starlette from opentelemetry.sdk.resources import Resource from opentelemetry.semconv.trace import SpanAttributes +from opentelemetry.test.globals_test import reset_trace_globals from opentelemetry.test.test_base import TestBase -from opentelemetry.trace import SpanKind, get_tracer -from opentelemetry.util.http import get_excluded_urls +from opentelemetry.trace import ( + NoOpTracerProvider, + SpanKind, + get_tracer, + set_tracer_provider, +) +from opentelemetry.util.http import ( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST, + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE, + get_excluded_urls, +) class TestStarletteManualInstrumentation(TestBase): @@ -244,3 +255,272 @@ def test_mark_span_internal_in_presence_of_another_span(self): self.assertEqual( parent_span.context.span_id, starlette_span.parent.span_id ) + + +class TestBaseWithCustomHeaders(TestBase): + def create_app(self): + app = self.create_starlette_app() + self._instrumentor.instrument_app(app=app) + return app + + def setUp(self): + super().setUp() + self.env_patch = patch.dict( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3", + }, + ) + self.env_patch.start() + self._instrumentor = otel_starlette.StarletteInstrumentor() + self._app = self.create_app() + self._client = TestClient(self._app) + + def tearDown(self) -> None: + super().tearDown() + self.env_patch.stop() + with self.disable_logging(): + self._instrumentor.uninstrument() + + @staticmethod + def create_starlette_app(): + app = applications.Starlette() + + @app.route("/foobar") + def _(request): + return PlainTextResponse( + content="hi", + headers={ + "custom-test-header-1": "test-header-value-1", + "custom-test-header-2": "test-header-value-2", + }, + ) + + @app.websocket_route("/foobar_web") + async def _(websocket: WebSocket) -> None: + message = await websocket.receive() + if message.get("type") == "websocket.connect": + await websocket.send( + { + "type": "websocket.accept", + "headers": [ + (b"custom-test-header-1", b"test-header-value-1"), + (b"custom-test-header-2", b"test-header-value-2"), + ], + } + ) + await websocket.send_json({"message": "hello world"}) + await websocket.close() + if message.get("type") == "websocket.disconnect": + pass + + return app + + +class TestHTTPAppWithCustomHeaders(TestBaseWithCustomHeaders): + def test_custom_request_headers_in_span_attributes(self): + expected = { + "http.request.header.custom_test_header_1": ( + "test-header-value-1", + ), + "http.request.header.custom_test_header_2": ( + "test-header-value-2", + ), + } + resp = self._client.get( + "/foobar", + headers={ + "custom-test-header-1": "test-header-value-1", + "custom-test-header-2": "test-header-value-2", + }, + ) + self.assertEqual(200, resp.status_code) + span_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(span_list), 3) + + server_span = [ + span for span in span_list if span.kind == SpanKind.SERVER + ][0] + + self.assertSpanHasAttributes(server_span, expected) + + def test_custom_request_headers_not_in_span_attributes(self): + not_expected = { + "http.request.header.custom_test_header_3": ( + "test-header-value-3", + ), + } + resp = self._client.get( + "/foobar", + headers={ + "custom-test-header-1": "test-header-value-1", + "custom-test-header-2": "test-header-value-2", + }, + ) + self.assertEqual(200, resp.status_code) + span_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(span_list), 3) + + server_span = [ + span for span in span_list if span.kind == SpanKind.SERVER + ][0] + + for key in not_expected: + self.assertNotIn(key, server_span.attributes) + + def test_custom_response_headers_in_span_attributes(self): + expected = { + "http.response.header.custom_test_header_1": ( + "test-header-value-1", + ), + "http.response.header.custom_test_header_2": ( + "test-header-value-2", + ), + } + resp = self._client.get("/foobar") + self.assertEqual(200, resp.status_code) + span_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(span_list), 3) + + server_span = [ + span for span in span_list if span.kind == SpanKind.SERVER + ][0] + + self.assertSpanHasAttributes(server_span, expected) + + def test_custom_response_headers_not_in_span_attributes(self): + not_expected = { + "http.response.header.custom_test_header_3": ( + "test-header-value-3", + ), + } + resp = self._client.get("/foobar") + self.assertEqual(200, resp.status_code) + span_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(span_list), 3) + + server_span = [ + span for span in span_list if span.kind == SpanKind.SERVER + ][0] + + for key in not_expected: + self.assertNotIn(key, server_span.attributes) + + +class TestWebSocketAppWithCustomHeaders(TestBaseWithCustomHeaders): + def test_custom_request_headers_in_span_attributes(self): + expected = { + "http.request.header.custom_test_header_1": ( + "test-header-value-1", + ), + "http.request.header.custom_test_header_2": ( + "test-header-value-2", + ), + } + with self._client.websocket_connect( + "/foobar_web", + headers={ + "custom-test-header-1": "test-header-value-1", + "custom-test-header-2": "test-header-value-2", + }, + ) as websocket: + data = websocket.receive_json() + self.assertEqual(data, {"message": "hello world"}) + + span_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(span_list), 5) + + server_span = [ + span for span in span_list if span.kind == SpanKind.SERVER + ][0] + self.assertSpanHasAttributes(server_span, expected) + + def test_custom_request_headers_not_in_span_attributes(self): + not_expected = { + "http.request.header.custom_test_header_3": ( + "test-header-value-3", + ), + } + with self._client.websocket_connect( + "/foobar_web", + headers={ + "custom-test-header-1": "test-header-value-1", + "custom-test-header-2": "test-header-value-2", + }, + ) as websocket: + data = websocket.receive_json() + self.assertEqual(data, {"message": "hello world"}) + + span_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(span_list), 5) + + server_span = [ + span for span in span_list if span.kind == SpanKind.SERVER + ][0] + + for key, _ in not_expected.items(): + self.assertNotIn(key, server_span.attributes) + + def test_custom_response_headers_in_span_attributes(self): + expected = { + "http.response.header.custom_test_header_1": ( + "test-header-value-1", + ), + "http.response.header.custom_test_header_2": ( + "test-header-value-2", + ), + } + with self._client.websocket_connect("/foobar_web") as websocket: + data = websocket.receive_json() + self.assertEqual(data, {"message": "hello world"}) + + span_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(span_list), 5) + + server_span = [ + span for span in span_list if span.kind == SpanKind.SERVER + ][0] + + self.assertSpanHasAttributes(server_span, expected) + + def test_custom_response_headers_not_in_span_attributes(self): + not_expected = { + "http.response.header.custom_test_header_3": ( + "test-header-value-3", + ), + } + with self._client.websocket_connect("/foobar_web") as websocket: + data = websocket.receive_json() + self.assertEqual(data, {"message": "hello world"}) + + span_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(span_list), 5) + + server_span = [ + span for span in span_list if span.kind == SpanKind.SERVER + ][0] + + for key, _ in not_expected.items(): + self.assertNotIn(key, server_span.attributes) + + +class TestNonRecordingSpanWithCustomHeaders(TestBaseWithCustomHeaders): + def setUp(self): + super().setUp() + reset_trace_globals() + set_tracer_provider(tracer_provider=NoOpTracerProvider()) + + self._app = self.create_app() + self._client = TestClient(self._app) + + def test_custom_header_not_present_in_non_recording_span(self): + resp = self._client.get( + "/foobar", + headers={ + "custom-test-header-1": "test-header-value-1", + }, + ) + self.assertEqual(200, resp.status_code) + span_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(span_list), 0)
Starlet: Capture request/response headers as span attributes part of #906
@owais : Can you please assign it to me?
2022-04-08T21:19:14
open-telemetry/opentelemetry-python-contrib
1,048
open-telemetry__opentelemetry-python-contrib-1048
[ "997" ]
e9f83e1292b0fe5f3478c9b23f3b5a5508481e68
diff --git a/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py b/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py --- a/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py @@ -420,14 +420,15 @@ def _finish_span(tracer, handler, error=None): status_code = error.status_code if not ctx and status_code == 404: ctx = _start_span(tracer, handler, _time_ns()) - if status_code != 404: + else: + status_code = 500 + reason = None + if status_code >= 500: finish_args = ( type(error), error, getattr(error, "__traceback__", None), ) - status_code = 500 - reason = None if not ctx: return
diff --git a/instrumentation/opentelemetry-instrumentation-tornado/tests/test_instrumentation.py b/instrumentation/opentelemetry-instrumentation-tornado/tests/test_instrumentation.py --- a/instrumentation/opentelemetry-instrumentation-tornado/tests/test_instrumentation.py +++ b/instrumentation/opentelemetry-instrumentation-tornado/tests/test_instrumentation.py @@ -317,6 +317,41 @@ def test_404(self): }, ) + def test_http_error(self): + response = self.fetch("/raise_403") + self.assertEqual(response.code, 403) + + spans = self.sorted_spans(self.memory_exporter.get_finished_spans()) + self.assertEqual(len(spans), 2) + server, client = spans + + self.assertEqual(server.name, "RaiseHTTPErrorHandler.get") + self.assertEqual(server.kind, SpanKind.SERVER) + self.assertSpanHasAttributes( + server, + { + SpanAttributes.HTTP_METHOD: "GET", + SpanAttributes.HTTP_SCHEME: "http", + SpanAttributes.HTTP_HOST: "127.0.0.1:" + + str(self.get_http_port()), + SpanAttributes.HTTP_TARGET: "/raise_403", + SpanAttributes.HTTP_CLIENT_IP: "127.0.0.1", + SpanAttributes.HTTP_STATUS_CODE: 403, + "tornado.handler": "tests.tornado_test_app.RaiseHTTPErrorHandler", + }, + ) + + self.assertEqual(client.name, "GET") + self.assertEqual(client.kind, SpanKind.CLIENT) + self.assertSpanHasAttributes( + client, + { + SpanAttributes.HTTP_URL: self.get_url("/raise_403"), + SpanAttributes.HTTP_METHOD: "GET", + SpanAttributes.HTTP_STATUS_CODE: 403, + }, + ) + def test_dynamic_handler(self): response = self.fetch("/dyna") self.assertEqual(response.code, 404) diff --git a/instrumentation/opentelemetry-instrumentation-tornado/tests/tornado_test_app.py b/instrumentation/opentelemetry-instrumentation-tornado/tests/tornado_test_app.py --- a/instrumentation/opentelemetry-instrumentation-tornado/tests/tornado_test_app.py +++ b/instrumentation/opentelemetry-instrumentation-tornado/tests/tornado_test_app.py @@ -105,6 +105,11 @@ def get(self): self.set_status(200) +class RaiseHTTPErrorHandler(tornado.web.RequestHandler): + def get(self): + raise tornado.web.HTTPError(403) + + def make_app(tracer): app = tornado.web.Application( [ @@ -116,6 +121,7 @@ def make_app(tracer): (r"/healthz", HealthCheckHandler), (r"/ping", HealthCheckHandler), (r"/test_custom_response_headers", CustomResponseHeaderHandler), + (r"/raise_403", RaiseHTTPErrorHandler), ] ) app.tracer = tracer
Tornado instrumetnation status_code 4ever 500 if error exsist Here https://github.com/open-telemetry/opentelemetry-python-contrib/blob/main/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py#L372-L379, when span finished, status_code is setting to 500, if error exists and status code from handler not equals 404. Is it correct behavior ? I see, it needed for setting description in Status. But, in this method, if status_code <=499, Status must be set to UNSET. In our case, if status_code <=499 will set ERROR. https://github.com/open-telemetry/opentelemetry-python-contrib/blob/dbb35a29465bcaf84380715c356726718724859b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/utils.py#L62-L63. Maybe needed extend this condition https://github.com/open-telemetry/opentelemetry-python-contrib/blob/main/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py#L372 to all 4xx http codes instead of just 404?
@nicholasgribanov It was unclear from the description what is the problem here? Can you explain what is the issue and how does the proposed solution fixes the issue? @srikanthccv thank's for a fast answer. In case, if I want to sampling spans on collector-level by processing with like this config: [ { name: error_policy, type: numeric_attribute, numeric_attribute: { key: "http.status_code", min_value: 500, max_value: 599 } } ] I wait spans only with http-status more when 500. But, now, it doesn't work. Beacause, on the Tornado instrumentation level, server spans with error and http-status not equal 404, will forcibly setting http.status_code to 500 https://github.com/open-telemetry/opentelemetry-python-contrib/blob/main/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py#L372-L379. You can see this here: ![Снимок экрана от 2022-03-17 11-14-30](https://user-images.githubusercontent.com/33231210/158958492-10d6046b-ce4a-4467-be55-528acb72f433.png) It's not right behavior. If you are waiting spans onlyf with http-status more than 500, you must not getting spans with 400 error. I see, it needed for setting description in Status. But, in this method, if status_code <=499, Status must be set to UNSET. In our case, if status_code <=499 will set ERROR. https://github.com/open-telemetry/opentelemetry-python-contrib/blob/dbb35a29465bcaf84380715c356726718724859b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/utils.py#L62-L63 I propose fix this and not change http.status_code, only for setting description message. Now I see, fix from my previusly message not right. Needed find way set descpription of error and not chage http.status_code. Ok, I see there is a discrepancy. I actually wonder why do we change the status code from 4XX to 500, @owais, do you have any input? Any updates ?
2022-04-11T10:48:51
open-telemetry/opentelemetry-python-contrib
1,061
open-telemetry__opentelemetry-python-contrib-1061
[ "1060" ]
c90935395fb52807490e3d50be58b6133c44b31b
diff --git a/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py b/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py --- a/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py @@ -77,7 +77,10 @@ import psutil from opentelemetry._metrics import get_meter -from opentelemetry._metrics.measurement import Measurement + +# FIXME Remove this pyling disabling line when Github issue is cleared +# pylint: disable=no-name-in-module +from opentelemetry._metrics.observation import Observation from opentelemetry.instrumentation.instrumentor import BaseInstrumentor from opentelemetry.instrumentation.system_metrics.package import _instruments from opentelemetry.instrumentation.system_metrics.version import __version__ @@ -318,18 +321,18 @@ def _instrument(self, **kwargs): def _uninstrument(self, **__): pass - def _get_system_cpu_time(self) -> Iterable[Measurement]: + def _get_system_cpu_time(self) -> Iterable[Observation]: """Observer callback for system CPU time""" for cpu, times in enumerate(psutil.cpu_times(percpu=True)): for metric in self._config["system.cpu.time"]: if hasattr(times, metric): self._system_cpu_time_labels["state"] = metric self._system_cpu_time_labels["cpu"] = cpu + 1 - yield Measurement( + yield Observation( getattr(times, metric), self._system_cpu_time_labels ) - def _get_system_cpu_utilization(self) -> Iterable[Measurement]: + def _get_system_cpu_utilization(self) -> Iterable[Observation]: """Observer callback for system CPU utilization""" for cpu, times_percent in enumerate( @@ -339,95 +342,95 @@ def _get_system_cpu_utilization(self) -> Iterable[Measurement]: if hasattr(times_percent, metric): self._system_cpu_utilization_labels["state"] = metric self._system_cpu_utilization_labels["cpu"] = cpu + 1 - yield Measurement( + yield Observation( getattr(times_percent, metric) / 100, self._system_cpu_utilization_labels, ) - def _get_system_memory_usage(self) -> Iterable[Measurement]: + def _get_system_memory_usage(self) -> Iterable[Observation]: """Observer callback for memory usage""" virtual_memory = psutil.virtual_memory() for metric in self._config["system.memory.usage"]: self._system_memory_usage_labels["state"] = metric if hasattr(virtual_memory, metric): - yield Measurement( + yield Observation( getattr(virtual_memory, metric), self._system_memory_usage_labels, ) - def _get_system_memory_utilization(self) -> Iterable[Measurement]: + def _get_system_memory_utilization(self) -> Iterable[Observation]: """Observer callback for memory utilization""" system_memory = psutil.virtual_memory() for metric in self._config["system.memory.utilization"]: self._system_memory_utilization_labels["state"] = metric if hasattr(system_memory, metric): - yield Measurement( + yield Observation( getattr(system_memory, metric) / system_memory.total, self._system_memory_utilization_labels, ) - def _get_system_swap_usage(self) -> Iterable[Measurement]: + def _get_system_swap_usage(self) -> Iterable[Observation]: """Observer callback for swap usage""" system_swap = psutil.swap_memory() for metric in self._config["system.swap.usage"]: self._system_swap_usage_labels["state"] = metric if hasattr(system_swap, metric): - yield Measurement( + yield Observation( getattr(system_swap, metric), self._system_swap_usage_labels, ) - def _get_system_swap_utilization(self) -> Iterable[Measurement]: + def _get_system_swap_utilization(self) -> Iterable[Observation]: """Observer callback for swap utilization""" system_swap = psutil.swap_memory() for metric in self._config["system.swap.utilization"]: if hasattr(system_swap, metric): self._system_swap_utilization_labels["state"] = metric - yield Measurement( + yield Observation( getattr(system_swap, metric) / system_swap.total, self._system_swap_utilization_labels, ) - def _get_system_disk_io(self) -> Iterable[Measurement]: + def _get_system_disk_io(self) -> Iterable[Observation]: """Observer callback for disk IO""" for device, counters in psutil.disk_io_counters(perdisk=True).items(): for metric in self._config["system.disk.io"]: if hasattr(counters, f"{metric}_bytes"): self._system_disk_io_labels["device"] = device self._system_disk_io_labels["direction"] = metric - yield Measurement( + yield Observation( getattr(counters, f"{metric}_bytes"), self._system_disk_io_labels, ) - def _get_system_disk_operations(self) -> Iterable[Measurement]: + def _get_system_disk_operations(self) -> Iterable[Observation]: """Observer callback for disk operations""" for device, counters in psutil.disk_io_counters(perdisk=True).items(): for metric in self._config["system.disk.operations"]: if hasattr(counters, f"{metric}_count"): self._system_disk_operations_labels["device"] = device self._system_disk_operations_labels["direction"] = metric - yield Measurement( + yield Observation( getattr(counters, f"{metric}_count"), self._system_disk_operations_labels, ) - def _get_system_disk_time(self) -> Iterable[Measurement]: + def _get_system_disk_time(self) -> Iterable[Observation]: """Observer callback for disk time""" for device, counters in psutil.disk_io_counters(perdisk=True).items(): for metric in self._config["system.disk.time"]: if hasattr(counters, f"{metric}_time"): self._system_disk_time_labels["device"] = device self._system_disk_time_labels["direction"] = metric - yield Measurement( + yield Observation( getattr(counters, f"{metric}_time") / 1000, self._system_disk_time_labels, ) - def _get_system_disk_merged(self) -> Iterable[Measurement]: + def _get_system_disk_merged(self) -> Iterable[Observation]: """Observer callback for disk merged operations""" # FIXME The units in the spec is 1, it seems like it should be @@ -438,12 +441,12 @@ def _get_system_disk_merged(self) -> Iterable[Measurement]: if hasattr(counters, f"{metric}_merged_count"): self._system_disk_merged_labels["device"] = device self._system_disk_merged_labels["direction"] = metric - yield Measurement( + yield Observation( getattr(counters, f"{metric}_merged_count"), self._system_disk_merged_labels, ) - def _get_system_network_dropped_packets(self) -> Iterable[Measurement]: + def _get_system_network_dropped_packets(self) -> Iterable[Observation]: """Observer callback for network dropped packets""" for device, counters in psutil.net_io_counters(pernic=True).items(): @@ -456,12 +459,12 @@ def _get_system_network_dropped_packets(self) -> Iterable[Measurement]: self._system_network_dropped_packets_labels[ "direction" ] = metric - yield Measurement( + yield Observation( getattr(counters, f"drop{in_out}"), self._system_network_dropped_packets_labels, ) - def _get_system_network_packets(self) -> Iterable[Measurement]: + def _get_system_network_packets(self) -> Iterable[Observation]: """Observer callback for network packets""" for device, counters in psutil.net_io_counters(pernic=True).items(): @@ -470,12 +473,12 @@ def _get_system_network_packets(self) -> Iterable[Measurement]: if hasattr(counters, f"packets_{recv_sent}"): self._system_network_packets_labels["device"] = device self._system_network_packets_labels["direction"] = metric - yield Measurement( + yield Observation( getattr(counters, f"packets_{recv_sent}"), self._system_network_packets_labels, ) - def _get_system_network_errors(self) -> Iterable[Measurement]: + def _get_system_network_errors(self) -> Iterable[Observation]: """Observer callback for network errors""" for device, counters in psutil.net_io_counters(pernic=True).items(): for metric in self._config["system.network.errors"]: @@ -483,12 +486,12 @@ def _get_system_network_errors(self) -> Iterable[Measurement]: if hasattr(counters, f"err{in_out}"): self._system_network_errors_labels["device"] = device self._system_network_errors_labels["direction"] = metric - yield Measurement( + yield Observation( getattr(counters, f"err{in_out}"), self._system_network_errors_labels, ) - def _get_system_network_io(self) -> Iterable[Measurement]: + def _get_system_network_io(self) -> Iterable[Observation]: """Observer callback for network IO""" for device, counters in psutil.net_io_counters(pernic=True).items(): @@ -497,12 +500,12 @@ def _get_system_network_io(self) -> Iterable[Measurement]: if hasattr(counters, f"bytes_{recv_sent}"): self._system_network_io_labels["device"] = device self._system_network_io_labels["direction"] = metric - yield Measurement( + yield Observation( getattr(counters, f"bytes_{recv_sent}"), self._system_network_io_labels, ) - def _get_system_network_connections(self) -> Iterable[Measurement]: + def _get_system_network_connections(self) -> Iterable[Observation]: """Observer callback for network connections""" # TODO How to find the device identifier for a particular # connection? @@ -535,35 +538,35 @@ def _get_system_network_connections(self) -> Iterable[Measurement]: } for connection_counter in connection_counters.values(): - yield Measurement( + yield Observation( connection_counter["counter"], connection_counter["labels"], ) - def _get_runtime_memory(self) -> Iterable[Measurement]: + def _get_runtime_memory(self) -> Iterable[Observation]: """Observer callback for runtime memory""" proc_memory = self._proc.memory_info() for metric in self._config["runtime.memory"]: if hasattr(proc_memory, metric): self._runtime_memory_labels["type"] = metric - yield Measurement( + yield Observation( getattr(proc_memory, metric), self._runtime_memory_labels, ) - def _get_runtime_cpu_time(self) -> Iterable[Measurement]: + def _get_runtime_cpu_time(self) -> Iterable[Observation]: """Observer callback for runtime CPU time""" proc_cpu = self._proc.cpu_times() for metric in self._config["runtime.cpu.time"]: if hasattr(proc_cpu, metric): self._runtime_cpu_time_labels["type"] = metric - yield Measurement( + yield Observation( getattr(proc_cpu, metric), self._runtime_cpu_time_labels, ) - def _get_runtime_gc_count(self) -> Iterable[Measurement]: + def _get_runtime_gc_count(self) -> Iterable[Observation]: """Observer callback for garbage collection""" for index, count in enumerate(gc.get_count()): self._runtime_gc_count_labels["count"] = str(index) - yield Measurement(count, self._runtime_gc_count_labels) + yield Observation(count, self._runtime_gc_count_labels)
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -6,7 +6,7 @@ on: - 'release/*' pull_request: env: - CORE_REPO_SHA: 516bf8ad04d628b20c103622f390f7a536142e9a + CORE_REPO_SHA: 7647a11774a029ead5e8ac864e6f55e9d06f463e jobs: build:
Rename Measurement to Observation From [this](https://github.com/open-telemetry/opentelemetry-python/pull/2617#issuecomment-1101830863) comment.
2022-04-18T23:09:02
open-telemetry/opentelemetry-python-contrib
1,066
open-telemetry__opentelemetry-python-contrib-1066
[ "1050" ]
2f7a666560343634577887e242629e432db9d587
diff --git a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/auto_instrumentation/sitecustomize.py b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/auto_instrumentation/sitecustomize.py --- a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/auto_instrumentation/sitecustomize.py +++ b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/auto_instrumentation/sitecustomize.py @@ -110,6 +110,13 @@ def _load_configurators(): def initialize(): + # prevents auto-instrumentation of subprocesses if code execs another python process + environ["PYTHONPATH"] = sub( + rf"{dirname(abspath(__file__))}{pathsep}?", + "", + environ["PYTHONPATH"], + ) + try: distro = _load_distros() distro.configure() @@ -117,12 +124,6 @@ def initialize(): _load_instrumentors(distro) except Exception: # pylint: disable=broad-except logger.exception("Failed to auto initialize opentelemetry") - finally: - environ["PYTHONPATH"] = sub( - rf"{dirname(abspath(__file__))}{pathsep}?", - "", - environ["PYTHONPATH"], - ) initialize()
opentelemetry-instrument command can cause recursive creation of subprocesses **Describe your environment** Python3.9, linux. **Steps to reproduce** Using `opentelemetry-instrument` with any exporter or instrumentation which invokes a python subprocess **during initialization**. For example, the `opentelemetry-exporter-gcp-trace` exporter may invoke the `gcloud` (written in python) command in a subprocess to get project information and authentication tokens. The subprocess will then try to autoinstrument, creating a recursive loop of subprocesses being created. **What is the expected behavior?** Auto-instrumentation should not apply to subprocesses created in the `initialize()` phase of auto-instrumentation. The `PYTHONPATH` environment variable should have the `sitecustomize.py` dirname stripped out at the beginning of `sitecustomize.py`. This would prevent subprocesses from being autoinstrumented during setup, which can cause a loop. **What is the actual behavior?** `PYTHONPATH` is correctly stripped later on to avoid this https://github.com/open-telemetry/opentelemetry-python-contrib/blob/e9f83e1292b0fe5f3478c9b23f3b5a5508481e68/opentelemetry-instrumentation/src/opentelemetry/instrumentation/auto_instrumentation/sitecustomize.py#L120-L125 However, any subprocesses created in [these lines](https://github.com/open-telemetry/opentelemetry-python-contrib/blob/e9f83e1292b0fe5f3478c9b23f3b5a5508481e68/opentelemetry-instrumentation/src/opentelemetry/instrumentation/auto_instrumentation/sitecustomize.py#L114-L117) will cause a loop. **Additional context** I can write a repro if necessary.
2022-04-20T21:29:21
open-telemetry/opentelemetry-python-contrib
1,072
open-telemetry__opentelemetry-python-contrib-1072
[ "939" ]
9e539391b21f741fc0cdc2b139e652199776bca6
diff --git a/instrumentation/opentelemetry-instrumentation-aiohttp-client/src/opentelemetry/instrumentation/aiohttp_client/__init__.py b/instrumentation/opentelemetry-instrumentation-aiohttp-client/src/opentelemetry/instrumentation/aiohttp_client/__init__.py --- a/instrumentation/opentelemetry-instrumentation-aiohttp-client/src/opentelemetry/instrumentation/aiohttp_client/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-aiohttp-client/src/opentelemetry/instrumentation/aiohttp_client/__init__.py @@ -180,27 +180,24 @@ async def on_request_start( http_method = params.method.upper() request_span_name = f"HTTP {http_method}" + request_url = ( + remove_url_credentials(trace_config_ctx.url_filter(params.url)) + if callable(trace_config_ctx.url_filter) + else remove_url_credentials(str(params.url)) + ) + + span_attributes = { + SpanAttributes.HTTP_METHOD: http_method, + SpanAttributes.HTTP_URL: request_url, + } trace_config_ctx.span = trace_config_ctx.tracer.start_span( - request_span_name, - kind=SpanKind.CLIENT, + request_span_name, kind=SpanKind.CLIENT, attributes=span_attributes ) if callable(request_hook): request_hook(trace_config_ctx.span, params) - if trace_config_ctx.span.is_recording(): - attributes = { - SpanAttributes.HTTP_METHOD: http_method, - SpanAttributes.HTTP_URL: remove_url_credentials( - trace_config_ctx.url_filter(params.url) - ) - if callable(trace_config_ctx.url_filter) - else remove_url_credentials(str(params.url)), - } - for key, value in attributes.items(): - trace_config_ctx.span.set_attribute(key, value) - trace_config_ctx.token = context_api.attach( trace.set_span_in_context(trace_config_ctx.span) )
opentelemetry-instrumentation-aiohttp-client
I would like to take this issue.
2022-04-27T21:24:38
open-telemetry/opentelemetry-python-contrib
1,079
open-telemetry__opentelemetry-python-contrib-1079
[ "1073" ]
f7fd1e069313dce6c4939146ade173a727cc4104
diff --git a/instrumentation/opentelemetry-instrumentation-aiohttp-client/src/opentelemetry/instrumentation/aiohttp_client/__init__.py b/instrumentation/opentelemetry-instrumentation-aiohttp-client/src/opentelemetry/instrumentation/aiohttp_client/__init__.py --- a/instrumentation/opentelemetry-instrumentation-aiohttp-client/src/opentelemetry/instrumentation/aiohttp_client/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-aiohttp-client/src/opentelemetry/instrumentation/aiohttp_client/__init__.py @@ -262,18 +262,24 @@ def _instrument( url_filter: _UrlFilterT = None, request_hook: _RequestHookT = None, response_hook: _ResponseHookT = None, + trace_configs: typing.Optional[aiohttp.TraceConfig] = None, ): """Enables tracing of all ClientSessions When a ClientSession gets created a TraceConfig is automatically added to the session's trace_configs. """ + + if trace_configs is None: + trace_configs = [] + # pylint:disable=unused-argument def instrumented_init(wrapped, instance, args, kwargs): if context_api.get_value(_SUPPRESS_INSTRUMENTATION_KEY): return wrapped(*args, **kwargs) - trace_configs = list(kwargs.get("trace_configs") or ()) + if kwargs.get("trace_configs"): + trace_configs.extend(kwargs.get("trace_configs")) trace_config = create_trace_config( url_filter=url_filter, @@ -328,12 +334,15 @@ def _instrument(self, **kwargs): such as API keys or user personal information. ``request_hook``: An optional callback that is invoked right after a span is created. ``response_hook``: An optional callback which is invoked right before the span is finished processing a response. + ``trace_configs``: An optional list of aiohttp.TraceConfig items, allowing customize enrichment of spans + based on aiohttp events (see specification: https://docs.aiohttp.org/en/stable/tracing_reference.html) """ _instrument( tracer_provider=kwargs.get("tracer_provider"), url_filter=kwargs.get("url_filter"), request_hook=kwargs.get("request_hook"), response_hook=kwargs.get("response_hook"), + trace_configs=kwargs.get("trace_configs"), ) def _uninstrument(self, **kwargs):
diff --git a/instrumentation/opentelemetry-instrumentation-aiohttp-client/tests/test_aiohttp_client_integration.py b/instrumentation/opentelemetry-instrumentation-aiohttp-client/tests/test_aiohttp_client_integration.py --- a/instrumentation/opentelemetry-instrumentation-aiohttp-client/tests/test_aiohttp_client_integration.py +++ b/instrumentation/opentelemetry-instrumentation-aiohttp-client/tests/test_aiohttp_client_integration.py @@ -386,6 +386,20 @@ def test_instrument(self): ) self.assertEqual(200, span.attributes[SpanAttributes.HTTP_STATUS_CODE]) + def test_instrument_with_custom_trace_config(self): + AioHttpClientInstrumentor().uninstrument() + AioHttpClientInstrumentor().instrument( + trace_configs=[aiohttp_client.create_trace_config()] + ) + + self.assert_spans(0) + + run_with_test_server( + self.get_default_request(), self.URL, self.default_handler + ) + + self.assert_spans(2) + def test_instrument_with_existing_trace_config(self): trace_config = aiohttp.TraceConfig() @@ -432,7 +446,7 @@ async def uninstrument_request(server: aiohttp.test_utils.TestServer): run_with_test_server( self.get_default_request(), self.URL, self.default_handler ) - self.assert_spans(1) + self.assert_spans(2) def test_suppress_instrumentation(self): token = context.attach(
Inject trace_configs as an argument to opentelemetry aiohttp_client._instrument instrumentation **Is your feature request related to a problem?** I would like to add data to a span based on on_request_chunk_sent event. Using the request/response hooks doesn't provide a good solution for my use case since it's "too late" in the timeline. **Describe the solution you'd like** I would like to pass trace_configs (or a single trace_config) to aiohttp_client opentelemetry instrumentation. It will allow me to specify which events I would like to "catch" and will allow more customization solving many use-cases that the request/response hooks cannot. **Describe alternatives you've considered** I've doubled the instrument_init method and set it up with my own trace_configs, bypassing opentelemetry implementation. **Additional context** If this issue will be approved I would like to contribute my solution, thanks
@nemoshlag Can you share little example of what this change/solution looks like and what are you trying to achieve? Hi @srikanthccv sure, pseudo usage from client side: `def trace_config(...)-> aiohttp.TraceConfig: async def on_request_chunk_sent(...): # do stuff AioHttpClientInstrumentor._instument(tracer_provider, request_hook, response_hook, trace_configs=trace_config)` And on opentelemetry instrumentation side: `def _instrument(tracer_provider: TracerProvider = None, args, kwargs): def instrumented_init(wrapped, instance, args, kwargs) -> None: trace_configs = list(kwargs.get("trace_configs") or ()) trace_config = create_trace_config( tracer_provider=tracer_provider, request_hook=kwargs.get("request_hook"), response_hook=kwargs.get("response_hook"), ) trace_configs.append(trace_config) ...` Feel free to send a PR.
2022-05-01T12:50:40
open-telemetry/opentelemetry-python-contrib
1,086
open-telemetry__opentelemetry-python-contrib-1086
[ "922", "922" ]
3e67893cbab3d920dcb80de7e1d2af84f8576b06
diff --git a/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/__init__.py b/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/__init__.py --- a/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/__init__.py @@ -104,7 +104,7 @@ def _instrument(self, **kwargs): if kwargs.get("engine") is not None: return EngineTracer( - _get_tracer(kwargs.get("engine"), tracer_provider), + _get_tracer(tracer_provider), kwargs.get("engine"), kwargs.get("enable_commenter", False), ) diff --git a/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/engine.py b/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/engine.py --- a/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/engine.py +++ b/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/engine.py @@ -16,6 +16,9 @@ from sqlalchemy.event import listen # pylint: disable=no-name-in-module from opentelemetry import trace +from opentelemetry.instrumentation.sqlalchemy.package import ( + _instrumenting_module_name, +) from opentelemetry.instrumentation.sqlalchemy.version import __version__ from opentelemetry.instrumentation.utils import ( _generate_opentelemetry_traceparent, @@ -40,9 +43,9 @@ def _normalize_vendor(vendor): return vendor -def _get_tracer(engine, tracer_provider=None): +def _get_tracer(tracer_provider=None): return trace.get_tracer( - _normalize_vendor(engine.name), + _instrumenting_module_name, __version__, tracer_provider=tracer_provider, ) @@ -55,7 +58,7 @@ def _wrap_create_async_engine_internal(func, module, args, kwargs): object that will listen to SQLAlchemy events. """ engine = func(*args, **kwargs) - EngineTracer(_get_tracer(engine, tracer_provider), engine.sync_engine) + EngineTracer(_get_tracer(tracer_provider), engine.sync_engine) return engine return _wrap_create_async_engine_internal @@ -68,7 +71,7 @@ def _wrap_create_engine_internal(func, module, args, kwargs): object that will listen to SQLAlchemy events. """ engine = func(*args, **kwargs) - EngineTracer(_get_tracer(engine, tracer_provider), engine) + EngineTracer(_get_tracer(tracer_provider), engine) return engine return _wrap_create_engine_internal diff --git a/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/package.py b/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/package.py --- a/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/package.py +++ b/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/package.py @@ -12,5 +12,6 @@ # See the License for the specific language governing permissions and # limitations under the License. +_instrumenting_module_name = "opentelemetry.instrumentation.sqlalchemy" _instruments = ("sqlalchemy",)
diff --git a/instrumentation/opentelemetry-instrumentation-sqlalchemy/tests/test_sqlalchemy.py b/instrumentation/opentelemetry-instrumentation-sqlalchemy/tests/test_sqlalchemy.py --- a/instrumentation/opentelemetry-instrumentation-sqlalchemy/tests/test_sqlalchemy.py +++ b/instrumentation/opentelemetry-instrumentation-sqlalchemy/tests/test_sqlalchemy.py @@ -70,6 +70,10 @@ async def run(): self.assertEqual(len(spans), 1) self.assertEqual(spans[0].name, "SELECT :memory:") self.assertEqual(spans[0].kind, trace.SpanKind.CLIENT) + self.assertEqual( + spans[0].instrumentation_scope.name, + "opentelemetry.instrumentation.sqlalchemy", + ) asyncio.get_event_loop().run_until_complete(run()) @@ -104,6 +108,10 @@ def test_create_engine_wrapper(self): self.assertEqual(len(spans), 1) self.assertEqual(spans[0].name, "SELECT :memory:") self.assertEqual(spans[0].kind, trace.SpanKind.CLIENT) + self.assertEqual( + spans[0].instrumentation_scope.name, + "opentelemetry.instrumentation.sqlalchemy", + ) def test_custom_tracer_provider(self): provider = TracerProvider( @@ -154,6 +162,10 @@ async def run(): self.assertEqual(len(spans), 1) self.assertEqual(spans[0].name, "SELECT :memory:") self.assertEqual(spans[0].kind, trace.SpanKind.CLIENT) + self.assertEqual( + spans[0].instrumentation_scope.name, + "opentelemetry.instrumentation.sqlalchemy", + ) asyncio.get_event_loop().run_until_complete(run())
SQLAlchemy instrumentation sets `otel.library.name` as the vendor, not the library name **Describe your environment** * Python 3.9.6 * `opentelemetry.instrumentation.sqlalchemy==0.28b1` **Steps to reproduce** Create an application that leverages SQLAlchemy and MySQL (or any vendor; I just used MySQL) Install `opentelemetry.instrumentation.sqlalchemy==0.28b1` Make a request to your backend application. Observe the resulting spans. **What is the expected behavior?** The `otel.library.name` should report as `opentelemetry.instrumentation.sqlalchemy`. **What is the actual behavior?** The `otel.library.name` is the [DB vendor](https://github.com/open-telemetry/opentelemetry-python-contrib/blob/main/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/engine.py#L40). In my case, it's `mysql`: ![Screen Shot 2022-02-14 at 4 30 49 PM](https://user-images.githubusercontent.com/33907262/153949771-2d8f3e64-b7c6-4b6e-907a-15c687b8bf8e.png) This is super confusing when there is a separate [`opentelemetry.instrumentation.mysql`](https://github.com/open-telemetry/opentelemetry-python-contrib/tree/main/instrumentation/opentelemetry-instrumentation-mysql) package that I'm not using. **Additional context** Nope! SQLAlchemy instrumentation sets `otel.library.name` as the vendor, not the library name **Describe your environment** * Python 3.9.6 * `opentelemetry.instrumentation.sqlalchemy==0.28b1` **Steps to reproduce** Create an application that leverages SQLAlchemy and MySQL (or any vendor; I just used MySQL) Install `opentelemetry.instrumentation.sqlalchemy==0.28b1` Make a request to your backend application. Observe the resulting spans. **What is the expected behavior?** The `otel.library.name` should report as `opentelemetry.instrumentation.sqlalchemy`. **What is the actual behavior?** The `otel.library.name` is the [DB vendor](https://github.com/open-telemetry/opentelemetry-python-contrib/blob/main/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/engine.py#L40). In my case, it's `mysql`: ![Screen Shot 2022-02-14 at 4 30 49 PM](https://user-images.githubusercontent.com/33907262/153949771-2d8f3e64-b7c6-4b6e-907a-15c687b8bf8e.png) This is super confusing when there is a separate [`opentelemetry.instrumentation.mysql`](https://github.com/open-telemetry/opentelemetry-python-contrib/tree/main/instrumentation/opentelemetry-instrumentation-mysql) package that I'm not using. **Additional context** Nope!
2022-05-10T17:02:50
open-telemetry/opentelemetry-python-contrib
1,089
open-telemetry__opentelemetry-python-contrib-1089
[ "1088" ]
10659f897086fe6037f14caece570a75b932a3ba
diff --git a/sdk-extension/opentelemetry-sdk-extension-aws/src/opentelemetry/sdk/extension/aws/resource/ec2.py b/sdk-extension/opentelemetry-sdk-extension-aws/src/opentelemetry/sdk/extension/aws/resource/ec2.py --- a/sdk-extension/opentelemetry-sdk-extension-aws/src/opentelemetry/sdk/extension/aws/resource/ec2.py +++ b/sdk-extension/opentelemetry-sdk-extension-aws/src/opentelemetry/sdk/extension/aws/resource/ec2.py @@ -34,7 +34,7 @@ def _aws_http_request(method, path, headers): Request( "http://169.254.169.254" + path, headers=headers, method=method ), - timeout=1000, + timeout=5, ) as response: return response.read().decode("utf-8") diff --git a/sdk-extension/opentelemetry-sdk-extension-aws/src/opentelemetry/sdk/extension/aws/resource/eks.py b/sdk-extension/opentelemetry-sdk-extension-aws/src/opentelemetry/sdk/extension/aws/resource/eks.py --- a/sdk-extension/opentelemetry-sdk-extension-aws/src/opentelemetry/sdk/extension/aws/resource/eks.py +++ b/sdk-extension/opentelemetry-sdk-extension-aws/src/opentelemetry/sdk/extension/aws/resource/eks.py @@ -37,7 +37,7 @@ def _aws_http_request(method, path, cred_value): headers={"Authorization": cred_value}, method=method, ), - timeout=2000, + timeout=5, context=ssl.create_default_context( cafile="/var/run/secrets/kubernetes.io/serviceaccount/ca.crt" ),
EC2 resource detector hangs for a long time outside of an EC2 instance **Describe your environment** Describe any aspect of your environment relevant to the problem, including your Python version, [platform](https://docs.python.org/3/library/platform.html), version numbers of installed dependencies, information about your cloud hosting provider, etc. If you're reporting a problem with a specific version of a library in this repo, please check whether the problem has been fixed on main. The environment I initially saw this in was a container running in Docker compose on an AWS EC2 instance but I've been able to reproduce it on my laptop as well. I think it will show up in anything not directly running in AWS. **Steps to reproduce** Describe exactly how to reproduce the error. Include a code sample if applicable. The following code reproduced the issue on my laptop: ```python from opentelemetry.sdk.extension.aws.resource.ec2 import AwsEc2ResourceDetector from opentelemetry.sdk.resources import get_aggregated_resources resource = get_aggregated_resources( detectors=[AwsEc2ResourceDetector()] ) ``` **What is the expected behavior?** It should complete quickly (this is the behavior I see running on an EC2 instance). **What is the actual behavior?** What did you see instead? On my laptop, it will hand ~indefinitely. Note: one solution is just to remove the resource detector but we'd like to be able to include it and just have it fail silently, which is the behavior we've seen in other resource detectors. **Additional context** I think the problem is here: https://github.com/open-telemetry/opentelemetry-python-contrib/blob/80969a06da77d1e616124de178d12a1ebe3ffe7f/sdk-extension/opentelemetry-sdk-extension-aws/src/opentelemetry/sdk/extension/aws/resource/ec2.py#L37 It looks like the request is using a 1000 _second_ timeout which I suspect is intended to be a 1000 _millisecond_ timeout. At least with the server program I've been working on that will block the startup of the program until the request completes. You can verify by running: ``` curl http://169.254.169.254/latest/api/token ``` Which is one of the requests that the resource detector makes -- it should hang indefinitely as well.
2022-05-13T21:45:58
open-telemetry/opentelemetry-python-contrib
1,093
open-telemetry__opentelemetry-python-contrib-1093
[ "1092" ]
80969a06da77d1e616124de178d12a1ebe3ffe7f
diff --git a/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py b/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py --- a/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py @@ -42,10 +42,10 @@ .. code:: python - from opentelemetry._metrics import set_meter_provider + from opentelemetry.metrics import set_meter_provider from opentelemetry.instrumentation.system_metrics import SystemMetricsInstrumentor - from opentelemetry.sdk._metrics import MeterProvider - from opentelemetry.sdk._metrics.export import ConsoleMetricExporter, PeriodicExportingMetricReader + from opentelemetry.sdk.metrics import MeterProvider + from opentelemetry.sdk.metrics.export import ConsoleMetricExporter, PeriodicExportingMetricReader exporter = ConsoleMetricExporter() @@ -76,13 +76,12 @@ import psutil -from opentelemetry._metrics import CallbackOptions, Observation, get_meter - # FIXME Remove this pyling disabling line when Github issue is cleared # pylint: disable=no-name-in-module from opentelemetry.instrumentation.instrumentor import BaseInstrumentor from opentelemetry.instrumentation.system_metrics.package import _instruments from opentelemetry.instrumentation.system_metrics.version import __version__ +from opentelemetry.metrics import CallbackOptions, Observation, get_meter from opentelemetry.sdk.util import get_dict_as_key _DEFAULT_CONFIG = {
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -6,7 +6,7 @@ on: - 'release/*' pull_request: env: - CORE_REPO_SHA: f367ec2045b2588be95dfa11913868c1d4fcbbc2 + CORE_REPO_SHA: 741389585b5d6d1af808a8939c5348113158f969 jobs: build: @@ -37,7 +37,7 @@ jobs: run: pip install -U tox-factor - name: Cache tox environment # Preserves .tox directory between runs for faster installs - uses: actions/cache@v2 + uses: actions/cache@v1 with: path: | .tox @@ -113,7 +113,7 @@ jobs: run: sudo apt-get install -y libsnappy-dev - name: Cache tox environment # Preserves .tox directory between runs for faster installs - uses: actions/cache@v2 + uses: actions/cache@v1 with: path: | .tox diff --git a/instrumentation/opentelemetry-instrumentation-system-metrics/tests/test_system_metrics.py b/instrumentation/opentelemetry-instrumentation-system-metrics/tests/test_system_metrics.py --- a/instrumentation/opentelemetry-instrumentation-system-metrics/tests/test_system_metrics.py +++ b/instrumentation/opentelemetry-instrumentation-system-metrics/tests/test_system_metrics.py @@ -21,8 +21,8 @@ from opentelemetry.instrumentation.system_metrics import ( SystemMetricsInstrumentor, ) -from opentelemetry.sdk._metrics import MeterProvider -from opentelemetry.sdk._metrics.export import InMemoryMetricReader +from opentelemetry.sdk.metrics import MeterProvider +from opentelemetry.sdk.metrics.export import InMemoryMetricReader from opentelemetry.test.test_base import TestBase @@ -70,8 +70,11 @@ def test_system_metrics_instrument(self): meter_provider = MeterProvider(metric_readers=[reader]) system_metrics = SystemMetricsInstrumentor() system_metrics.instrument(meter_provider=meter_provider) - metrics = reader.get_metrics() - metric_names = list({x.name for x in metrics}) + metric_names = [] + for resource_metrics in reader.get_metrics_data().resource_metrics: + for scope_metrics in resource_metrics.scope_metrics: + for metric in scope_metrics.metrics: + metric_names.append(metric.name) self.assertEqual(len(metric_names), 17) observer_names = [ @@ -100,17 +103,22 @@ def test_system_metrics_instrument(self): def _assert_metrics(self, observer_name, reader, expected): assertions = 0 - for metric in reader.get_metrics(): # pylint: disable=protected-access - for expect in expected: - if ( - metric.attributes == expect.attributes - and metric.name == observer_name - ): - self.assertEqual( - metric.point.value, - expect.value, - ) - assertions += 1 + # pylint: disable=too-many-nested-blocks + for resource_metrics in reader.get_metrics_data().resource_metrics: + for scope_metrics in resource_metrics.scope_metrics: + for metric in scope_metrics.metrics: + for data_point in metric.data.data_points: + for expect in expected: + if ( + dict(data_point.attributes) + == expect.attributes + and metric.name == observer_name + ): + self.assertEqual( + data_point.value, + expect.value, + ) + assertions += 1 self.assertEqual(len(expected), assertions) def _test_metrics(self, observer_name, expected):
Make metrics public Similar to [this](https://github.com/open-telemetry/opentelemetry-python/pull/2684).
2022-05-16T21:46:07
open-telemetry/opentelemetry-python-contrib
1,097
open-telemetry__opentelemetry-python-contrib-1097
[ "1077" ]
8afbce753332729739f84e477d993d267d2c3551
diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py b/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py --- a/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py @@ -214,8 +214,8 @@ def uninstrument_connection(connection): Returns: An uninstrumented connection. """ - if isinstance(connection, wrapt.ObjectProxy): - return connection.__wrapped__ + if isinstance(connection, _TracedConnectionProxy): + return connection._connection _logger.warning("Connection is not instrumented") return connection @@ -300,28 +300,35 @@ def get_connection_attributes(self, connection): self.span_attributes[SpanAttributes.NET_PEER_PORT] = port +class _TracedConnectionProxy: + pass + + def get_traced_connection_proxy( connection, db_api_integration, *args, **kwargs ): # pylint: disable=abstract-method - class TracedConnectionProxy(wrapt.ObjectProxy): - # pylint: disable=unused-argument - def __init__(self, connection, *args, **kwargs): - wrapt.ObjectProxy.__init__(self, connection) + class TracedConnectionProxy(type(connection), _TracedConnectionProxy): + def __init__(self, connection): + self._connection = connection + + def __getattr__(self, name): + return object.__getattribute__( + object.__getattribute__(self, "_connection"), name + ) def cursor(self, *args, **kwargs): return get_traced_cursor_proxy( - self.__wrapped__.cursor(*args, **kwargs), db_api_integration + self._connection.cursor(*args, **kwargs), db_api_integration ) - def __enter__(self): - self.__wrapped__.__enter__() - return self - - def __exit__(self, *args, **kwargs): - self.__wrapped__.__exit__(*args, **kwargs) + # For some reason this is necessary as trying to access the close + # method of self._connection via __getattr__ leads to unexplained + # errors. + def close(self): + self._connection.close() - return TracedConnectionProxy(connection, *args, **kwargs) + return TracedConnectionProxy(connection) class CursorTracer:
diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/tests/test_dbapi_integration.py b/instrumentation/opentelemetry-instrumentation-dbapi/tests/test_dbapi_integration.py --- a/instrumentation/opentelemetry-instrumentation-dbapi/tests/test_dbapi_integration.py +++ b/instrumentation/opentelemetry-instrumentation-dbapi/tests/test_dbapi_integration.py @@ -262,14 +262,14 @@ def test_callproc(self): @mock.patch("opentelemetry.instrumentation.dbapi") def test_wrap_connect(self, mock_dbapi): - dbapi.wrap_connect(self.tracer, mock_dbapi, "connect", "-") + dbapi.wrap_connect(self.tracer, MockConnectionEmpty(), "connect", "-") connection = mock_dbapi.connect() self.assertEqual(mock_dbapi.connect.call_count, 1) - self.assertIsInstance(connection.__wrapped__, mock.Mock) + self.assertIsInstance(connection._connection, mock.Mock) @mock.patch("opentelemetry.instrumentation.dbapi") def test_unwrap_connect(self, mock_dbapi): - dbapi.wrap_connect(self.tracer, mock_dbapi, "connect", "-") + dbapi.wrap_connect(self.tracer, MockConnectionEmpty(), "connect", "-") connection = mock_dbapi.connect() self.assertEqual(mock_dbapi.connect.call_count, 1) @@ -279,19 +279,21 @@ def test_unwrap_connect(self, mock_dbapi): self.assertIsInstance(connection, mock.Mock) def test_instrument_connection(self): - connection = mock.Mock() + connection = MockConnectionEmpty() # Avoid get_attributes failing because can't concatenate mock + # pylint: disable=attribute-defined-outside-init connection.database = "-" connection2 = dbapi.instrument_connection(self.tracer, connection, "-") - self.assertIs(connection2.__wrapped__, connection) + self.assertIs(connection2._connection, connection) def test_uninstrument_connection(self): - connection = mock.Mock() + connection = MockConnectionEmpty() # Set connection.database to avoid a failure because mock can't # be concatenated + # pylint: disable=attribute-defined-outside-init connection.database = "-" connection2 = dbapi.instrument_connection(self.tracer, connection, "-") - self.assertIs(connection2.__wrapped__, connection) + self.assertIs(connection2._connection, connection) connection3 = dbapi.uninstrument_connection(connection2) self.assertIs(connection3, connection) @@ -307,10 +309,12 @@ def mock_connect(*args, **kwargs): server_host = kwargs.get("server_host") server_port = kwargs.get("server_port") user = kwargs.get("user") - return MockConnection(database, server_port, server_host, user) + return MockConnectionWithAttributes( + database, server_port, server_host, user + ) -class MockConnection: +class MockConnectionWithAttributes: def __init__(self, database, server_port, server_host, user): self.database = database self.server_port = server_port @@ -343,3 +347,7 @@ def executemany(self, query, params=None, throw_exception=False): def callproc(self, query, params=None, throw_exception=False): if throw_exception: raise Exception("Test Exception") + + +class MockConnectionEmpty: + pass diff --git a/instrumentation/opentelemetry-instrumentation-mysql/tests/test_mysql_integration.py b/instrumentation/opentelemetry-instrumentation-mysql/tests/test_mysql_integration.py --- a/instrumentation/opentelemetry-instrumentation-mysql/tests/test_mysql_integration.py +++ b/instrumentation/opentelemetry-instrumentation-mysql/tests/test_mysql_integration.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -from unittest import mock +from unittest.mock import Mock, patch import mysql.connector @@ -22,15 +22,24 @@ from opentelemetry.test.test_base import TestBase +def mock_connect(*args, **kwargs): + class MockConnection: + def cursor(self): + # pylint: disable=no-self-use + return Mock() + + return MockConnection() + + class TestMysqlIntegration(TestBase): def tearDown(self): super().tearDown() with self.disable_logging(): MySQLInstrumentor().uninstrument() - @mock.patch("mysql.connector.connect") + @patch("mysql.connector.connect", new=mock_connect) # pylint: disable=unused-argument - def test_instrumentor(self, mock_connect): + def test_instrumentor(self): MySQLInstrumentor().instrument() cnx = mysql.connector.connect(database="test") @@ -58,9 +67,8 @@ def test_instrumentor(self, mock_connect): spans_list = self.memory_exporter.get_finished_spans() self.assertEqual(len(spans_list), 1) - @mock.patch("mysql.connector.connect") - # pylint: disable=unused-argument - def test_custom_tracer_provider(self, mock_connect): + @patch("mysql.connector.connect", new=mock_connect) + def test_custom_tracer_provider(self): resource = resources.Resource.create({}) result = self.create_tracer_provider(resource=resource) tracer_provider, exporter = result @@ -77,9 +85,9 @@ def test_custom_tracer_provider(self, mock_connect): self.assertIs(span.resource, resource) - @mock.patch("mysql.connector.connect") + @patch("mysql.connector.connect", new=mock_connect) # pylint: disable=unused-argument - def test_instrument_connection(self, mock_connect): + def test_instrument_connection(self): cnx = mysql.connector.connect(database="test") query = "SELECT * FROM test" cursor = cnx.cursor() @@ -95,9 +103,9 @@ def test_instrument_connection(self, mock_connect): spans_list = self.memory_exporter.get_finished_spans() self.assertEqual(len(spans_list), 1) - @mock.patch("mysql.connector.connect") + @patch("mysql.connector.connect", new=mock_connect) # pylint: disable=unused-argument - def test_uninstrument_connection(self, mock_connect): + def test_uninstrument_connection(self): MySQLInstrumentor().instrument() cnx = mysql.connector.connect(database="test") query = "SELECT * FROM test" diff --git a/instrumentation/opentelemetry-instrumentation-pymysql/tests/test_pymysql_integration.py b/instrumentation/opentelemetry-instrumentation-pymysql/tests/test_pymysql_integration.py --- a/instrumentation/opentelemetry-instrumentation-pymysql/tests/test_pymysql_integration.py +++ b/instrumentation/opentelemetry-instrumentation-pymysql/tests/test_pymysql_integration.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -from unittest import mock +from unittest.mock import Mock, patch import pymysql @@ -22,15 +22,24 @@ from opentelemetry.test.test_base import TestBase +def mock_connect(*args, **kwargs): + class MockConnection: + def cursor(self): + # pylint: disable=no-self-use + return Mock() + + return MockConnection() + + class TestPyMysqlIntegration(TestBase): def tearDown(self): super().tearDown() with self.disable_logging(): PyMySQLInstrumentor().uninstrument() - @mock.patch("pymysql.connect") + @patch("pymysql.connect", new=mock_connect) # pylint: disable=unused-argument - def test_instrumentor(self, mock_connect): + def test_instrumentor(self): PyMySQLInstrumentor().instrument() cnx = pymysql.connect(database="test") @@ -58,9 +67,9 @@ def test_instrumentor(self, mock_connect): spans_list = self.memory_exporter.get_finished_spans() self.assertEqual(len(spans_list), 1) - @mock.patch("pymysql.connect") + @patch("pymysql.connect", new=mock_connect) # pylint: disable=unused-argument - def test_custom_tracer_provider(self, mock_connect): + def test_custom_tracer_provider(self): resource = resources.Resource.create({}) result = self.create_tracer_provider(resource=resource) tracer_provider, exporter = result @@ -78,9 +87,9 @@ def test_custom_tracer_provider(self, mock_connect): self.assertIs(span.resource, resource) - @mock.patch("pymysql.connect") + @patch("pymysql.connect", new=mock_connect) # pylint: disable=unused-argument - def test_instrument_connection(self, mock_connect): + def test_instrument_connection(self): cnx = pymysql.connect(database="test") query = "SELECT * FROM test" cursor = cnx.cursor() @@ -96,9 +105,9 @@ def test_instrument_connection(self, mock_connect): spans_list = self.memory_exporter.get_finished_spans() self.assertEqual(len(spans_list), 1) - @mock.patch("pymysql.connect") + @patch("pymysql.connect", new=mock_connect) # pylint: disable=unused-argument - def test_uninstrument_connection(self, mock_connect): + def test_uninstrument_connection(self): PyMySQLInstrumentor().instrument() cnx = pymysql.connect(database="test") query = "SELECT * FROM test"
dbapi instrumentation breaks psycopg2 when registering types. **Describe your environment** I'm using dbapi instrumentation to instrument postgresql. When I attempt to register jsonb, psycopg2 crashes. This issue is nearly identical to #143, with the exception that I'm not using `Psycopg2Instrumentor`. The reason I'm using dbapi instrumentation vs `Psycopg2Instrumentor` is because the latter does not support capturing parameters as span attributes. **Steps to reproduce** ```python from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.instrumentation import dbapi as dbapi_instrumentor import psycopg2 import psycopg2.extras trace.set_tracer_provider(TracerProvider()) db_connection_attributes = { "database": "info.dbname", "port": "info.port", "host": "info.host", "user": "info.user", } dbapi_instrumentor.trace_integration( psycopg2, "connect", "postgresql", db_connection_attributes, capture_parameters=True, ) cnx = psycopg2.connect(host='localhost', port='5432', dbname='postgres', password='1234', user='postgres') psycopg2.extras.register_default_jsonb(conn_or_curs=cnx, loads=lambda x: x) ``` results in ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.7/site-packages/psycopg2/_json.py", line 156, in register_default_jsonb loads=loads, oid=JSONB_OID, array_oid=JSONBARRAY_OID, name='jsonb') File "/usr/local/lib/python3.7/site-packages/psycopg2/_json.py", line 125, in register_json register_type(JSON, not globally and conn_or_curs or None) TypeError: argument 2 must be a connection, cursor or None ``` **What is the expected behavior?** For psycopg2 to not crash when used with dbapi instrumentation. **What is the actual behavior?** It crashes when psycopg2 enforces connection or cursor types. **Additional context** Add any other context about the problem here.
2022-05-19T01:55:39
open-telemetry/opentelemetry-python-contrib
1,110
open-telemetry__opentelemetry-python-contrib-1110
[ "1039" ]
0007c9046c74d724c342c769bca2a874357be907
diff --git a/instrumentation/opentelemetry-instrumentation-requests/src/opentelemetry/instrumentation/requests/__init__.py b/instrumentation/opentelemetry-instrumentation-requests/src/opentelemetry/instrumentation/requests/__init__.py --- a/instrumentation/opentelemetry-instrumentation-requests/src/opentelemetry/instrumentation/requests/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-requests/src/opentelemetry/instrumentation/requests/__init__.py @@ -50,7 +50,9 @@ import functools import types -from typing import Collection +from timeit import default_timer +from typing import Callable, Collection, Iterable, Optional +from urllib.parse import urlparse from requests.models import Response from requests.sessions import Session @@ -67,9 +69,11 @@ _SUPPRESS_INSTRUMENTATION_KEY, http_status_to_status_code, ) +from opentelemetry.metrics import Histogram, get_meter from opentelemetry.propagate import inject from opentelemetry.semconv.trace import SpanAttributes -from opentelemetry.trace import SpanKind, get_tracer +from opentelemetry.trace import SpanKind, Tracer, get_tracer +from opentelemetry.trace.span import Span from opentelemetry.trace.status import Status from opentelemetry.util.http import ( get_excluded_urls, @@ -84,7 +88,11 @@ # pylint: disable=unused-argument # pylint: disable=R0915 def _instrument( - tracer, span_callback=None, name_callback=None, excluded_urls=None + tracer: Tracer, + duration_histogram: Histogram, + span_callback: Optional[Callable[[Span, Response], str]] = None, + name_callback: Optional[Callable[[str, str], str]] = None, + excluded_urls: Iterable[str] = None, ): """Enables tracing of all requests calls that go through :code:`requests.session.Session.request` (this includes @@ -140,6 +148,7 @@ def call_wrapped(): request.method, request.url, call_wrapped, get_or_create_headers ) + # pylint: disable-msg=too-many-locals,too-many-branches def _instrumented_requests_call( method: str, url: str, call_wrapped, get_or_create_headers ): @@ -164,6 +173,23 @@ def _instrumented_requests_call( SpanAttributes.HTTP_URL: url, } + metric_labels = { + SpanAttributes.HTTP_METHOD: method, + } + + try: + parsed_url = urlparse(url) + metric_labels[SpanAttributes.HTTP_SCHEME] = parsed_url.scheme + if parsed_url.hostname: + metric_labels[SpanAttributes.HTTP_HOST] = parsed_url.hostname + metric_labels[ + SpanAttributes.NET_PEER_NAME + ] = parsed_url.hostname + if parsed_url.port: + metric_labels[SpanAttributes.NET_PEER_PORT] = parsed_url.port + except ValueError: + pass + with tracer.start_as_current_span( span_name, kind=SpanKind.CLIENT, attributes=span_attributes ) as span, set_ip_on_next_http_connection(span): @@ -175,12 +201,18 @@ def _instrumented_requests_call( token = context.attach( context.set_value(_SUPPRESS_HTTP_INSTRUMENTATION_KEY, True) ) + + start_time = default_timer() + try: result = call_wrapped() # *** PROCEED except Exception as exc: # pylint: disable=W0703 exception = exc result = getattr(exc, "response", None) finally: + elapsed_time = max( + round((default_timer() - start_time) * 1000), 0 + ) context.detach(token) if isinstance(result, Response): @@ -191,9 +223,23 @@ def _instrumented_requests_call( span.set_status( Status(http_status_to_status_code(result.status_code)) ) + + metric_labels[ + SpanAttributes.HTTP_STATUS_CODE + ] = result.status_code + + if result.raw is not None: + version = getattr(result.raw, "version", None) + if version: + metric_labels[SpanAttributes.HTTP_FLAVOR] = ( + "1.1" if version == 11 else "1.0" + ) + if span_callback is not None: span_callback(span, result) + duration_histogram.record(elapsed_time, attributes=metric_labels) + if exception is not None: raise exception.with_traceback(exception.__traceback__) @@ -258,8 +304,20 @@ def _instrument(self, **kwargs): tracer_provider = kwargs.get("tracer_provider") tracer = get_tracer(__name__, __version__, tracer_provider) excluded_urls = kwargs.get("excluded_urls") + meter_provider = kwargs.get("meter_provider") + meter = get_meter( + __name__, + __version__, + meter_provider, + ) + duration_histogram = meter.create_histogram( + name="http.client.duration", + unit="ms", + description="measures the duration of the outbound HTTP request", + ) _instrument( tracer, + duration_histogram, span_callback=kwargs.get("span_callback"), name_callback=kwargs.get("name_callback"), excluded_urls=_excluded_urls_from_env diff --git a/instrumentation/opentelemetry-instrumentation-requests/src/opentelemetry/instrumentation/requests/package.py b/instrumentation/opentelemetry-instrumentation-requests/src/opentelemetry/instrumentation/requests/package.py --- a/instrumentation/opentelemetry-instrumentation-requests/src/opentelemetry/instrumentation/requests/package.py +++ b/instrumentation/opentelemetry-instrumentation-requests/src/opentelemetry/instrumentation/requests/package.py @@ -14,3 +14,5 @@ _instruments = ("requests ~= 2.0",) + +_supports_metrics = True
diff --git a/instrumentation/opentelemetry-instrumentation-requests/tests/test_requests_integration.py b/instrumentation/opentelemetry-instrumentation-requests/tests/test_requests_integration.py --- a/instrumentation/opentelemetry-instrumentation-requests/tests/test_requests_integration.py +++ b/instrumentation/opentelemetry-instrumentation-requests/tests/test_requests_integration.py @@ -487,3 +487,47 @@ def perform_request(url: str, session: requests.Session = None): request = requests.Request("GET", url) prepared_request = session.prepare_request(request) return session.send(prepared_request) + + +class TestRequestsIntergrationMetric(TestBase): + URL = "http://examplehost:8000/status/200" + + def setUp(self): + super().setUp() + RequestsInstrumentor().instrument(meter_provider=self.meter_provider) + + httpretty.enable() + httpretty.register_uri(httpretty.GET, self.URL, body="Hello!") + + def tearDown(self): + super().tearDown() + RequestsInstrumentor().uninstrument() + httpretty.disable() + + @staticmethod + def perform_request(url: str) -> requests.Response: + return requests.get(url) + + def test_basic_metric_success(self): + self.perform_request(self.URL) + + expected_attributes = { + "http.status_code": 200, + "http.host": "examplehost", + "net.peer.port": 8000, + "net.peer.name": "examplehost", + "http.method": "GET", + "http.flavor": "1.1", + "http.scheme": "http", + } + + for ( + resource_metrics + ) in self.memory_metrics_reader.get_metrics_data().resource_metrics: + for scope_metrics in resource_metrics.scope_metrics: + for metric in scope_metrics.metrics: + for data_point in metric.data.data_points: + self.assertDictEqual( + expected_attributes, dict(data_point.attributes) + ) + self.assertEqual(data_point.count, 1)
[instrumentation-requests] Restore metrics The requests instrumentation used to produce metrics: https://github.com/open-telemetry/opentelemetry-python-contrib/blob/metrics/instrumentation/opentelemetry-instrumentation-requests/src/opentelemetry/instrumentation/requests/__init__.py This issue is to restore that functionality.
@codeboten Can you assign this issue to me? @ashu658 done!
2022-05-31T11:47:31
open-telemetry/opentelemetry-python-contrib
1,124
open-telemetry__opentelemetry-python-contrib-1124
[ "1123" ]
6876ad857ffcef07b09d3017217d2545e8ed6ece
diff --git a/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py b/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py --- a/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py @@ -49,7 +49,7 @@ exporter = ConsoleMetricExporter() - set_meter_provider(MeterProvider(PeriodicExportingMetricReader(exporter))) + set_meter_provider(MeterProvider([PeriodicExportingMetricReader(exporter)])) SystemMetricsInstrumentor().instrument() # metrics are collected asynchronously
Wrong metric reader argument in system metrics example The [system metrics example](https://github.com/open-telemetry/opentelemetry-python-contrib/blob/main/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py#L52) does not use a list of metric readers as an argument to `MeterProvider`.
2022-06-08T11:56:37
open-telemetry/opentelemetry-python-contrib
1,128
open-telemetry__opentelemetry-python-contrib-1128
[ "1126" ]
6503cdf2fead1eb18abce28c69e751f596accec8
diff --git a/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py b/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py --- a/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py @@ -158,6 +158,7 @@ def response_hook(span: Span, environ: WSGIEnvironment, status: str, response_he import functools import typing import wsgiref.util as wsgiref_util +from timeit import default_timer from opentelemetry import context, trace from opentelemetry.instrumentation.utils import ( @@ -165,6 +166,7 @@ def response_hook(span: Span, environ: WSGIEnvironment, status: str, response_he http_status_to_status_code, ) from opentelemetry.instrumentation.wsgi.version import __version__ +from opentelemetry.metrics import get_meter from opentelemetry.propagators.textmap import Getter from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.trace.status import Status, StatusCode @@ -181,6 +183,26 @@ def response_hook(span: Span, environ: WSGIEnvironment, status: str, response_he _CARRIER_KEY_PREFIX = "HTTP_" _CARRIER_KEY_PREFIX_LEN = len(_CARRIER_KEY_PREFIX) +# List of recommended attributes +_duration_attrs = [ + SpanAttributes.HTTP_METHOD, + SpanAttributes.HTTP_HOST, + SpanAttributes.HTTP_SCHEME, + SpanAttributes.HTTP_STATUS_CODE, + SpanAttributes.HTTP_FLAVOR, + SpanAttributes.HTTP_SERVER_NAME, + SpanAttributes.NET_HOST_NAME, + SpanAttributes.NET_HOST_PORT, +] + +_active_requests_count_attrs = [ + SpanAttributes.HTTP_METHOD, + SpanAttributes.HTTP_HOST, + SpanAttributes.HTTP_SCHEME, + SpanAttributes.HTTP_FLAVOR, + SpanAttributes.HTTP_SERVER_NAME, +] + class WSGIGetter(Getter[dict]): def get( @@ -304,6 +326,14 @@ def collect_custom_response_headers_attributes(response_headers): return attributes +def _parse_status_code(resp_status): + status_code, _ = resp_status.split(" ", 1) + try: + return int(status_code) + except ValueError: + return None + + def add_response_attributes( span, start_response_status, response_headers ): # pylint: disable=unused-argument @@ -352,18 +382,39 @@ class OpenTelemetryMiddleware: """ def __init__( - self, wsgi, request_hook=None, response_hook=None, tracer_provider=None + self, + wsgi, + request_hook=None, + response_hook=None, + tracer_provider=None, + meter_provider=None, ): self.wsgi = wsgi self.tracer = trace.get_tracer(__name__, __version__, tracer_provider) + self.meter = get_meter(__name__, __version__, meter_provider) + self.duration_histogram = self.meter.create_histogram( + name="http.server.duration", + unit="ms", + description="measures the duration of the inbound HTTP request", + ) + self.active_requests_counter = self.meter.create_up_down_counter( + name="http.server.active_requests", + unit="requests", + description="measures the number of concurrent HTTP requests that are currently in-flight", + ) self.request_hook = request_hook self.response_hook = response_hook @staticmethod - def _create_start_response(span, start_response, response_hook): + def _create_start_response( + span, start_response, response_hook, duration_attrs + ): @functools.wraps(start_response) def _start_response(status, response_headers, *args, **kwargs): add_response_attributes(span, status, response_headers) + status_code = _parse_status_code(status) + if status_code is not None: + duration_attrs[SpanAttributes.HTTP_STATUS_CODE] = status_code if span.is_recording() and span.kind == trace.SpanKind.SERVER: custom_attributes = collect_custom_response_headers_attributes( response_headers @@ -376,6 +427,7 @@ def _start_response(status, response_headers, *args, **kwargs): return _start_response + # pylint: disable=too-many-branches def __call__(self, environ, start_response): """The WSGI application @@ -383,13 +435,24 @@ def __call__(self, environ, start_response): environ: A WSGI environment. start_response: The WSGI start_response callable. """ + req_attrs = collect_request_attributes(environ) + active_requests_count_attrs = {} + for attr_key in _active_requests_count_attrs: + if req_attrs.get(attr_key) is not None: + active_requests_count_attrs[attr_key] = req_attrs[attr_key] + + duration_attrs = {} + for attr_key in _duration_attrs: + if req_attrs.get(attr_key) is not None: + duration_attrs[attr_key] = req_attrs[attr_key] + span, token = _start_internal_or_server_span( tracer=self.tracer, span_name=get_default_span_name(environ), start_time=None, context_carrier=environ, context_getter=wsgi_getter, - attributes=collect_request_attributes(environ), + attributes=req_attrs, ) if span.is_recording() and span.kind == trace.SpanKind.SERVER: custom_attributes = collect_custom_request_headers_attributes( @@ -405,15 +468,15 @@ def __call__(self, environ, start_response): if response_hook: response_hook = functools.partial(response_hook, span, environ) + start = default_timer() + self.active_requests_counter.add(1, active_requests_count_attrs) try: with trace.use_span(span): start_response = self._create_start_response( - span, start_response, response_hook + span, start_response, response_hook, duration_attrs ) iterable = self.wsgi(environ, start_response) - return _end_span_after_iterating( - iterable, span, self.tracer, token - ) + return _end_span_after_iterating(iterable, span, token) except Exception as ex: if span.is_recording(): span.set_status(Status(StatusCode.ERROR, str(ex))) @@ -421,12 +484,16 @@ def __call__(self, environ, start_response): if token is not None: context.detach(token) raise + finally: + duration = max(round((default_timer() - start) * 1000), 0) + self.duration_histogram.record(duration, duration_attrs) + self.active_requests_counter.add(-1, active_requests_count_attrs) # Put this in a subfunction to not delay the call to the wrapped # WSGI application (instrumentation should change the application # behavior as little as possible). -def _end_span_after_iterating(iterable, span, tracer, token): +def _end_span_after_iterating(iterable, span, token): try: with trace.use_span(span): yield from iterable diff --git a/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/package.py b/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/package.py --- a/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/package.py +++ b/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/package.py @@ -14,3 +14,5 @@ _instruments = tuple() + +_supports_metrics = True diff --git a/scripts/generate_instrumentation_readme.py b/scripts/generate_instrumentation_readme.py --- a/scripts/generate_instrumentation_readme.py +++ b/scripts/generate_instrumentation_readme.py @@ -23,8 +23,8 @@ _prefix = "opentelemetry-instrumentation-" header = """ -| Instrumentation | Supported Packages | -| --------------- | ------------------ |""" +| Instrumentation | Supported Packages | Metrics support | +| --------------- | ------------------ | --------------- |""" def main(): @@ -62,11 +62,14 @@ def main(): exec(fh.read(), pkg_info) instruments = pkg_info["_instruments"] + supports_metrics = pkg_info.get("_supports_metrics") if not instruments: instruments = (name,) + metric_column = "Yes" if supports_metrics else "No" + table.append( - f"| [{instrumentation}](./{instrumentation}) | {','.join(instruments)} |" + f"| [{instrumentation}](./{instrumentation}) | {','.join(instruments)} | {metric_column}" ) with open(
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -6,7 +6,7 @@ on: - 'release/*' pull_request: env: - CORE_REPO_SHA: c82829283d3e99aa2e089d1774ee509619650617 + CORE_REPO_SHA: d4d7c67663cc22615748d632e1c8c5799e8eacae jobs: build: @@ -42,7 +42,7 @@ jobs: path: | .tox ~/.cache/pip - key: v5-build-tox-cache-${{ env.RUN_MATRIX_COMBINATION }}-${{ hashFiles('tox.ini', 'gen-requirements.txt', 'dev-requirements.txt') }} + key: v6-build-tox-cache-${{ env.RUN_MATRIX_COMBINATION }}-${{ hashFiles('tox.ini', 'gen-requirements.txt', 'dev-requirements.txt') }} - name: run tox run: tox -f ${{ matrix.python-version }}-${{ matrix.package }} -- --benchmark-json=${{ env.RUN_MATRIX_COMBINATION }}-benchmark.json # - name: Find and merge ${{ matrix.package }} benchmarks @@ -118,7 +118,7 @@ jobs: path: | .tox ~/.cache/pip - key: v5-misc-tox-cache-${{ matrix.tox-environment }}-${{ hashFiles('tox.ini', 'dev-requirements.txt', 'gen-requirements.txt', 'docs-requirements.txt') }} + key: v6-misc-tox-cache-${{ matrix.tox-environment }}-${{ hashFiles('tox.ini', 'dev-requirements.txt', 'gen-requirements.txt', 'docs-requirements.txt') }} - name: run tox run: tox -e ${{ matrix.tox-environment }} - name: Ensure generated code is up to date diff --git a/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware.py b/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware.py --- a/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware.py +++ b/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware.py @@ -35,7 +35,6 @@ from opentelemetry.sdk.trace import Span from opentelemetry.sdk.trace.id_generator import RandomIdGenerator from opentelemetry.semconv.trace import SpanAttributes -from opentelemetry.test.test_base import TestBase from opentelemetry.test.wsgitestutil import WsgiTestBase from opentelemetry.trace import ( SpanKind, @@ -84,7 +83,7 @@ _django_instrumentor = DjangoInstrumentor() -class TestMiddleware(TestBase, WsgiTestBase): +class TestMiddleware(WsgiTestBase): @classmethod def setUpClass(cls): conf.settings.configure(ROOT_URLCONF=modules[__name__]) @@ -402,7 +401,7 @@ def test_trace_response_headers(self): self.memory_exporter.clear() -class TestMiddlewareWithTracerProvider(TestBase, WsgiTestBase): +class TestMiddlewareWithTracerProvider(WsgiTestBase): @classmethod def setUpClass(cls): conf.settings.configure(ROOT_URLCONF=modules[__name__]) @@ -460,7 +459,7 @@ def test_django_with_wsgi_instrumented(self): ) -class TestMiddlewareWsgiWithCustomHeaders(TestBase, WsgiTestBase): +class TestMiddlewareWsgiWithCustomHeaders(WsgiTestBase): @classmethod def setUpClass(cls): conf.settings.configure(ROOT_URLCONF=modules[__name__]) diff --git a/instrumentation/opentelemetry-instrumentation-flask/tests/test_automatic.py b/instrumentation/opentelemetry-instrumentation-flask/tests/test_automatic.py --- a/instrumentation/opentelemetry-instrumentation-flask/tests/test_automatic.py +++ b/instrumentation/opentelemetry-instrumentation-flask/tests/test_automatic.py @@ -17,14 +17,13 @@ from werkzeug.wrappers import Response from opentelemetry.instrumentation.flask import FlaskInstrumentor -from opentelemetry.test.test_base import TestBase from opentelemetry.test.wsgitestutil import WsgiTestBase # pylint: disable=import-error from .base_test import InstrumentationTest -class TestAutomatic(InstrumentationTest, TestBase, WsgiTestBase): +class TestAutomatic(InstrumentationTest, WsgiTestBase): def setUp(self): super().setUp() diff --git a/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py b/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py --- a/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py +++ b/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py @@ -26,7 +26,6 @@ from opentelemetry.instrumentation.wsgi import OpenTelemetryMiddleware from opentelemetry.sdk.resources import Resource from opentelemetry.semconv.trace import SpanAttributes -from opentelemetry.test.test_base import TestBase from opentelemetry.test.wsgitestutil import WsgiTestBase from opentelemetry.util.http import get_excluded_urls @@ -50,7 +49,7 @@ def expected_attributes(override_attributes): return default_attributes -class TestProgrammatic(InstrumentationTest, TestBase, WsgiTestBase): +class TestProgrammatic(InstrumentationTest, WsgiTestBase): def setUp(self): super().setUp() @@ -252,7 +251,7 @@ def test_exclude_lists_from_explicit(self): self.assertEqual(len(span_list), 1) -class TestProgrammaticHooks(InstrumentationTest, TestBase, WsgiTestBase): +class TestProgrammaticHooks(InstrumentationTest, WsgiTestBase): def setUp(self): super().setUp() @@ -300,9 +299,7 @@ def test_hooks(self): self.assertEqual(resp.headers["hook_attr"], "hello otel") -class TestProgrammaticHooksWithoutApp( - InstrumentationTest, TestBase, WsgiTestBase -): +class TestProgrammaticHooksWithoutApp(InstrumentationTest, WsgiTestBase): def setUp(self): super().setUp() @@ -350,9 +347,7 @@ def test_no_app_hooks(self): self.assertEqual(resp.headers["hook_attr"], "hello otel without app") -class TestProgrammaticCustomTracerProvider( - InstrumentationTest, TestBase, WsgiTestBase -): +class TestProgrammaticCustomTracerProvider(InstrumentationTest, WsgiTestBase): def setUp(self): super().setUp() resource = Resource.create({"service.name": "flask-api"}) @@ -383,7 +378,7 @@ def test_custom_span_name(self): class TestProgrammaticCustomTracerProviderWithoutApp( - InstrumentationTest, TestBase, WsgiTestBase + InstrumentationTest, WsgiTestBase ): def setUp(self): super().setUp() @@ -417,7 +412,7 @@ def test_custom_span_name(self): class TestProgrammaticWrappedWithOtherFramework( - InstrumentationTest, TestBase, WsgiTestBase + InstrumentationTest, WsgiTestBase ): def setUp(self): super().setUp() @@ -444,9 +439,7 @@ def test_mark_span_internal_in_presence_of_span_from_other_framework(self): ) -class TestCustomRequestResponseHeaders( - InstrumentationTest, TestBase, WsgiTestBase -): +class TestCustomRequestResponseHeaders(InstrumentationTest, WsgiTestBase): def setUp(self): super().setUp() diff --git a/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_automatic.py b/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_automatic.py --- a/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_automatic.py +++ b/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_automatic.py @@ -19,7 +19,6 @@ from opentelemetry import trace from opentelemetry.instrumentation.pyramid import PyramidInstrumentor from opentelemetry.test.globals_test import reset_trace_globals -from opentelemetry.test.test_base import TestBase from opentelemetry.test.wsgitestutil import WsgiTestBase from opentelemetry.trace import SpanKind from opentelemetry.trace.status import StatusCode @@ -32,7 +31,7 @@ from .pyramid_base_test import InstrumentationTest -class TestAutomatic(InstrumentationTest, TestBase, WsgiTestBase): +class TestAutomatic(InstrumentationTest, WsgiTestBase): def setUp(self): super().setUp() @@ -158,9 +157,7 @@ def test_400s_response_is_not_an_error(self): self.assertEqual(len(span_list), 1) -class TestWrappedWithOtherFramework( - InstrumentationTest, TestBase, WsgiTestBase -): +class TestWrappedWithOtherFramework(InstrumentationTest, WsgiTestBase): def setUp(self): super().setUp() PyramidInstrumentor().instrument() @@ -189,9 +186,7 @@ def test_with_existing_span(self): ) -class TestCustomRequestResponseHeaders( - InstrumentationTest, TestBase, WsgiTestBase -): +class TestCustomRequestResponseHeaders(InstrumentationTest, WsgiTestBase): def setUp(self): super().setUp() PyramidInstrumentor().instrument() @@ -296,9 +291,7 @@ def test_custom_response_header_not_added_in_internal_span(self): self.assertNotIn(key, span.attributes) -class TestCustomHeadersNonRecordingSpan( - InstrumentationTest, TestBase, WsgiTestBase -): +class TestCustomHeadersNonRecordingSpan(InstrumentationTest, WsgiTestBase): def setUp(self): super().setUp() # This is done because set_tracer_provider cannot override the diff --git a/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_programmatic.py b/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_programmatic.py --- a/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_programmatic.py +++ b/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_programmatic.py @@ -24,7 +24,6 @@ ) from opentelemetry.instrumentation.pyramid import PyramidInstrumentor from opentelemetry.semconv.trace import SpanAttributes -from opentelemetry.test.test_base import TestBase from opentelemetry.test.wsgitestutil import WsgiTestBase from opentelemetry.util.http import get_excluded_urls @@ -48,7 +47,7 @@ def expected_attributes(override_attributes): return default_attributes -class TestProgrammatic(InstrumentationTest, TestBase, WsgiTestBase): +class TestProgrammatic(InstrumentationTest, WsgiTestBase): def setUp(self): super().setUp() config = Configurator() diff --git a/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py b/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py --- a/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py +++ b/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py @@ -20,6 +20,10 @@ import opentelemetry.instrumentation.wsgi as otel_wsgi from opentelemetry import trace as trace_api +from opentelemetry.sdk.metrics.export import ( + HistogramDataPoint, + NumberDataPoint, +) from opentelemetry.sdk.resources import Resource from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.test.test_base import TestBase @@ -99,6 +103,16 @@ def wsgi_with_custom_response_headers(environ, start_response): return [b"*"] +_expected_metric_names = [ + "http.server.active_requests", + "http.server.duration", +] +_recommended_attrs = { + "http.server.active_requests": otel_wsgi._active_requests_count_attrs, + "http.server.duration": otel_wsgi._duration_attrs, +} + + class TestWsgiApplication(WsgiTestBase): def validate_response( self, @@ -230,6 +244,36 @@ def test_wsgi_internal_error(self): StatusCode.ERROR, ) + def test_wsgi_metrics(self): + app = otel_wsgi.OpenTelemetryMiddleware(error_wsgi_unhandled) + self.assertRaises(ValueError, app, self.environ, self.start_response) + self.assertRaises(ValueError, app, self.environ, self.start_response) + self.assertRaises(ValueError, app, self.environ, self.start_response) + metrics_list = self.memory_metrics_reader.get_metrics_data() + number_data_point_seen = False + histogram_data_point_seen = False + + self.assertTrue(len(metrics_list.resource_metrics) != 0) + for resource_metric in metrics_list.resource_metrics: + self.assertTrue(len(resource_metric.scope_metrics) != 0) + for scope_metric in resource_metric.scope_metrics: + self.assertTrue(len(scope_metric.metrics) != 0) + for metric in scope_metric.metrics: + self.assertIn(metric.name, _expected_metric_names) + data_points = list(metric.data.data_points) + self.assertEqual(len(data_points), 1) + for point in data_points: + if isinstance(point, HistogramDataPoint): + self.assertEqual(point.count, 3) + histogram_data_point_seen = True + if isinstance(point, NumberDataPoint): + number_data_point_seen = True + for attr in point.attributes: + self.assertIn( + attr, _recommended_attrs[metric.name] + ) + self.assertTrue(number_data_point_seen and histogram_data_point_seen) + def test_default_span_name_missing_request_method(self): """Test that default span_names with missing request method.""" self.environ.pop("REQUEST_METHOD") @@ -461,7 +505,7 @@ def test_mark_span_internal_in_presence_of_span_from_other_framework(self): ) -class TestAdditionOfCustomRequestResponseHeaders(WsgiTestBase, TestBase): +class TestAdditionOfCustomRequestResponseHeaders(WsgiTestBase): def setUp(self): super().setUp() tracer_provider, _ = TestBase.create_tracer_provider()
[instrumentation-wsgi] add metric instrumentation for wsgi Add support for the [`http.server`](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/semantic_conventions/http-metrics.md#http-server) metric semantic conventions in WSGI.
2022-06-11T17:02:58
open-telemetry/opentelemetry-python-contrib
1,129
open-telemetry__opentelemetry-python-contrib-1129
[ "1125" ]
51ba801bfda31c3d57902d9f9df938cee1236eb8
diff --git a/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py b/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py --- a/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py @@ -101,6 +101,7 @@ "system.network.connections": ["family", "type"], "runtime.memory": ["rss", "vms"], "runtime.cpu.time": ["user", "system"], + "runtime.gc_count": None, } @@ -149,6 +150,7 @@ def instrumentation_dependencies(self) -> Collection[str]: return _instruments def _instrument(self, **kwargs): + # pylint: disable=too-many-branches meter_provider = kwargs.get("meter_provider") self._meter = get_meter( __name__, @@ -156,47 +158,53 @@ def _instrument(self, **kwargs): meter_provider, ) - self._meter.create_observable_counter( - name="system.cpu.time", - callbacks=[self._get_system_cpu_time], - description="System CPU time", - unit="seconds", - ) + if "system.cpu.time" in self._config: + self._meter.create_observable_counter( + name="system.cpu.time", + callbacks=[self._get_system_cpu_time], + description="System CPU time", + unit="seconds", + ) - self._meter.create_observable_gauge( - name="system.cpu.utilization", - callbacks=[self._get_system_cpu_utilization], - description="System CPU utilization", - unit="1", - ) + if "system.cpu.utilization" in self._config: + self._meter.create_observable_gauge( + name="system.cpu.utilization", + callbacks=[self._get_system_cpu_utilization], + description="System CPU utilization", + unit="1", + ) - self._meter.create_observable_gauge( - name="system.memory.usage", - callbacks=[self._get_system_memory_usage], - description="System memory usage", - unit="bytes", - ) + if "system.memory.usage" in self._config: + self._meter.create_observable_gauge( + name="system.memory.usage", + callbacks=[self._get_system_memory_usage], + description="System memory usage", + unit="bytes", + ) - self._meter.create_observable_gauge( - name="system.memory.utilization", - callbacks=[self._get_system_memory_utilization], - description="System memory utilization", - unit="1", - ) + if "system.memory.utilization" in self._config: + self._meter.create_observable_gauge( + name="system.memory.utilization", + callbacks=[self._get_system_memory_utilization], + description="System memory utilization", + unit="1", + ) - self._meter.create_observable_gauge( - name="system.swap.usage", - callbacks=[self._get_system_swap_usage], - description="System swap usage", - unit="pages", - ) + if "system.swap.usage" in self._config: + self._meter.create_observable_gauge( + name="system.swap.usage", + callbacks=[self._get_system_swap_usage], + description="System swap usage", + unit="pages", + ) - self._meter.create_observable_gauge( - name="system.swap.utilization", - callbacks=[self._get_system_swap_utilization], - description="System swap utilization", - unit="1", - ) + if "system.swap.utilization" in self._config: + self._meter.create_observable_gauge( + name="system.swap.utilization", + callbacks=[self._get_system_swap_utilization], + description="System swap utilization", + unit="1", + ) # TODO Add _get_system_swap_page_faults @@ -217,26 +225,29 @@ def _instrument(self, **kwargs): # value_type=int, # ) - self._meter.create_observable_counter( - name="system.disk.io", - callbacks=[self._get_system_disk_io], - description="System disk IO", - unit="bytes", - ) + if "system.disk.io" in self._config: + self._meter.create_observable_counter( + name="system.disk.io", + callbacks=[self._get_system_disk_io], + description="System disk IO", + unit="bytes", + ) - self._meter.create_observable_counter( - name="system.disk.operations", - callbacks=[self._get_system_disk_operations], - description="System disk operations", - unit="operations", - ) + if "system.disk.operations" in self._config: + self._meter.create_observable_counter( + name="system.disk.operations", + callbacks=[self._get_system_disk_operations], + description="System disk operations", + unit="operations", + ) - self._meter.create_observable_counter( - name="system.disk.time", - callbacks=[self._get_system_disk_time], - description="System disk time", - unit="seconds", - ) + if "system.disk.time" in self._config: + self._meter.create_observable_counter( + name="system.disk.time", + callbacks=[self._get_system_disk_time], + description="System disk time", + unit="seconds", + ) # TODO Add _get_system_filesystem_usage @@ -260,61 +271,69 @@ def _instrument(self, **kwargs): # TODO Filesystem information can be obtained with os.statvfs in Unix-like # OSs, how to do the same in Windows? - self._meter.create_observable_counter( - name="system.network.dropped_packets", - callbacks=[self._get_system_network_dropped_packets], - description="System network dropped_packets", - unit="packets", - ) + if "system.network.dropped.packets" in self._config: + self._meter.create_observable_counter( + name="system.network.dropped_packets", + callbacks=[self._get_system_network_dropped_packets], + description="System network dropped_packets", + unit="packets", + ) - self._meter.create_observable_counter( - name="system.network.packets", - callbacks=[self._get_system_network_packets], - description="System network packets", - unit="packets", - ) + if "system.network.packets" in self._config: + self._meter.create_observable_counter( + name="system.network.packets", + callbacks=[self._get_system_network_packets], + description="System network packets", + unit="packets", + ) - self._meter.create_observable_counter( - name="system.network.errors", - callbacks=[self._get_system_network_errors], - description="System network errors", - unit="errors", - ) + if "system.network.errors" in self._config: + self._meter.create_observable_counter( + name="system.network.errors", + callbacks=[self._get_system_network_errors], + description="System network errors", + unit="errors", + ) - self._meter.create_observable_counter( - name="system.network.io", - callbacks=[self._get_system_network_io], - description="System network io", - unit="bytes", - ) + if "system.network.io" in self._config: + self._meter.create_observable_counter( + name="system.network.io", + callbacks=[self._get_system_network_io], + description="System network io", + unit="bytes", + ) - self._meter.create_observable_up_down_counter( - name="system.network.connections", - callbacks=[self._get_system_network_connections], - description="System network connections", - unit="connections", - ) + if "system.network.connections" in self._config: + self._meter.create_observable_up_down_counter( + name="system.network.connections", + callbacks=[self._get_system_network_connections], + description="System network connections", + unit="connections", + ) - self._meter.create_observable_counter( - name=f"runtime.{self._python_implementation}.memory", - callbacks=[self._get_runtime_memory], - description=f"Runtime {self._python_implementation} memory", - unit="bytes", - ) + if "runtime.memory" in self._config: + self._meter.create_observable_counter( + name=f"runtime.{self._python_implementation}.memory", + callbacks=[self._get_runtime_memory], + description=f"Runtime {self._python_implementation} memory", + unit="bytes", + ) - self._meter.create_observable_counter( - name=f"runtime.{self._python_implementation}.cpu_time", - callbacks=[self._get_runtime_cpu_time], - description=f"Runtime {self._python_implementation} CPU time", - unit="seconds", - ) + if "runtime.cpu.time" in self._config: + self._meter.create_observable_counter( + name=f"runtime.{self._python_implementation}.cpu_time", + callbacks=[self._get_runtime_cpu_time], + description=f"Runtime {self._python_implementation} CPU time", + unit="seconds", + ) - self._meter.create_observable_counter( - name=f"runtime.{self._python_implementation}.gc_count", - callbacks=[self._get_runtime_gc_count], - description=f"Runtime {self._python_implementation} GC count", - unit="bytes", - ) + if "runtime.gc_count" in self._config: + self._meter.create_observable_counter( + name=f"runtime.{self._python_implementation}.gc_count", + callbacks=[self._get_runtime_gc_count], + description=f"Runtime {self._python_implementation} GC count", + unit="bytes", + ) def _uninstrument(self, **__): pass @@ -329,7 +348,8 @@ def _get_system_cpu_time( self._system_cpu_time_labels["state"] = metric self._system_cpu_time_labels["cpu"] = cpu + 1 yield Observation( - getattr(times, metric), self._system_cpu_time_labels + getattr(times, metric), + self._system_cpu_time_labels.copy(), ) def _get_system_cpu_utilization( @@ -346,7 +366,7 @@ def _get_system_cpu_utilization( self._system_cpu_utilization_labels["cpu"] = cpu + 1 yield Observation( getattr(times_percent, metric) / 100, - self._system_cpu_utilization_labels, + self._system_cpu_utilization_labels.copy(), ) def _get_system_memory_usage( @@ -359,7 +379,7 @@ def _get_system_memory_usage( if hasattr(virtual_memory, metric): yield Observation( getattr(virtual_memory, metric), - self._system_memory_usage_labels, + self._system_memory_usage_labels.copy(), ) def _get_system_memory_utilization( @@ -373,7 +393,7 @@ def _get_system_memory_utilization( if hasattr(system_memory, metric): yield Observation( getattr(system_memory, metric) / system_memory.total, - self._system_memory_utilization_labels, + self._system_memory_utilization_labels.copy(), ) def _get_system_swap_usage( @@ -387,7 +407,7 @@ def _get_system_swap_usage( if hasattr(system_swap, metric): yield Observation( getattr(system_swap, metric), - self._system_swap_usage_labels, + self._system_swap_usage_labels.copy(), ) def _get_system_swap_utilization( @@ -401,7 +421,7 @@ def _get_system_swap_utilization( self._system_swap_utilization_labels["state"] = metric yield Observation( getattr(system_swap, metric) / system_swap.total, - self._system_swap_utilization_labels, + self._system_swap_utilization_labels.copy(), ) def _get_system_disk_io( @@ -415,7 +435,7 @@ def _get_system_disk_io( self._system_disk_io_labels["direction"] = metric yield Observation( getattr(counters, f"{metric}_bytes"), - self._system_disk_io_labels, + self._system_disk_io_labels.copy(), ) def _get_system_disk_operations( @@ -429,7 +449,7 @@ def _get_system_disk_operations( self._system_disk_operations_labels["direction"] = metric yield Observation( getattr(counters, f"{metric}_count"), - self._system_disk_operations_labels, + self._system_disk_operations_labels.copy(), ) def _get_system_disk_time( @@ -443,7 +463,7 @@ def _get_system_disk_time( self._system_disk_time_labels["direction"] = metric yield Observation( getattr(counters, f"{metric}_time") / 1000, - self._system_disk_time_labels, + self._system_disk_time_labels.copy(), ) def _get_system_disk_merged( @@ -461,7 +481,7 @@ def _get_system_disk_merged( self._system_disk_merged_labels["direction"] = metric yield Observation( getattr(counters, f"{metric}_merged_count"), - self._system_disk_merged_labels, + self._system_disk_merged_labels.copy(), ) def _get_system_network_dropped_packets( @@ -481,7 +501,7 @@ def _get_system_network_dropped_packets( ] = metric yield Observation( getattr(counters, f"drop{in_out}"), - self._system_network_dropped_packets_labels, + self._system_network_dropped_packets_labels.copy(), ) def _get_system_network_packets( @@ -497,7 +517,7 @@ def _get_system_network_packets( self._system_network_packets_labels["direction"] = metric yield Observation( getattr(counters, f"packets_{recv_sent}"), - self._system_network_packets_labels, + self._system_network_packets_labels.copy(), ) def _get_system_network_errors( @@ -512,7 +532,7 @@ def _get_system_network_errors( self._system_network_errors_labels["direction"] = metric yield Observation( getattr(counters, f"err{in_out}"), - self._system_network_errors_labels, + self._system_network_errors_labels.copy(), ) def _get_system_network_io( @@ -528,7 +548,7 @@ def _get_system_network_io( self._system_network_io_labels["direction"] = metric yield Observation( getattr(counters, f"bytes_{recv_sent}"), - self._system_network_io_labels, + self._system_network_io_labels.copy(), ) def _get_system_network_connections( @@ -581,7 +601,7 @@ def _get_runtime_memory( self._runtime_memory_labels["type"] = metric yield Observation( getattr(proc_memory, metric), - self._runtime_memory_labels, + self._runtime_memory_labels.copy(), ) def _get_runtime_cpu_time( @@ -594,7 +614,7 @@ def _get_runtime_cpu_time( self._runtime_cpu_time_labels["type"] = metric yield Observation( getattr(proc_cpu, metric), - self._runtime_cpu_time_labels, + self._runtime_cpu_time_labels.copy(), ) def _get_runtime_gc_count( @@ -603,4 +623,4 @@ def _get_runtime_gc_count( """Observer callback for garbage collection""" for index, count in enumerate(gc.get_count()): self._runtime_gc_count_labels["count"] = str(index) - yield Observation(count, self._runtime_gc_count_labels) + yield Observation(count, self._runtime_gc_count_labels.copy())
Non-config keys queried when using system metrics with custom configuration Was trying [this](https://github.com/open-telemetry/opentelemetry-python/tree/main/docs/examples/metrics) example but with this code instead: ```python from opentelemetry.metrics import set_meter_provider from opentelemetry.instrumentation.system_metrics import SystemMetricsInstrumentor from opentelemetry.sdk.metrics import MeterProvider from opentelemetry.sdk.metrics.export import ConsoleMetricExporter, PeriodicExportingMetricReader from time import sleep exporter = ConsoleMetricExporter() set_meter_provider(MeterProvider([PeriodicExportingMetricReader(exporter)])) configuration = { "system.memory.usage": ["used", "free", "cached"], "system.cpu.time": ["idle", "user", "system", "irq"], "system.network.io": ["trasmit", "receive"], "runtime.memory": ["rss", "vms"], "runtime.cpu.time": ["user", "system"], } SystemMetricsInstrumentor().instrument() SystemMetricsInstrumentor(config=configuration).instrument() # SystemMetricsInstrumentor().instrument() sleep(0.1) ``` Got these errors: ``` Attempting to instrument while already instrumented Callback failed for instrument system.cpu.utilization. Traceback (most recent call last): File "/home/ocelotl/github/ocelotl/opentelemetry-python/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/instrument.py", line 122, in callback for api_measurement in callback(callback_options): File "/home/ocelotl/github/ocelotl/opentelemetry-python-contrib/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py", line 343, in _get_system_cpu_utilization for metric in self._config["system.cpu.utilization"]: KeyError: 'system.cpu.utilization' Callback failed for instrument system.memory.utilization. Traceback (most recent call last): File "/home/ocelotl/github/ocelotl/opentelemetry-python/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/instrument.py", line 122, in callback for api_measurement in callback(callback_options): File "/home/ocelotl/github/ocelotl/opentelemetry-python-contrib/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py", line 371, in _get_system_memory_utilization for metric in self._config["system.memory.utilization"]: KeyError: 'system.memory.utilization' Callback failed for instrument system.swap.usage. Traceback (most recent call last): File "/home/ocelotl/github/ocelotl/opentelemetry-python/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/instrument.py", line 122, in callback for api_measurement in callback(callback_options): File "/home/ocelotl/github/ocelotl/opentelemetry-python-contrib/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py", line 385, in _get_system_swap_usage for metric in self._config["system.swap.usage"]: KeyError: 'system.swap.usage' Callback failed for instrument system.swap.utilization. Traceback (most recent call last): File "/home/ocelotl/github/ocelotl/opentelemetry-python/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/instrument.py", line 122, in callback for api_measurement in callback(callback_options): File "/home/ocelotl/github/ocelotl/opentelemetry-python-contrib/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py", line 399, in _get_system_swap_utilization for metric in self._config["system.swap.utilization"]: KeyError: 'system.swap.utilization' Callback failed for instrument system.disk.io. Traceback (most recent call last): File "/home/ocelotl/github/ocelotl/opentelemetry-python/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/instrument.py", line 122, in callback for api_measurement in callback(callback_options): File "/home/ocelotl/github/ocelotl/opentelemetry-python-contrib/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py", line 412, in _get_system_disk_io for metric in self._config["system.disk.io"]: KeyError: 'system.disk.io' Callback failed for instrument system.disk.operations. Traceback (most recent call last): File "/home/ocelotl/github/ocelotl/opentelemetry-python/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/instrument.py", line 122, in callback for api_measurement in callback(callback_options): File "/home/ocelotl/github/ocelotl/opentelemetry-python-contrib/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py", line 426, in _get_system_disk_operations for metric in self._config["system.disk.operations"]: KeyError: 'system.disk.operations' Callback failed for instrument system.disk.time. Traceback (most recent call last): File "/home/ocelotl/github/ocelotl/opentelemetry-python/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/instrument.py", line 122, in callback for api_measurement in callback(callback_options): File "/home/ocelotl/github/ocelotl/opentelemetry-python-contrib/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py", line 440, in _get_system_disk_time for metric in self._config["system.disk.time"]: KeyError: 'system.disk.time' Callback failed for instrument system.network.dropped_packets. Traceback (most recent call last): File "/home/ocelotl/github/ocelotl/opentelemetry-python/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/instrument.py", line 122, in callback for api_measurement in callback(callback_options): File "/home/ocelotl/github/ocelotl/opentelemetry-python-contrib/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py", line 473, in _get_system_network_dropped_packets for metric in self._config["system.network.dropped.packets"]: KeyError: 'system.network.dropped.packets' Callback failed for instrument system.network.packets. Traceback (most recent call last): File "/home/ocelotl/github/ocelotl/opentelemetry-python/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/instrument.py", line 122, in callback for api_measurement in callback(callback_options): File "/home/ocelotl/github/ocelotl/opentelemetry-python-contrib/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py", line 493, in _get_system_network_packets for metric in self._config["system.network.dropped.packets"]: KeyError: 'system.network.dropped.packets' Callback failed for instrument system.network.errors. Traceback (most recent call last): File "/home/ocelotl/github/ocelotl/opentelemetry-python/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/instrument.py", line 122, in callback for api_measurement in callback(callback_options): File "/home/ocelotl/github/ocelotl/opentelemetry-python-contrib/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py", line 508, in _get_system_network_errors for metric in self._config["system.network.errors"]: KeyError: 'system.network.errors' Callback failed for instrument system.network.io. Traceback (most recent call last): File "/home/ocelotl/github/ocelotl/opentelemetry-python/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/instrument.py", line 122, in callback for api_measurement in callback(callback_options): File "/home/ocelotl/github/ocelotl/opentelemetry-python-contrib/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py", line 524, in _get_system_network_io for metric in self._config["system.network.dropped.packets"]: KeyError: 'system.network.dropped.packets' Callback failed for instrument system.network.connections. Traceback (most recent call last): File "/home/ocelotl/github/ocelotl/opentelemetry-python/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/instrument.py", line 122, in callback for api_measurement in callback(callback_options): File "/home/ocelotl/github/ocelotl/opentelemetry-python-contrib/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py", line 544, in _get_system_network_connections for metric in self._config["system.network.connections"]: KeyError: 'system.network.connections' ```
2022-06-13T12:41:12
open-telemetry/opentelemetry-python-contrib
1,134
open-telemetry__opentelemetry-python-contrib-1134
[ "1133" ]
9e2dbecedc4fde0642fc1efcaa6fbe9b6f4e47dd
diff --git a/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/__init__.py b/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/__init__.py --- a/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/__init__.py @@ -56,12 +56,14 @@ import sqlalchemy from packaging.version import parse as parse_version +from sqlalchemy.engine.base import Engine from wrapt import wrap_function_wrapper as _w from opentelemetry.instrumentation.instrumentor import BaseInstrumentor from opentelemetry.instrumentation.sqlalchemy.engine import ( EngineTracer, _get_tracer, + _wrap_connect, _wrap_create_async_engine, _wrap_create_engine, ) @@ -97,13 +99,17 @@ def _instrument(self, **kwargs): "create_engine", _wrap_create_engine(tracer_provider), ) + _w( + "sqlalchemy.engine.base", + "Engine.connect", + _wrap_connect(tracer_provider), + ) if parse_version(sqlalchemy.__version__).release >= (1, 4): _w( "sqlalchemy.ext.asyncio", "create_async_engine", _wrap_create_async_engine(tracer_provider), ) - if kwargs.get("engine") is not None: return EngineTracer( _get_tracer(tracer_provider), @@ -127,5 +133,6 @@ def _instrument(self, **kwargs): def _uninstrument(self, **kwargs): unwrap(sqlalchemy, "create_engine") unwrap(sqlalchemy.engine, "create_engine") + unwrap(Engine, "connect") if parse_version(sqlalchemy.__version__).release >= (1, 4): unwrap(sqlalchemy.ext.asyncio, "create_async_engine") diff --git a/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/engine.py b/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/engine.py --- a/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/engine.py +++ b/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/engine.py @@ -77,6 +77,23 @@ def _wrap_create_engine_internal(func, module, args, kwargs): return _wrap_create_engine_internal +def _wrap_connect(tracer_provider=None): + tracer = trace.get_tracer( + _instrumenting_module_name, + __version__, + tracer_provider=tracer_provider, + ) + + # pylint: disable=unused-argument + def _wrap_connect_internal(func, module, args, kwargs): + with tracer.start_as_current_span( + "connect", kind=trace.SpanKind.CLIENT + ): + return func(*args, **kwargs) + + return _wrap_connect_internal + + class EngineTracer: def __init__(self, tracer, engine, enable_commenter=False): self.tracer = tracer
diff --git a/instrumentation/opentelemetry-instrumentation-sqlalchemy/tests/test_sqlalchemy.py b/instrumentation/opentelemetry-instrumentation-sqlalchemy/tests/test_sqlalchemy.py --- a/instrumentation/opentelemetry-instrumentation-sqlalchemy/tests/test_sqlalchemy.py +++ b/instrumentation/opentelemetry-instrumentation-sqlalchemy/tests/test_sqlalchemy.py @@ -46,9 +46,13 @@ def test_trace_integration(self): cnx.execute("SELECT 1 + 1;").fetchall() spans = self.memory_exporter.get_finished_spans() - self.assertEqual(len(spans), 1) - self.assertEqual(spans[0].name, "SELECT :memory:") + self.assertEqual(len(spans), 2) + # first span - the connection to the db + self.assertEqual(spans[0].name, "connect") self.assertEqual(spans[0].kind, trace.SpanKind.CLIENT) + # second span - the query itself + self.assertEqual(spans[1].name, "SELECT :memory:") + self.assertEqual(spans[1].kind, trace.SpanKind.CLIENT) def test_instrument_two_engines(self): engine_1 = create_engine("sqlite:///:memory:") @@ -65,8 +69,20 @@ def test_instrument_two_engines(self): cnx_2.execute("SELECT 1 + 1;").fetchall() spans = self.memory_exporter.get_finished_spans() + # 2 queries + 2 engine connect + self.assertEqual(len(spans), 4) - self.assertEqual(len(spans), 2) + def test_instrument_engine_connect(self): + engine = create_engine("sqlite:///:memory:") + + SQLAlchemyInstrumentor().instrument( + engine=engine, + tracer_provider=self.tracer_provider, + ) + + engine.connect() + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 1) @pytest.mark.skipif( not sqlalchemy.__version__.startswith("1.4"), @@ -85,11 +101,15 @@ async def run(): async with engine.connect() as cnx: await cnx.execute(sqlalchemy.text("SELECT 1 + 1;")) spans = self.memory_exporter.get_finished_spans() - self.assertEqual(len(spans), 1) - self.assertEqual(spans[0].name, "SELECT :memory:") + self.assertEqual(len(spans), 2) + # first span - the connection to the db + self.assertEqual(spans[0].name, "connect") self.assertEqual(spans[0].kind, trace.SpanKind.CLIENT) + # second span - the query + self.assertEqual(spans[1].name, "SELECT :memory:") + self.assertEqual(spans[1].kind, trace.SpanKind.CLIENT) self.assertEqual( - spans[0].instrumentation_scope.name, + spans[1].instrumentation_scope.name, "opentelemetry.instrumentation.sqlalchemy", ) @@ -99,7 +119,10 @@ def test_not_recording(self): mock_tracer = mock.Mock() mock_span = mock.Mock() mock_span.is_recording.return_value = False + mock_span.__enter__ = mock.Mock(return_value=(mock.Mock(), None)) + mock_span.__exit__ = mock.Mock(return_value=None) mock_tracer.start_span.return_value = mock_span + mock_tracer.start_as_current_span.return_value = mock_span with mock.patch("opentelemetry.trace.get_tracer") as tracer: tracer.return_value = mock_tracer engine = create_engine("sqlite:///:memory:") @@ -123,11 +146,15 @@ def test_create_engine_wrapper(self): cnx.execute("SELECT 1 + 1;").fetchall() spans = self.memory_exporter.get_finished_spans() - self.assertEqual(len(spans), 1) - self.assertEqual(spans[0].name, "SELECT :memory:") + self.assertEqual(len(spans), 2) + # first span - the connection to the db + self.assertEqual(spans[0].name, "connect") self.assertEqual(spans[0].kind, trace.SpanKind.CLIENT) + # second span - the query + self.assertEqual(spans[1].name, "SELECT :memory:") + self.assertEqual(spans[1].kind, trace.SpanKind.CLIENT) self.assertEqual( - spans[0].instrumentation_scope.name, + spans[1].instrumentation_scope.name, "opentelemetry.instrumentation.sqlalchemy", ) @@ -153,7 +180,7 @@ def test_custom_tracer_provider(self): cnx.execute("SELECT 1 + 1;").fetchall() spans = self.memory_exporter.get_finished_spans() - self.assertEqual(len(spans), 1) + self.assertEqual(len(spans), 2) self.assertEqual(spans[0].resource.attributes["service.name"], "test") self.assertEqual( spans[0].resource.attributes["deployment.environment"], "env" @@ -177,11 +204,15 @@ async def run(): async with engine.connect() as cnx: await cnx.execute(sqlalchemy.text("SELECT 1 + 1;")) spans = self.memory_exporter.get_finished_spans() - self.assertEqual(len(spans), 1) - self.assertEqual(spans[0].name, "SELECT :memory:") + self.assertEqual(len(spans), 2) + # first span - the connection to the db + self.assertEqual(spans[0].name, "connect") self.assertEqual(spans[0].kind, trace.SpanKind.CLIENT) + # second span - the query + self.assertEqual(spans[1].name, "SELECT :memory:") + self.assertEqual(spans[1].kind, trace.SpanKind.CLIENT) self.assertEqual( - spans[0].instrumentation_scope.name, + spans[1].instrumentation_scope.name, "opentelemetry.instrumentation.sqlalchemy", ) @@ -199,8 +230,8 @@ def test_generate_commenter(self): cnx = engine.connect() cnx.execute("SELECT 1 + 1;").fetchall() spans = self.memory_exporter.get_finished_spans() - self.assertEqual(len(spans), 1) - span = spans[0] + self.assertEqual(len(spans), 2) + span = spans[1] self.assertIn( EngineTracer._generate_comment(span), self.caplog.records[-2].getMessage(), diff --git a/tests/opentelemetry-docker-tests/tests/sqlalchemy_tests/mixins.py b/tests/opentelemetry-docker-tests/tests/sqlalchemy_tests/mixins.py --- a/tests/opentelemetry-docker-tests/tests/sqlalchemy_tests/mixins.py +++ b/tests/opentelemetry-docker-tests/tests/sqlalchemy_tests/mixins.py @@ -128,8 +128,9 @@ def test_orm_insert(self): self.session.commit() spans = self.memory_exporter.get_finished_spans() - self.assertEqual(len(spans), 1) - span = spans[0] + # one span for the connection and one for the query + self.assertEqual(len(spans), 2) + span = spans[1] stmt = "INSERT INTO players (id, name) VALUES " if span.attributes.get(SpanAttributes.DB_SYSTEM) == "sqlite": stmt += "(?, ?)" @@ -148,8 +149,9 @@ def test_session_query(self): self.assertEqual(len(out), 0) spans = self.memory_exporter.get_finished_spans() - self.assertEqual(len(spans), 1) - span = spans[0] + # one span for the connection and one for the query + self.assertEqual(len(spans), 2) + span = spans[1] stmt = "SELECT players.id AS players_id, players.name AS players_name \nFROM players \nWHERE players.name = " if span.attributes.get(SpanAttributes.DB_SYSTEM) == "sqlite": stmt += "?" @@ -170,8 +172,9 @@ def test_engine_connect_execute(self): self.assertEqual(len(rows), 0) spans = self.memory_exporter.get_finished_spans() - self.assertEqual(len(spans), 1) - span = spans[0] + # one span for the connection and one for the query + self.assertEqual(len(spans), 2) + span = spans[1] self._check_span(span, "SELECT") self.assertEqual( span.attributes.get(SpanAttributes.DB_STATEMENT), @@ -190,8 +193,9 @@ def test_parent(self): self.assertEqual(len(rows), 0) spans = self.memory_exporter.get_finished_spans() - self.assertEqual(len(spans), 2) - child_span, parent_span = spans + # one span for the connection and two for the queries + self.assertEqual(len(spans), 3) + _, child_span, parent_span = spans # confirm the parenting self.assertIsNone(parent_span.parent) @@ -247,5 +251,5 @@ def insert_players(session): # batch inserts together which means `insert_players` only generates one span. # See https://docs.sqlalchemy.org/en/14/changelog/migration_14.html#orm-batch-inserts-with-psycopg2-now-batch-statements-with-returning-in-most-cases self.assertEqual( - len(spans), 5 if self.VENDOR not in ["postgresql"] else 3 + len(spans), 8 if self.VENDOR not in ["postgresql"] else 6 ) diff --git a/tests/opentelemetry-docker-tests/tests/sqlalchemy_tests/test_mssql.py b/tests/opentelemetry-docker-tests/tests/sqlalchemy_tests/test_mssql.py --- a/tests/opentelemetry-docker-tests/tests/sqlalchemy_tests/test_mssql.py +++ b/tests/opentelemetry-docker-tests/tests/sqlalchemy_tests/test_mssql.py @@ -69,8 +69,9 @@ def test_engine_execute_errors(self): conn.execute("SELECT * FROM a_wrong_table").fetchall() spans = self.memory_exporter.get_finished_spans() - self.assertEqual(len(spans), 1) - span = spans[0] + # one span for the connection and one for the query + self.assertEqual(len(spans), 2) + span = spans[1] # span fields self.assertEqual(span.name, "SELECT opentelemetry-tests") self.assertEqual( @@ -96,9 +97,9 @@ def test_orm_insert(self): self.session.commit() spans = self.memory_exporter.get_finished_spans() - # identity insert on before the insert, insert, and identity insert off after the insert - self.assertEqual(len(spans), 3) - span = spans[1] + # connect, identity insert on before the insert, insert, and identity insert off after the insert + self.assertEqual(len(spans), 4) + span = spans[2] self._check_span(span, "INSERT") self.assertIn( "INSERT INTO players", diff --git a/tests/opentelemetry-docker-tests/tests/sqlalchemy_tests/test_mysql.py b/tests/opentelemetry-docker-tests/tests/sqlalchemy_tests/test_mysql.py --- a/tests/opentelemetry-docker-tests/tests/sqlalchemy_tests/test_mysql.py +++ b/tests/opentelemetry-docker-tests/tests/sqlalchemy_tests/test_mysql.py @@ -68,8 +68,9 @@ def test_engine_execute_errors(self): conn.execute("SELECT * FROM a_wrong_table").fetchall() spans = self.memory_exporter.get_finished_spans() - self.assertEqual(len(spans), 1) - span = spans[0] + # one span for the connection and one for the query + self.assertEqual(len(spans), 2) + span = spans[1] # span fields self.assertEqual(span.name, "SELECT opentelemetry-tests") self.assertEqual( diff --git a/tests/opentelemetry-docker-tests/tests/sqlalchemy_tests/test_postgres.py b/tests/opentelemetry-docker-tests/tests/sqlalchemy_tests/test_postgres.py --- a/tests/opentelemetry-docker-tests/tests/sqlalchemy_tests/test_postgres.py +++ b/tests/opentelemetry-docker-tests/tests/sqlalchemy_tests/test_postgres.py @@ -62,8 +62,9 @@ def test_engine_execute_errors(self): conn.execute("SELECT * FROM a_wrong_table").fetchall() spans = self.memory_exporter.get_finished_spans() - self.assertEqual(len(spans), 1) - span = spans[0] + # one span for the connection and one for the query + self.assertEqual(len(spans), 2) + span = spans[1] # span fields self.assertEqual(span.name, "SELECT opentelemetry-tests") self.assertEqual( diff --git a/tests/opentelemetry-docker-tests/tests/sqlalchemy_tests/test_sqlite.py b/tests/opentelemetry-docker-tests/tests/sqlalchemy_tests/test_sqlite.py --- a/tests/opentelemetry-docker-tests/tests/sqlalchemy_tests/test_sqlite.py +++ b/tests/opentelemetry-docker-tests/tests/sqlalchemy_tests/test_sqlite.py @@ -38,8 +38,9 @@ def test_engine_execute_errors(self): conn.execute(stmt).fetchall() spans = self.memory_exporter.get_finished_spans() - self.assertEqual(len(spans), 1) - span = spans[0] + # one span for the connection and one span for the query + self.assertEqual(len(spans), 2) + span = spans[1] # span fields self.assertEqual(span.name, "SELECT :memory:") self.assertEqual(
Instrument SQLAlchemy engine connection phase ** Is your feature request related to a problem? ** The SQLAlchemy instrumentation does not trace the actual connection to the database **Describe the solution you'd like** I want that `connect` function will also be traced **Describe alternatives you've considered** Which alternative solutions or features have you considered? **Additional context** We are working with SQLAlchemy (snowflake db) and we implemented a solution where we can see the `connect` span also as attached in the screenshot (the span is `database-connect`) ![image](https://user-images.githubusercontent.com/12069200/173789203-b75f42d2-7ae6-4c11-aa0c-4937ede75422.png)
2022-06-15T09:14:07
open-telemetry/opentelemetry-python-contrib
1,137
open-telemetry__opentelemetry-python-contrib-1137
[ "1037" ]
f03bef257998c4109072316d21210ed168ce2a4b
diff --git a/instrumentation/opentelemetry-instrumentation-pyramid/src/opentelemetry/instrumentation/pyramid/callbacks.py b/instrumentation/opentelemetry-instrumentation-pyramid/src/opentelemetry/instrumentation/pyramid/callbacks.py --- a/instrumentation/opentelemetry-instrumentation-pyramid/src/opentelemetry/instrumentation/pyramid/callbacks.py +++ b/instrumentation/opentelemetry-instrumentation-pyramid/src/opentelemetry/instrumentation/pyramid/callbacks.py @@ -15,7 +15,7 @@ from logging import getLogger from pyramid.events import BeforeTraversal -from pyramid.httpexceptions import HTTPError, HTTPException +from pyramid.httpexceptions import HTTPException, HTTPServerError from pyramid.settings import asbool from pyramid.tweens import EXCVIEW @@ -198,9 +198,9 @@ def trace_tween(request): activation = request.environ.get(_ENVIRON_ACTIVATION_KEY) - # Only considering HTTPClientError and HTTPServerError - # to make sure HTTPRedirection is not reported as error - if isinstance(response, HTTPError): + # Only considering HTTPServerError + # to make sure 200, 300 and 400 exceptions are not reported as error + if isinstance(response, HTTPServerError): activation.__exit__( type(response), response,
diff --git a/instrumentation/opentelemetry-instrumentation-pyramid/tests/pyramid_base_test.py b/instrumentation/opentelemetry-instrumentation-pyramid/tests/pyramid_base_test.py --- a/instrumentation/opentelemetry-instrumentation-pyramid/tests/pyramid_base_test.py +++ b/instrumentation/opentelemetry-instrumentation-pyramid/tests/pyramid_base_test.py @@ -24,6 +24,8 @@ def _hello_endpoint(request): helloid = int(request.matchdict["helloid"]) if helloid == 500: raise exc.HTTPInternalServerError() + if helloid == 404: + raise exc.HTTPNotFound() if helloid == 302: raise exc.HTTPFound() if helloid == 204: diff --git a/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_automatic.py b/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_automatic.py --- a/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_automatic.py +++ b/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_automatic.py @@ -136,6 +136,27 @@ def test_204_empty_response_is_not_an_error(self): span_list = self.memory_exporter.get_finished_spans() self.assertEqual(len(span_list), 1) + def test_400s_response_is_not_an_error(self): + tween_list = "pyramid.tweens.excview_tween_factory" + config = Configurator(settings={"pyramid.tweens": tween_list}) + self._common_initialization(config) + resp = self.client.get("/hello/404") + self.assertEqual(404, resp.status_code) + span_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(span_list), 1) + self.assertEqual(span_list[0].status.status_code, StatusCode.UNSET) + + PyramidInstrumentor().uninstrument() + + self.config = Configurator() + + self._common_initialization(self.config) + + resp = self.client.get("/hello/404") + self.assertEqual(404, resp.status_code) + span_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(span_list), 1) + class TestWrappedWithOtherFramework( InstrumentationTest, TestBase, WsgiTestBase
Ignore exception attributes for a given route or status (Pyramid) It would be convenient to provide a way to specify routes and/or status codes are not exceptional. A common pattern within Pyramid is to raise the desired response for certain business flows (e.g. raise a 301 to force a redirect, raise a 204 after deleting an entity, etc) rather than properly return. Because the response was raised and handled as an `HTTPException` the span is decorated with exception attributes even though the request was not actually exceptional. This causes many vendors to interpret a false-positive when calculating things like error rate. There is history of this functionality in other instrumentation: - https://ddtrace.readthedocs.io/en/stable/advanced_usage.html#custom-error-codes - https://docs.newrelic.com/docs/apm/agents/python-agent/configuration/python-agent-configuration/#error-ignore - https://docs.newrelic.com/docs/apm/agents/python-agent/configuration/python-agent-configuration/#error-ignore-status-codes
Having investigated this further, it looks like Pyramid instrumentation is miscategorizing most 200s and 300s exceptions as errors. Created a pull to fix that. I if understand correctly, we should ignore 4xx as well and only record 5xx exceptions as errors. According to the spec: > For HTTP status codes in the 4xx range span status MUST be left unset in case of SpanKind.SERVER and MUST be set to Error in case of SpanKind.CLIENT. > For HTTP status codes in the 5xx range, as well as any other code the client failed to interpret, span status MUST be set to Error. I think we are talking only about server spans here right? In that case only 5xx should be set to the span status as an error unless I misunderstood something. https://opentelemetry.io/docs/reference/specification/trace/semantic_conventions/http/#status
2022-06-16T19:19:00
open-telemetry/opentelemetry-python-contrib
1,177
open-telemetry__opentelemetry-python-contrib-1177
[ "1167" ]
ee4083982f5919e1366de62b9cf4dac28cc8a314
diff --git a/instrumentation/opentelemetry-instrumentation-redis/src/opentelemetry/instrumentation/redis/__init__.py b/instrumentation/opentelemetry-instrumentation-redis/src/opentelemetry/instrumentation/redis/__init__.py --- a/instrumentation/opentelemetry-instrumentation-redis/src/opentelemetry/instrumentation/redis/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-redis/src/opentelemetry/instrumentation/redis/__init__.py @@ -122,9 +122,12 @@ def response_hook(span, instance, response): if redis.VERSION >= _REDIS_ASYNCIO_VERSION: import redis.asyncio +_REDIS_CLUSTER_VERSION = (4, 1, 0) +_REDIS_ASYNCIO_CLUSTER_VERSION = (4, 3, 0) + def _set_connection_attributes(span, conn): - if not span.is_recording(): + if not span.is_recording() or not hasattr(conn, "connection_pool"): return for key, value in _extract_conn_attributes( conn.connection_pool.connection_kwargs @@ -159,10 +162,29 @@ def _traced_execute_command(func, instance, args, kwargs): return response def _traced_execute_pipeline(func, instance, args, kwargs): - cmds = [_format_command_args(c) for c, _ in instance.command_stack] - resource = "\n".join(cmds) + try: + command_stack = ( + instance.command_stack + if hasattr(instance, "command_stack") + else instance._command_stack + ) - span_name = " ".join([args[0] for args, _ in instance.command_stack]) + cmds = [ + _format_command_args(c.args if hasattr(c, "args") else c[0]) + for c in command_stack + ] + resource = "\n".join(cmds) + + span_name = " ".join( + [ + (c.args[0] if hasattr(c, "args") else c[0][0]) + for c in command_stack + ] + ) + except (AttributeError, IndexError): + command_stack = [] + resource = "" + span_name = "" with tracer.start_as_current_span( span_name, kind=trace.SpanKind.CLIENT @@ -171,7 +193,7 @@ def _traced_execute_pipeline(func, instance, args, kwargs): span.set_attribute(SpanAttributes.DB_STATEMENT, resource) _set_connection_attributes(span, instance) span.set_attribute( - "db.redis.pipeline_length", len(instance.command_stack) + "db.redis.pipeline_length", len(command_stack) ) response = func(*args, **kwargs) if callable(response_hook): @@ -196,6 +218,17 @@ def _traced_execute_pipeline(func, instance, args, kwargs): f"{pipeline_class}.immediate_execute_command", _traced_execute_command, ) + if redis.VERSION >= _REDIS_CLUSTER_VERSION: + wrap_function_wrapper( + "redis.cluster", + "RedisCluster.execute_command", + _traced_execute_command, + ) + wrap_function_wrapper( + "redis.cluster", + "ClusterPipeline.execute", + _traced_execute_pipeline, + ) if redis.VERSION >= _REDIS_ASYNCIO_VERSION: wrap_function_wrapper( "redis.asyncio", @@ -212,6 +245,17 @@ def _traced_execute_pipeline(func, instance, args, kwargs): f"{pipeline_class}.immediate_execute_command", _traced_execute_command, ) + if redis.VERSION >= _REDIS_ASYNCIO_CLUSTER_VERSION: + wrap_function_wrapper( + "redis.asyncio.cluster", + "RedisCluster.execute_command", + _traced_execute_command, + ) + wrap_function_wrapper( + "redis.asyncio.cluster", + "ClusterPipeline.execute", + _traced_execute_pipeline, + ) class RedisInstrumentor(BaseInstrumentor): @@ -258,8 +302,14 @@ def _uninstrument(self, **kwargs): unwrap(redis.Redis, "pipeline") unwrap(redis.client.Pipeline, "execute") unwrap(redis.client.Pipeline, "immediate_execute_command") + if redis.VERSION >= _REDIS_CLUSTER_VERSION: + unwrap(redis.cluster.RedisCluster, "execute_command") + unwrap(redis.cluster.ClusterPipeline, "execute") if redis.VERSION >= _REDIS_ASYNCIO_VERSION: unwrap(redis.asyncio.Redis, "execute_command") unwrap(redis.asyncio.Redis, "pipeline") unwrap(redis.asyncio.client.Pipeline, "execute") unwrap(redis.asyncio.client.Pipeline, "immediate_execute_command") + if redis.VERSION >= _REDIS_ASYNCIO_CLUSTER_VERSION: + unwrap(redis.asyncio.cluster.RedisCluster, "execute_command") + unwrap(redis.asyncio.cluster.ClusterPipeline, "execute")
diff --git a/tests/opentelemetry-docker-tests/tests/docker-compose.yml b/tests/opentelemetry-docker-tests/tests/docker-compose.yml --- a/tests/opentelemetry-docker-tests/tests/docker-compose.yml +++ b/tests/opentelemetry-docker-tests/tests/docker-compose.yml @@ -27,6 +27,17 @@ services: image: redis:4.0-alpine ports: - "127.0.0.1:6379:6379" + otrediscluster: + image: grokzen/redis-cluster:6.2.0 + environment: + - IP=0.0.0.0 + ports: + - "127.0.0.1:7000:7000" + - "127.0.0.1:7001:7001" + - "127.0.0.1:7002:7002" + - "127.0.0.1:7003:7003" + - "127.0.0.1:7004:7004" + - "127.0.0.1:7005:7005" otjaeger: image: jaegertracing/all-in-one:1.8 environment: diff --git a/tests/opentelemetry-docker-tests/tests/redis/test_redis_functional.py b/tests/opentelemetry-docker-tests/tests/redis/test_redis_functional.py --- a/tests/opentelemetry-docker-tests/tests/redis/test_redis_functional.py +++ b/tests/opentelemetry-docker-tests/tests/redis/test_redis_functional.py @@ -124,6 +124,72 @@ def test_parent(self): self.assertEqual(child_span.name, "GET") +class TestRedisClusterInstrument(TestBase): + def setUp(self): + super().setUp() + self.redis_client = redis.cluster.RedisCluster( + host="localhost", port=7000 + ) + self.redis_client.flushall() + RedisInstrumentor().instrument(tracer_provider=self.tracer_provider) + + def tearDown(self): + super().tearDown() + RedisInstrumentor().uninstrument() + + def _check_span(self, span, name): + self.assertEqual(span.name, name) + self.assertIs(span.status.status_code, trace.StatusCode.UNSET) + + def test_basics(self): + self.assertIsNone(self.redis_client.get("cheese")) + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 1) + span = spans[0] + self._check_span(span, "GET") + self.assertEqual( + span.attributes.get(SpanAttributes.DB_STATEMENT), "GET cheese" + ) + self.assertEqual(span.attributes.get("db.redis.args_length"), 2) + + def test_pipeline_traced(self): + with self.redis_client.pipeline(transaction=False) as pipeline: + pipeline.set("blah", 32) + pipeline.rpush("foo", "éé") + pipeline.hgetall("xxx") + pipeline.execute() + + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 1) + span = spans[0] + self._check_span(span, "SET RPUSH HGETALL") + self.assertEqual( + span.attributes.get(SpanAttributes.DB_STATEMENT), + "SET blah 32\nRPUSH foo éé\nHGETALL xxx", + ) + self.assertEqual(span.attributes.get("db.redis.pipeline_length"), 3) + + def test_parent(self): + """Ensure OpenTelemetry works with redis.""" + ot_tracer = trace.get_tracer("redis_svc") + + with ot_tracer.start_as_current_span("redis_get"): + self.assertIsNone(self.redis_client.get("cheese")) + + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 2) + child_span, parent_span = spans[0], spans[1] + + # confirm the parenting + self.assertIsNone(parent_span.parent) + self.assertIs(child_span.parent, parent_span.get_span_context()) + + self.assertEqual(parent_span.name, "redis_get") + self.assertEqual(parent_span.instrumentation_info.name, "redis_svc") + + self.assertEqual(child_span.name, "GET") + + def async_call(coro): loop = asyncio.get_event_loop() return loop.run_until_complete(coro) @@ -238,6 +304,77 @@ def test_parent(self): self.assertEqual(child_span.name, "GET") +class TestAsyncRedisClusterInstrument(TestBase): + def setUp(self): + super().setUp() + self.redis_client = redis.asyncio.cluster.RedisCluster( + host="localhost", port=7000 + ) + async_call(self.redis_client.flushall()) + RedisInstrumentor().instrument(tracer_provider=self.tracer_provider) + + def tearDown(self): + super().tearDown() + RedisInstrumentor().uninstrument() + + def _check_span(self, span, name): + self.assertEqual(span.name, name) + self.assertIs(span.status.status_code, trace.StatusCode.UNSET) + + def test_basics(self): + self.assertIsNone(async_call(self.redis_client.get("cheese"))) + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 1) + span = spans[0] + self._check_span(span, "GET") + self.assertEqual( + span.attributes.get(SpanAttributes.DB_STATEMENT), "GET cheese" + ) + self.assertEqual(span.attributes.get("db.redis.args_length"), 2) + + def test_pipeline_traced(self): + async def pipeline_simple(): + async with self.redis_client.pipeline( + transaction=False + ) as pipeline: + pipeline.set("blah", 32) + pipeline.rpush("foo", "éé") + pipeline.hgetall("xxx") + await pipeline.execute() + + async_call(pipeline_simple()) + + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 1) + span = spans[0] + self._check_span(span, "SET RPUSH HGETALL") + self.assertEqual( + span.attributes.get(SpanAttributes.DB_STATEMENT), + "SET blah 32\nRPUSH foo éé\nHGETALL xxx", + ) + self.assertEqual(span.attributes.get("db.redis.pipeline_length"), 3) + + def test_parent(self): + """Ensure OpenTelemetry works with redis.""" + ot_tracer = trace.get_tracer("redis_svc") + + with ot_tracer.start_as_current_span("redis_get"): + self.assertIsNone(async_call(self.redis_client.get("cheese"))) + + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 2) + child_span, parent_span = spans[0], spans[1] + + # confirm the parenting + self.assertIsNone(parent_span.parent) + self.assertIs(child_span.parent, parent_span.get_span_context()) + + self.assertEqual(parent_span.name, "redis_get") + self.assertEqual(parent_span.instrumentation_info.name, "redis_svc") + + self.assertEqual(child_span.name, "GET") + + class TestRedisDBIndexInstrument(TestBase): def setUp(self): super().setUp()
[Redis] RedisCluster support Redis instrumentation does not support RedisCluster ([redis.asyncio.cluster.RedisCluster](https://github.com/redis/redis-py/blob/master/redis/asyncio/cluster.py#L102)). I tried to instrument RedisCluster using `opentelemetry-instrumentation-redis` as below, but the application did not export any traces related redis. ```python from opentelemetry.instrumentation.redis import RedisInstrumentor from redis.asyncio.cluster import RedisCluster as Redis RedisInstrumentor().instrument() client = await Redis(host=host, port=6379) client.get("my-key") ``` It would be very helpful if redis instrumentation supports RedisCluster.
@sungwonh Would you like send a PR for this? The important part is to write wrapper functions for cluster similar to [this](https://github.com/open-telemetry/opentelemetry-python-contrib/blob/main/instrumentation/opentelemetry-instrumentation-redis/src/opentelemetry/instrumentation/redis/__init__.py#L186-L197). @srikanthccv OK. I will send a PR for this.
2022-07-02T12:47:46
open-telemetry/opentelemetry-python-contrib
1,186
open-telemetry__opentelemetry-python-contrib-1186
[ "1155" ]
14077a95c55e3f285d94679c6fe45b3bcce23622
diff --git a/instrumentation/opentelemetry-instrumentation-flask/src/opentelemetry/instrumentation/flask/__init__.py b/instrumentation/opentelemetry-instrumentation-flask/src/opentelemetry/instrumentation/flask/__init__.py --- a/instrumentation/opentelemetry-instrumentation-flask/src/opentelemetry/instrumentation/flask/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-flask/src/opentelemetry/instrumentation/flask/__init__.py @@ -141,6 +141,7 @@ def response_hook(span: Span, status: str, response_headers: List): """ from logging import getLogger +from timeit import default_timer from typing import Collection import flask @@ -154,6 +155,7 @@ def response_hook(span: Span, status: str, response_headers: List): get_global_response_propagator, ) from opentelemetry.instrumentation.utils import _start_internal_or_server_span +from opentelemetry.metrics import get_meter from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.util._time import _time_ns from opentelemetry.util.http import get_excluded_urls, parse_excluded_urls @@ -165,7 +167,6 @@ def response_hook(span: Span, status: str, response_headers: List): _ENVIRON_ACTIVATION_KEY = "opentelemetry-flask.activation_key" _ENVIRON_TOKEN = "opentelemetry-flask.token" - _excluded_urls_from_env = get_excluded_urls("FLASK") @@ -178,13 +179,26 @@ def get_default_span_name(): return span_name -def _rewrapped_app(wsgi_app, response_hook=None, excluded_urls=None): +def _rewrapped_app( + wsgi_app, + active_requests_counter, + duration_histogram, + response_hook=None, + excluded_urls=None, +): def _wrapped_app(wrapped_app_environ, start_response): # We want to measure the time for route matching, etc. # In theory, we could start the span here and use # update_name later but that API is "highly discouraged" so # we better avoid it. wrapped_app_environ[_ENVIRON_STARTTIME_KEY] = _time_ns() + start = default_timer() + attributes = otel_wsgi.collect_request_attributes(wrapped_app_environ) + active_requests_count_attrs = ( + otel_wsgi._parse_active_request_count_attrs(attributes) + ) + duration_attrs = otel_wsgi._parse_duration_attrs(attributes) + active_requests_counter.add(1, active_requests_count_attrs) def _start_response(status, response_headers, *args, **kwargs): if flask.request and ( @@ -204,6 +218,11 @@ def _start_response(status, response_headers, *args, **kwargs): otel_wsgi.add_response_attributes( span, status, response_headers ) + status_code = otel_wsgi._parse_status_code(status) + if status_code is not None: + duration_attrs[ + SpanAttributes.HTTP_STATUS_CODE + ] = status_code if ( span.is_recording() and span.kind == trace.SpanKind.SERVER @@ -223,13 +242,19 @@ def _start_response(status, response_headers, *args, **kwargs): response_hook(span, status, response_headers) return start_response(status, response_headers, *args, **kwargs) - return wsgi_app(wrapped_app_environ, _start_response) + result = wsgi_app(wrapped_app_environ, _start_response) + duration = max(round((default_timer() - start) * 1000), 0) + duration_histogram.record(duration, duration_attrs) + active_requests_counter.add(-1, active_requests_count_attrs) + return result return _wrapped_app def _wrapped_before_request( - request_hook=None, tracer=None, excluded_urls=None + request_hook=None, + tracer=None, + excluded_urls=None, ): def _before_request(): if excluded_urls and excluded_urls.url_disabled(flask.request.url): @@ -278,7 +303,9 @@ def _before_request(): return _before_request -def _wrapped_teardown_request(excluded_urls=None): +def _wrapped_teardown_request( + excluded_urls=None, +): def _teardown_request(exc): # pylint: disable=E1101 if excluded_urls and excluded_urls.url_disabled(flask.request.url): @@ -290,7 +317,6 @@ def _teardown_request(exc): # a way that doesn't run `before_request`, like when it is created # with `app.test_request_context`. return - if exc is None: activation.__exit__(None, None, None) else: @@ -310,6 +336,7 @@ class _InstrumentedFlask(flask.Flask): _tracer_provider = None _request_hook = None _response_hook = None + _meter_provider = None def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -317,8 +344,24 @@ def __init__(self, *args, **kwargs): self._original_wsgi_app = self.wsgi_app self._is_instrumented_by_opentelemetry = True + meter = get_meter( + __name__, __version__, _InstrumentedFlask._meter_provider + ) + duration_histogram = meter.create_histogram( + name="http.server.duration", + unit="ms", + description="measures the duration of the inbound HTTP request", + ) + active_requests_counter = meter.create_up_down_counter( + name="http.server.active_requests", + unit="requests", + description="measures the number of concurrent HTTP requests that are currently in-flight", + ) + self.wsgi_app = _rewrapped_app( self.wsgi_app, + active_requests_counter, + duration_histogram, _InstrumentedFlask._response_hook, excluded_urls=_InstrumentedFlask._excluded_urls, ) @@ -367,6 +410,8 @@ def _instrument(self, **kwargs): if excluded_urls is None else parse_excluded_urls(excluded_urls) ) + meter_provider = kwargs.get("meter_provider") + _InstrumentedFlask._meter_provider = meter_provider flask.Flask = _InstrumentedFlask def _uninstrument(self, **kwargs): @@ -379,6 +424,7 @@ def instrument_app( response_hook=None, tracer_provider=None, excluded_urls=None, + meter_provider=None, ): if not hasattr(app, "_is_instrumented_by_opentelemetry"): app._is_instrumented_by_opentelemetry = False @@ -389,9 +435,25 @@ def instrument_app( if excluded_urls is not None else _excluded_urls_from_env ) + meter = get_meter(__name__, __version__, meter_provider) + duration_histogram = meter.create_histogram( + name="http.server.duration", + unit="ms", + description="measures the duration of the inbound HTTP request", + ) + active_requests_counter = meter.create_up_down_counter( + name="http.server.active_requests", + unit="requests", + description="measures the number of concurrent HTTP requests that are currently in-flight", + ) + app._original_wsgi_app = app.wsgi_app app.wsgi_app = _rewrapped_app( - app.wsgi_app, response_hook, excluded_urls=excluded_urls + app.wsgi_app, + active_requests_counter, + duration_histogram, + response_hook, + excluded_urls=excluded_urls, ) tracer = trace.get_tracer(__name__, __version__, tracer_provider) diff --git a/instrumentation/opentelemetry-instrumentation-flask/src/opentelemetry/instrumentation/flask/package.py b/instrumentation/opentelemetry-instrumentation-flask/src/opentelemetry/instrumentation/flask/package.py --- a/instrumentation/opentelemetry-instrumentation-flask/src/opentelemetry/instrumentation/flask/package.py +++ b/instrumentation/opentelemetry-instrumentation-flask/src/opentelemetry/instrumentation/flask/package.py @@ -14,3 +14,5 @@ _instruments = ("flask >= 1.0, < 3.0",) + +_supports_metrics = True diff --git a/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py b/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py --- a/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py @@ -334,6 +334,22 @@ def _parse_status_code(resp_status): return None +def _parse_active_request_count_attrs(req_attrs): + active_requests_count_attrs = {} + for attr_key in _active_requests_count_attrs: + if req_attrs.get(attr_key) is not None: + active_requests_count_attrs[attr_key] = req_attrs[attr_key] + return active_requests_count_attrs + + +def _parse_duration_attrs(req_attrs): + duration_attrs = {} + for attr_key in _duration_attrs: + if req_attrs.get(attr_key) is not None: + duration_attrs[attr_key] = req_attrs[attr_key] + return duration_attrs + + def add_response_attributes( span, start_response_status, response_headers ): # pylint: disable=unused-argument @@ -436,15 +452,10 @@ def __call__(self, environ, start_response): start_response: The WSGI start_response callable. """ req_attrs = collect_request_attributes(environ) - active_requests_count_attrs = {} - for attr_key in _active_requests_count_attrs: - if req_attrs.get(attr_key) is not None: - active_requests_count_attrs[attr_key] = req_attrs[attr_key] - - duration_attrs = {} - for attr_key in _duration_attrs: - if req_attrs.get(attr_key) is not None: - duration_attrs[attr_key] = req_attrs[attr_key] + active_requests_count_attrs = _parse_active_request_count_attrs( + req_attrs + ) + duration_attrs = _parse_duration_attrs(req_attrs) span, token = _start_internal_or_server_span( tracer=self.tracer,
diff --git a/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py b/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py --- a/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py +++ b/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +from timeit import default_timer from unittest.mock import Mock, patch from flask import Flask, request @@ -23,7 +24,15 @@ get_global_response_propagator, set_global_response_propagator, ) -from opentelemetry.instrumentation.wsgi import OpenTelemetryMiddleware +from opentelemetry.instrumentation.wsgi import ( + OpenTelemetryMiddleware, + _active_requests_count_attrs, + _duration_attrs, +) +from opentelemetry.sdk.metrics.export import ( + HistogramDataPoint, + NumberDataPoint, +) from opentelemetry.sdk.resources import Resource from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.test.wsgitestutil import WsgiTestBase @@ -49,6 +58,16 @@ def expected_attributes(override_attributes): return default_attributes +_expected_metric_names = [ + "http.server.active_requests", + "http.server.duration", +] +_recommended_attrs = { + "http.server.active_requests": _active_requests_count_attrs, + "http.server.duration": _duration_attrs, +} + + class TestProgrammatic(InstrumentationTest, WsgiTestBase): def setUp(self): super().setUp() @@ -250,6 +269,106 @@ def test_exclude_lists_from_explicit(self): span_list = self.memory_exporter.get_finished_spans() self.assertEqual(len(span_list), 1) + def test_flask_metrics(self): + start = default_timer() + self.client.get("/hello/123") + self.client.get("/hello/321") + self.client.get("/hello/756") + duration = max(round((default_timer() - start) * 1000), 0) + metrics_list = self.memory_metrics_reader.get_metrics_data() + number_data_point_seen = False + histogram_data_point_seen = False + self.assertTrue(len(metrics_list.resource_metrics) != 0) + for resource_metric in metrics_list.resource_metrics: + self.assertTrue(len(resource_metric.scope_metrics) != 0) + for scope_metric in resource_metric.scope_metrics: + self.assertTrue(len(scope_metric.metrics) != 0) + for metric in scope_metric.metrics: + self.assertIn(metric.name, _expected_metric_names) + data_points = list(metric.data.data_points) + self.assertEqual(len(data_points), 1) + for point in data_points: + if isinstance(point, HistogramDataPoint): + self.assertEqual(point.count, 3) + self.assertAlmostEqual( + duration, point.sum, delta=10 + ) + histogram_data_point_seen = True + if isinstance(point, NumberDataPoint): + number_data_point_seen = True + for attr in point.attributes: + self.assertIn( + attr, _recommended_attrs[metric.name] + ) + self.assertTrue(number_data_point_seen and histogram_data_point_seen) + + def test_flask_metric_values(self): + start = default_timer() + self.client.post("/hello/756") + self.client.post("/hello/756") + self.client.post("/hello/756") + duration = max(round((default_timer() - start) * 1000), 0) + metrics_list = self.memory_metrics_reader.get_metrics_data() + for resource_metric in metrics_list.resource_metrics: + for scope_metric in resource_metric.scope_metrics: + for metric in scope_metric.metrics: + for point in list(metric.data.data_points): + if isinstance(point, HistogramDataPoint): + self.assertEqual(point.count, 3) + self.assertAlmostEqual( + duration, point.sum, delta=10 + ) + if isinstance(point, NumberDataPoint): + self.assertEqual(point.value, 0) + + def test_basic_metric_success(self): + self.client.get("/hello/756") + expected_duration_attributes = { + "http.method": "GET", + "http.host": "localhost", + "http.scheme": "http", + "http.flavor": "1.1", + "http.server_name": "localhost", + "net.host.port": 80, + "http.status_code": 200, + } + expected_requests_count_attributes = { + "http.method": "GET", + "http.host": "localhost", + "http.scheme": "http", + "http.flavor": "1.1", + "http.server_name": "localhost", + } + metrics_list = self.memory_metrics_reader.get_metrics_data() + for resource_metric in metrics_list.resource_metrics: + for scope_metrics in resource_metric.scope_metrics: + for metric in scope_metrics.metrics: + for point in list(metric.data.data_points): + if isinstance(point, HistogramDataPoint): + self.assertDictEqual( + expected_duration_attributes, + dict(point.attributes), + ) + self.assertEqual(point.count, 1) + elif isinstance(point, NumberDataPoint): + self.assertDictEqual( + expected_requests_count_attributes, + dict(point.attributes), + ) + self.assertEqual(point.value, 0) + + def test_metric_uninstrument(self): + self.client.delete("/hello/756") + FlaskInstrumentor().uninstrument_app(self.app) + self.client.delete("/hello/756") + metrics_list = self.memory_metrics_reader.get_metrics_data() + for resource_metric in metrics_list.resource_metrics: + for scope_metric in resource_metric.scope_metrics: + for metric in scope_metric.metrics: + for point in list(metric.data.data_points): + if isinstance(point, HistogramDataPoint): + self.assertEqual(point.count, 1) + class TestProgrammaticHooks(InstrumentationTest, WsgiTestBase): def setUp(self):
Metrics instrumentation flask HTPP metrics: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/semantic_conventions/http-metrics.md
@srikanthccv Please assign this issue to me.
2022-07-07T10:54:40
open-telemetry/opentelemetry-python-contrib
1,197
open-telemetry__opentelemetry-python-contrib-1197
[ "1160" ]
ebe6d1804bccff184edb379d7780469762c7b854
diff --git a/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py b/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py --- a/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py @@ -149,6 +149,7 @@ def client_response_hook(span: Span, message: dict): import typing import urllib from functools import wraps +from timeit import default_timer from typing import Tuple from asgiref.compatibility import guarantee_single_callable @@ -162,6 +163,7 @@ def client_response_hook(span: Span, message: dict): _start_internal_or_server_span, http_status_to_status_code, ) +from opentelemetry.metrics import get_meter from opentelemetry.propagators.textmap import Getter, Setter from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.trace import Span, set_span_in_context @@ -169,6 +171,8 @@ def client_response_hook(span: Span, message: dict): from opentelemetry.util.http import ( OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST, OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE, + _parse_active_request_count_attrs, + _parse_duration_attrs, get_custom_headers, normalise_request_header_name, normalise_response_header_name, @@ -391,9 +395,21 @@ def __init__( client_request_hook: _ClientRequestHookT = None, client_response_hook: _ClientResponseHookT = None, tracer_provider=None, + meter_provider=None, ): self.app = guarantee_single_callable(app) self.tracer = trace.get_tracer(__name__, __version__, tracer_provider) + self.meter = get_meter(__name__, __version__, meter_provider) + self.duration_histogram = self.meter.create_histogram( + name="http.server.duration", + unit="ms", + description="measures the duration of the inbound HTTP request", + ) + self.active_requests_counter = self.meter.create_up_down_counter( + name="http.server.active_requests", + unit="requests", + description="measures the number of concurrent HTTP requests that are currently in-flight", + ) self.excluded_urls = excluded_urls self.default_span_details = ( default_span_details or get_default_span_details @@ -426,12 +442,17 @@ async def __call__(self, scope, receive, send): context_carrier=scope, context_getter=asgi_getter, ) - + attributes = collect_request_attributes(scope) + attributes.update(additional_attributes) + active_requests_count_attrs = _parse_active_request_count_attrs( + attributes + ) + duration_attrs = _parse_duration_attrs(attributes) + if scope["type"] == "http": + self.active_requests_counter.add(1, active_requests_count_attrs) try: with trace.use_span(span, end_on_exit=True) as current_span: if current_span.is_recording(): - attributes = collect_request_attributes(scope) - attributes.update(additional_attributes) for key, value in attributes.items(): current_span.set_attribute(key, value) @@ -454,10 +475,18 @@ async def __call__(self, scope, receive, send): span_name, scope, send, + duration_attrs, ) + start = default_timer() await self.app(scope, otel_receive, otel_send) finally: + if scope["type"] == "http": + duration = max(round((default_timer() - start) * 1000), 0) + self.duration_histogram.record(duration, duration_attrs) + self.active_requests_counter.add( + -1, active_requests_count_attrs + ) if token: context.detach(token) @@ -478,7 +507,9 @@ async def otel_receive(): return otel_receive - def _get_otel_send(self, server_span, server_span_name, scope, send): + def _get_otel_send( + self, server_span, server_span_name, scope, send, duration_attrs + ): @wraps(send) async def otel_send(message): with self.tracer.start_as_current_span( @@ -489,6 +520,9 @@ async def otel_send(message): if send_span.is_recording(): if message["type"] == "http.response.start": status_code = message["status"] + duration_attrs[ + SpanAttributes.HTTP_STATUS_CODE + ] = status_code set_status_code(server_span, status_code) set_status_code(send_span, status_code) elif message["type"] == "websocket.send": diff --git a/util/opentelemetry-util-http/src/opentelemetry/util/http/__init__.py b/util/opentelemetry-util-http/src/opentelemetry/util/http/__init__.py --- a/util/opentelemetry-util-http/src/opentelemetry/util/http/__init__.py +++ b/util/opentelemetry-util-http/src/opentelemetry/util/http/__init__.py @@ -18,6 +18,8 @@ from typing import Iterable, List from urllib.parse import urlparse, urlunparse +from opentelemetry.semconv.trace import SpanAttributes + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST = ( "OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST" ) @@ -25,6 +27,26 @@ "OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE" ) +# List of recommended metrics attributes +_duration_attrs = [ + SpanAttributes.HTTP_METHOD, + SpanAttributes.HTTP_HOST, + SpanAttributes.HTTP_SCHEME, + SpanAttributes.HTTP_STATUS_CODE, + SpanAttributes.HTTP_FLAVOR, + SpanAttributes.HTTP_SERVER_NAME, + SpanAttributes.NET_HOST_NAME, + SpanAttributes.NET_HOST_PORT, +] + +_active_requests_count_attrs = [ + SpanAttributes.HTTP_METHOD, + SpanAttributes.HTTP_HOST, + SpanAttributes.HTTP_SCHEME, + SpanAttributes.HTTP_FLAVOR, + SpanAttributes.HTTP_SERVER_NAME, +] + class ExcludeList: """Class to exclude certain paths (given as a list of regexes) from tracing requests""" @@ -125,3 +147,19 @@ def get_custom_headers(env_var: str) -> List[str]: for custom_headers in custom_headers.split(",") ] return custom_headers + + +def _parse_active_request_count_attrs(req_attrs): + active_requests_count_attrs = {} + for attr_key in _active_requests_count_attrs: + if req_attrs.get(attr_key) is not None: + active_requests_count_attrs[attr_key] = req_attrs[attr_key] + return active_requests_count_attrs + + +def _parse_duration_attrs(req_attrs): + duration_attrs = {} + for attr_key in _duration_attrs: + if req_attrs.get(attr_key) is not None: + duration_attrs[attr_key] = req_attrs[attr_key] + return duration_attrs
diff --git a/instrumentation/opentelemetry-instrumentation-asgi/tests/test_asgi_middleware.py b/instrumentation/opentelemetry-instrumentation-asgi/tests/test_asgi_middleware.py --- a/instrumentation/opentelemetry-instrumentation-asgi/tests/test_asgi_middleware.py +++ b/instrumentation/opentelemetry-instrumentation-asgi/tests/test_asgi_middleware.py @@ -14,6 +14,7 @@ import sys import unittest +from timeit import default_timer from unittest import mock import opentelemetry.instrumentation.asgi as otel_asgi @@ -24,6 +25,10 @@ set_global_response_propagator, ) from opentelemetry.sdk import resources +from opentelemetry.sdk.metrics.export import ( + HistogramDataPoint, + NumberDataPoint, +) from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.test.asgitestutil import ( AsgiTestBase, @@ -34,8 +39,19 @@ from opentelemetry.util.http import ( OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST, OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE, + _active_requests_count_attrs, + _duration_attrs, ) +_expected_metric_names = [ + "http.server.active_requests", + "http.server.duration", +] +_recommended_attrs = { + "http.server.active_requests": _active_requests_count_attrs, + "http.server.duration": _duration_attrs, +} + async def http_app(scope, receive, send): message = await receive() @@ -523,6 +539,101 @@ def update_expected_hook_results(expected): outputs, modifiers=[update_expected_hook_results] ) + def test_asgi_metrics(self): + app = otel_asgi.OpenTelemetryMiddleware(simple_asgi) + self.seed_app(app) + self.send_default_request() + self.seed_app(app) + self.send_default_request() + self.seed_app(app) + self.send_default_request() + metrics_list = self.memory_metrics_reader.get_metrics_data() + number_data_point_seen = False + histogram_data_point_seen = False + self.assertTrue(len(metrics_list.resource_metrics) != 0) + for resource_metric in metrics_list.resource_metrics: + self.assertTrue(len(resource_metric.scope_metrics) != 0) + for scope_metric in resource_metric.scope_metrics: + self.assertTrue(len(scope_metric.metrics) != 0) + for metric in scope_metric.metrics: + self.assertIn(metric.name, _expected_metric_names) + data_points = list(metric.data.data_points) + self.assertEqual(len(data_points), 1) + for point in data_points: + if isinstance(point, HistogramDataPoint): + self.assertEqual(point.count, 3) + histogram_data_point_seen = True + if isinstance(point, NumberDataPoint): + number_data_point_seen = True + for attr in point.attributes: + self.assertIn( + attr, _recommended_attrs[metric.name] + ) + self.assertTrue(number_data_point_seen and histogram_data_point_seen) + + def test_basic_metric_success(self): + app = otel_asgi.OpenTelemetryMiddleware(simple_asgi) + self.seed_app(app) + start = default_timer() + self.send_default_request() + duration = max(round((default_timer() - start) * 1000), 0) + expected_duration_attributes = { + "http.method": "GET", + "http.host": "127.0.0.1", + "http.scheme": "http", + "http.flavor": "1.0", + "net.host.port": 80, + "http.status_code": 200, + } + expected_requests_count_attributes = { + "http.method": "GET", + "http.host": "127.0.0.1", + "http.scheme": "http", + "http.flavor": "1.0", + } + metrics_list = self.memory_metrics_reader.get_metrics_data() + for resource_metric in metrics_list.resource_metrics: + for scope_metrics in resource_metric.scope_metrics: + for metric in scope_metrics.metrics: + for point in list(metric.data.data_points): + if isinstance(point, HistogramDataPoint): + self.assertDictEqual( + expected_duration_attributes, + dict(point.attributes), + ) + self.assertEqual(point.count, 1) + self.assertAlmostEqual( + duration, point.sum, delta=5 + ) + elif isinstance(point, NumberDataPoint): + self.assertDictEqual( + expected_requests_count_attributes, + dict(point.attributes), + ) + self.assertEqual(point.value, 0) + + def test_no_metric_for_websockets(self): + self.scope = { + "type": "websocket", + "http_version": "1.1", + "scheme": "ws", + "path": "/", + "query_string": b"", + "headers": [], + "client": ("127.0.0.1", 32767), + "server": ("127.0.0.1", 80), + } + app = otel_asgi.OpenTelemetryMiddleware(simple_asgi) + self.seed_app(app) + self.send_input({"type": "websocket.connect"}) + self.send_input({"type": "websocket.receive", "text": "ping"}) + self.send_input({"type": "websocket.disconnect"}) + self.get_all_output() + metrics_list = self.memory_metrics_reader.get_metrics_data() + self.assertEqual( + len(metrics_list.resource_metrics[0].scope_metrics), 0 + ) + class TestAsgiAttributes(unittest.TestCase): def setUp(self):
Metrics instrumentation asgi HTTP Metrics: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/semantic_conventions/http-metrics.md
I started working on this by following WSGI's package's lead. I can't really make any promises as I'm having some trouble setting up my dev environment, but thought I'd drop a note here. I am going to assign this to you. If you can't work on it anymore just leave a comment. @mmalecki If you have not yet started working on it or if you are stuck, I would like to pick this issue. Also this issue is a blocker for #1156 assigned to me. c.c.: @srikanthccv Please do @TheAnshul756. I got stuck, sadly.
2022-07-19T11:05:53
open-telemetry/opentelemetry-python-contrib
1,198
open-telemetry__opentelemetry-python-contrib-1198
[ "1144" ]
cbf005be6fb17f35b4cbaa4e76ac30bb64b3a258
diff --git a/instrumentation/opentelemetry-instrumentation-urllib3/src/opentelemetry/instrumentation/urllib3/__init__.py b/instrumentation/opentelemetry-instrumentation-urllib3/src/opentelemetry/instrumentation/urllib3/__init__.py --- a/instrumentation/opentelemetry-instrumentation-urllib3/src/opentelemetry/instrumentation/urllib3/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-urllib3/src/opentelemetry/instrumentation/urllib3/__init__.py @@ -66,6 +66,7 @@ def response_hook(span, request, response): import contextlib import typing +from timeit import default_timer from typing import Collection import urllib3.connectionpool @@ -83,9 +84,10 @@ def response_hook(span, request, response): http_status_to_status_code, unwrap, ) +from opentelemetry.metrics import Histogram, get_meter from opentelemetry.propagate import inject from opentelemetry.semconv.trace import SpanAttributes -from opentelemetry.trace import Span, SpanKind, get_tracer +from opentelemetry.trace import Span, SpanKind, Tracer, get_tracer from opentelemetry.trace.status import Status from opentelemetry.util.http.httplib import set_ip_on_next_http_connection @@ -135,8 +137,31 @@ def _instrument(self, **kwargs): """ tracer_provider = kwargs.get("tracer_provider") tracer = get_tracer(__name__, __version__, tracer_provider) + + meter_provider = kwargs.get("meter_provider") + meter = get_meter(__name__, __version__, meter_provider) + + duration_histogram = meter.create_histogram( + name="http.client.duration", + unit="ms", + description="measures the duration outbound HTTP requests", + ) + request_size_histogram = meter.create_histogram( + name="http.client.request.size", + unit="By", + description="measures the size of HTTP request messages (compressed)", + ) + response_size_histogram = meter.create_histogram( + name="http.client.response.size", + unit="By", + description="measures the size of HTTP response messages (compressed)", + ) + _instrument( tracer, + duration_histogram, + request_size_histogram, + response_size_histogram, request_hook=kwargs.get("request_hook"), response_hook=kwargs.get("response_hook"), url_filter=kwargs.get("url_filter"), @@ -147,7 +172,10 @@ def _uninstrument(self, **kwargs): def _instrument( - tracer, + tracer: Tracer, + duration_histogram: Histogram, + request_size_histogram: Histogram, + response_size_histogram: Histogram, request_hook: _RequestHookT = None, response_hook: _ResponseHookT = None, url_filter: _UrlFilterT = None, @@ -175,11 +203,30 @@ def instrumented_urlopen(wrapped, instance, args, kwargs): inject(headers) with _suppress_further_instrumentation(): + start_time = default_timer() response = wrapped(*args, **kwargs) + elapsed_time = round((default_timer() - start_time) * 1000) _apply_response(span, response) if callable(response_hook): response_hook(span, instance, response) + + request_size = 0 if body is None else len(body) + response_size = int(response.headers.get("Content-Length", 0)) + metric_attributes = _create_metric_attributes( + instance, response, method + ) + + duration_histogram.record( + elapsed_time, attributes=metric_attributes + ) + request_size_histogram.record( + request_size, attributes=metric_attributes + ) + response_size_histogram.record( + response_size, attributes=metric_attributes + ) + return response wrapt.wrap_function_wrapper( @@ -254,6 +301,29 @@ def _is_instrumentation_suppressed() -> bool: ) +def _create_metric_attributes( + instance: urllib3.connectionpool.HTTPConnectionPool, + response: urllib3.response.HTTPResponse, + method: str, +) -> dict: + metric_attributes = { + SpanAttributes.HTTP_METHOD: method, + SpanAttributes.HTTP_HOST: instance.host, + SpanAttributes.HTTP_SCHEME: instance.scheme, + SpanAttributes.HTTP_STATUS_CODE: response.status, + SpanAttributes.NET_PEER_NAME: instance.host, + SpanAttributes.NET_PEER_PORT: instance.port, + } + + version = getattr(response, "version") + if version: + metric_attributes[SpanAttributes.HTTP_FLAVOR] = ( + "1.1" if version == 11 else "1.0" + ) + + return metric_attributes + + @contextlib.contextmanager def _suppress_further_instrumentation(): token = context.attach( diff --git a/instrumentation/opentelemetry-instrumentation-urllib3/src/opentelemetry/instrumentation/urllib3/package.py b/instrumentation/opentelemetry-instrumentation-urllib3/src/opentelemetry/instrumentation/urllib3/package.py --- a/instrumentation/opentelemetry-instrumentation-urllib3/src/opentelemetry/instrumentation/urllib3/package.py +++ b/instrumentation/opentelemetry-instrumentation-urllib3/src/opentelemetry/instrumentation/urllib3/package.py @@ -14,3 +14,5 @@ _instruments = ("urllib3 >= 1.0.0, < 2.0.0",) + +_supports_metrics = True
diff --git a/instrumentation/opentelemetry-instrumentation-urllib3/tests/test_urllib3_ip_support.py b/instrumentation/opentelemetry-instrumentation-urllib3/tests/test_urllib3_ip_support.py --- a/instrumentation/opentelemetry-instrumentation-urllib3/tests/test_urllib3_ip_support.py +++ b/instrumentation/opentelemetry-instrumentation-urllib3/tests/test_urllib3_ip_support.py @@ -12,8 +12,11 @@ # See the License for the specific language governing permissions and # limitations under the License. +from timeit import default_timer + import urllib3 import urllib3.exceptions +from urllib3.request import encode_multipart_formdata from opentelemetry import trace from opentelemetry.instrumentation.urllib3 import URLLib3Instrumentor @@ -84,3 +87,136 @@ def assert_success_span( "net.peer.ip": self.assert_ip, } self.assertGreaterEqual(span.attributes.items(), attributes.items()) + + +class TestURLLib3InstrumentorMetric(HttpTestBase, TestBase): + def setUp(self): + super().setUp() + self.assert_ip = self.server.server_address[0] + self.assert_port = self.server.server_address[1] + self.http_host = ":".join(map(str, self.server.server_address[:2])) + self.http_url_base = "http://" + self.http_host + self.http_url = self.http_url_base + "/status/200" + URLLib3Instrumentor().instrument(meter_provider=self.meter_provider) + + def tearDown(self): + super().tearDown() + URLLib3Instrumentor().uninstrument() + + def test_metric_uninstrument(self): + with urllib3.PoolManager() as pool: + pool.request("GET", self.http_url) + URLLib3Instrumentor().uninstrument() + pool.request("GET", self.http_url) + + metrics_list = self.memory_metrics_reader.get_metrics_data() + for resource_metric in metrics_list.resource_metrics: + for scope_metric in resource_metric.scope_metrics: + for metric in scope_metric.metrics: + for point in list(metric.data.data_points): + self.assertEqual(point.count, 1) + + def test_basic_metric_check_client_size_get(self): + with urllib3.PoolManager() as pool: + start_time = default_timer() + response = pool.request("GET", self.http_url) + client_duration_estimated = (default_timer() - start_time) * 1000 + + expected_attributes = { + "http.status_code": 200, + "http.host": self.assert_ip, + "http.method": "GET", + "http.flavor": "1.1", + "http.scheme": "http", + "net.peer.name": self.assert_ip, + "net.peer.port": self.assert_port, + } + expected_data = { + "http.client.request.size": 0, + "http.client.response.size": len(response.data), + } + expected_metrics = [ + "http.client.duration", + "http.client.request.size", + "http.client.response.size", + ] + + resource_metrics = ( + self.memory_metrics_reader.get_metrics_data().resource_metrics + ) + for metrics in resource_metrics: + for scope_metrics in metrics.scope_metrics: + self.assertEqual(len(scope_metrics.metrics), 3) + for metric in scope_metrics.metrics: + for data_point in metric.data.data_points: + if metric.name in expected_data: + self.assertEqual( + data_point.sum, expected_data[metric.name] + ) + if metric.name == "http.client.duration": + self.assertAlmostEqual( + data_point.sum, + client_duration_estimated, + delta=1000, + ) + self.assertIn(metric.name, expected_metrics) + self.assertDictEqual( + expected_attributes, + dict(data_point.attributes), + ) + self.assertEqual(data_point.count, 1) + + def test_basic_metric_check_client_size_post(self): + with urllib3.PoolManager() as pool: + start_time = default_timer() + data_fields = {"data": "test"} + response = pool.request("POST", self.http_url, fields=data_fields) + client_duration_estimated = (default_timer() - start_time) * 1000 + + expected_attributes = { + "http.status_code": 501, + "http.host": self.assert_ip, + "http.method": "POST", + "http.flavor": "1.1", + "http.scheme": "http", + "net.peer.name": self.assert_ip, + "net.peer.port": self.assert_port, + } + + body = encode_multipart_formdata(data_fields)[0] + + expected_data = { + "http.client.request.size": len(body), + "http.client.response.size": len(response.data), + } + expected_metrics = [ + "http.client.duration", + "http.client.request.size", + "http.client.response.size", + ] + + resource_metrics = ( + self.memory_metrics_reader.get_metrics_data().resource_metrics + ) + for metrics in resource_metrics: + for scope_metrics in metrics.scope_metrics: + self.assertEqual(len(scope_metrics.metrics), 3) + for metric in scope_metrics.metrics: + for data_point in metric.data.data_points: + if metric.name in expected_data: + self.assertEqual( + data_point.sum, expected_data[metric.name] + ) + if metric.name == "http.client.duration": + self.assertAlmostEqual( + data_point.sum, + client_duration_estimated, + delta=1000, + ) + self.assertIn(metric.name, expected_metrics) + + self.assertDictEqual( + expected_attributes, + dict(data_point.attributes), + ) + self.assertEqual(data_point.count, 1)
Metrics instrumentation urllib3 HTPP metrics semconv https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/semantic_conventions/http-metrics.md
Can you please assign this issue to me?
2022-07-19T11:33:15
open-telemetry/opentelemetry-python-contrib
1,208
open-telemetry__opentelemetry-python-contrib-1208
[ "1043" ]
c2f9ebe382ee231101da4a32363683b103de8309
diff --git a/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/__init__.py b/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/__init__.py --- a/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/__init__.py @@ -205,6 +205,7 @@ def response_hook(span, request, response): from opentelemetry.instrumentation.django.package import _instruments from opentelemetry.instrumentation.django.version import __version__ from opentelemetry.instrumentation.instrumentor import BaseInstrumentor +from opentelemetry.metrics import get_meter from opentelemetry.trace import get_tracer DJANGO_2_0 = django_version >= (2, 0) @@ -244,19 +245,29 @@ def _instrument(self, **kwargs): return tracer_provider = kwargs.get("tracer_provider") + meter_provider = kwargs.get("meter_provider") tracer = get_tracer( __name__, __version__, tracer_provider=tracer_provider, ) - + meter = get_meter(__name__, __version__, meter_provider=meter_provider) _DjangoMiddleware._tracer = tracer - + _DjangoMiddleware._meter = meter _DjangoMiddleware._otel_request_hook = kwargs.pop("request_hook", None) _DjangoMiddleware._otel_response_hook = kwargs.pop( "response_hook", None ) - + _DjangoMiddleware._duration_histogram = meter.create_histogram( + name="http.server.duration", + unit="ms", + description="measures the duration of the inbound http request", + ) + _DjangoMiddleware._active_request_counter = meter.create_up_down_counter( + name="http.server.active_requests", + unit="requests", + description="measures the number of concurent HTTP requests those are currently in flight", + ) # This can not be solved, but is an inherent problem of this approach: # the order of middleware entries matters, and here you have no control # on that: diff --git a/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/middleware/otel_middleware.py b/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/middleware/otel_middleware.py --- a/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/middleware/otel_middleware.py +++ b/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/middleware/otel_middleware.py @@ -15,6 +15,7 @@ import types from logging import getLogger from time import time +from timeit import default_timer from typing import Callable from django import VERSION as django_version @@ -41,7 +42,12 @@ from opentelemetry.instrumentation.wsgi import wsgi_getter from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.trace import Span, SpanKind, use_span -from opentelemetry.util.http import get_excluded_urls, get_traced_request_attrs +from opentelemetry.util.http import ( + _parse_active_request_count_attrs, + _parse_duration_attrs, + get_excluded_urls, + get_traced_request_attrs, +) try: from django.core.urlresolvers import ( # pylint: disable=no-name-in-module @@ -139,10 +145,19 @@ class _DjangoMiddleware(MiddlewareMixin): _environ_token = "opentelemetry-instrumentor-django.token" _environ_span_key = "opentelemetry-instrumentor-django.span_key" _environ_exception_key = "opentelemetry-instrumentor-django.exception_key" - + _environ_active_request_attr_key = ( + "opentelemetry-instrumentor-django.active_request_attr_key" + ) + _environ_duration_attr_key = ( + "opentelemetry-instrumentor-django.duration_attr_key" + ) + _environ_timer_key = "opentelemetry-instrumentor-django.timer_key" _traced_request_attrs = get_traced_request_attrs("DJANGO") _excluded_urls = get_excluded_urls("DJANGO") _tracer = None + _meter = None + _duration_histogram = None + _active_request_counter = None _otel_request_hook: Callable[[Span, HttpRequest], None] = None _otel_response_hook: Callable[ @@ -171,6 +186,7 @@ def _get_span_name(request): except Resolver404: return f"HTTP {request.method}" + # pylint: disable=too-many-locals def process_request(self, request): # request.META is a dictionary containing all available HTTP headers # Read more about request.META here: @@ -185,7 +201,6 @@ def process_request(self, request): # pylint:disable=W0212 request._otel_start_time = time() - request_meta = request.META if is_asgi_request: @@ -208,7 +223,16 @@ def process_request(self, request): ) attributes = collect_request_attributes(carrier) + active_requests_count_attrs = _parse_active_request_count_attrs( + attributes + ) + duration_attrs = _parse_duration_attrs(attributes) + request.META[ + self._environ_active_request_attr_key + ] = active_requests_count_attrs + request.META[self._environ_duration_attr_key] = duration_attrs + self._active_request_counter.add(1, active_requests_count_attrs) if span.is_recording(): attributes = extract_attributes_from_object( request, self._traced_request_attrs, attributes @@ -242,7 +266,8 @@ def process_request(self, request): activation = use_span(span, end_on_exit=True) activation.__enter__() # pylint: disable=E1101 - + request_start_time = default_timer() + request.META[self._environ_timer_key] = request_start_time request.META[self._environ_activation_key] = activation request.META[self._environ_span_key] = span if token: @@ -281,6 +306,7 @@ def process_exception(self, request, exception): request.META[self._environ_exception_key] = exception # pylint: disable=too-many-branches + # pylint: disable=too-many-locals def process_response(self, request, response): if self._excluded_urls.url_disabled(request.build_absolute_uri("?")): return response @@ -291,6 +317,17 @@ def process_response(self, request, response): activation = request.META.pop(self._environ_activation_key, None) span = request.META.pop(self._environ_span_key, None) + active_requests_count_attrs = request.META.pop( + self._environ_active_request_attr_key, None + ) + duration_attrs = request.META.pop( + self._environ_duration_attr_key, None + ) + if duration_attrs: + duration_attrs[ + SpanAttributes.HTTP_STATUS_CODE + ] = response.status_code + request_start_time = request.META.pop(self._environ_timer_key, None) if activation and span: if is_asgi_request: @@ -341,6 +378,12 @@ def process_response(self, request, response): else: activation.__exit__(None, None, None) + if request_start_time is not None: + duration = max( + round((default_timer() - request_start_time) * 1000), 0 + ) + self._duration_histogram.record(duration, duration_attrs) + self._active_request_counter.add(-1, active_requests_count_attrs) if request.META.get(self._environ_token, None) is not None: detach(request.META.get(self._environ_token)) request.META.pop(self._environ_token) diff --git a/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/package.py b/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/package.py --- a/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/package.py +++ b/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/package.py @@ -14,3 +14,4 @@ _instruments = ("django >= 1.10",) +_supports_metrics = True
diff --git a/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware.py b/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware.py --- a/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware.py +++ b/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware.py @@ -15,6 +15,7 @@ # pylint: disable=E0611 from sys import modules +from timeit import default_timer from unittest.mock import Mock, patch from django import VERSION, conf @@ -32,6 +33,10 @@ set_global_response_propagator, ) from opentelemetry.sdk import resources +from opentelemetry.sdk.metrics.export import ( + HistogramDataPoint, + NumberDataPoint, +) from opentelemetry.sdk.trace import Span from opentelemetry.sdk.trace.id_generator import RandomIdGenerator from opentelemetry.semconv.trace import SpanAttributes @@ -45,6 +50,8 @@ from opentelemetry.util.http import ( OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST, OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE, + _active_requests_count_attrs, + _duration_attrs, get_excluded_urls, get_traced_request_attrs, ) @@ -406,6 +413,64 @@ def test_trace_response_headers(self): ) self.memory_exporter.clear() + # pylint: disable=too-many-locals + def test_wsgi_metrics(self): + _expected_metric_names = [ + "http.server.active_requests", + "http.server.duration", + ] + _recommended_attrs = { + "http.server.active_requests": _active_requests_count_attrs, + "http.server.duration": _duration_attrs, + } + start = default_timer() + for _ in range(3): + response = Client().get("/span_name/1234/") + self.assertEqual(response.status_code, 200) + duration = max(round((default_timer() - start) * 1000), 0) + metrics_list = self.memory_metrics_reader.get_metrics_data() + number_data_point_seen = False + histrogram_data_point_seen = False + + self.assertTrue(len(metrics_list.resource_metrics) != 0) + for resource_metric in metrics_list.resource_metrics: + self.assertTrue(len(resource_metric.scope_metrics) != 0) + for scope_metric in resource_metric.scope_metrics: + self.assertTrue(len(scope_metric.metrics) != 0) + for metric in scope_metric.metrics: + self.assertIn(metric.name, _expected_metric_names) + data_points = list(metric.data.data_points) + self.assertEqual(len(data_points), 1) + for point in data_points: + if isinstance(point, HistogramDataPoint): + self.assertEqual(point.count, 3) + histrogram_data_point_seen = True + self.assertAlmostEqual( + duration, point.sum, delta=100 + ) + if isinstance(point, NumberDataPoint): + number_data_point_seen = True + self.assertEqual(point.value, 0) + for attr in point.attributes: + self.assertIn( + attr, _recommended_attrs[metric.name] + ) + self.assertTrue(histrogram_data_point_seen and number_data_point_seen) + + def test_wsgi_metrics_unistrument(self): + Client().get("/span_name/1234/") + _django_instrumentor.uninstrument() + Client().get("/span_name/1234/") + metrics_list = self.memory_metrics_reader.get_metrics_data() + for resource_metric in metrics_list.resource_metrics: + for scope_metric in resource_metric.scope_metrics: + for metric in scope_metric.metrics: + for point in list(metric.data.data_points): + if isinstance(point, HistogramDataPoint): + self.assertEqual(1, point.count) + if isinstance(point, NumberDataPoint): + self.assertEqual(0, point.value) + class TestMiddlewareWithTracerProvider(WsgiTestBase): @classmethod
[instrumentation-django] Restore metrics The django instrumentation used to produce metrics: https://github.com/open-telemetry/opentelemetry-python-contrib/blob/metrics/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/__init__.py This issue is to restore that functionality.
Hi @codeboten: can you assign this issue to me?
2022-07-29T19:48:29
open-telemetry/opentelemetry-python-contrib
1,230
open-telemetry__opentelemetry-python-contrib-1230
[ "1157" ]
08db974e262d33c6cb36643826ca1f0966bec517
diff --git a/instrumentation/opentelemetry-instrumentation-falcon/src/opentelemetry/instrumentation/falcon/__init__.py b/instrumentation/opentelemetry-instrumentation-falcon/src/opentelemetry/instrumentation/falcon/__init__.py --- a/instrumentation/opentelemetry-instrumentation-falcon/src/opentelemetry/instrumentation/falcon/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-falcon/src/opentelemetry/instrumentation/falcon/__init__.py @@ -144,6 +144,7 @@ def response_hook(span, req, resp): from logging import getLogger from sys import exc_info from time import time_ns +from timeit import default_timer from typing import Collection import falcon @@ -163,6 +164,7 @@ def response_hook(span, req, resp): extract_attributes_from_object, http_status_to_status_code, ) +from opentelemetry.metrics import get_meter from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.trace.status import Status from opentelemetry.util.http import get_excluded_urls, get_traced_request_attrs @@ -202,12 +204,24 @@ def __init__(self, *args, **kwargs): # inject trace middleware self._middlewares_list = kwargs.pop("middleware", []) tracer_provider = otel_opts.pop("tracer_provider", None) + meter_provider = otel_opts.pop("meter_provider", None) if not isinstance(self._middlewares_list, (list, tuple)): self._middlewares_list = [self._middlewares_list] self._otel_tracer = trace.get_tracer( __name__, __version__, tracer_provider ) + self._otel_meter = get_meter(__name__, __version__, meter_provider) + self.duration_histogram = self._otel_meter.create_histogram( + name="http.server.duration", + unit="ms", + description="measures the duration of the inbound HTTP request", + ) + self.active_requests_counter = self._otel_meter.create_up_down_counter( + name="http.server.active_requests", + unit="requests", + description="measures the number of concurrent HTTP requests that are currently in-flight", + ) trace_middleware = _TraceMiddleware( self._otel_tracer, @@ -261,6 +275,7 @@ def _handle_exception( def __call__(self, env, start_response): # pylint: disable=E1101 + # pylint: disable=too-many-locals if self._otel_excluded_urls.url_disabled(env.get("PATH_INFO", "/")): return super().__call__(env, start_response) @@ -276,9 +291,14 @@ def __call__(self, env, start_response): context_carrier=env, context_getter=otel_wsgi.wsgi_getter, ) + attributes = otel_wsgi.collect_request_attributes(env) + active_requests_count_attrs = ( + otel_wsgi._parse_active_request_count_attrs(attributes) + ) + duration_attrs = otel_wsgi._parse_duration_attrs(attributes) + self.active_requests_counter.add(1, active_requests_count_attrs) if span.is_recording(): - attributes = otel_wsgi.collect_request_attributes(env) for key, value in attributes.items(): span.set_attribute(key, value) if span.is_recording() and span.kind == trace.SpanKind.SERVER: @@ -302,6 +322,7 @@ def _start_response(status, response_headers, *args, **kwargs): context.detach(token) return response + start = default_timer() try: return super().__call__(env, _start_response) except Exception as exc: @@ -313,6 +334,13 @@ def _start_response(status, response_headers, *args, **kwargs): if token is not None: context.detach(token) raise + finally: + duration_attrs[ + SpanAttributes.HTTP_STATUS_CODE + ] = span.attributes.get(SpanAttributes.HTTP_STATUS_CODE) + duration = max(round((default_timer() - start) * 1000), 0) + self.duration_histogram.record(duration, duration_attrs) + self.active_requests_counter.add(-1, active_requests_count_attrs) class _TraceMiddleware:
diff --git a/instrumentation/opentelemetry-instrumentation-falcon/tests/test_falcon.py b/instrumentation/opentelemetry-instrumentation-falcon/tests/test_falcon.py --- a/instrumentation/opentelemetry-instrumentation-falcon/tests/test_falcon.py +++ b/instrumentation/opentelemetry-instrumentation-falcon/tests/test_falcon.py @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from timeit import default_timer from unittest.mock import Mock, patch import pytest @@ -26,6 +27,14 @@ get_global_response_propagator, set_global_response_propagator, ) +from opentelemetry.instrumentation.wsgi import ( + _active_requests_count_attrs, + _duration_attrs, +) +from opentelemetry.sdk.metrics.export import ( + HistogramDataPoint, + NumberDataPoint, +) from opentelemetry.sdk.resources import Resource from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.test.test_base import TestBase @@ -38,6 +47,15 @@ from .app import make_app +_expected_metric_names = [ + "http.server.active_requests", + "http.server.duration", +] +_recommended_attrs = { + "http.server.active_requests": _active_requests_count_attrs, + "http.server.duration": _duration_attrs, +} + class TestFalconBase(TestBase): def setUp(self): @@ -254,6 +272,87 @@ def test_uninstrument_after_instrument(self): spans = self.memory_exporter.get_finished_spans() self.assertEqual(len(spans), 0) + def test_falcon_metrics(self): + self.client().simulate_get("/hello/756") + self.client().simulate_get("/hello/756") + self.client().simulate_get("/hello/756") + metrics_list = self.memory_metrics_reader.get_metrics_data() + number_data_point_seen = False + histogram_data_point_seen = False + self.assertTrue(len(metrics_list.resource_metrics) != 0) + for resource_metric in metrics_list.resource_metrics: + self.assertTrue(len(resource_metric.scope_metrics) != 0) + for scope_metric in resource_metric.scope_metrics: + self.assertTrue(len(scope_metric.metrics) != 0) + for metric in scope_metric.metrics: + self.assertIn(metric.name, _expected_metric_names) + data_points = list(metric.data.data_points) + self.assertEqual(len(data_points), 1) + for point in data_points: + if isinstance(point, HistogramDataPoint): + self.assertEqual(point.count, 3) + histogram_data_point_seen = True + if isinstance(point, NumberDataPoint): + number_data_point_seen = True + for attr in point.attributes: + self.assertIn( + attr, _recommended_attrs[metric.name] + ) + self.assertTrue(number_data_point_seen and histogram_data_point_seen) + + def test_falcon_metric_values(self): + expected_duration_attributes = { + "http.method": "GET", + "http.host": "falconframework.org", + "http.scheme": "http", + "http.flavor": "1.1", + "http.server_name": "falconframework.org", + "net.host.port": 80, + "http.status_code": 404, + } + expected_requests_count_attributes = { + "http.method": "GET", + "http.host": "falconframework.org", + "http.scheme": "http", + "http.flavor": "1.1", + "http.server_name": "falconframework.org", + } + start = default_timer() + self.client().simulate_get("/hello/756") + duration = max(round((default_timer() - start) * 1000), 0) + metrics_list = self.memory_metrics_reader.get_metrics_data() + for resource_metric in metrics_list.resource_metrics: + for scope_metric in resource_metric.scope_metrics: + for metric in scope_metric.metrics: + for point in list(metric.data.data_points): + if isinstance(point, HistogramDataPoint): + self.assertDictEqual( + expected_duration_attributes, + dict(point.attributes), + ) + self.assertEqual(point.count, 1) + self.assertAlmostEqual( + duration, point.sum, delta=10 + ) + if isinstance(point, NumberDataPoint): + self.assertDictEqual( + expected_requests_count_attributes, + dict(point.attributes), + ) + self.assertEqual(point.value, 0) + + def test_metric_uninstrument(self): + self.client().simulate_request(method="POST", path="/hello/756") + FalconInstrumentor().uninstrument() + self.client().simulate_request(method="POST", path="/hello/756") + metrics_list = self.memory_metrics_reader.get_metrics_data() + for resource_metric in metrics_list.resource_metrics: + for scope_metric in resource_metric.scope_metrics: + for metric in scope_metric.metrics: + for point in list(metric.data.data_points): + if isinstance(point, HistogramDataPoint): + self.assertEqual(point.count, 1) + class TestFalconInstrumentationWithTracerProvider(TestBase): def setUp(self):
Metrics instrumentation falcon HTTP metrics: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/semantic_conventions/http-metrics.md
@srikanthccv Assign this to me.
2022-08-16T06:38:40
open-telemetry/opentelemetry-python-contrib
1,234
open-telemetry__opentelemetry-python-contrib-1234
[ "1202" ]
7625b82dffaa04173d6f7cb733d354977dbe9c84
diff --git a/instrumentation/opentelemetry-instrumentation-boto3sqs/src/opentelemetry/instrumentation/boto3sqs/__init__.py b/instrumentation/opentelemetry-instrumentation-boto3sqs/src/opentelemetry/instrumentation/boto3sqs/__init__.py --- a/instrumentation/opentelemetry-instrumentation-boto3sqs/src/opentelemetry/instrumentation/boto3sqs/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-boto3sqs/src/opentelemetry/instrumentation/boto3sqs/__init__.py @@ -29,7 +29,7 @@ Boto3SQSInstrumentor().instrument() """ import logging -from typing import Any, Collection, Dict, Generator, List, Optional +from typing import Any, Collection, Dict, Generator, List, Mapping, Optional import boto3 import botocore.client @@ -53,33 +53,31 @@ from .version import __version__ _logger = logging.getLogger(__name__) -# We use this prefix so we can request all instrumentation MessageAttributeNames with a wildcard, without harming -# existing filters -_OPENTELEMETRY_ATTRIBUTE_IDENTIFIER: str = "otel." -_OTEL_IDENTIFIER_LENGTH = len(_OPENTELEMETRY_ATTRIBUTE_IDENTIFIER) + +_IS_SQS_INSTRUMENTED_ATTRIBUTE = "_otel_boto3sqs_instrumented" class Boto3SQSGetter(Getter[CarrierT]): def get(self, carrier: CarrierT, key: str) -> Optional[List[str]]: - value = carrier.get(f"{_OPENTELEMETRY_ATTRIBUTE_IDENTIFIER}{key}", {}) - if not value: + msg_attr = carrier.get(key) + if not isinstance(msg_attr, Mapping): + return None + + value = msg_attr.get("StringValue") + if value is None: return None - return [value.get("StringValue")] + + return [value] def keys(self, carrier: CarrierT) -> List[str]: - return [ - key[_OTEL_IDENTIFIER_LENGTH:] - if key.startswith(_OPENTELEMETRY_ATTRIBUTE_IDENTIFIER) - else key - for key in carrier.keys() - ] + return list(carrier.keys()) class Boto3SQSSetter(Setter[CarrierT]): def set(self, carrier: CarrierT, key: str, value: str) -> None: # This is a limitation defined by AWS for SQS MessageAttributes size if len(carrier.items()) < 10: - carrier[f"{_OPENTELEMETRY_ATTRIBUTE_IDENTIFIER}{key}"] = { + carrier[key] = { "StringValue": value, "DataType": "String", } @@ -145,6 +143,7 @@ def instrumentation_dependencies(self) -> Collection[str]: def _enrich_span( span: Span, queue_name: str, + queue_url: str, conversation_id: Optional[str] = None, operation: Optional[MessagingOperationValues] = None, message_id: Optional[str] = None, @@ -157,12 +156,12 @@ def _enrich_span( SpanAttributes.MESSAGING_DESTINATION_KIND, MessagingDestinationKindValues.QUEUE.value, ) + span.set_attribute(SpanAttributes.MESSAGING_URL, queue_url) + if operation: span.set_attribute( SpanAttributes.MESSAGING_OPERATION, operation.value ) - else: - span.set_attribute(SpanAttributes.MESSAGING_TEMP_DESTINATION, True) if conversation_id: span.set_attribute( SpanAttributes.MESSAGING_CONVERSATION_ID, conversation_id @@ -190,15 +189,19 @@ def _extract_queue_name_from_url(queue_url: str) -> str: return queue_url.split("/")[-1] def _create_processing_span( - self, queue_name: str, receipt_handle: str, message: Dict[str, Any] + self, + queue_name: str, + queue_url: str, + receipt_handle: str, + message: Dict[str, Any], ) -> None: message_attributes = message.get("MessageAttributes", {}) links = [] ctx = propagate.extract(message_attributes, getter=boto3sqs_getter) - if ctx: - for item in ctx.values(): - if hasattr(item, "get_span_context"): - links.append(Link(context=item.get_span_context())) + parent_span_ctx = trace.get_current_span(ctx).get_span_context() + if parent_span_ctx.is_valid: + links.append(Link(context=parent_span_ctx)) + span = self._tracer.start_span( name=f"{queue_name} process", links=links, kind=SpanKind.CONSUMER ) @@ -208,11 +211,12 @@ def _create_processing_span( Boto3SQSInstrumentor._enrich_span( span, queue_name, + queue_url, message_id=message_id, operation=MessagingOperationValues.PROCESS, ) - def _wrap_send_message(self) -> None: + def _wrap_send_message(self, sqs_class: type) -> None: def send_wrapper(wrapped, instance, args, kwargs): if context.get_value(_SUPPRESS_INSTRUMENTATION_KEY): return wrapped(*args, **kwargs) @@ -227,7 +231,7 @@ def send_wrapper(wrapped, instance, args, kwargs): kind=SpanKind.PRODUCER, end_on_exit=True, ) as span: - Boto3SQSInstrumentor._enrich_span(span, queue_name) + Boto3SQSInstrumentor._enrich_span(span, queue_name, queue_url) attributes = kwargs.pop("MessageAttributes", {}) propagate.inject(attributes, setter=boto3sqs_setter) retval = wrapped(*args, MessageAttributes=attributes, **kwargs) @@ -239,9 +243,9 @@ def send_wrapper(wrapped, instance, args, kwargs): ) return retval - wrap_function_wrapper(self._sqs_class, "send_message", send_wrapper) + wrap_function_wrapper(sqs_class, "send_message", send_wrapper) - def _wrap_send_message_batch(self) -> None: + def _wrap_send_message_batch(self, sqs_class: type) -> None: def send_batch_wrapper(wrapped, instance, args, kwargs): queue_url = kwargs.get("QueueUrl") entries = kwargs.get("Entries") @@ -260,12 +264,11 @@ def send_batch_wrapper(wrapped, instance, args, kwargs): for entry in entries: entry_id = entry["Id"] span = self._tracer.start_span( - name=f"{queue_name} send", - kind=SpanKind.PRODUCER, + name=f"{queue_name} send", kind=SpanKind.PRODUCER ) ids_to_spans[entry_id] = span Boto3SQSInstrumentor._enrich_span( - span, queue_name, conversation_id=entry_id + span, queue_name, queue_url, conversation_id=entry_id ) with trace.use_span(span): if "MessageAttributes" not in entry: @@ -288,15 +291,15 @@ def send_batch_wrapper(wrapped, instance, args, kwargs): return retval wrap_function_wrapper( - self._sqs_class, "send_message_batch", send_batch_wrapper + sqs_class, "send_message_batch", send_batch_wrapper ) - def _wrap_receive_message(self) -> None: + def _wrap_receive_message(self, sqs_class: type) -> None: def receive_message_wrapper(wrapped, instance, args, kwargs): queue_url = kwargs.get("QueueUrl") message_attribute_names = kwargs.pop("MessageAttributeNames", []) - message_attribute_names.append( - f"{_OPENTELEMETRY_ATTRIBUTE_IDENTIFIER}*" + message_attribute_names.extend( + propagate.get_global_textmap().fields ) queue_name = Boto3SQSInstrumentor._extract_queue_name_from_url( queue_url @@ -309,6 +312,7 @@ def receive_message_wrapper(wrapped, instance, args, kwargs): Boto3SQSInstrumentor._enrich_span( span, queue_name, + queue_url, operation=MessagingOperationValues.RECEIVE, ) retval = wrapped( @@ -327,7 +331,7 @@ def receive_message_wrapper(wrapped, instance, args, kwargs): receipt_handle ) self._create_processing_span( - queue_name, receipt_handle, message + queue_name, queue_url, receipt_handle, message ) retval["Messages"] = Boto3SQSInstrumentor.ContextableList( messages @@ -335,10 +339,11 @@ def receive_message_wrapper(wrapped, instance, args, kwargs): return retval wrap_function_wrapper( - self._sqs_class, "receive_message", receive_message_wrapper + sqs_class, "receive_message", receive_message_wrapper ) - def _wrap_delete_message(self) -> None: + @staticmethod + def _wrap_delete_message(sqs_class: type) -> None: def delete_message_wrapper(wrapped, instance, args, kwargs): receipt_handle = kwargs.get("ReceiptHandle") if receipt_handle: @@ -346,10 +351,11 @@ def delete_message_wrapper(wrapped, instance, args, kwargs): return wrapped(*args, **kwargs) wrap_function_wrapper( - self._sqs_class, "delete_message", delete_message_wrapper + sqs_class, "delete_message", delete_message_wrapper ) - def _wrap_delete_message_batch(self) -> None: + @staticmethod + def _wrap_delete_message_batch(sqs_class: type) -> None: def delete_message_wrapper_batch(wrapped, instance, args, kwargs): entries = kwargs.get("Entries") for entry in entries: @@ -361,9 +367,7 @@ def delete_message_wrapper_batch(wrapped, instance, args, kwargs): return wrapped(*args, **kwargs) wrap_function_wrapper( - self._sqs_class, - "delete_message_batch", - delete_message_wrapper_batch, + sqs_class, "delete_message_batch", delete_message_wrapper_batch ) def _wrap_client_creation(self) -> None: @@ -375,43 +379,45 @@ def _wrap_client_creation(self) -> None: def client_wrapper(wrapped, instance, args, kwargs): retval = wrapped(*args, **kwargs) - if not self._did_decorate: - self._decorate_sqs() + self._decorate_sqs(type(retval)) return retval wrap_function_wrapper(boto3, "client", client_wrapper) - def _decorate_sqs(self) -> None: + def _decorate_sqs(self, sqs_class: type) -> None: """ Since botocore creates classes on the fly using schemas, we try to find the class that inherits from the base class and is SQS to wrap. """ # We define SQS client as the only client that implements send_message_batch - sqs_class = [ - cls - for cls in botocore.client.BaseClient.__subclasses__() - if hasattr(cls, "send_message_batch") - ] - if sqs_class: - self._sqs_class = sqs_class[0] - self._did_decorate = True - self._wrap_send_message() - self._wrap_send_message_batch() - self._wrap_receive_message() - self._wrap_delete_message() - self._wrap_delete_message_batch() - - def _un_decorate_sqs(self) -> None: - if self._did_decorate: - unwrap(self._sqs_class, "send_message") - unwrap(self._sqs_class, "send_message_batch") - unwrap(self._sqs_class, "receive_message") - unwrap(self._sqs_class, "delete_message") - unwrap(self._sqs_class, "delete_message_batch") - self._did_decorate = False + if not hasattr(sqs_class, "send_message_batch"): + return + + if getattr(sqs_class, _IS_SQS_INSTRUMENTED_ATTRIBUTE, False): + return + + setattr(sqs_class, _IS_SQS_INSTRUMENTED_ATTRIBUTE, True) + + self._wrap_send_message(sqs_class) + self._wrap_send_message_batch(sqs_class) + self._wrap_receive_message(sqs_class) + self._wrap_delete_message(sqs_class) + self._wrap_delete_message_batch(sqs_class) + + @staticmethod + def _un_decorate_sqs(sqs_class: type) -> None: + if not getattr(sqs_class, _IS_SQS_INSTRUMENTED_ATTRIBUTE, False): + return + + unwrap(sqs_class, "send_message") + unwrap(sqs_class, "send_message_batch") + unwrap(sqs_class, "receive_message") + unwrap(sqs_class, "delete_message") + unwrap(sqs_class, "delete_message_batch") + + setattr(sqs_class, _IS_SQS_INSTRUMENTED_ATTRIBUTE, False) def _instrument(self, **kwargs: Dict[str, Any]) -> None: - self._did_decorate: bool = False self._tracer_provider: Optional[TracerProvider] = kwargs.get( "tracer_provider" ) @@ -419,8 +425,12 @@ def _instrument(self, **kwargs: Dict[str, Any]) -> None: __name__, __version__, self._tracer_provider ) self._wrap_client_creation() - self._decorate_sqs() + + for client_cls in botocore.client.BaseClient.__subclasses__(): + self._decorate_sqs(client_cls) def _uninstrument(self, **kwargs: Dict[str, Any]) -> None: unwrap(boto3, "client") - self._un_decorate_sqs() + + for client_cls in botocore.client.BaseClient.__subclasses__(): + self._un_decorate_sqs(client_cls)
diff --git a/instrumentation/opentelemetry-instrumentation-boto3sqs/tests/test_boto3sqs_instrumentation.py b/instrumentation/opentelemetry-instrumentation-boto3sqs/tests/test_boto3sqs_instrumentation.py --- a/instrumentation/opentelemetry-instrumentation-boto3sqs/tests/test_boto3sqs_instrumentation.py +++ b/instrumentation/opentelemetry-instrumentation-boto3sqs/tests/test_boto3sqs_instrumentation.py @@ -14,79 +14,72 @@ # pylint: disable=no-name-in-module -from unittest import TestCase +from contextlib import contextmanager +from typing import Any, Dict +from unittest import TestCase, mock import boto3 -import botocore.client +from botocore.awsrequest import AWSResponse from wrapt import BoundFunctionWrapper, FunctionWrapper from opentelemetry.instrumentation.boto3sqs import ( - _OPENTELEMETRY_ATTRIBUTE_IDENTIFIER, Boto3SQSGetter, Boto3SQSInstrumentor, Boto3SQSSetter, ) +from opentelemetry.semconv.trace import ( + MessagingDestinationKindValues, + MessagingOperationValues, + SpanAttributes, +) +from opentelemetry.test.test_base import TestBase +from opentelemetry.trace import SpanKind +from opentelemetry.trace.span import Span, format_span_id, format_trace_id -# pylint: disable=attribute-defined-outside-init -class TestBoto3SQSInstrumentor(TestCase): - def define_sqs_mock(self) -> None: - # pylint: disable=R0201 - class SQSClientMock(botocore.client.BaseClient): - def send_message(self, *args, **kwargs): - ... - - def send_message_batch(self, *args, **kwargs): - ... - - def receive_message(self, *args, **kwargs): - ... +def _make_sqs_client(): + return boto3.client( + "sqs", + region_name="us-east-1", + aws_access_key_id="dummy", + aws_secret_access_key="dummy", + ) - def delete_message(self, *args, **kwargs): - ... - def delete_message_batch(self, *args, **kwargs): - ... +class TestBoto3SQSInstrumentor(TestCase): + def _assert_instrumented(self, client): + self.assertIsInstance(boto3.client, FunctionWrapper) + self.assertIsInstance(client.send_message, BoundFunctionWrapper) + self.assertIsInstance(client.send_message_batch, BoundFunctionWrapper) + self.assertIsInstance(client.receive_message, BoundFunctionWrapper) + self.assertIsInstance(client.delete_message, BoundFunctionWrapper) + self.assertIsInstance( + client.delete_message_batch, BoundFunctionWrapper + ) - self._boto_sqs_mock = SQSClientMock + @staticmethod + @contextmanager + def _active_instrumentor(): + Boto3SQSInstrumentor().instrument() + try: + yield + finally: + Boto3SQSInstrumentor().uninstrument() def test_instrument_api_before_client_init(self) -> None: - instrumentation = Boto3SQSInstrumentor() - - instrumentation.instrument() - self.assertTrue(isinstance(boto3.client, FunctionWrapper)) - instrumentation.uninstrument() + with self._active_instrumentor(): + client = _make_sqs_client() + self._assert_instrumented(client) def test_instrument_api_after_client_init(self) -> None: - self.define_sqs_mock() - instrumentation = Boto3SQSInstrumentor() + client = _make_sqs_client() + with self._active_instrumentor(): + self._assert_instrumented(client) - instrumentation.instrument() - self.assertTrue(isinstance(boto3.client, FunctionWrapper)) - self.assertTrue( - isinstance(self._boto_sqs_mock.send_message, BoundFunctionWrapper) - ) - self.assertTrue( - isinstance( - self._boto_sqs_mock.send_message_batch, BoundFunctionWrapper - ) - ) - self.assertTrue( - isinstance( - self._boto_sqs_mock.receive_message, BoundFunctionWrapper - ) - ) - self.assertTrue( - isinstance( - self._boto_sqs_mock.delete_message, BoundFunctionWrapper - ) - ) - self.assertTrue( - isinstance( - self._boto_sqs_mock.delete_message_batch, BoundFunctionWrapper - ) - ) - instrumentation.uninstrument() + def test_instrument_multiple_clients(self): + with self._active_instrumentor(): + self._assert_instrumented(_make_sqs_client()) + self._assert_instrumented(_make_sqs_client()) class TestBoto3SQSGetter(TestCase): @@ -101,29 +94,17 @@ def test_get_none(self) -> None: def test_get_value(self) -> None: key = "test" value = "value" - carrier = { - f"{_OPENTELEMETRY_ATTRIBUTE_IDENTIFIER}{key}": { - "StringValue": value, - "DataType": "String", - } - } + carrier = {key: {"StringValue": value, "DataType": "String"}} val = self.getter.get(carrier, key) self.assertEqual(val, [value]) def test_keys(self): - key1 = "test1" - value1 = "value1" - key2 = "test2" - value2 = "value2" carrier = { - f"{_OPENTELEMETRY_ATTRIBUTE_IDENTIFIER}{key1}": { - "StringValue": value1, - "DataType": "String", - }, - key2: {"StringValue": value2, "DataType": "String"}, + "test1": {"StringValue": "value1", "DataType": "String"}, + "test2": {"StringValue": "value2", "DataType": "String"}, } keys = self.getter.keys(carrier) - self.assertEqual(keys, [key1, key2]) + self.assertEqual(keys, list(carrier.keys())) def test_keys_empty(self): keys = self.getter.keys({}) @@ -145,8 +126,188 @@ def test_simple(self): for dict_key, dict_val in carrier[original_key].items(): self.assertEqual(original_value[dict_key], dict_val) # Ensure the new key is added well - self.assertIn( - f"{_OPENTELEMETRY_ATTRIBUTE_IDENTIFIER}{key}", carrier.keys() + self.assertEqual(carrier[key]["StringValue"], value) + + +class TestBoto3SQSInstrumentation(TestBase): + def setUp(self): + super().setUp() + self._reset_instrumentor() + Boto3SQSInstrumentor().instrument() + + self._client = _make_sqs_client() + self._queue_name = "MyQueue" + self._queue_url = f"https://sqs.us-east-1.amazonaws.com/123456789012/{self._queue_name}" + + def tearDown(self): + super().tearDown() + Boto3SQSInstrumentor().uninstrument() + self._reset_instrumentor() + + @staticmethod + def _reset_instrumentor(): + Boto3SQSInstrumentor.received_messages_spans.clear() + Boto3SQSInstrumentor.current_span_related_to_token = None + Boto3SQSInstrumentor.current_context_token = None + + @staticmethod + def _make_aws_response_func(response): + def _response_func(*args, **kwargs): + return AWSResponse("http://127.0.0.1", 200, {}, "{}"), response + + return _response_func + + @contextmanager + def _mocked_endpoint(self, response): + response_func = self._make_aws_response_func(response) + with mock.patch( + "botocore.endpoint.Endpoint.make_request", new=response_func + ): + yield + + def _assert_injected_span(self, msg_attrs: Dict[str, Any], span: Span): + trace_parent = msg_attrs["traceparent"]["StringValue"] + ctx = span.get_span_context() + self.assertEqual( + self._to_trace_parent(ctx.trace_id, ctx.span_id), + trace_parent.lower(), ) - new_value = carrier[f"{_OPENTELEMETRY_ATTRIBUTE_IDENTIFIER}{key}"] - self.assertEqual(new_value["StringValue"], value) + + def _default_span_attrs(self): + return { + SpanAttributes.MESSAGING_SYSTEM: "aws.sqs", + SpanAttributes.MESSAGING_DESTINATION: self._queue_name, + SpanAttributes.MESSAGING_DESTINATION_KIND: MessagingDestinationKindValues.QUEUE.value, + SpanAttributes.MESSAGING_URL: self._queue_url, + } + + @staticmethod + def _to_trace_parent(trace_id: int, span_id: int) -> str: + return f"00-{format_trace_id(trace_id)}-{format_span_id(span_id)}-01".lower() + + def _get_only_span(self): + spans = self.get_finished_spans() + self.assertEqual(1, len(spans)) + return spans[0] + + @staticmethod + def _make_message(message_id: str, body: str, receipt: str): + return { + "MessageId": message_id, + "ReceiptHandle": receipt, + "MD5OfBody": "777", + "Body": body, + "Attributes": {}, + "MD5OfMessageAttributes": "111", + "MessageAttributes": {}, + } + + def _add_trace_parent( + self, message: Dict[str, Any], trace_id: int, span_id: int + ): + message["MessageAttributes"]["traceparent"] = { + "StringValue": self._to_trace_parent(trace_id, span_id), + "DataType": "String", + } + + def test_send_message(self): + message_id = "123456789" + mock_response = { + "MD5OfMessageBody": "1234", + "MD5OfMessageAttributes": "5678", + "MD5OfMessageSystemAttributes": "9012", + "MessageId": message_id, + "SequenceNumber": "0", + } + + message_attrs = {} + + with self._mocked_endpoint(mock_response): + self._client.send_message( + QueueUrl=self._queue_url, + MessageBody="hello msg", + MessageAttributes=message_attrs, + ) + + span = self._get_only_span() + self.assertEqual(f"{self._queue_name} send", span.name) + self.assertEqual(SpanKind.PRODUCER, span.kind) + self.assertEqual( + { + SpanAttributes.MESSAGING_MESSAGE_ID: message_id, + **self._default_span_attrs(), + }, + span.attributes, + ) + self._assert_injected_span(message_attrs, span) + + def test_receive_message(self): + msg_def = { + "1": {"receipt": "01", "trace_id": 10, "span_id": 1}, + "2": {"receipt": "02", "trace_id": 20, "span_id": 2}, + } + + mock_response = {"Messages": []} + for msg_id, attrs in msg_def.items(): + message = self._make_message( + msg_id, f"hello {msg_id}", attrs["receipt"] + ) + self._add_trace_parent( + message, attrs["trace_id"], attrs["span_id"] + ) + mock_response["Messages"].append(message) + + message_attr_names = [] + + with self._mocked_endpoint(mock_response): + response = self._client.receive_message( + QueueUrl=self._queue_url, + MessageAttributeNames=message_attr_names, + ) + + self.assertIn("traceparent", message_attr_names) + + # receive span + span = self._get_only_span() + self.assertEqual(f"{self._queue_name} receive", span.name) + self.assertEqual(SpanKind.CONSUMER, span.kind) + self.assertEqual( + { + SpanAttributes.MESSAGING_OPERATION: MessagingOperationValues.RECEIVE.value, + **self._default_span_attrs(), + }, + span.attributes, + ) + + self.memory_exporter.clear() + + # processing spans + self.assertEqual(2, len(response["Messages"])) + for msg in response["Messages"]: + msg_id = msg["MessageId"] + attrs = msg_def[msg_id] + with self._mocked_endpoint(None): + self._client.delete_message( + QueueUrl=self._queue_url, ReceiptHandle=attrs["receipt"] + ) + + span = self._get_only_span() + self.assertEqual(f"{self._queue_name} process", span.name) + + # processing span attributes + self.assertEqual( + { + SpanAttributes.MESSAGING_MESSAGE_ID: msg_id, + SpanAttributes.MESSAGING_OPERATION: MessagingOperationValues.PROCESS.value, + **self._default_span_attrs(), + }, + span.attributes, + ) + + # processing span links + self.assertEqual(1, len(span.links)) + link = span.links[0] + self.assertEqual(attrs["trace_id"], link.context.trace_id) + self.assertEqual(attrs["span_id"], link.context.span_id) + + self.memory_exporter.clear()
boto3sqs: Do not override propagator-determined key The boto3sqs instrumentation prepends "otel." to all attributes it adds to SQS messages (relevant code: https://github.com/open-telemetry/opentelemetry-python-contrib/blob/7c75b3867bb81d59037e7a3f5ab5c3dfe1bb5733/instrumentation/opentelemetry-instrumentation-boto3sqs/src/opentelemetry/instrumentation/boto3sqs/__init__.py#L56-L82). This will make it impossible to write a propagator that works with instrumentations (of OTel or other vendors) that don't use this prefix. The reasons cited at https://www.oxeye.io/blog/diving-into-opentelemetrys-specs: * Prevents propagators setting keys that start with AWS. or Amazon., which would be rejected -- a rather weak reason IMHO as this is very unlikely to happen and there are other, perhaps more likely, rules that keys must adhere to that are not addressed. * Keys needed for extraction, or prefix thereof, must be known before calling the receive API which requires a list of attributes to receive -- this can be solved by using [`TextMapPropagator.fields`](https://github.com/open-telemetry/opentelemetry-python/blob/v1.11.1/opentelemetry-api/src/opentelemetry/propagators/textmap.py#L185-L196), although it is meant for listing injected fields, these will usually be the same as extracted ones. This is also what Node.Js does: https://github.com/open-telemetry/opentelemetry-js-contrib/blob/1db1fecc16ecb3dbad530de530418260e54c087a/plugins/node/opentelemetry-instrumentation-aws-sdk/src/services/sqs.ts#L71-L75 So I suggest to remove the `otel.` prefix and instead use [`TextMapPropagator.fields`](https://github.com/open-telemetry/opentelemetry-python/blob/v1.11.1/opentelemetry-api/src/opentelemetry/propagators/textmap.py#L185-L196) to ensure the required attributes are fetched. CC @oxeye-nikolay
Sorry, I meant to open this issue in https://github.com/open-telemetry/opentelemetry-python-contrib. Can you please transfer it? Thank you!
2022-08-18T06:15:35
open-telemetry/opentelemetry-python-contrib
1,240
open-telemetry__opentelemetry-python-contrib-1240
[ "1239" ]
f48b3136c4094d9e65878ee5c31424bb69e8688a
diff --git a/instrumentation/opentelemetry-instrumentation-grpc/src/opentelemetry/instrumentation/grpc/__init__.py b/instrumentation/opentelemetry-instrumentation-grpc/src/opentelemetry/instrumentation/grpc/__init__.py --- a/instrumentation/opentelemetry-instrumentation-grpc/src/opentelemetry/instrumentation/grpc/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-grpc/src/opentelemetry/instrumentation/grpc/__init__.py @@ -43,7 +43,8 @@ SimpleSpanProcessor(ConsoleSpanExporter()) ) - instrumentor = GrpcInstrumentorClient().instrument() + grpc_client_instrumentor = GrpcInstrumentorClient() + grpc_client_instrumentor.instrument() def run(): with grpc.insecure_channel("localhost:50051") as channel: @@ -180,7 +181,7 @@ class GrpcInstrumentorClient(BaseInstrumentor): Usage:: grpc_client_instrumentor = GrpcInstrumentorClient() - grpc.client_instrumentor.instrument() + grpc_client_instrumentor.instrument() """
Typos in gRPC instrumentation example codes **Describe your environment** * Platform: any * Python version: any * Library version: main HEAD as of Aug 24th **Steps to reproduce** See [documents for gRPC instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/grpc/grpc.html) **What is the expected behavior?** For client instrumentation example, I would see either of the followings: 1. `GrpcInstrumentorClient().instrument()` is called without return value assignment. 2. Get the return value of `GrpcInstrumentorClient()` and call `instrument()` method of it. **What is the actual behavior?** I see the following example codes. In the [Usage Client](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/grpc/grpc.html#usage-client) section: ```python instrumentor = GrpcInstrumentorClient().instrument() ``` And in the [GrpcInstrumentorClient class document](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/grpc/grpc.html#usage-client): ```python grpc_client_instrumentor = GrpcInstrumentorClient() grpc.client_instrumentor.instrument() ``` where 2nd line is calling non existing package. It should be typo of the variable defined in 1st line. **Additional context** I was trying implement the code to fix #373 and found this issue, so I created separate issue here. I'll create a PR for this shortly.
2022-08-24T01:09:09
open-telemetry/opentelemetry-python-contrib
1,242
open-telemetry__opentelemetry-python-contrib-1242
[ "1149" ]
318a3a3afc05ee60801768ab37e3b1e3d6e535b0
diff --git a/instrumentation/opentelemetry-instrumentation-pyramid/src/opentelemetry/instrumentation/pyramid/callbacks.py b/instrumentation/opentelemetry-instrumentation-pyramid/src/opentelemetry/instrumentation/pyramid/callbacks.py --- a/instrumentation/opentelemetry-instrumentation-pyramid/src/opentelemetry/instrumentation/pyramid/callbacks.py +++ b/instrumentation/opentelemetry-instrumentation-pyramid/src/opentelemetry/instrumentation/pyramid/callbacks.py @@ -14,6 +14,7 @@ from logging import getLogger from time import time_ns +from timeit import default_timer from pyramid.events import BeforeTraversal from pyramid.httpexceptions import HTTPException, HTTPServerError @@ -27,6 +28,7 @@ ) from opentelemetry.instrumentation.pyramid.version import __version__ from opentelemetry.instrumentation.utils import _start_internal_or_server_span +from opentelemetry.metrics import get_meter from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.util.http import get_excluded_urls @@ -122,8 +124,20 @@ def _before_traversal(event): def trace_tween_factory(handler, registry): + # pylint: disable=too-many-statements settings = registry.settings enabled = asbool(settings.get(SETTING_TRACE_ENABLED, True)) + meter = get_meter(__name__, __version__) + duration_histogram = meter.create_histogram( + name="http.server.duration", + unit="ms", + description="measures the duration of the inbound HTTP request", + ) + active_requests_counter = meter.create_up_down_counter( + name="http.server.active_requests", + unit="requests", + description="measures the number of concurrent HTTP requests that are currently in-flight", + ) if not enabled: # If disabled, make a tween that signals to the @@ -137,14 +151,23 @@ def disabled_tween(request): # make a request tracing function # pylint: disable=too-many-branches def trace_tween(request): - # pylint: disable=E1101 + # pylint: disable=E1101, too-many-locals if _excluded_urls.url_disabled(request.url): request.environ[_ENVIRON_ENABLED_KEY] = False # short-circuit when we don't want to trace anything return handler(request) + attributes = otel_wsgi.collect_request_attributes(request.environ) + request.environ[_ENVIRON_ENABLED_KEY] = True request.environ[_ENVIRON_STARTTIME_KEY] = time_ns() + active_requests_count_attrs = ( + otel_wsgi._parse_active_request_count_attrs(attributes) + ) + duration_attrs = otel_wsgi._parse_duration_attrs(attributes) + + start = default_timer() + active_requests_counter.add(1, active_requests_count_attrs) response = None status = None @@ -165,6 +188,15 @@ def trace_tween(request): status = "500 InternalServerError" raise finally: + duration = max(round((default_timer() - start) * 1000), 0) + status = getattr(response, "status", status) + status_code = otel_wsgi._parse_status_code(status) + if status_code is not None: + duration_attrs[ + SpanAttributes.HTTP_STATUS_CODE + ] = otel_wsgi._parse_status_code(status) + duration_histogram.record(duration, duration_attrs) + active_requests_counter.add(-1, active_requests_count_attrs) span = request.environ.get(_ENVIRON_SPAN_KEY) enabled = request.environ.get(_ENVIRON_ENABLED_KEY) if not span and enabled: @@ -174,7 +206,6 @@ def trace_tween(request): "PyramidInstrumentor().instrument_config(config) is called" ) elif enabled: - status = getattr(response, "status", status) if status is not None: otel_wsgi.add_response_attributes(
diff --git a/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_automatic.py b/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_automatic.py --- a/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_automatic.py +++ b/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_automatic.py @@ -12,12 +12,17 @@ # See the License for the specific language governing permissions and # limitations under the License. +from timeit import default_timer from unittest.mock import patch from pyramid.config import Configurator from opentelemetry import trace from opentelemetry.instrumentation.pyramid import PyramidInstrumentor +from opentelemetry.sdk.metrics.export import ( + HistogramDataPoint, + NumberDataPoint, +) from opentelemetry.test.globals_test import reset_trace_globals from opentelemetry.test.wsgitestutil import WsgiTestBase from opentelemetry.trace import SpanKind @@ -25,11 +30,22 @@ from opentelemetry.util.http import ( OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST, OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE, + _active_requests_count_attrs, + _duration_attrs, ) # pylint: disable=import-error from .pyramid_base_test import InstrumentationTest +_expected_metric_names = [ + "http.server.active_requests", + "http.server.duration", +] +_recommended_attrs = { + "http.server.active_requests": _active_requests_count_attrs, + "http.server.duration": _duration_attrs, +} + class TestAutomatic(InstrumentationTest, WsgiTestBase): def setUp(self): @@ -156,6 +172,89 @@ def test_400s_response_is_not_an_error(self): span_list = self.memory_exporter.get_finished_spans() self.assertEqual(len(span_list), 1) + def test_pyramid_metric(self): + self.client.get("/hello/756") + self.client.get("/hello/756") + self.client.get("/hello/756") + metrics_list = self.memory_metrics_reader.get_metrics_data() + number_data_point_seen = False + histogram_data_point_seen = False + self.assertTrue(len(metrics_list.resource_metrics) == 1) + for resource_metric in metrics_list.resource_metrics: + self.assertTrue(len(resource_metric.scope_metrics) == 1) + for scope_metric in resource_metric.scope_metrics: + self.assertTrue(len(scope_metric.metrics) == 2) + for metric in scope_metric.metrics: + self.assertIn(metric.name, _expected_metric_names) + data_points = list(metric.data.data_points) + self.assertEqual(len(data_points), 1) + for point in data_points: + if isinstance(point, HistogramDataPoint): + self.assertEqual(point.count, 3) + histogram_data_point_seen = True + if isinstance(point, NumberDataPoint): + number_data_point_seen = True + for attr in point.attributes: + self.assertIn( + attr, _recommended_attrs[metric.name] + ) + self.assertTrue(number_data_point_seen and histogram_data_point_seen) + + def test_basic_metric_success(self): + start = default_timer() + self.client.get("/hello/756") + duration = max(round((default_timer() - start) * 1000), 0) + expected_duration_attributes = { + "http.method": "GET", + "http.host": "localhost", + "http.scheme": "http", + "http.flavor": "1.1", + "http.server_name": "localhost", + "net.host.port": 80, + "http.status_code": 200, + } + expected_requests_count_attributes = { + "http.method": "GET", + "http.host": "localhost", + "http.scheme": "http", + "http.flavor": "1.1", + "http.server_name": "localhost", + } + metrics_list = self.memory_metrics_reader.get_metrics_data() + for metric in ( + metrics_list.resource_metrics[0].scope_metrics[0].metrics + ): + for point in list(metric.data.data_points): + if isinstance(point, HistogramDataPoint): + self.assertDictEqual( + expected_duration_attributes, + dict(point.attributes), + ) + self.assertEqual(point.count, 1) + self.assertAlmostEqual(duration, point.sum, delta=20) + if isinstance(point, NumberDataPoint): + self.assertDictEqual( + expected_requests_count_attributes, + dict(point.attributes), + ) + self.assertEqual(point.value, 0) + + def test_metric_uninstruemnt(self): + self.client.get("/hello/756") + PyramidInstrumentor().uninstrument() + self.config = Configurator() + self._common_initialization(self.config) + self.client.get("/hello/756") + metrics_list = self.memory_metrics_reader.get_metrics_data() + for metric in ( + metrics_list.resource_metrics[0].scope_metrics[0].metrics + ): + for point in list(metric.data.data_points): + if isinstance(point, HistogramDataPoint): + self.assertEqual(point.count, 1) + if isinstance(point, NumberDataPoint): + self.assertEqual(point.value, 0) + class TestWrappedWithOtherFramework(InstrumentationTest, WsgiTestBase): def setUp(self):
Metrics instrumentation pyramid HTTP metrics semconv: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/semantic_conventions/http-metrics.md
Can you assign this to me? I am a bit busy these days. Does someone wants to take up this issue? Hello @ashu658 I'm willing to work on this issue. Can you please assign this to me? Thanks @TheAnshul756 Assigned!
2022-08-24T08:29:11
open-telemetry/opentelemetry-python-contrib
1,246
open-telemetry__opentelemetry-python-contrib-1246
[ "1207" ]
03d97ffaf948302b8c49d2877ca118838519e407
diff --git a/instrumentation/opentelemetry-instrumentation-aiohttp-client/src/opentelemetry/instrumentation/aiohttp_client/__init__.py b/instrumentation/opentelemetry-instrumentation-aiohttp-client/src/opentelemetry/instrumentation/aiohttp_client/__init__.py --- a/instrumentation/opentelemetry-instrumentation-aiohttp-client/src/opentelemetry/instrumentation/aiohttp_client/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-aiohttp-client/src/opentelemetry/instrumentation/aiohttp_client/__init__.py @@ -262,7 +262,9 @@ def _instrument( url_filter: _UrlFilterT = None, request_hook: _RequestHookT = None, response_hook: _ResponseHookT = None, - trace_configs: typing.Optional[aiohttp.TraceConfig] = None, + trace_configs: typing.Optional[ + typing.Sequence[aiohttp.TraceConfig] + ] = None, ): """Enables tracing of all ClientSessions @@ -270,16 +272,15 @@ def _instrument( the session's trace_configs. """ - if trace_configs is None: - trace_configs = [] + trace_configs = trace_configs or () # pylint:disable=unused-argument def instrumented_init(wrapped, instance, args, kwargs): if context_api.get_value(_SUPPRESS_INSTRUMENTATION_KEY): return wrapped(*args, **kwargs) - if kwargs.get("trace_configs"): - trace_configs.extend(kwargs.get("trace_configs")) + client_trace_configs = list(kwargs.get("trace_configs", ())) + client_trace_configs.extend(trace_configs) trace_config = create_trace_config( url_filter=url_filter, @@ -288,9 +289,9 @@ def instrumented_init(wrapped, instance, args, kwargs): tracer_provider=tracer_provider, ) trace_config._is_instrumented_by_opentelemetry = True - trace_configs.append(trace_config) + client_trace_configs.append(trace_config) - kwargs["trace_configs"] = trace_configs + kwargs["trace_configs"] = client_trace_configs return wrapped(*args, **kwargs) wrapt.wrap_function_wrapper(
diff --git a/instrumentation/opentelemetry-instrumentation-aiohttp-client/tests/test_aiohttp_client_integration.py b/instrumentation/opentelemetry-instrumentation-aiohttp-client/tests/test_aiohttp_client_integration.py --- a/instrumentation/opentelemetry-instrumentation-aiohttp-client/tests/test_aiohttp_client_integration.py +++ b/instrumentation/opentelemetry-instrumentation-aiohttp-client/tests/test_aiohttp_client_integration.py @@ -387,18 +387,35 @@ def test_instrument(self): self.assertEqual(200, span.attributes[SpanAttributes.HTTP_STATUS_CODE]) def test_instrument_with_custom_trace_config(self): + trace_config = aiohttp.TraceConfig() + AioHttpClientInstrumentor().uninstrument() - AioHttpClientInstrumentor().instrument( - trace_configs=[aiohttp_client.create_trace_config()] - ) + AioHttpClientInstrumentor().instrument(trace_configs=[trace_config]) - self.assert_spans(0) + async def make_request(server: aiohttp.test_utils.TestServer): + async with aiohttp.test_utils.TestClient(server) as client: + trace_configs = client.session._trace_configs + self.assertEqual(2, len(trace_configs)) + self.assertTrue(trace_config in trace_configs) + async with client as session: + await session.get(TestAioHttpClientInstrumentor.URL) - run_with_test_server( - self.get_default_request(), self.URL, self.default_handler - ) + run_with_test_server(make_request, self.URL, self.default_handler) + self.assert_spans(1) + + def test_every_request_by_new_session_creates_one_span(self): + async def make_request(server: aiohttp.test_utils.TestServer): + async with aiohttp.test_utils.TestClient(server) as client: + async with client as session: + await session.get(TestAioHttpClientInstrumentor.URL) - self.assert_spans(2) + for request_no in range(3): + self.memory_exporter.clear() + with self.subTest(request_no=request_no): + run_with_test_server( + make_request, self.URL, self.default_handler + ) + self.assert_spans(1) def test_instrument_with_existing_trace_config(self): trace_config = aiohttp.TraceConfig() @@ -446,7 +463,7 @@ async def uninstrument_request(server: aiohttp.test_utils.TestServer): run_with_test_server( self.get_default_request(), self.URL, self.default_handler ) - self.assert_spans(2) + self.assert_spans(1) def test_suppress_instrumentation(self): token = context.attach(
instrumentation-aiohttp-client: Number of created spans per request increases by 1 with every new request Latest release 0.32b0 introduced a bug where an additional span is created every time a new aiohttp ClientSession is created. This leads to 1 span per request when the first session is created, 2 spans when the second session gets created, ... and so on. When `AioHttpClientInstrumentor.instrument()` the instrumentor intercepts the `ClientSession.__init__` call and injects a TraceConfig instance into the parameters that are passed to the ClientSession. With the latest release an additional parameter `trace_configs` was added to the `AioHttpClientInstrumentor.instrument()` method. The problem is that the `trace_configs` argument is now injected into every newly created ClientSession but it is also shared between all ClientSessions. Every time a new ClientSession is created the instrumented `__init__` call now adds one additional trace_config to the shared `trace_configs` argument (associated code can be found [here](https://github.com/open-telemetry/opentelemetry-python-contrib/blob/v0.32b0/instrumentation/opentelemetry-instrumentation-aiohttp-client/src/opentelemetry/instrumentation/aiohttp_client/__init__.py#L281-L282)). Since one trace_config defines the hooks to create and end one span, every added trace_config will produce an additional span per request. **Steps to reproduce** Instrument the aiohttp-client with `AioHttpClientInstrumentor.instrument()`. Create at least two ClientSessions and make one HTTP request to some arbitrary URL. The produced spans increase with every new ClientSession that is created. Describe exactly how to reproduce the error. Include a code sample if applicable. **What is the expected behavior?** One span per HTTP request independent of the number of ClientSessions that are created. **What is the actual behavior?** Number of created spans increase with each newly created ClientSession.
Thinking about it some more i don't quite see the purpose of the newly added `trace_configs` parameter in `AioHttpClientInstrumentor.instrument()`. A `TraceConfig` is the mechanism that aiohttp provides to trace requests by registering callbacks for all kind of events (start, end, exception, ...). This is what the instrumentor already uses to create and end spans accordingly. From an OpenTelemetry point of view adding further TraceConfigs would just mean creating more spans. So imo the `trace_configs` parameter to externally add additional TraceConfigs doesn't make much sense. Same problem with 0.33b0 release @mariojonke if the last change is not necessary feel free to send a pull request with fix.
2022-08-26T09:28:55
open-telemetry/opentelemetry-python-contrib
1,252
open-telemetry__opentelemetry-python-contrib-1252
[ "1145" ]
c615fa74da3ad9443cc92a80902cd25360884282
diff --git a/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py b/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py --- a/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py @@ -157,7 +157,8 @@ def client_resposne_hook(span, future): from functools import partial from logging import getLogger from time import time_ns -from typing import Collection +from timeit import default_timer +from typing import Collection, Dict import tornado.web import wrapt @@ -177,6 +178,8 @@ def client_resposne_hook(span, future): http_status_to_status_code, unwrap, ) +from opentelemetry.metrics import get_meter +from opentelemetry.metrics._internal.instrument import Histogram from opentelemetry.propagators import textmap from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.trace.status import Status, StatusCode @@ -197,6 +200,14 @@ def client_resposne_hook(span, future): _HANDLER_CONTEXT_KEY = "_otel_trace_context_key" _OTEL_PATCHED_KEY = "_otel_patched_key" +_START_TIME = "start_time" +_CLIENT_DURATION_HISTOGRAM = "http.client.duration" +_CLIENT_REQUEST_SIZE_HISTOGRAM = "http.client.request.size" +_CLIENT_RESPONSE_SIZE_HISTOGRAM = "http.client.response.size" +_SERVER_DURATION_HISTOGRAM = "http.server.duration" +_SERVER_REQUEST_SIZE_HISTOGRAM = "http.server.request.size" +_SERVER_RESPONSE_SIZE_HISTOGRAM = "http.server.response.size" +_SERVER_ACTIVE_REQUESTS_HISTOGRAM = "http.server.active_requests" _excluded_urls = get_excluded_urls("TORNADO") _traced_request_attrs = get_traced_request_attrs("TORNADO") @@ -233,13 +244,21 @@ def _instrument(self, **kwargs): tracer_provider = kwargs.get("tracer_provider") tracer = trace.get_tracer(__name__, __version__, tracer_provider) + meter_provider = kwargs.get("meter_provider") + meter = get_meter(__name__, __version__, meter_provider) + + client_histograms = _create_client_histograms(meter) + server_histograms = _create_server_histograms(meter) + client_request_hook = kwargs.get("client_request_hook", None) client_response_hook = kwargs.get("client_response_hook", None) server_request_hook = kwargs.get("server_request_hook", None) def handler_init(init, handler, args, kwargs): cls = handler.__class__ - if patch_handler_class(tracer, cls, server_request_hook): + if patch_handler_class( + tracer, server_histograms, cls, server_request_hook + ): self.patched_handlers.append(cls) return init(*args, **kwargs) @@ -250,7 +269,13 @@ def handler_init(init, handler, args, kwargs): "tornado.httpclient", "AsyncHTTPClient.fetch", partial( - fetch_async, tracer, client_request_hook, client_response_hook + fetch_async, + tracer, + client_request_hook, + client_response_hook, + client_histograms[_CLIENT_DURATION_HISTOGRAM], + client_histograms[_CLIENT_REQUEST_SIZE_HISTOGRAM], + client_histograms[_CLIENT_RESPONSE_SIZE_HISTOGRAM], ), ) @@ -262,14 +287,71 @@ def _uninstrument(self, **kwargs): self.patched_handlers = [] -def patch_handler_class(tracer, cls, request_hook=None): +def _create_server_histograms(meter) -> Dict[str, Histogram]: + histograms = { + _SERVER_DURATION_HISTOGRAM: meter.create_histogram( + name="http.server.duration", + unit="ms", + description="measures the duration outbound HTTP requests", + ), + _SERVER_REQUEST_SIZE_HISTOGRAM: meter.create_histogram( + name="http.server.request.size", + unit="By", + description="measures the size of HTTP request messages (compressed)", + ), + _SERVER_RESPONSE_SIZE_HISTOGRAM: meter.create_histogram( + name="http.server.response.size", + unit="By", + description="measures the size of HTTP response messages (compressed)", + ), + _SERVER_ACTIVE_REQUESTS_HISTOGRAM: meter.create_up_down_counter( + name="http.server.active_requests", + unit="requests", + description="measures the number of concurrent HTTP requests that are currently in-flight", + ), + } + + return histograms + + +def _create_client_histograms(meter) -> Dict[str, Histogram]: + histograms = { + _CLIENT_DURATION_HISTOGRAM: meter.create_histogram( + name="http.client.duration", + unit="ms", + description="measures the duration outbound HTTP requests", + ), + _CLIENT_REQUEST_SIZE_HISTOGRAM: meter.create_histogram( + name="http.client.request.size", + unit="By", + description="measures the size of HTTP request messages (compressed)", + ), + _CLIENT_RESPONSE_SIZE_HISTOGRAM: meter.create_histogram( + name="http.client.response.size", + unit="By", + description="measures the size of HTTP response messages (compressed)", + ), + } + + return histograms + + +def patch_handler_class(tracer, server_histograms, cls, request_hook=None): if getattr(cls, _OTEL_PATCHED_KEY, False): return False setattr(cls, _OTEL_PATCHED_KEY, True) - _wrap(cls, "prepare", partial(_prepare, tracer, request_hook)) - _wrap(cls, "on_finish", partial(_on_finish, tracer)) - _wrap(cls, "log_exception", partial(_log_exception, tracer)) + _wrap( + cls, + "prepare", + partial(_prepare, tracer, server_histograms, request_hook), + ) + _wrap(cls, "on_finish", partial(_on_finish, tracer, server_histograms)) + _wrap( + cls, + "log_exception", + partial(_log_exception, tracer, server_histograms), + ) return True @@ -289,28 +371,40 @@ def _wrap(cls, method_name, wrapper): wrapt.apply_patch(cls, method_name, wrapper) -def _prepare(tracer, request_hook, func, handler, args, kwargs): - start_time = time_ns() +def _prepare( + tracer, server_histograms, request_hook, func, handler, args, kwargs +): + server_histograms[_START_TIME] = default_timer() + request = handler.request if _excluded_urls.url_disabled(request.uri): return func(*args, **kwargs) - ctx = _start_span(tracer, handler, start_time) + + _record_prepare_metrics(server_histograms, handler) + + ctx = _start_span(tracer, handler) if request_hook: request_hook(ctx.span, handler) return func(*args, **kwargs) -def _on_finish(tracer, func, handler, args, kwargs): +def _on_finish(tracer, server_histograms, func, handler, args, kwargs): response = func(*args, **kwargs) + + _record_on_finish_metrics(server_histograms, handler) + _finish_span(tracer, handler) + return response -def _log_exception(tracer, func, handler, args, kwargs): +def _log_exception(tracer, server_histograms, func, handler, args, kwargs): error = None if len(args) == 3: error = args[1] + _record_on_finish_metrics(server_histograms, handler, error) + _finish_span(tracer, handler, error) return func(*args, **kwargs) @@ -377,11 +471,11 @@ def _get_full_handler_name(handler): return f"{klass.__module__}.{klass.__qualname__}" -def _start_span(tracer, handler, start_time) -> _TraceContext: +def _start_span(tracer, handler) -> _TraceContext: span, token = _start_internal_or_server_span( tracer=tracer, span_name=_get_operation_name(handler, handler.request), - start_time=start_time, + start_time=time_ns(), context_carrier=handler.request.headers, context_getter=textmap.default_getter, ) @@ -423,7 +517,7 @@ def _finish_span(tracer, handler, error=None): if isinstance(error, tornado.web.HTTPError): status_code = error.status_code if not ctx and status_code == 404: - ctx = _start_span(tracer, handler, time_ns()) + ctx = _start_span(tracer, handler) else: status_code = 500 reason = None @@ -462,3 +556,65 @@ def _finish_span(tracer, handler, error=None): if ctx.token: context.detach(ctx.token) delattr(handler, _HANDLER_CONTEXT_KEY) + + +def _record_prepare_metrics(server_histograms, handler): + request_size = int(handler.request.headers.get("Content-Length", 0)) + metric_attributes = _create_metric_attributes(handler) + + server_histograms[_SERVER_REQUEST_SIZE_HISTOGRAM].record( + request_size, attributes=metric_attributes + ) + + active_requests_attributes = _create_active_requests_attributes( + handler.request + ) + server_histograms[_SERVER_ACTIVE_REQUESTS_HISTOGRAM].add( + 1, attributes=active_requests_attributes + ) + + +def _record_on_finish_metrics(server_histograms, handler, error=None): + elapsed_time = round( + (default_timer() - server_histograms[_START_TIME]) * 1000 + ) + + response_size = int(handler._headers.get("Content-Length", 0)) + metric_attributes = _create_metric_attributes(handler) + + if isinstance(error, tornado.web.HTTPError): + metric_attributes[SpanAttributes.HTTP_STATUS_CODE] = error.status_code + + server_histograms[_SERVER_RESPONSE_SIZE_HISTOGRAM].record( + response_size, attributes=metric_attributes + ) + + server_histograms[_SERVER_DURATION_HISTOGRAM].record( + elapsed_time, attributes=metric_attributes + ) + + active_requests_attributes = _create_active_requests_attributes( + handler.request + ) + server_histograms[_SERVER_ACTIVE_REQUESTS_HISTOGRAM].add( + -1, attributes=active_requests_attributes + ) + + +def _create_active_requests_attributes(request): + metric_attributes = { + SpanAttributes.HTTP_METHOD: request.method, + SpanAttributes.HTTP_SCHEME: request.protocol, + SpanAttributes.HTTP_FLAVOR: request.version, + SpanAttributes.HTTP_HOST: request.host, + SpanAttributes.HTTP_TARGET: request.path, + } + + return metric_attributes + + +def _create_metric_attributes(handler): + metric_attributes = _create_active_requests_attributes(handler.request) + metric_attributes[SpanAttributes.HTTP_STATUS_CODE] = handler.get_status() + + return metric_attributes diff --git a/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/client.py b/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/client.py --- a/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/client.py +++ b/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/client.py @@ -41,7 +41,18 @@ def _normalize_request(args, kwargs): return (new_args, new_kwargs) -def fetch_async(tracer, request_hook, response_hook, func, _, args, kwargs): +def fetch_async( + tracer, + request_hook, + response_hook, + duration_histogram, + request_size_histogram, + response_size_histogram, + func, + _, + args, + kwargs, +): start_time = time_ns() # Return immediately if no args were provided (error) @@ -78,21 +89,34 @@ def fetch_async(tracer, request_hook, response_hook, func, _, args, kwargs): _finish_tracing_callback, span=span, response_hook=response_hook, + duration_histogram=duration_histogram, + request_size_histogram=request_size_histogram, + response_size_histogram=response_size_histogram, ) ) return future -def _finish_tracing_callback(future, span, response_hook): +def _finish_tracing_callback( + future, + span, + response_hook, + duration_histogram, + request_size_histogram, + response_size_histogram, +): status_code = None description = None exc = future.exception() + + response = future.result() + if span.is_recording() and exc: if isinstance(exc, HTTPError): status_code = exc.code description = f"{type(exc).__name__}: {exc}" else: - status_code = future.result().code + status_code = response.code if status_code is not None: span.set_attribute(SpanAttributes.HTTP_STATUS_CODE, status_code) @@ -102,6 +126,27 @@ def _finish_tracing_callback(future, span, response_hook): description=description, ) ) + + metric_attributes = _create_metric_attributes(response) + request_size = int(response.request.headers.get("Content-Length", 0)) + response_size = int(response.headers.get("Content-Length", 0)) + + duration_histogram.record( + response.request_time, attributes=metric_attributes + ) + request_size_histogram.record(request_size, attributes=metric_attributes) + response_size_histogram.record(response_size, attributes=metric_attributes) + if response_hook: response_hook(span, future) span.end() + + +def _create_metric_attributes(response): + metric_attributes = { + SpanAttributes.HTTP_STATUS_CODE: response.code, + SpanAttributes.HTTP_URL: remove_url_credentials(response.request.url), + SpanAttributes.HTTP_METHOD: response.request.method, + } + + return metric_attributes diff --git a/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/package.py b/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/package.py --- a/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/package.py +++ b/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/package.py @@ -14,3 +14,5 @@ _instruments = ("tornado >= 5.1.1",) + +_supports_metrics = True
diff --git a/instrumentation/opentelemetry-instrumentation-tornado/tests/test_instrumentation.py b/instrumentation/opentelemetry-instrumentation-tornado/tests/test_instrumentation.py --- a/instrumentation/opentelemetry-instrumentation-tornado/tests/test_instrumentation.py +++ b/instrumentation/opentelemetry-instrumentation-tornado/tests/test_instrumentation.py @@ -55,12 +55,12 @@ def get_app(self): return app def setUp(self): + super().setUp() TornadoInstrumentor().instrument( server_request_hook=getattr(self, "server_request_hook", None), client_request_hook=getattr(self, "client_request_hook", None), client_response_hook=getattr(self, "client_response_hook", None), ) - super().setUp() # pylint: disable=protected-access self.env_patch = patch.dict( "os.environ", @@ -110,9 +110,9 @@ def test_patch_references(self): def test_patch_applied_only_once(self): tracer = trace.get_tracer(__name__) - self.assertTrue(patch_handler_class(tracer, AsyncHandler)) - self.assertFalse(patch_handler_class(tracer, AsyncHandler)) - self.assertFalse(patch_handler_class(tracer, AsyncHandler)) + self.assertTrue(patch_handler_class(tracer, {}, AsyncHandler)) + self.assertFalse(patch_handler_class(tracer, {}, AsyncHandler)) + self.assertFalse(patch_handler_class(tracer, {}, AsyncHandler)) unpatch_handler_class(AsyncHandler) diff --git a/instrumentation/opentelemetry-instrumentation-tornado/tests/test_metrics_instrumentation.py b/instrumentation/opentelemetry-instrumentation-tornado/tests/test_metrics_instrumentation.py new file mode 100644 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-tornado/tests/test_metrics_instrumentation.py @@ -0,0 +1,235 @@ +# Copyright The OpenTelemetry Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from timeit import default_timer + +from tornado.testing import AsyncHTTPTestCase + +from opentelemetry import trace +from opentelemetry.instrumentation.tornado import TornadoInstrumentor +from opentelemetry.sdk.metrics.export import ( + HistogramDataPoint, + NumberDataPoint, +) +from opentelemetry.test.test_base import TestBase + +from .tornado_test_app import make_app + + +class TornadoTest(AsyncHTTPTestCase, TestBase): + # pylint:disable=no-self-use + def get_app(self): + tracer = trace.get_tracer(__name__) + app = make_app(tracer) + return app + + def get_sorted_metrics(self): + resource_metrics = ( + self.memory_metrics_reader.get_metrics_data().resource_metrics + ) + for metrics in resource_metrics: + for scope_metrics in metrics.scope_metrics: + all_metrics = list(scope_metrics.metrics) + return self.sorted_metrics(all_metrics) + + @staticmethod + def sorted_metrics(metrics): + """ + Sorts metrics by metric name. + """ + return sorted( + metrics, + key=lambda m: m.name, + ) + + def assert_metric_expected( + self, metric, expected_value, expected_attributes + ): + data_point = next(metric.data.data_points) + + if isinstance(data_point, HistogramDataPoint): + self.assertEqual( + data_point.sum, + expected_value, + ) + elif isinstance(data_point, NumberDataPoint): + self.assertEqual( + data_point.value, + expected_value, + ) + + self.assertDictEqual( + expected_attributes, + dict(data_point.attributes), + ) + + def assert_duration_metric_expected( + self, metric, duration_estimated, expected_attributes + ): + data_point = next(metric.data.data_points) + + self.assertAlmostEqual( + data_point.sum, + duration_estimated, + delta=200, + ) + + self.assertDictEqual( + expected_attributes, + dict(data_point.attributes), + ) + + def setUp(self): + super().setUp() + TornadoInstrumentor().instrument( + server_request_hook=getattr(self, "server_request_hook", None), + client_request_hook=getattr(self, "client_request_hook", None), + client_response_hook=getattr(self, "client_response_hook", None), + meter_provider=self.meter_provider, + ) + + def tearDown(self): + TornadoInstrumentor().uninstrument() + super().tearDown() + + +class TestTornadoInstrumentor(TornadoTest): + def test_basic_metrics(self): + start_time = default_timer() + response = self.fetch("/") + client_duration_estimated = (default_timer() - start_time) * 1000 + + metrics = self.get_sorted_metrics() + self.assertEqual(len(metrics), 7) + + ( + client_duration, + client_request_size, + client_response_size, + ) = metrics[:3] + + ( + server_active_request, + server_duration, + server_request_size, + server_response_size, + ) = metrics[3:] + + self.assertEqual( + server_active_request.name, "http.server.active_requests" + ) + self.assert_metric_expected( + server_active_request, + 0, + { + "http.method": "GET", + "http.flavor": "HTTP/1.1", + "http.scheme": "http", + "http.target": "/", + "http.host": response.request.headers["host"], + }, + ) + + self.assertEqual(server_duration.name, "http.server.duration") + self.assert_duration_metric_expected( + server_duration, + client_duration_estimated, + { + "http.status_code": response.code, + "http.method": "GET", + "http.flavor": "HTTP/1.1", + "http.scheme": "http", + "http.target": "/", + "http.host": response.request.headers["host"], + }, + ) + + self.assertEqual(server_request_size.name, "http.server.request.size") + self.assert_metric_expected( + server_request_size, + 0, + { + "http.status_code": 200, + "http.method": "GET", + "http.flavor": "HTTP/1.1", + "http.scheme": "http", + "http.target": "/", + "http.host": response.request.headers["host"], + }, + ) + + self.assertEqual( + server_response_size.name, "http.server.response.size" + ) + self.assert_metric_expected( + server_response_size, + len(response.body), + { + "http.status_code": response.code, + "http.method": "GET", + "http.flavor": "HTTP/1.1", + "http.scheme": "http", + "http.target": "/", + "http.host": response.request.headers["host"], + }, + ) + + self.assertEqual(client_duration.name, "http.client.duration") + self.assert_duration_metric_expected( + client_duration, + client_duration_estimated, + { + "http.status_code": response.code, + "http.method": "GET", + "http.url": response.effective_url, + }, + ) + + self.assertEqual(client_request_size.name, "http.client.request.size") + self.assert_metric_expected( + client_request_size, + 0, + { + "http.status_code": response.code, + "http.method": "GET", + "http.url": response.effective_url, + }, + ) + + self.assertEqual( + client_response_size.name, "http.client.response.size" + ) + self.assert_metric_expected( + client_response_size, + len(response.body), + { + "http.status_code": response.code, + "http.method": "GET", + "http.url": response.effective_url, + }, + ) + + def test_metric_uninstrument(self): + self.fetch("/") + TornadoInstrumentor().uninstrument() + self.fetch("/") + + metrics_list = self.memory_metrics_reader.get_metrics_data() + for resource_metric in metrics_list.resource_metrics: + for scope_metric in resource_metric.scope_metrics: + for metric in scope_metric.metrics: + for point in list(metric.data.data_points): + if isinstance(point, HistogramDataPoint): + self.assertEqual(point.count, 1)
Metrics instrumentation tornado HTPP Server semconv https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/semantic_conventions/http-metrics.md#http-server
Can you assign this issue to me?
2022-08-30T11:39:09
open-telemetry/opentelemetry-python-contrib
1,253
open-telemetry__opentelemetry-python-contrib-1253
[ "1184" ]
56530ebdfc82581d9d813ee591b7eac401f2bbf0
diff --git a/util/opentelemetry-util-http/src/opentelemetry/util/http/__init__.py b/util/opentelemetry-util-http/src/opentelemetry/util/http/__init__.py --- a/util/opentelemetry-util-http/src/opentelemetry/util/http/__init__.py +++ b/util/opentelemetry-util-http/src/opentelemetry/util/http/__init__.py @@ -13,6 +13,7 @@ # limitations under the License. from os import environ +from re import IGNORECASE as RE_IGNORECASE from re import compile as re_compile from re import search from typing import Iterable, List @@ -20,6 +21,9 @@ from opentelemetry.semconv.trace import SpanAttributes +OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS = ( + "OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS" +) OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST = ( "OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST" ) @@ -60,6 +64,22 @@ def url_disabled(self, url: str) -> bool: return bool(self._excluded_urls and search(self._regex, url)) +class SanitizeValue: + """Class to sanitize (remove sensitive data from) certain headers (given as a list of regexes)""" + + def __init__(self, sanitized_fields: Iterable[str]): + self._sanitized_fields = sanitized_fields + if self._sanitized_fields: + self._regex = re_compile("|".join(sanitized_fields), RE_IGNORECASE) + + def sanitize_header_value(self, header: str, value: str) -> str: + return ( + "[REDACTED]" + if (self._sanitized_fields and search(self._regex, header)) + else value + ) + + _root = r"OTEL_PYTHON_{}" @@ -90,7 +110,7 @@ def get_excluded_urls(instrumentation: str) -> ExcludeList: def parse_excluded_urls(excluded_urls: str) -> ExcludeList: """ - Small helper to put an arbitrary url list inside of ExcludeList + Small helper to put an arbitrary url list inside an ExcludeList """ if excluded_urls: excluded_url_list = [
diff --git a/util/opentelemetry-util-http/tests/test_capture_custom_headers.py b/util/opentelemetry-util-http/tests/test_capture_custom_headers.py --- a/util/opentelemetry-util-http/tests/test_capture_custom_headers.py +++ b/util/opentelemetry-util-http/tests/test_capture_custom_headers.py @@ -16,8 +16,10 @@ from unittest.mock import patch from opentelemetry.util.http import ( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS, OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST, OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE, + SanitizeValue, get_custom_headers, normalise_request_header_name, normalise_response_header_name, @@ -58,6 +60,48 @@ def test_get_custom_response_header(self): ], ) + @patch.dict( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS: "My-Secret-Header,My-Secret-Header-2" + }, + ) + def test_get_custom_sanitize_header(self): + sanitized_fields = get_custom_headers( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS + ) + self.assertEqual( + sanitized_fields, + ["My-Secret-Header", "My-Secret-Header-2"], + ) + + @patch.dict( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS: "My-Secret-Header,My-Secret-Header-2" + }, + ) + def test_sanitize(self): + sanitized_fields = get_custom_headers( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS + ) + + sanitize = SanitizeValue(sanitized_fields) + + self.assertEqual( + sanitize.sanitize_header_value( + header="My-Secret-Header", value="My-Secret-Value" + ), + "[REDACTED]", + ) + + self.assertEqual( + sanitize.sanitize_header_value( + header="My-Not-Secret-Header", value="My-Not-Secret-Value" + ), + "My-Not-Secret-Value", + ) + def test_normalise_request_header_name(self): key = normalise_request_header_name("Test-Header") self.assertEqual(key, "http.request.header.test_header")
Add more features for adding HTTP request / response headers to spans. I already have https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1172 open for this, and I'll be breaking it in to smaller pieces at @lzchen 's request. **Is your feature request related to a problem?** Currently, you can only provide a list of full HTTP request / response header names to be added to the span. There is also no capacity for header value redaction. **Describe the solution you'd like** It would be nice to be able to specify a regex or "all" to get all headers. Header value redaction is also a must-have for us. **Describe alternatives you've considered** I considered doing this in my application, but it makes more sense to add it here.
2022-08-30T16:47:08
open-telemetry/opentelemetry-python-contrib
1,258
open-telemetry__opentelemetry-python-contrib-1258
[ "1256" ]
156203ca799c8760c30e848a42abbc768cb2a835
diff --git a/instrumentation/opentelemetry-instrumentation-fastapi/src/opentelemetry/instrumentation/fastapi/__init__.py b/instrumentation/opentelemetry-instrumentation-fastapi/src/opentelemetry/instrumentation/fastapi/__init__.py --- a/instrumentation/opentelemetry-instrumentation-fastapi/src/opentelemetry/instrumentation/fastapi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-fastapi/src/opentelemetry/instrumentation/fastapi/__init__.py @@ -192,6 +192,8 @@ def instrument_app( meter=meter, ) app._is_instrumented_by_opentelemetry = True + if app not in _InstrumentedFastAPI._instrumented_fastapi_apps: + _InstrumentedFastAPI._instrumented_fastapi_apps.add(app) else: _logger.warning( "Attempting to instrument FastAPI app while already instrumented" @@ -232,6 +234,9 @@ def _instrument(self, **kwargs): fastapi.FastAPI = _InstrumentedFastAPI def _uninstrument(self, **kwargs): + for instance in _InstrumentedFastAPI._instrumented_fastapi_apps: + self.uninstrument_app(instance) + _InstrumentedFastAPI._instrumented_fastapi_apps.clear() fastapi.FastAPI = self._original_fastapi @@ -242,6 +247,7 @@ class _InstrumentedFastAPI(fastapi.FastAPI): _server_request_hook: _ServerRequestHookT = None _client_request_hook: _ClientRequestHookT = None _client_response_hook: _ClientResponseHookT = None + _instrumented_fastapi_apps = set() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -259,6 +265,11 @@ def __init__(self, *args, **kwargs): meter=meter, ) self._is_instrumented_by_opentelemetry = True + _InstrumentedFastAPI._instrumented_fastapi_apps.add(self) + + def __del__(self): + if self in _InstrumentedFastAPI._instrumented_fastapi_apps: + _InstrumentedFastAPI._instrumented_fastapi_apps.remove(self) def _get_route_details(scope):
diff --git a/instrumentation/opentelemetry-instrumentation-fastapi/tests/test_fastapi_instrumentation.py b/instrumentation/opentelemetry-instrumentation-fastapi/tests/test_fastapi_instrumentation.py --- a/instrumentation/opentelemetry-instrumentation-fastapi/tests/test_fastapi_instrumentation.py +++ b/instrumentation/opentelemetry-instrumentation-fastapi/tests/test_fastapi_instrumentation.py @@ -274,16 +274,11 @@ def test_metric_uninstruemnt_app(self): self.assertEqual(point.value, 0) def test_metric_uninstrument(self): - # instrumenting class and creating app to send request - self._instrumentor.instrument() - app = self._create_fastapi_app() - client = TestClient(app) - client.get("/foobar") - # uninstrumenting class and creating the app again + if not isinstance(self, TestAutoInstrumentation): + self._instrumentor.instrument() + self._client.get("/foobar") self._instrumentor.uninstrument() - app = self._create_fastapi_app() - client = TestClient(app) - client.get("/foobar") + self._client.get("/foobar") metrics_list = self.memory_metrics_reader.get_metrics_data() for metric in ( @@ -416,6 +411,15 @@ def test_mulitple_way_instrumentation(self): count += 1 self.assertEqual(count, 1) + def test_uninstrument_after_instrument(self): + app = self._create_fastapi_app() + client = TestClient(app) + client.get("/foobar") + self._instrumentor.uninstrument() + client.get("/foobar") + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 3) + def tearDown(self): self._instrumentor.uninstrument() super().tearDown()
Uninstrument Existing fastapi instances Existing instances shouldn't continue to send any telemetry after the `uninstrument`. _Originally posted by @srikanthccv in https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1199#discussion_r957094027_ `uninstrument` method of `FastAPIInstrumentor` restore the original `fastapi.FastAPI` class, but all the existing objects of the earlier instrumented class do not get uninstrumented, which is not the expected behaviour.
@srikanthccv please assign this to me.
2022-09-01T08:38:59
open-telemetry/opentelemetry-python-contrib
1,313
open-telemetry__opentelemetry-python-contrib-1313
[ "1312" ]
ff9651e5ff3d17171e5928271aca1095bd5dbbcd
diff --git a/instrumentation/opentelemetry-instrumentation-fastapi/src/opentelemetry/instrumentation/fastapi/__init__.py b/instrumentation/opentelemetry-instrumentation-fastapi/src/opentelemetry/instrumentation/fastapi/__init__.py --- a/instrumentation/opentelemetry-instrumentation-fastapi/src/opentelemetry/instrumentation/fastapi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-fastapi/src/opentelemetry/instrumentation/fastapi/__init__.py @@ -247,6 +247,7 @@ def __init__(self, *args, **kwargs): client_response_hook=_InstrumentedFastAPI._client_response_hook, tracer_provider=_InstrumentedFastAPI._tracer_provider, ) + self._is_instrumented_by_opentelemetry = True def _get_route_details(scope):
diff --git a/instrumentation/opentelemetry-instrumentation-fastapi/tests/test_fastapi_instrumentation.py b/instrumentation/opentelemetry-instrumentation-fastapi/tests/test_fastapi_instrumentation.py --- a/instrumentation/opentelemetry-instrumentation-fastapi/tests/test_fastapi_instrumentation.py +++ b/instrumentation/opentelemetry-instrumentation-fastapi/tests/test_fastapi_instrumentation.py @@ -274,6 +274,14 @@ def test_request(self): self.assertEqual(span.resource.attributes["key1"], "value1") self.assertEqual(span.resource.attributes["key2"], "value2") + def test_mulitple_way_instrumentation(self): + self._instrumentor.instrument_app(self._app) + count = 0 + for middleware in self._app.user_middleware: + if middleware.cls is OpenTelemetryMiddleware: + count += 1 + self.assertEqual(count, 1) + def tearDown(self): self._instrumentor.uninstrument() super().tearDown()
is_instrumented_by_opentelemetry is not set in _InstrumentedFastAPI class **Steps to reproduce** If `instrument_app` function is called for already instrumented object of `_InstrumentedFastAPI` then it will add Opentelemtery middleware again in the `user_middleware` list as `is_instrumented_by_opentelemetry` is not set in the `__init__` function of `_InstrumentedFastAPI`. **What is the expected behavior?** If a fastapi app is already instrumented, i.e., it already has otel middleware in it then it shouldn't add another one. **What is the actual behavior?** Multiple otel middlewares are added.
2022-09-02T08:56:42
open-telemetry/opentelemetry-python-contrib
1,323
open-telemetry__opentelemetry-python-contrib-1323
[ "1116" ]
99f29b4b08f923c957a02d424c573bca248b7552
diff --git a/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py b/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py --- a/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py @@ -366,6 +366,32 @@ def get_default_span_details(scope: dict) -> Tuple[str, dict]: return span_name, {} +def _collect_target_attribute( + scope: typing.Dict[str, typing.Any] +) -> typing.Optional[str]: + """ + Returns the target path as defined by the Semantic Conventions. + + This value is suitable to use in metrics as it should replace concrete + values with a parameterized name. Example: /api/users/{user_id} + + Refer to the specification + https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/semantic_conventions/http-metrics.md#parameterized-attributes + + Note: this function requires specific code for each framework, as there's no + standard attribute to use. + """ + # FastAPI + root_path = scope.get("root_path", "") + + route = scope.get("route") + path_format = getattr(route, "path_format", None) + if path_format: + return f"{root_path}{path_format}" + + return None + + class OpenTelemetryMiddleware: """The ASGI application middleware. @@ -387,6 +413,7 @@ class OpenTelemetryMiddleware: the current globally configured one is used. """ + # pylint: disable=too-many-branches def __init__( self, app, @@ -454,6 +481,12 @@ async def __call__(self, scope, receive, send): attributes ) duration_attrs = _parse_duration_attrs(attributes) + + target = _collect_target_attribute(scope) + if target: + active_requests_count_attrs[SpanAttributes.HTTP_TARGET] = target + duration_attrs[SpanAttributes.HTTP_TARGET] = target + if scope["type"] == "http": self.active_requests_counter.add(1, active_requests_count_attrs) try: @@ -496,6 +529,8 @@ async def __call__(self, scope, receive, send): if token: context.detach(token) + # pylint: enable=too-many-branches + def _get_otel_receive(self, server_span_name, scope, receive): @wraps(receive) async def otel_receive():
diff --git a/instrumentation/opentelemetry-instrumentation-asgi/tests/test_asgi_middleware.py b/instrumentation/opentelemetry-instrumentation-asgi/tests/test_asgi_middleware.py --- a/instrumentation/opentelemetry-instrumentation-asgi/tests/test_asgi_middleware.py +++ b/instrumentation/opentelemetry-instrumentation-asgi/tests/test_asgi_middleware.py @@ -12,6 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. +# pylint: disable=too-many-lines + import sys import unittest from timeit import default_timer @@ -626,6 +628,37 @@ def test_basic_metric_success(self): ) self.assertEqual(point.value, 0) + def test_metric_target_attribute(self): + expected_target = "/api/user/{id}" + + class TestRoute: + path_format = expected_target + + self.scope["route"] = TestRoute() + app = otel_asgi.OpenTelemetryMiddleware(simple_asgi) + self.seed_app(app) + self.send_default_request() + + metrics_list = self.memory_metrics_reader.get_metrics_data() + assertions = 0 + for resource_metric in metrics_list.resource_metrics: + for scope_metrics in resource_metric.scope_metrics: + for metric in scope_metrics.metrics: + for point in metric.data.data_points: + if isinstance(point, HistogramDataPoint): + self.assertEqual( + point.attributes["http.target"], + expected_target, + ) + assertions += 1 + elif isinstance(point, NumberDataPoint): + self.assertEqual( + point.attributes["http.target"], + expected_target, + ) + assertions += 1 + self.assertEqual(assertions, 2) + def test_no_metric_for_websockets(self): self.scope = { "type": "websocket", @@ -719,6 +752,37 @@ def test_credential_removal(self): attrs[SpanAttributes.HTTP_URL], "http://httpbin.org/status/200" ) + def test_collect_target_attribute_missing(self): + self.assertIsNone(otel_asgi._collect_target_attribute(self.scope)) + + def test_collect_target_attribute_fastapi(self): + class TestRoute: + path_format = "/api/users/{user_id}" + + self.scope["route"] = TestRoute() + self.assertEqual( + otel_asgi._collect_target_attribute(self.scope), + "/api/users/{user_id}", + ) + + def test_collect_target_attribute_fastapi_mounted(self): + class TestRoute: + path_format = "/users/{user_id}" + + self.scope["route"] = TestRoute() + self.scope["root_path"] = "/api/v2" + self.assertEqual( + otel_asgi._collect_target_attribute(self.scope), + "/api/v2/users/{user_id}", + ) + + def test_collect_target_attribute_fastapi_starlette_invalid(self): + self.scope["route"] = object() + self.assertIsNone( + otel_asgi._collect_target_attribute(self.scope), + "HTTP_TARGET values is not None", + ) + class TestWrappedApplication(AsgiTestBase): def test_mark_span_internal_in_presence_of_span_from_other_framework(self):
Fix HTTP instrumentation not being suppressed # Description Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change. This change aims to fix the issue outlined in #930 where urllib3 downstream spans are not being suppressed with a requests upstream, causing an extra span to be created. The root cause of this bug lies in the create_key() method in opentelemetry context which adds a unique `uuid` to the end of each key created. Since a new `_SUPPRESS_HTTP_INSTRUMENTATION` key is being created in the instrumentation for each library, this results in a different key being created by each instrumentation instead of the creation of a single key that suppresses HTTP instrumentation so proceeding libraries know not to instrument further. This fix involves creating the `_SUPPRESS_HTTP_INSTRUMENTATION` once in opentelemetry context to avoid the bug that causes a new suppress http instrumentation key to be created by each instrumentation. By having only 1 key that is accessible to all instrumentations, its true value can be passed on from one instrumentation to the next without being set to None every time the instrumentation of a new library begins. This does not conflict with the [context spec](https://github.com/open-telemetry/opentelemetry-specification/blob/v1.1.0/specification/context/context.md#context) since the `_SUPPRESS_HTTP_INSTRUMENTATION_KEY` is meant to be shared, and creating a unique version of it in each library instrumentation is not the correct implementation of this concept. Fixes #930 ## Type of change Please delete options that are not relevant. - [x] Bug fix (non-breaking change which fixes an issue) # How Has This Been Tested? Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration - [x] Tox unit tests for each affected library # Does This PR Require a Core Repo Change? - [x] Yes, please refer to [PR # 2729](https://github.com/open-telemetry/opentelemetry-python/pull/2729) in the core repo # Checklist: See [contributing.md](https://github.com/open-telemetry/opentelemetry-python-contrib/blob/main/CONTRIBUTING.md) for styleguide, changelog guidelines, and more. - [x] Followed the style guidelines of this project - [x] Changelogs have been updated - [x] Unit tests have been added
<a href="https://easycla.lfx.linuxfoundation.org/#/?version=2"><img src="https://s3.amazonaws.com/cla-project-logo-prod/cla-signed.svg" alt="CLA Signed" align="left" height="28" width="328" ></a><br/><br />The committers listed above are authorized under a signed CLA.<ul><li>:white_check_mark: login: carolabadeer / name: Carol Abadeer (5905853c953598b6eb92cfbfe3f1034bf126f633, 6558b1e2e366d6e4cbc3ac56d29627ee9366a89c, 7d35f17f93055a3ec036eb08b6d7259e44521f00)</li></ul>
2022-09-10T05:12:30
open-telemetry/opentelemetry-python-contrib
1,324
open-telemetry__opentelemetry-python-contrib-1324
[ "1170" ]
8e0c8d954bc1ccf4b593402e1828cec530a9ee73
diff --git a/instrumentation/opentelemetry-instrumentation-asyncpg/src/opentelemetry/instrumentation/asyncpg/__init__.py b/instrumentation/opentelemetry-instrumentation-asyncpg/src/opentelemetry/instrumentation/asyncpg/__init__.py --- a/instrumentation/opentelemetry-instrumentation-asyncpg/src/opentelemetry/instrumentation/asyncpg/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-asyncpg/src/opentelemetry/instrumentation/asyncpg/__init__.py @@ -134,6 +134,11 @@ async def _do_execute(self, func, instance, args, kwargs): params = getattr(instance, "_params", {}) name = args[0] if args[0] else params.get("database", "postgresql") + try: + name = name.split()[0] + except IndexError: + name = "" + with self._tracer.start_as_current_span( name, kind=SpanKind.CLIENT ) as span:
diff --git a/tests/opentelemetry-docker-tests/tests/asyncpg/test_asyncpg_functional.py b/tests/opentelemetry-docker-tests/tests/asyncpg/test_asyncpg_functional.py --- a/tests/opentelemetry-docker-tests/tests/asyncpg/test_asyncpg_functional.py +++ b/tests/opentelemetry-docker-tests/tests/asyncpg/test_asyncpg_functional.py @@ -62,7 +62,7 @@ def test_instrumented_execute_method_without_arguments(self, *_, **__): self.assertEqual(len(spans), 1) self.assertIs(StatusCode.UNSET, spans[0].status.status_code) self.check_span(spans[0]) - self.assertEqual(spans[0].name, "SELECT 42;") + self.assertEqual(spans[0].name, "SELECT") self.assertEqual( spans[0].attributes[SpanAttributes.DB_STATEMENT], "SELECT 42;" ) @@ -72,6 +72,7 @@ def test_instrumented_fetch_method_without_arguments(self, *_, **__): spans = self.memory_exporter.get_finished_spans() self.assertEqual(len(spans), 1) self.check_span(spans[0]) + self.assertEqual(spans[0].name, "SELECT") self.assertEqual( spans[0].attributes[SpanAttributes.DB_STATEMENT], "SELECT 42;" ) @@ -189,7 +190,7 @@ def test_instrumented_execute_method_with_arguments(self, *_, **__): self.assertIs(StatusCode.UNSET, spans[0].status.status_code) self.check_span(spans[0]) - self.assertEqual(spans[0].name, "SELECT $1;") + self.assertEqual(spans[0].name, "SELECT") self.assertEqual( spans[0].attributes[SpanAttributes.DB_STATEMENT], "SELECT $1;" ) @@ -203,6 +204,7 @@ def test_instrumented_fetch_method_with_arguments(self, *_, **__): self.assertEqual(len(spans), 1) self.check_span(spans[0]) + self.assertEqual(spans[0].name, "SELECT") self.assertEqual( spans[0].attributes[SpanAttributes.DB_STATEMENT], "SELECT $1;" )
AsyncPG Instrumentation Span Names are too long when using query string **Is your feature request related to a problem?** Not a problem per se however, the `asyncpg` instrumentation uses sets span names as the query string which results in some very messing looking trace names in jaeger, datadog, etc and outright doesn't work with promscale due to long queries exhaust the available bytes for btree indexes. **Describe the solution you'd like** - The ability to change the name of the span with a hook or something similar. The `httpx` instrumentation provides hooks that receive the span and the name can be updated there. - Just use a shorter or truncated version of the query as the name. Which alternative solutions or features have you considered? Not using the `asyncpg` instrumentation and manually instrumenting specific queries.
psycopg instrumentation uses only [the first word of the statement](https://github.com/open-telemetry/opentelemetry-python-contrib/blob/main/instrumentation/opentelemetry-instrumentation-psycopg2/src/opentelemetry/instrumentation/psycopg2/__init__.py#L218-L219). i think i can do the same with asyncpg. span name shouldn't be a high cardinal value such as a statement. feel free to send a patch.
2022-09-11T11:05:50
open-telemetry/opentelemetry-python-contrib
1,327
open-telemetry__opentelemetry-python-contrib-1327
[ "1146" ]
65329a89b0ca37930a0b23aa5b82862771bd6811
diff --git a/instrumentation/opentelemetry-instrumentation-starlette/src/opentelemetry/instrumentation/starlette/__init__.py b/instrumentation/opentelemetry-instrumentation-starlette/src/opentelemetry/instrumentation/starlette/__init__.py --- a/instrumentation/opentelemetry-instrumentation-starlette/src/opentelemetry/instrumentation/starlette/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-starlette/src/opentelemetry/instrumentation/starlette/__init__.py @@ -131,6 +131,8 @@ def client_response_hook(span: Span, message: dict): from opentelemetry.instrumentation.asgi import OpenTelemetryMiddleware from opentelemetry.instrumentation.asgi.package import _instruments from opentelemetry.instrumentation.instrumentor import BaseInstrumentor +from opentelemetry.instrumentation.starlette.version import __version__ +from opentelemetry.metrics import get_meter from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.trace import Span from opentelemetry.util.http import get_excluded_urls @@ -156,9 +158,11 @@ def instrument_app( server_request_hook: _ServerRequestHookT = None, client_request_hook: _ClientRequestHookT = None, client_response_hook: _ClientResponseHookT = None, + meter_provider=None, tracer_provider=None, ): """Instrument an uninstrumented Starlette application.""" + meter = get_meter(__name__, __version__, meter_provider) if not getattr(app, "is_instrumented_by_opentelemetry", False): app.add_middleware( OpenTelemetryMiddleware, @@ -168,9 +172,24 @@ def instrument_app( client_request_hook=client_request_hook, client_response_hook=client_response_hook, tracer_provider=tracer_provider, + meter=meter, ) app.is_instrumented_by_opentelemetry = True + # adding apps to set for uninstrumenting + if app not in _InstrumentedStarlette._instrumented_starlette_apps: + _InstrumentedStarlette._instrumented_starlette_apps.add(app) + + @staticmethod + def uninstrument_app(app: applications.Starlette): + app.user_middleware = [ + x + for x in app.user_middleware + if x.cls is not OpenTelemetryMiddleware + ] + app.middleware_stack = app.build_middleware_stack() + app._is_instrumented_by_opentelemetry = False + def instrumentation_dependencies(self) -> Collection[str]: return _instruments @@ -186,20 +205,32 @@ def _instrument(self, **kwargs): _InstrumentedStarlette._client_response_hook = kwargs.get( "client_response_hook" ) + _InstrumentedStarlette._meter_provider = kwargs.get("_meter_provider") + applications.Starlette = _InstrumentedStarlette def _uninstrument(self, **kwargs): + + """uninstrumenting all created apps by user""" + for instance in _InstrumentedStarlette._instrumented_starlette_apps: + self.uninstrument_app(instance) + _InstrumentedStarlette._instrumented_starlette_apps.clear() applications.Starlette = self._original_starlette class _InstrumentedStarlette(applications.Starlette): _tracer_provider = None + _meter_provider = None _server_request_hook: _ServerRequestHookT = None _client_request_hook: _ClientRequestHookT = None _client_response_hook: _ClientResponseHookT = None + _instrumented_starlette_apps = set() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) + meter = get_meter( + __name__, __version__, _InstrumentedStarlette._meter_provider + ) self.add_middleware( OpenTelemetryMiddleware, excluded_urls=_excluded_urls, @@ -208,7 +239,14 @@ def __init__(self, *args, **kwargs): client_request_hook=_InstrumentedStarlette._client_request_hook, client_response_hook=_InstrumentedStarlette._client_response_hook, tracer_provider=_InstrumentedStarlette._tracer_provider, + meter=meter, ) + self._is_instrumented_by_opentelemetry = True + # adding apps to set for uninstrumenting + _InstrumentedStarlette._instrumented_starlette_apps.add(self) + + def __del__(self): + _InstrumentedStarlette._instrumented_starlette_apps.remove(self) def _get_route_details(scope): diff --git a/instrumentation/opentelemetry-instrumentation-starlette/src/opentelemetry/instrumentation/starlette/package.py b/instrumentation/opentelemetry-instrumentation-starlette/src/opentelemetry/instrumentation/starlette/package.py --- a/instrumentation/opentelemetry-instrumentation-starlette/src/opentelemetry/instrumentation/starlette/package.py +++ b/instrumentation/opentelemetry-instrumentation-starlette/src/opentelemetry/instrumentation/starlette/package.py @@ -14,3 +14,5 @@ _instruments = ("starlette ~= 0.13.0",) + +_supports_metrics = True
diff --git a/instrumentation/opentelemetry-instrumentation-starlette/tests/test_starlette_instrumentation.py b/instrumentation/opentelemetry-instrumentation-starlette/tests/test_starlette_instrumentation.py --- a/instrumentation/opentelemetry-instrumentation-starlette/tests/test_starlette_instrumentation.py +++ b/instrumentation/opentelemetry-instrumentation-starlette/tests/test_starlette_instrumentation.py @@ -13,6 +13,7 @@ # limitations under the License. import unittest +from timeit import default_timer from unittest.mock import patch from starlette import applications @@ -22,6 +23,10 @@ from starlette.websockets import WebSocket import opentelemetry.instrumentation.starlette as otel_starlette +from opentelemetry.sdk.metrics.export import ( + HistogramDataPoint, + NumberDataPoint, +) from opentelemetry.sdk.resources import Resource from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.test.globals_test import reset_trace_globals @@ -35,9 +40,20 @@ from opentelemetry.util.http import ( OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST, OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE, + _active_requests_count_attrs, + _duration_attrs, get_excluded_urls, ) +_expected_metric_names = [ + "http.server.active_requests", + "http.server.duration", +] +_recommended_attrs = { + "http.server.active_requests": _active_requests_count_attrs, + "http.server.duration": _duration_attrs, +} + class TestStarletteManualInstrumentation(TestBase): def _create_app(self): @@ -100,6 +116,109 @@ def test_starlette_excluded_urls(self): spans = self.memory_exporter.get_finished_spans() self.assertEqual(len(spans), 0) + def test_starlette_metrics(self): + self._client.get("/foobar") + self._client.get("/foobar") + self._client.get("/foobar") + metrics_list = self.memory_metrics_reader.get_metrics_data() + number_data_point_seen = False + histogram_data_point_seen = False + self.assertTrue(len(metrics_list.resource_metrics) == 1) + for resource_metric in metrics_list.resource_metrics: + self.assertTrue(len(resource_metric.scope_metrics) == 1) + for scope_metric in resource_metric.scope_metrics: + self.assertTrue(len(scope_metric.metrics) == 2) + for metric in scope_metric.metrics: + self.assertIn(metric.name, _expected_metric_names) + data_points = list(metric.data.data_points) + self.assertEqual(len(data_points), 1) + for point in data_points: + if isinstance(point, HistogramDataPoint): + self.assertEqual(point.count, 3) + histogram_data_point_seen = True + if isinstance(point, NumberDataPoint): + number_data_point_seen = True + for attr in point.attributes: + self.assertIn( + attr, _recommended_attrs[metric.name] + ) + self.assertTrue(number_data_point_seen and histogram_data_point_seen) + + def test_basic_post_request_metric_success(self): + start = default_timer() + expected_duration_attributes = { + "http.flavor": "1.1", + "http.host": "testserver", + "http.method": "POST", + "http.scheme": "http", + "http.server_name": "testserver", + "http.status_code": 405, + "net.host.port": 80, + } + expected_requests_count_attributes = { + "http.flavor": "1.1", + "http.host": "testserver", + "http.method": "POST", + "http.scheme": "http", + "http.server_name": "testserver", + } + self._client.post("/foobar") + duration = max(round((default_timer() - start) * 1000), 0) + metrics_list = self.memory_metrics_reader.get_metrics_data() + for metric in ( + metrics_list.resource_metrics[0].scope_metrics[0].metrics + ): + for point in list(metric.data.data_points): + if isinstance(point, HistogramDataPoint): + self.assertEqual(point.count, 1) + self.assertAlmostEqual(duration, point.sum, delta=30) + self.assertDictEqual( + dict(point.attributes), expected_duration_attributes + ) + if isinstance(point, NumberDataPoint): + self.assertDictEqual( + expected_requests_count_attributes, + dict(point.attributes), + ) + self.assertEqual(point.value, 0) + + def test_metric_for_uninstrment_app_method(self): + self._client.get("/foobar") + # uninstrumenting the existing client app + self._instrumentor.uninstrument_app(self._app) + self._client.get("/foobar") + self._client.get("/foobar") + metrics_list = self.memory_metrics_reader.get_metrics_data() + for metric in ( + metrics_list.resource_metrics[0].scope_metrics[0].metrics + ): + for point in list(metric.data.data_points): + if isinstance(point, HistogramDataPoint): + self.assertEqual(point.count, 1) + if isinstance(point, NumberDataPoint): + self.assertEqual(point.value, 0) + + def test_metric_uninstrument_inherited_by_base(self): + # instrumenting class and creating app to send request + self._instrumentor.instrument() + app = self._create_starlette_app() + client = TestClient(app) + client.get("/foobar") + # calling uninstrument and checking for telemetry data + self._instrumentor.uninstrument() + client.get("/foobar") + client.get("/foobar") + client.get("/foobar") + metrics_list = self.memory_metrics_reader.get_metrics_data() + for metric in ( + metrics_list.resource_metrics[0].scope_metrics[0].metrics + ): + for point in list(metric.data.data_points): + if isinstance(point, HistogramDataPoint): + self.assertEqual(point.count, 1) + if isinstance(point, NumberDataPoint): + self.assertEqual(point.value, 0) + @staticmethod def _create_starlette_app(): def home(_):
Metrics instrumentation starlette HTTP Server semconv https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/semantic_conventions/http-metrics.md#http-server
Hi Can you assign it to me? hey @srikanthccv Can you assign this to me . @rahulmukherjee68 I have assigned it to you
2022-09-13T09:07:44
open-telemetry/opentelemetry-python-contrib
1,333
open-telemetry__opentelemetry-python-contrib-1333
[ "1184" ]
d5369a4431a27104ef2f15a625a078f146b78820
diff --git a/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py b/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py --- a/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py @@ -15,8 +15,7 @@ """ The opentelemetry-instrumentation-asgi package provides an ASGI middleware that can be used -on any ASGI framework (such as Django-channels / Quart) to track requests -timing through OpenTelemetry. +on any ASGI framework (such as Django-channels / Quart) to track request timing through OpenTelemetry. Usage (Quart) ------------- @@ -71,9 +70,14 @@ async def hello(): Request/Response hooks ********************** -Utilize request/response hooks to execute custom logic to be performed before/after performing a request. The server request hook takes in a server span and ASGI -scope object for every incoming request. The client request hook is called with the internal span and an ASGI scope which is sent as a dictionary for when the method receive is called. -The client response hook is called with the internal span and an ASGI event which is sent as a dictionary for when the method send is called. +This instrumentation supports request and response hooks. These are functions that get called +right after a span is created for a request and right before the span is finished for the response. + +- The server request hook is passed a server span and ASGI scope object for every incoming request. +- The client request hook is called with the internal span and an ASGI scope when the method ``receive`` is called. +- The client response hook is called with the internal span and an ASGI event when the method ``send`` is called. + +For example, .. code-block:: python @@ -93,54 +97,93 @@ def client_response_hook(span: Span, message: dict): Capture HTTP request and response headers ***************************************** -You can configure the agent to capture predefined HTTP headers as span attributes, according to the `semantic convention <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers>`_. +You can configure the agent to capture specified HTTP headers as span attributes, according to the +`semantic convention <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers>`_. Request headers *************** -To capture predefined HTTP request headers as span attributes, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST`` -to a comma-separated list of HTTP header names. +To capture HTTP request headers as span attributes, set the environment variable +``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST`` to a comma delimited list of HTTP header names. For example, - :: export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="content-type,custom_request_header" -will extract ``content-type`` and ``custom_request_header`` from request headers and add them as span attributes. +will extract ``content-type`` and ``custom_request_header`` from the request headers and add them as span attributes. + +Request header names in ASGI are case-insensitive. So, giving the header name as ``CUStom-Header`` in the environment +variable will capture the header named ``custom-header``. + +Regular expressions may also be used to match multiple headers that correspond to the given pattern. For example: +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="Accept.*,X-.*" -It is recommended that you should give the correct names of the headers to be captured in the environment variable. -Request header names in ASGI are case insensitive. So, giving header name as ``CUStom-Header`` in environment variable will be able capture header with name ``custom-header``. +Would match all request headers that start with ``Accept`` and ``X-``. -The name of the added span attribute will follow the format ``http.request.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ). -The value of the attribute will be single item list containing all the header values. +To capture all request headers, set ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST`` to ``".*"``. +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST=".*" -Example of the added span attribute, +The name of the added span attribute will follow the format ``http.request.header.<header_name>`` where ``<header_name>`` +is the normalized HTTP header name (lowercase, with ``-`` replaced by ``_``). The value of the attribute will be a +single item list containing all the header values. + +For example: ``http.request.header.custom_request_header = ["<value1>,<value2>"]`` Response headers **************** -To capture predefined HTTP response headers as span attributes, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`` -to a comma-separated list of HTTP header names. +To capture HTTP response headers as span attributes, set the environment variable +``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`` to a comma delimited list of HTTP header names. For example, - :: export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="content-type,custom_response_header" -will extract ``content-type`` and ``custom_response_header`` from response headers and add them as span attributes. +will extract ``content-type`` and ``custom_response_header`` from the response headers and add them as span attributes. + +Response header names in ASGI are case-insensitive. So, giving the header name as ``CUStom-Header`` in the environment +variable will capture the header named ``custom-header``. + +Regular expressions may also be used to match multiple headers that correspond to the given pattern. For example: +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="Content.*,X-.*" -It is recommended that you should give the correct names of the headers to be captured in the environment variable. -Response header names captured in ASGI are case insensitive. So, giving header name as ``CUStomHeader`` in environment variable will be able capture header with name ``customheader``. +Would match all response headers that start with ``Content`` and ``X-``. -The name of the added span attribute will follow the format ``http.response.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ). -The value of the attribute will be single item list containing all the header values. +To capture all response headers, set ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`` to ``".*"``. +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE=".*" -Example of the added span attribute, +The name of the added span attribute will follow the format ``http.response.header.<header_name>`` where ``<header_name>`` +is the normalized HTTP header name (lowercase, with ``-`` replaced by ``_``). The value of the attribute will be a +single item list containing all the header values. + +For example: ``http.response.header.custom_response_header = ["<value1>,<value2>"]`` +Sanitizing headers +****************** +In order to prevent storing sensitive data such as personally identifiable information (PII), session keys, passwords, +etc, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS`` +to a comma delimited list of HTTP header names to be sanitized. Regexes may be used, and all header names will be +matched in a case-insensitive manner. + +For example, +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS=".*session.*,set-cookie" + +will replace the value of headers such as ``session-id`` and ``set-cookie`` with ``[REDACTED]`` in the span. + Note: - Environment variable names to capture http headers are still experimental, and thus are subject to change. + The environment variable names used to capture HTTP headers are still experimental, and thus are subject to change. API --- @@ -170,8 +213,10 @@ def client_response_hook(span: Span, message: dict): from opentelemetry.trace import Span, set_span_in_context from opentelemetry.trace.status import Status, StatusCode from opentelemetry.util.http import ( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS, OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST, OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE, + SanitizeValue, _parse_active_request_count_attrs, _parse_duration_attrs, get_custom_headers, @@ -203,19 +248,19 @@ def get( if not headers: return None - # asgi header keys are in lower case + # ASGI header keys are in lower case key = key.lower() decoded = [ _value.decode("utf8") for (_key, _value) in headers - if _key.decode("utf8") == key + if _key.decode("utf8").lower() == key ] if not decoded: return None return decoded def keys(self, carrier: dict) -> typing.List[str]: - return list(carrier.keys()) + return [_key.decode("utf8") for (_key, _value) in carrier] asgi_getter = ASGIGetter() @@ -290,35 +335,50 @@ def collect_custom_request_headers_attributes(scope): """returns custom HTTP request headers to be added into SERVER span as span attributes Refer specification https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers""" - attributes = {} - custom_request_headers = get_custom_headers( - OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST + sanitize = SanitizeValue( + get_custom_headers( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS + ) ) - for header in custom_request_headers: - values = asgi_getter.get(scope, header) - if values: - key = normalise_request_header_name(header) - attributes.setdefault(key, []).extend(values) + # Decode headers before processing. + headers = { + _key.decode("utf8"): _value.decode("utf8") + for (_key, _value) in scope.get("headers") + } - return attributes + return sanitize.sanitize_header_values( + headers, + get_custom_headers( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST + ), + normalise_request_header_name, + ) def collect_custom_response_headers_attributes(message): """returns custom HTTP response headers to be added into SERVER span as span attributes Refer specification https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers""" - attributes = {} - custom_response_headers = get_custom_headers( - OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE + + sanitize = SanitizeValue( + get_custom_headers( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS + ) ) - for header in custom_response_headers: - values = asgi_getter.get(message, header) - if values: - key = normalise_response_header_name(header) - attributes.setdefault(key, []).extend(values) + # Decode headers before processing. + headers = { + _key.decode("utf8"): _value.decode("utf8") + for (_key, _value) in message.get("headers") + } - return attributes + return sanitize.sanitize_header_values( + headers, + get_custom_headers( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE + ), + normalise_response_header_name, + ) def get_host_port_url_tuple(scope): @@ -354,7 +414,7 @@ def set_status_code(span, status_code): def get_default_span_details(scope: dict) -> Tuple[str, dict]: """Default implementation for get_default_span_details Args: - scope: the asgi scope dictionary + scope: the ASGI scope dictionary Returns: a tuple of the span name, and any attributes to attach to the span. """ @@ -455,7 +515,7 @@ async def __call__(self, scope, receive, send): """The ASGI application Args: - scope: A ASGI environment. + scope: An ASGI environment. receive: An awaitable callable yielding dictionaries send: An awaitable callable taking a single dictionary as argument. """ diff --git a/util/opentelemetry-util-http/src/opentelemetry/util/http/__init__.py b/util/opentelemetry-util-http/src/opentelemetry/util/http/__init__.py --- a/util/opentelemetry-util-http/src/opentelemetry/util/http/__init__.py +++ b/util/opentelemetry-util-http/src/opentelemetry/util/http/__init__.py @@ -79,6 +79,34 @@ def sanitize_header_value(self, header: str, value: str) -> str: else value ) + def sanitize_header_values( + self, headers: dict, header_regexes: list, normalize_function: callable + ) -> dict: + values = {} + + if header_regexes: + header_regexes_compiled = re_compile( + "|".join("^" + i + "$" for i in header_regexes), + RE_IGNORECASE, + ) + + for header_name in list( + filter( + header_regexes_compiled.match, + headers.keys(), + ) + ): + header_values = headers.get(header_name) + if header_values: + key = normalize_function(header_name.lower()) + values[key] = [ + self.sanitize_header_value( + header=header_name, value=header_values + ) + ] + + return values + _root = r"OTEL_PYTHON_{}"
diff --git a/instrumentation/opentelemetry-instrumentation-asgi/tests/test_asgi_custom_headers.py b/instrumentation/opentelemetry-instrumentation-asgi/tests/test_asgi_custom_headers.py new file mode 100644 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asgi/tests/test_asgi_custom_headers.py @@ -0,0 +1,335 @@ +from unittest import mock + +import opentelemetry.instrumentation.asgi as otel_asgi +from opentelemetry.test.asgitestutil import AsgiTestBase +from opentelemetry.test.test_base import TestBase +from opentelemetry.trace import SpanKind +from opentelemetry.util.http import ( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS, + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST, + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE, +) + +from .test_asgi_middleware import simple_asgi + + +async def http_app_with_custom_headers(scope, receive, send): + message = await receive() + assert scope["type"] == "http" + if message.get("type") == "http.request": + await send( + { + "type": "http.response.start", + "status": 200, + "headers": [ + (b"Content-Type", b"text/plain"), + (b"custom-test-header-1", b"test-header-value-1"), + (b"custom-test-header-2", b"test-header-value-2"), + ( + b"my-custom-regex-header-1", + b"my-custom-regex-value-1,my-custom-regex-value-2", + ), + ( + b"My-Custom-Regex-Header-2", + b"my-custom-regex-value-3,my-custom-regex-value-4", + ), + (b"my-secret-header", b"my-secret-value"), + ], + } + ) + await send({"type": "http.response.body", "body": b"*"}) + + +async def websocket_app_with_custom_headers(scope, receive, send): + assert scope["type"] == "websocket" + while True: + message = await receive() + if message.get("type") == "websocket.connect": + await send( + { + "type": "websocket.accept", + "headers": [ + (b"custom-test-header-1", b"test-header-value-1"), + (b"custom-test-header-2", b"test-header-value-2"), + ( + b"my-custom-regex-header-1", + b"my-custom-regex-value-1,my-custom-regex-value-2", + ), + ( + b"My-Custom-Regex-Header-2", + b"my-custom-regex-value-3,my-custom-regex-value-4", + ), + (b"my-secret-header", b"my-secret-value"), + ], + } + ) + + if message.get("type") == "websocket.receive": + if message.get("text") == "ping": + await send({"type": "websocket.send", "text": "pong"}) + + if message.get("type") == "websocket.disconnect": + break + + [email protected]( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS: ".*my-secret.*", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3,Regex-Test-Header-.*,Regex-Invalid-Test-Header-.*,.*my-secret.*", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3,my-custom-regex-header-.*,invalid-regex-header-.*,.*my-secret.*", + }, +) +class TestCustomHeaders(AsgiTestBase, TestBase): + def setUp(self): + super().setUp() + self.tracer_provider, self.exporter = TestBase.create_tracer_provider() + self.tracer = self.tracer_provider.get_tracer(__name__) + self.app = otel_asgi.OpenTelemetryMiddleware( + simple_asgi, tracer_provider=self.tracer_provider + ) + + def test_http_custom_request_headers_in_span_attributes(self): + self.scope["headers"].extend( + [ + (b"custom-test-header-1", b"test-header-value-1"), + (b"custom-test-header-2", b"test-header-value-2"), + (b"Regex-Test-Header-1", b"Regex Test Value 1"), + (b"regex-test-header-2", b"RegexTestValue2,RegexTestValue3"), + (b"My-Secret-Header", b"My Secret Value"), + ] + ) + self.seed_app(self.app) + self.send_default_request() + self.get_all_output() + span_list = self.exporter.get_finished_spans() + expected = { + "http.request.header.custom_test_header_1": ( + "test-header-value-1", + ), + "http.request.header.custom_test_header_2": ( + "test-header-value-2", + ), + "http.request.header.regex_test_header_1": ("Regex Test Value 1",), + "http.request.header.regex_test_header_2": ( + "RegexTestValue2,RegexTestValue3", + ), + "http.request.header.my_secret_header": ("[REDACTED]",), + } + for span in span_list: + if span.kind == SpanKind.SERVER: + self.assertSpanHasAttributes(span, expected) + + def test_http_custom_request_headers_not_in_span_attributes(self): + self.scope["headers"].extend( + [ + (b"custom-test-header-1", b"test-header-value-1"), + ] + ) + self.seed_app(self.app) + self.send_default_request() + self.get_all_output() + span_list = self.exporter.get_finished_spans() + expected = { + "http.request.header.custom_test_header_1": ( + "test-header-value-1", + ), + } + not_expected = { + "http.request.header.custom_test_header_2": ( + "test-header-value-2", + ), + } + for span in span_list: + if span.kind == SpanKind.SERVER: + self.assertSpanHasAttributes(span, expected) + for key, _ in not_expected.items(): + self.assertNotIn(key, span.attributes) + + def test_http_custom_response_headers_in_span_attributes(self): + self.app = otel_asgi.OpenTelemetryMiddleware( + http_app_with_custom_headers, tracer_provider=self.tracer_provider + ) + self.seed_app(self.app) + self.send_default_request() + self.get_all_output() + span_list = self.exporter.get_finished_spans() + expected = { + "http.response.header.custom_test_header_1": ( + "test-header-value-1", + ), + "http.response.header.custom_test_header_2": ( + "test-header-value-2", + ), + "http.response.header.my_custom_regex_header_1": ( + "my-custom-regex-value-1,my-custom-regex-value-2", + ), + "http.response.header.my_custom_regex_header_2": ( + "my-custom-regex-value-3,my-custom-regex-value-4", + ), + "http.response.header.my_secret_header": ("[REDACTED]",), + } + for span in span_list: + if span.kind == SpanKind.SERVER: + self.assertSpanHasAttributes(span, expected) + + def test_http_custom_response_headers_not_in_span_attributes(self): + self.app = otel_asgi.OpenTelemetryMiddleware( + http_app_with_custom_headers, tracer_provider=self.tracer_provider + ) + self.seed_app(self.app) + self.send_default_request() + self.get_all_output() + span_list = self.exporter.get_finished_spans() + not_expected = { + "http.response.header.custom_test_header_3": ( + "test-header-value-3", + ), + } + for span in span_list: + if span.kind == SpanKind.SERVER: + for key, _ in not_expected.items(): + self.assertNotIn(key, span.attributes) + + def test_websocket_custom_request_headers_in_span_attributes(self): + self.scope = { + "type": "websocket", + "http_version": "1.1", + "scheme": "ws", + "path": "/", + "query_string": b"", + "headers": [ + (b"custom-test-header-1", b"test-header-value-1"), + (b"custom-test-header-2", b"test-header-value-2"), + (b"Regex-Test-Header-1", b"Regex Test Value 1"), + (b"regex-test-header-2", b"RegexTestValue2,RegexTestValue3"), + (b"My-Secret-Header", b"My Secret Value"), + ], + "client": ("127.0.0.1", 32767), + "server": ("127.0.0.1", 80), + } + self.seed_app(self.app) + self.send_input({"type": "websocket.connect"}) + self.send_input({"type": "websocket.receive", "text": "ping"}) + self.send_input({"type": "websocket.disconnect"}) + + self.get_all_output() + span_list = self.exporter.get_finished_spans() + expected = { + "http.request.header.custom_test_header_1": ( + "test-header-value-1", + ), + "http.request.header.custom_test_header_2": ( + "test-header-value-2", + ), + "http.request.header.regex_test_header_1": ("Regex Test Value 1",), + "http.request.header.regex_test_header_2": ( + "RegexTestValue2,RegexTestValue3", + ), + "http.request.header.my_secret_header": ("[REDACTED]",), + } + for span in span_list: + if span.kind == SpanKind.SERVER: + self.assertSpanHasAttributes(span, expected) + + def test_websocket_custom_request_headers_not_in_span_attributes(self): + self.scope = { + "type": "websocket", + "http_version": "1.1", + "scheme": "ws", + "path": "/", + "query_string": b"", + "headers": [ + (b"Custom-Test-Header-1", b"test-header-value-1"), + (b"Custom-Test-Header-2", b"test-header-value-2"), + ], + "client": ("127.0.0.1", 32767), + "server": ("127.0.0.1", 80), + } + self.seed_app(self.app) + self.send_input({"type": "websocket.connect"}) + self.send_input({"type": "websocket.receive", "text": "ping"}) + self.send_input({"type": "websocket.disconnect"}) + + self.get_all_output() + span_list = self.exporter.get_finished_spans() + not_expected = { + "http.request.header.custom_test_header_3": ( + "test-header-value-3", + ), + } + for span in span_list: + if span.kind == SpanKind.SERVER: + for key, _ in not_expected.items(): + self.assertNotIn(key, span.attributes) + + def test_websocket_custom_response_headers_in_span_attributes(self): + self.scope = { + "type": "websocket", + "http_version": "1.1", + "scheme": "ws", + "path": "/", + "query_string": b"", + "headers": [], + "client": ("127.0.0.1", 32767), + "server": ("127.0.0.1", 80), + } + self.app = otel_asgi.OpenTelemetryMiddleware( + websocket_app_with_custom_headers, + tracer_provider=self.tracer_provider, + ) + self.seed_app(self.app) + self.send_input({"type": "websocket.connect"}) + self.send_input({"type": "websocket.receive", "text": "ping"}) + self.send_input({"type": "websocket.disconnect"}) + self.get_all_output() + span_list = self.exporter.get_finished_spans() + expected = { + "http.response.header.custom_test_header_1": ( + "test-header-value-1", + ), + "http.response.header.custom_test_header_2": ( + "test-header-value-2", + ), + "http.response.header.my_custom_regex_header_1": ( + "my-custom-regex-value-1,my-custom-regex-value-2", + ), + "http.response.header.my_custom_regex_header_2": ( + "my-custom-regex-value-3,my-custom-regex-value-4", + ), + "http.response.header.my_secret_header": ("[REDACTED]",), + } + for span in span_list: + if span.kind == SpanKind.SERVER: + self.assertSpanHasAttributes(span, expected) + + def test_websocket_custom_response_headers_not_in_span_attributes(self): + self.scope = { + "type": "websocket", + "http_version": "1.1", + "scheme": "ws", + "path": "/", + "query_string": b"", + "headers": [], + "client": ("127.0.0.1", 32767), + "server": ("127.0.0.1", 80), + } + self.app = otel_asgi.OpenTelemetryMiddleware( + websocket_app_with_custom_headers, + tracer_provider=self.tracer_provider, + ) + self.seed_app(self.app) + self.send_input({"type": "websocket.connect"}) + self.send_input({"type": "websocket.receive", "text": "ping"}) + self.send_input({"type": "websocket.disconnect"}) + self.get_all_output() + span_list = self.exporter.get_finished_spans() + not_expected = { + "http.response.header.custom_test_header_3": ( + "test-header-value-3", + ), + } + for span in span_list: + if span.kind == SpanKind.SERVER: + for key, _ in not_expected.items(): + self.assertNotIn(key, span.attributes) diff --git a/instrumentation/opentelemetry-instrumentation-asgi/tests/test_asgi_middleware.py b/instrumentation/opentelemetry-instrumentation-asgi/tests/test_asgi_middleware.py --- a/instrumentation/opentelemetry-instrumentation-asgi/tests/test_asgi_middleware.py +++ b/instrumentation/opentelemetry-instrumentation-asgi/tests/test_asgi_middleware.py @@ -39,8 +39,6 @@ from opentelemetry.test.test_base import TestBase from opentelemetry.trace import SpanKind, format_span_id, format_trace_id from opentelemetry.util.http import ( - OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST, - OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE, _active_requests_count_attrs, _duration_attrs, ) @@ -84,47 +82,6 @@ async def websocket_app(scope, receive, send): break -async def http_app_with_custom_headers(scope, receive, send): - message = await receive() - assert scope["type"] == "http" - if message.get("type") == "http.request": - await send( - { - "type": "http.response.start", - "status": 200, - "headers": [ - (b"Content-Type", b"text/plain"), - (b"custom-test-header-1", b"test-header-value-1"), - (b"custom-test-header-2", b"test-header-value-2"), - ], - } - ) - await send({"type": "http.response.body", "body": b"*"}) - - -async def websocket_app_with_custom_headers(scope, receive, send): - assert scope["type"] == "websocket" - while True: - message = await receive() - if message.get("type") == "websocket.connect": - await send( - { - "type": "websocket.accept", - "headers": [ - (b"custom-test-header-1", b"test-header-value-1"), - (b"custom-test-header-2", b"test-header-value-2"), - ], - } - ) - - if message.get("type") == "websocket.receive": - if message.get("text") == "ping": - await send({"type": "websocket.send", "text": "pong"}) - - if message.get("type") == "websocket.disconnect": - break - - async def simple_asgi(scope, receive, send): assert isinstance(scope, dict) if scope["type"] == "http": @@ -817,237 +774,5 @@ async def wrapped_app(scope, receive, send): ) [email protected]( - "os.environ", - { - OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3", - OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3", - }, -) -class TestCustomHeaders(AsgiTestBase, TestBase): - def setUp(self): - super().setUp() - self.tracer_provider, self.exporter = TestBase.create_tracer_provider() - self.tracer = self.tracer_provider.get_tracer(__name__) - self.app = otel_asgi.OpenTelemetryMiddleware( - simple_asgi, tracer_provider=self.tracer_provider - ) - - def test_http_custom_request_headers_in_span_attributes(self): - self.scope["headers"].extend( - [ - (b"custom-test-header-1", b"test-header-value-1"), - (b"custom-test-header-2", b"test-header-value-2"), - ] - ) - self.seed_app(self.app) - self.send_default_request() - self.get_all_output() - span_list = self.exporter.get_finished_spans() - expected = { - "http.request.header.custom_test_header_1": ( - "test-header-value-1", - ), - "http.request.header.custom_test_header_2": ( - "test-header-value-2", - ), - } - for span in span_list: - if span.kind == SpanKind.SERVER: - self.assertSpanHasAttributes(span, expected) - - def test_http_custom_request_headers_not_in_span_attributes(self): - self.scope["headers"].extend( - [ - (b"custom-test-header-1", b"test-header-value-1"), - ] - ) - self.seed_app(self.app) - self.send_default_request() - self.get_all_output() - span_list = self.exporter.get_finished_spans() - expected = { - "http.request.header.custom_test_header_1": ( - "test-header-value-1", - ), - } - not_expected = { - "http.request.header.custom_test_header_2": ( - "test-header-value-2", - ), - } - for span in span_list: - if span.kind == SpanKind.SERVER: - self.assertSpanHasAttributes(span, expected) - for key, _ in not_expected.items(): - self.assertNotIn(key, span.attributes) - - def test_http_custom_response_headers_in_span_attributes(self): - self.app = otel_asgi.OpenTelemetryMiddleware( - http_app_with_custom_headers, tracer_provider=self.tracer_provider - ) - self.seed_app(self.app) - self.send_default_request() - self.get_all_output() - span_list = self.exporter.get_finished_spans() - expected = { - "http.response.header.custom_test_header_1": ( - "test-header-value-1", - ), - "http.response.header.custom_test_header_2": ( - "test-header-value-2", - ), - } - for span in span_list: - if span.kind == SpanKind.SERVER: - self.assertSpanHasAttributes(span, expected) - - def test_http_custom_response_headers_not_in_span_attributes(self): - self.app = otel_asgi.OpenTelemetryMiddleware( - http_app_with_custom_headers, tracer_provider=self.tracer_provider - ) - self.seed_app(self.app) - self.send_default_request() - self.get_all_output() - span_list = self.exporter.get_finished_spans() - not_expected = { - "http.response.header.custom_test_header_3": ( - "test-header-value-3", - ), - } - for span in span_list: - if span.kind == SpanKind.SERVER: - for key, _ in not_expected.items(): - self.assertNotIn(key, span.attributes) - - def test_websocket_custom_request_headers_in_span_attributes(self): - self.scope = { - "type": "websocket", - "http_version": "1.1", - "scheme": "ws", - "path": "/", - "query_string": b"", - "headers": [ - (b"custom-test-header-1", b"test-header-value-1"), - (b"custom-test-header-2", b"test-header-value-2"), - ], - "client": ("127.0.0.1", 32767), - "server": ("127.0.0.1", 80), - } - self.seed_app(self.app) - self.send_input({"type": "websocket.connect"}) - self.send_input({"type": "websocket.receive", "text": "ping"}) - self.send_input({"type": "websocket.disconnect"}) - - self.get_all_output() - span_list = self.exporter.get_finished_spans() - expected = { - "http.request.header.custom_test_header_1": ( - "test-header-value-1", - ), - "http.request.header.custom_test_header_2": ( - "test-header-value-2", - ), - } - for span in span_list: - if span.kind == SpanKind.SERVER: - self.assertSpanHasAttributes(span, expected) - - def test_websocket_custom_request_headers_not_in_span_attributes(self): - self.scope = { - "type": "websocket", - "http_version": "1.1", - "scheme": "ws", - "path": "/", - "query_string": b"", - "headers": [ - (b"Custom-Test-Header-1", b"test-header-value-1"), - (b"Custom-Test-Header-2", b"test-header-value-2"), - ], - "client": ("127.0.0.1", 32767), - "server": ("127.0.0.1", 80), - } - self.seed_app(self.app) - self.send_input({"type": "websocket.connect"}) - self.send_input({"type": "websocket.receive", "text": "ping"}) - self.send_input({"type": "websocket.disconnect"}) - - self.get_all_output() - span_list = self.exporter.get_finished_spans() - not_expected = { - "http.request.header.custom_test_header_3": ( - "test-header-value-3", - ), - } - for span in span_list: - if span.kind == SpanKind.SERVER: - for key, _ in not_expected.items(): - self.assertNotIn(key, span.attributes) - - def test_websocket_custom_response_headers_in_span_attributes(self): - self.scope = { - "type": "websocket", - "http_version": "1.1", - "scheme": "ws", - "path": "/", - "query_string": b"", - "headers": [], - "client": ("127.0.0.1", 32767), - "server": ("127.0.0.1", 80), - } - self.app = otel_asgi.OpenTelemetryMiddleware( - websocket_app_with_custom_headers, - tracer_provider=self.tracer_provider, - ) - self.seed_app(self.app) - self.send_input({"type": "websocket.connect"}) - self.send_input({"type": "websocket.receive", "text": "ping"}) - self.send_input({"type": "websocket.disconnect"}) - self.get_all_output() - span_list = self.exporter.get_finished_spans() - expected = { - "http.response.header.custom_test_header_1": ( - "test-header-value-1", - ), - "http.response.header.custom_test_header_2": ( - "test-header-value-2", - ), - } - for span in span_list: - if span.kind == SpanKind.SERVER: - self.assertSpanHasAttributes(span, expected) - - def test_websocket_custom_response_headers_not_in_span_attributes(self): - self.scope = { - "type": "websocket", - "http_version": "1.1", - "scheme": "ws", - "path": "/", - "query_string": b"", - "headers": [], - "client": ("127.0.0.1", 32767), - "server": ("127.0.0.1", 80), - } - self.app = otel_asgi.OpenTelemetryMiddleware( - websocket_app_with_custom_headers, - tracer_provider=self.tracer_provider, - ) - self.seed_app(self.app) - self.send_input({"type": "websocket.connect"}) - self.send_input({"type": "websocket.receive", "text": "ping"}) - self.send_input({"type": "websocket.disconnect"}) - self.get_all_output() - span_list = self.exporter.get_finished_spans() - not_expected = { - "http.response.header.custom_test_header_3": ( - "test-header-value-3", - ), - } - for span in span_list: - if span.kind == SpanKind.SERVER: - for key, _ in not_expected.items(): - self.assertNotIn(key, span.attributes) - - if __name__ == "__main__": unittest.main()
Add more features for adding HTTP request / response headers to spans. I already have https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1172 open for this, and I'll be breaking it in to smaller pieces at @lzchen 's request. **Is your feature request related to a problem?** Currently, you can only provide a list of full HTTP request / response header names to be added to the span. There is also no capacity for header value redaction. **Describe the solution you'd like** It would be nice to be able to specify a regex or "all" to get all headers. Header value redaction is also a must-have for us. **Describe alternatives you've considered** I considered doing this in my application, but it makes more sense to add it here.
2022-09-14T16:26:30
open-telemetry/opentelemetry-python-contrib
1,341
open-telemetry__opentelemetry-python-contrib-1341
[ "1325" ]
50b5465279bd477ac36cbdb46f2a3495b10d85ce
diff --git a/instrumentation/opentelemetry-instrumentation-falcon/src/opentelemetry/instrumentation/falcon/__init__.py b/instrumentation/opentelemetry-instrumentation-falcon/src/opentelemetry/instrumentation/falcon/__init__.py --- a/instrumentation/opentelemetry-instrumentation-falcon/src/opentelemetry/instrumentation/falcon/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-falcon/src/opentelemetry/instrumentation/falcon/__init__.py @@ -194,14 +194,16 @@ def response_hook(span, req, resp): class _InstrumentedFalconAPI(getattr(falcon, _instrument_app)): + _instrumented_falcon_apps = set() + def __init__(self, *args, **kwargs): otel_opts = kwargs.pop("_otel_opts", {}) # inject trace middleware - middlewares = kwargs.pop("middleware", []) + self._middlewares_list = kwargs.pop("middleware", []) tracer_provider = otel_opts.pop("tracer_provider", None) - if not isinstance(middlewares, (list, tuple)): - middlewares = [middlewares] + if not isinstance(self._middlewares_list, (list, tuple)): + self._middlewares_list = [self._middlewares_list] self._otel_tracer = trace.get_tracer( __name__, __version__, tracer_provider @@ -215,12 +217,18 @@ def __init__(self, *args, **kwargs): otel_opts.pop("request_hook", None), otel_opts.pop("response_hook", None), ) - middlewares.insert(0, trace_middleware) - kwargs["middleware"] = middlewares + self._middlewares_list.insert(0, trace_middleware) + kwargs["middleware"] = self._middlewares_list self._otel_excluded_urls = get_excluded_urls("FALCON") + self._is_instrumented_by_opentelemetry = True + _InstrumentedFalconAPI._instrumented_falcon_apps.add(self) super().__init__(*args, **kwargs) + def __del__(self): + if self in _InstrumentedFalconAPI._instrumented_falcon_apps: + _InstrumentedFalconAPI._instrumented_falcon_apps.remove(self) + def _handle_exception( self, arg1, arg2, arg3, arg4 ): # pylint: disable=C0103 @@ -229,6 +237,9 @@ def _handle_exception( # Translation layer for handling the changed arg position of "ex" in Falcon > 2 vs # Falcon < 2 + if not self._is_instrumented_by_opentelemetry: + return super()._handle_exception(arg1, arg2, arg3, arg4) + if _falcon_version == 1: ex = arg1 req = arg2 @@ -253,6 +264,9 @@ def __call__(self, env, start_response): if self._otel_excluded_urls.url_disabled(env.get("PATH_INFO", "/")): return super().__call__(env, start_response) + if not self._is_instrumented_by_opentelemetry: + return super().__call__(env, start_response) + start_time = time_ns() span, token = _start_internal_or_server_span( @@ -414,6 +428,33 @@ class FalconInstrumentor(BaseInstrumentor): def instrumentation_dependencies(self) -> Collection[str]: return _instruments + def _remove_instrumented_middleware(self, app): + if ( + hasattr(app, "_is_instrumented_by_opentelemetry") + and app._is_instrumented_by_opentelemetry + ): + if _falcon_version == 3: + app._unprepared_middleware = [ + x + for x in app._unprepared_middleware + if not isinstance(x, _TraceMiddleware) + ] + app._middleware = app._prepare_middleware( + app._unprepared_middleware, + independent_middleware=app._independent_middleware, + ) + else: + app._middlewares_list = [ + x + for x in app._middlewares_list + if not isinstance(x, _TraceMiddleware) + ] + app._middleware = falcon.api_helpers.prepare_middleware( + app._middlewares_list, + independent_middleware=app._independent_middleware, + ) + app._is_instrumented_by_opentelemetry = False + def _instrument(self, **opts): self._original_falcon_api = getattr(falcon, _instrument_app) @@ -425,4 +466,7 @@ def __init__(self, *args, **kwargs): setattr(falcon, _instrument_app, FalconAPI) def _uninstrument(self, **kwargs): + for app in _InstrumentedFalconAPI._instrumented_falcon_apps: + self._remove_instrumented_middleware(app) + _InstrumentedFalconAPI._instrumented_falcon_apps.clear() setattr(falcon, _instrument_app, self._original_falcon_api)
diff --git a/instrumentation/opentelemetry-instrumentation-falcon/tests/test_falcon.py b/instrumentation/opentelemetry-instrumentation-falcon/tests/test_falcon.py --- a/instrumentation/opentelemetry-instrumentation-falcon/tests/test_falcon.py +++ b/instrumentation/opentelemetry-instrumentation-falcon/tests/test_falcon.py @@ -242,6 +242,18 @@ def test_traced_not_recording(self): self.assertFalse(mock_span.set_attribute.called) self.assertFalse(mock_span.set_status.called) + def test_uninstrument_after_instrument(self): + self.client().simulate_get(path="/hello") + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 1) + + FalconInstrumentor().uninstrument() + self.memory_exporter.clear() + + self.client().simulate_get(path="/hello") + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 0) + class TestFalconInstrumentationWithTracerProvider(TestBase): def setUp(self):
FalconInstrumentor().uninstrument() method do not uninstrument existing Falcon Apps Similar to #1256 in FastAPI, falcon uninstrument method do not uninstrument existing falcon instrumented apps, which is not the expected behaviour.
@srikanthccv Please assign this to me. Hello @srikanthccv Looks like there is no method to manually uninstrument an api/app in falcon similar to [`uninstrument_app` in fastapi](https://github.com/open-telemetry/opentelemetry-python-contrib/blob/main/instrumentation/opentelemetry-instrumentation-fastapi/src/opentelemetry/instrumentation/fastapi/__init__.py#L201). Should I implement one, as it will be required to uninstrument existing instances? To reduce the scope of this issue just add a private helper which can pop the middleware. The `instrument_app`/`uninstrument_app` can be a feature request to address in separate ticket.
2022-09-19T09:49:50
open-telemetry/opentelemetry-python-contrib
1,345
open-telemetry__opentelemetry-python-contrib-1345
[ "1337" ]
fc98f0832e61d14e3992294fffc30d62269843f4
diff --git a/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py b/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py --- a/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py @@ -420,7 +420,9 @@ def _get_system_swap_utilization( if hasattr(system_swap, metric): self._system_swap_utilization_labels["state"] = metric yield Observation( - getattr(system_swap, metric) / system_swap.total, + getattr(system_swap, metric) / system_swap.total + if system_swap.total + else 0, self._system_swap_utilization_labels.copy(), )
Getting ZeroDivisionError in Swap Utilization **Describe your environment** Python: 3.9 opentelemetry-instrumentation-psycopg2 = "^0.33b0" opentelemetry-instrumentation-django = "^0.33b0" opentelemetry-instrumentation-celery = "^0.33b0" opentelemetry-exporter-otlp-proto-grpc = "^1.12.0" Running on ECS (Docker) The problem is with system metrics in this line, the when container is configured without swap memory https://github.com/open-telemetry/opentelemetry-python-contrib/blob/76a565e8bde7f81a04315eae8431d21fc6e79383/instrumentation/opentelemetry-instrumentation-system-metrics/src/opentelemetry/instrumentation/system_metrics/__init__.py#L503 **Steps to reproduce** Create a container with 0 Swap memory and run with system metrics **What is the expected behavior?** Just work **What is the actual behavior?** Giving ZeroDivisionError
2022-09-20T14:21:33
open-telemetry/opentelemetry-python-contrib
1,394
open-telemetry__opentelemetry-python-contrib-1394
[ "1393" ]
496d6581cce21ed89aaccbd5d6cadc5741e3c66f
diff --git a/instrumentation/opentelemetry-instrumentation-aiohttp-client/src/opentelemetry/instrumentation/aiohttp_client/__init__.py b/instrumentation/opentelemetry-instrumentation-aiohttp-client/src/opentelemetry/instrumentation/aiohttp_client/__init__.py --- a/instrumentation/opentelemetry-instrumentation-aiohttp-client/src/opentelemetry/instrumentation/aiohttp_client/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-aiohttp-client/src/opentelemetry/instrumentation/aiohttp_client/__init__.py @@ -232,12 +232,13 @@ async def on_request_exception( if trace_config_ctx.span is None: return - if callable(response_hook): - response_hook(trace_config_ctx.span, params) - if trace_config_ctx.span.is_recording() and params.exception: trace_config_ctx.span.set_status(Status(StatusCode.ERROR)) trace_config_ctx.span.record_exception(params.exception) + + if callable(response_hook): + response_hook(trace_config_ctx.span, params) + _end_trace(trace_config_ctx) def _trace_config_ctx_factory(**kwargs):
aiohttp-client: Allow overriding of span status Version 0.34b0 In the aiohttp-client instrumentation, the `response_hook` is [called before setting the status and the status_code of the span](https://github.com/open-telemetry/opentelemetry-python-contrib/blob/75953f3b25c2ffb5427371aaf065671b441aca26/instrumentation/opentelemetry-instrumentation-aiohttp-client/src/opentelemetry/instrumentation/aiohttp_client/__init__.py#L235). This means the user cannot set a custom status on the span, as it will be immediately overridden by the default value. In my specific usecase I am making requests as a cache, where a cache-miss returns a 404 response. These spans are than tagged with the `StatusCode.ERROR`, which is a bit annoying to me as these responses are completely expected and accepted. Therefore I would like to override the StatusCode on those requests in the response_hook. I am happy to provide a fix for this. **What is the expected behavior?** `reponse_hook` should be called after setting the span status, to allow for overriding it. **What is the actual behavior?** `reponse_hook` is called before setting the span status **Additional context** I compared this with the httpx and requests instrumentation. In those instrumentations, overriding the status in the hook is possible.
2022-10-20T21:35:21
open-telemetry/opentelemetry-python-contrib
1,400
open-telemetry__opentelemetry-python-contrib-1400
[ "1392" ]
83f37eddf2c7f2dac77128b6b27bef57ba167e90
diff --git a/instrumentation/opentelemetry-instrumentation-confluent-kafka/src/opentelemetry/instrumentation/confluent_kafka/__init__.py b/instrumentation/opentelemetry-instrumentation-confluent-kafka/src/opentelemetry/instrumentation/confluent_kafka/__init__.py --- a/instrumentation/opentelemetry-instrumentation-confluent-kafka/src/opentelemetry/instrumentation/confluent_kafka/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-confluent-kafka/src/opentelemetry/instrumentation/confluent_kafka/__init__.py @@ -20,7 +20,7 @@ ..code:: python - from opentelemetry.instrumentation.confluentkafka import ConfluentKafkaInstrumentor + from opentelemetry.instrumentation.confluent_kafka import ConfluentKafkaInstrumentor from confluent_kafka import Producer, Consumer # Instrument kafka @@ -69,7 +69,7 @@ def instrument_producer(producer: Producer, tracer_provider=None) def instrument_consumer(consumer: Consumer, tracer_provider=None) for example: .. code: python - from opentelemetry.instrumentation.confluentkafka import ConfluentKafkaInstrumentor + from opentelemetry.instrumentation.confluent_kafka import ConfluentKafkaInstrumentor from confluent_kafka import Producer, Consumer inst = ConfluentKafkaInstrumentor()
Fix ConfluentKafkaInstrumentor usage **Describe your environment** Docker image running `python:3.10.7-slim-bullseye` as base **Steps to reproduce** ```python3 from opentelemetry.instrumentation.confluentkafka import ConfluentKafkaInstrumentor # Instrument kafka ConfluentKafkaInstrumentor().instrument() ``` **What is the expected behavior?** Instrumentation to work just by adding the lines above. **What is the actual behavior?** > ModuleNotFoundError: No module named 'opentelemetry.instrumentation.confluentkafka' **Additional context** The solution is to actually make the import like this: ```python3 from opentelemetry.instrumentation.confluent_kafka import ConfluentKafkaInstrumentor ```
This isn't really a bug with the package. The docs have a typo. Feel free to send pull request.
2022-10-24T11:09:08
open-telemetry/opentelemetry-python-contrib
1,402
open-telemetry__opentelemetry-python-contrib-1402
[ "1184" ]
9d6ba63e06db78d187008f5aa8fe7fe216b270d2
diff --git a/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py b/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py --- a/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py @@ -85,8 +85,15 @@ def GET(self): Request/Response hooks ********************** -Utilize request/response hooks to execute custom logic to be performed before/after performing a request. Environ is an instance of WSGIEnvironment. -Response_headers is a list of key-value (tuples) representing the response headers returned from the response. +This instrumentation supports request and response hooks. These are functions that get called +right after a span is created for a request and right before the span is finished for the response. + +- The client request hook is called with the internal span and an instance of WSGIEnvironment when the method + ``receive`` is called. +- The client response hook is called with the internal span, the status of the response and a list of key-value (tuples) + representing the response headers returned from the response when the method ``send`` is called. + +For example, .. code-block:: python @@ -102,54 +109,93 @@ def response_hook(span: Span, environ: WSGIEnvironment, status: str, response_he Capture HTTP request and response headers ***************************************** -You can configure the agent to capture predefined HTTP headers as span attributes, according to the `semantic convention <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers>`_. +You can configure the agent to capture specified HTTP headers as span attributes, according to the +`semantic convention <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers>`_. Request headers *************** -To capture predefined HTTP request headers as span attributes, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST`` -to a comma-separated list of HTTP header names. +To capture HTTP request headers as span attributes, set the environment variable +``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST`` to a comma delimited list of HTTP header names. For example, - :: export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="content-type,custom_request_header" -will extract ``content-type`` and ``custom_request_header`` from request headers and add them as span attributes. +will extract ``content-type`` and ``custom_request_header`` from the request headers and add them as span attributes. -It is recommended that you should give the correct names of the headers to be captured in the environment variable. -Request header names in wsgi are case insensitive and - characters are replaced by _. So, giving header name as ``CUStom_Header`` in environment variable will be able capture header with name ``custom-header``. +Request header names in WSGI are case-insensitive and ``-`` characters are replaced by ``_``. So, giving the header +name as ``CUStom_Header`` in the environment variable will capture the header named ``custom-header``. -The name of the added span attribute will follow the format ``http.request.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ). -The value of the attribute will be single item list containing all the header values. +Regular expressions may also be used to match multiple headers that correspond to the given pattern. For example: +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="Accept.*,X-.*" + +Would match all request headers that start with ``Accept`` and ``X-``. + +To capture all request headers, set ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST`` to ``".*"``. +:: -Example of the added span attribute, + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST=".*" + +The name of the added span attribute will follow the format ``http.request.header.<header_name>`` where ``<header_name>`` +is the normalized HTTP header name (lowercase, with ``-`` replaced by ``_``). The value of the attribute will be a +single item list containing all the header values. + +For example: ``http.request.header.custom_request_header = ["<value1>,<value2>"]`` Response headers **************** -To capture predefined HTTP response headers as span attributes, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`` -to a comma-separated list of HTTP header names. +To capture HTTP response headers as span attributes, set the environment variable +``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`` to a comma delimited list of HTTP header names. For example, - :: export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="content-type,custom_response_header" -will extract ``content-type`` and ``custom_response_header`` from response headers and add them as span attributes. +will extract ``content-type`` and ``custom_response_header`` from the response headers and add them as span attributes. + +Response header names in WSGI are case-insensitive. So, giving the header name as ``CUStom-Header`` in the environment +variable will capture the header named ``custom-header``. + +Regular expressions may also be used to match multiple headers that correspond to the given pattern. For example: +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="Content.*,X-.*" + +Would match all response headers that start with ``Content`` and ``X-``. -It is recommended that you should give the correct names of the headers to be captured in the environment variable. -Response header names captured in wsgi are case insensitive. So, giving header name as ``CUStomHeader`` in environment variable will be able capture header with name ``customheader``. +To capture all response headers, set ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`` to ``".*"``. +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE=".*" -The name of the added span attribute will follow the format ``http.response.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ). -The value of the attribute will be single item list containing all the header values. +The name of the added span attribute will follow the format ``http.response.header.<header_name>`` where ``<header_name>`` +is the normalized HTTP header name (lowercase, with ``-`` replaced by ``_``). The value of the attribute will be a +single item list containing all the header values. -Example of the added span attribute, +For example: ``http.response.header.custom_response_header = ["<value1>,<value2>"]`` +Sanitizing headers +****************** +In order to prevent storing sensitive data such as personally identifiable information (PII), session keys, passwords, +etc, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS`` +to a comma delimited list of HTTP header names to be sanitized. Regexes may be used, and all header names will be +matched in a case-insensitive manner. + +For example, +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS=".*session.*,set-cookie" + +will replace the value of headers such as ``session-id`` and ``set-cookie`` with ``[REDACTED]`` in the span. + Note: - Environment variable names to capture http headers are still experimental, and thus are subject to change. + The environment variable names used to capture HTTP headers are still experimental, and thus are subject to change. API --- @@ -172,8 +218,10 @@ def response_hook(span: Span, environ: WSGIEnvironment, status: str, response_he from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.trace.status import Status, StatusCode from opentelemetry.util.http import ( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS, OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST, OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE, + SanitizeValue, get_custom_headers, normalise_request_header_name, normalise_response_header_name, @@ -293,38 +341,49 @@ def collect_custom_request_headers_attributes(environ): """Returns custom HTTP request headers which are configured by the user from the PEP3333-conforming WSGI environ to be used as span creation attributes as described in the specification https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers""" - attributes = {} - custom_request_headers_name = get_custom_headers( - OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST + + sanitize = SanitizeValue( + get_custom_headers( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS + ) + ) + + headers = { + key[_CARRIER_KEY_PREFIX_LEN:].replace("_", "-"): val + for key, val in environ.items() + if key.startswith(_CARRIER_KEY_PREFIX) + } + + return sanitize.sanitize_header_values( + headers, + get_custom_headers( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST + ), + normalise_request_header_name, ) - for header_name in custom_request_headers_name: - wsgi_env_var = header_name.upper().replace("-", "_") - header_values = environ.get(f"HTTP_{wsgi_env_var}") - if header_values: - key = normalise_request_header_name(header_name) - attributes[key] = [header_values] - return attributes def collect_custom_response_headers_attributes(response_headers): """Returns custom HTTP response headers which are configured by the user from the PEP3333-conforming WSGI environ as described in the specification https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers""" - attributes = {} - custom_response_headers_name = get_custom_headers( - OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE + + sanitize = SanitizeValue( + get_custom_headers( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS + ) ) response_headers_dict = {} if response_headers: - for header_name, header_value in response_headers: - response_headers_dict[header_name.lower()] = header_value - - for header_name in custom_response_headers_name: - header_values = response_headers_dict.get(header_name.lower()) - if header_values: - key = normalise_response_header_name(header_name) - attributes[key] = [header_values] - return attributes + response_headers_dict = dict(response_headers) + + return sanitize.sanitize_header_values( + response_headers_dict, + get_custom_headers( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE + ), + normalise_response_header_name, + ) def _parse_status_code(resp_status):
diff --git a/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py b/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py --- a/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py +++ b/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py @@ -30,6 +30,7 @@ from opentelemetry.test.wsgitestutil import WsgiTestBase from opentelemetry.trace import StatusCode from opentelemetry.util.http import ( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS, OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST, OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE, ) @@ -98,6 +99,15 @@ def wsgi_with_custom_response_headers(environ, start_response): ("content-type", "text/plain; charset=utf-8"), ("content-length", "100"), ("my-custom-header", "my-custom-value-1,my-custom-header-2"), + ( + "my-custom-regex-header-1", + "my-custom-regex-value-1,my-custom-regex-value-2", + ), + ( + "My-Custom-Regex-Header-2", + "my-custom-regex-value-3,my-custom-regex-value-4", + ), + ("My-Secret-Header", "My Secret Value"), ], ) return [b"*"] @@ -521,7 +531,8 @@ def iterate_response(self, response): @mock.patch.dict( "os.environ", { - OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS: ".*my-secret.*", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3,Regex-Test-Header-.*,Regex-Invalid-Test-Header-.*,.*my-secret.*", }, ) def test_custom_request_headers_non_recording_span(self): @@ -531,6 +542,9 @@ def test_custom_request_headers_non_recording_span(self): { "HTTP_CUSTOM_TEST_HEADER_1": "Test Value 2", "HTTP_CUSTOM_TEST_HEADER_2": "TestValue2,TestValue3", + "HTTP_REGEX_TEST_HEADER_1": "Regex Test Value 1", + "HTTP_REGEX_TEST_HEADER_2": "RegexTestValue2,RegexTestValue3", + "HTTP_MY_SECRET_HEADER": "My Secret Value", } ) app = otel_wsgi.OpenTelemetryMiddleware( @@ -544,7 +558,8 @@ def test_custom_request_headers_non_recording_span(self): @mock.patch.dict( "os.environ", { - OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3" + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS: ".*my-secret.*", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3,Regex-Test-Header-.*,Regex-Invalid-Test-Header-.*,.*my-secret.*", }, ) def test_custom_request_headers_added_in_server_span(self): @@ -552,6 +567,9 @@ def test_custom_request_headers_added_in_server_span(self): { "HTTP_CUSTOM_TEST_HEADER_1": "Test Value 1", "HTTP_CUSTOM_TEST_HEADER_2": "TestValue2,TestValue3", + "HTTP_REGEX_TEST_HEADER_1": "Regex Test Value 1", + "HTTP_REGEX_TEST_HEADER_2": "RegexTestValue2,RegexTestValue3", + "HTTP_MY_SECRET_HEADER": "My Secret Value", } ) app = otel_wsgi.OpenTelemetryMiddleware(simple_wsgi) @@ -563,6 +581,11 @@ def test_custom_request_headers_added_in_server_span(self): "http.request.header.custom_test_header_2": ( "TestValue2,TestValue3", ), + "http.request.header.regex_test_header_1": ("Regex Test Value 1",), + "http.request.header.regex_test_header_2": ( + "RegexTestValue2,RegexTestValue3", + ), + "http.request.header.my_secret_header": ("[REDACTED]",), } self.assertSpanHasAttributes(span, expected) @@ -595,7 +618,8 @@ def test_custom_request_headers_not_added_in_internal_span(self): @mock.patch.dict( "os.environ", { - OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "content-type,content-length,my-custom-header,invalid-header" + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS: ".*my-secret.*", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "content-type,content-length,my-custom-header,invalid-header,my-custom-regex-header-.*,invalid-regex-header-.*,.*my-secret.*", }, ) def test_custom_response_headers_added_in_server_span(self): @@ -613,6 +637,13 @@ def test_custom_response_headers_added_in_server_span(self): "http.response.header.my_custom_header": ( "my-custom-value-1,my-custom-header-2", ), + "http.response.header.my_custom_regex_header_1": ( + "my-custom-regex-value-1,my-custom-regex-value-2", + ), + "http.response.header.my_custom_regex_header_2": ( + "my-custom-regex-value-3,my-custom-regex-value-4", + ), + "http.response.header.my_secret_header": ("[REDACTED]",), } self.assertSpanHasAttributes(span, expected)
Add more features for adding HTTP request / response headers to spans. I already have https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1172 open for this, and I'll be breaking it in to smaller pieces at @lzchen 's request. **Is your feature request related to a problem?** Currently, you can only provide a list of full HTTP request / response header names to be added to the span. There is also no capacity for header value redaction. **Describe the solution you'd like** It would be nice to be able to specify a regex or "all" to get all headers. Header value redaction is also a must-have for us. **Describe alternatives you've considered** I considered doing this in my application, but it makes more sense to add it here.
2022-10-24T16:15:41
open-telemetry/opentelemetry-python-contrib
1,403
open-telemetry__opentelemetry-python-contrib-1403
[ "1184" ]
40e4e2e5985d416aa5e7f1ae7ca8f293e7c66044
diff --git a/instrumentation/opentelemetry-instrumentation-fastapi/src/opentelemetry/instrumentation/fastapi/__init__.py b/instrumentation/opentelemetry-instrumentation-fastapi/src/opentelemetry/instrumentation/fastapi/__init__.py --- a/instrumentation/opentelemetry-instrumentation-fastapi/src/opentelemetry/instrumentation/fastapi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-fastapi/src/opentelemetry/instrumentation/fastapi/__init__.py @@ -34,8 +34,9 @@ async def foobar(): Exclude lists ************* -To exclude certain URLs from being tracked, set the environment variable ``OTEL_PYTHON_FASTAPI_EXCLUDED_URLS`` -(or ``OTEL_PYTHON_EXCLUDED_URLS`` as fallback) with comma delimited regexes representing which URLs to exclude. +To exclude certain URLs from tracking, set the environment variable ``OTEL_PYTHON_FASTAPI_EXCLUDED_URLS`` +(or ``OTEL_PYTHON_EXCLUDED_URLS`` to cover all instrumentations) to a string of comma delimited regexes that match the +URLs. For example, @@ -45,7 +46,7 @@ async def foobar(): will exclude requests such as ``https://site/client/123/info`` and ``https://site/xyz/healthcheck``. -You can also pass the comma delimited regexes to the ``instrument_app`` method directly: +You can also pass comma delimited regexes directly to the ``instrument_app`` method: .. code-block:: python @@ -54,9 +55,12 @@ async def foobar(): Request/Response hooks ********************** -Utilize request/response hooks to execute custom logic to be performed before/after performing a request. The server request hook takes in a server span and ASGI -scope object for every incoming request. The client request hook is called with the internal span and an ASGI scope which is sent as a dictionary for when the method receive is called. -The client response hook is called with the internal span and an ASGI event which is sent as a dictionary for when the method send is called. +This instrumentation supports request and response hooks. These are functions that get called +right after a span is created for a request and right before the span is finished for the response. + +- The server request hook is passed a server span and ASGI scope object for every incoming request. +- The client request hook is called with the internal span and an ASGI scope when the method ``receive`` is called. +- The client response hook is called with the internal span and an ASGI event when the method ``send`` is called. .. code-block:: python @@ -76,54 +80,93 @@ def client_response_hook(span: Span, message: dict): Capture HTTP request and response headers ***************************************** -You can configure the agent to capture predefined HTTP headers as span attributes, according to the `semantic convention <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers>`_. +You can configure the agent to capture specified HTTP headers as span attributes, according to the +`semantic convention <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers>`_. Request headers *************** -To capture predefined HTTP request headers as span attributes, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST`` -to a comma-separated list of HTTP header names. +To capture HTTP request headers as span attributes, set the environment variable +``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST`` to a comma delimited list of HTTP header names. For example, - :: export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="content-type,custom_request_header" -will extract ``content-type`` and ``custom_request_header`` from request headers and add them as span attributes. +will extract ``content-type`` and ``custom_request_header`` from the request headers and add them as span attributes. + +Request header names in FastAPI are case-insensitive. So, giving the header name as ``CUStom-Header`` in the environment +variable will capture the header named ``custom-header``. + +Regular expressions may also be used to match multiple headers that correspond to the given pattern. For example: +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="Accept.*,X-.*" -It is recommended that you should give the correct names of the headers to be captured in the environment variable. -Request header names in fastapi are case insensitive. So, giving header name as ``CUStom-Header`` in environment variable will be able capture header with name ``custom-header``. +Would match all request headers that start with ``Accept`` and ``X-``. -The name of the added span attribute will follow the format ``http.request.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ). -The value of the attribute will be single item list containing all the header values. +To capture all request headers, set ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST`` to ``".*"``. +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST=".*" + +The name of the added span attribute will follow the format ``http.request.header.<header_name>`` where ``<header_name>`` +is the normalized HTTP header name (lowercase, with ``-`` replaced by ``_``). The value of the attribute will be a +single item list containing all the header values. -Example of the added span attribute, +For example: ``http.request.header.custom_request_header = ["<value1>,<value2>"]`` Response headers **************** -To capture predefined HTTP response headers as span attributes, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`` -to a comma-separated list of HTTP header names. +To capture HTTP response headers as span attributes, set the environment variable +``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`` to a comma delimited list of HTTP header names. For example, - :: export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="content-type,custom_response_header" -will extract ``content-type`` and ``custom_response_header`` from response headers and add them as span attributes. +will extract ``content-type`` and ``custom_response_header`` from the response headers and add them as span attributes. + +Response header names in FastAPI are case-insensitive. So, giving the header name as ``CUStom-Header`` in the environment +variable will capture the header named ``custom-header``. -It is recommended that you should give the correct names of the headers to be captured in the environment variable. -Response header names captured in fastapi are case insensitive. So, giving header name as ``CUStomHeader`` in environment variable will be able capture header with name ``customheader``. +Regular expressions may also be used to match multiple headers that correspond to the given pattern. For example: +:: -The name of the added span attribute will follow the format ``http.response.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ). -The value of the attribute will be single item list containing all the header values. + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="Content.*,X-.*" -Example of the added span attribute, +Would match all response headers that start with ``Content`` and ``X-``. + +To capture all response headers, set ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`` to ``".*"``. +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE=".*" + +The name of the added span attribute will follow the format ``http.response.header.<header_name>`` where ``<header_name>`` +is the normalized HTTP header name (lowercase, with ``-`` replaced by ``_``). The value of the attribute will be a +single item list containing all the header values. + +For example: ``http.response.header.custom_response_header = ["<value1>,<value2>"]`` +Sanitizing headers +****************** +In order to prevent storing sensitive data such as personally identifiable information (PII), session keys, passwords, +etc, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS`` +to a comma delimited list of HTTP header names to be sanitized. Regexes may be used, and all header names will be +matched in a case-insensitive manner. + +For example, +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS=".*session.*,set-cookie" + +will replace the value of headers such as ``session-id`` and ``set-cookie`` with ``[REDACTED]`` in the span. + Note: - Environment variable names to capture http headers are still experimental, and thus are subject to change. + The environment variable names used to capture HTTP headers are still experimental, and thus are subject to change. API ---
diff --git a/instrumentation/opentelemetry-instrumentation-fastapi/tests/test_fastapi_instrumentation.py b/instrumentation/opentelemetry-instrumentation-fastapi/tests/test_fastapi_instrumentation.py --- a/instrumentation/opentelemetry-instrumentation-fastapi/tests/test_fastapi_instrumentation.py +++ b/instrumentation/opentelemetry-instrumentation-fastapi/tests/test_fastapi_instrumentation.py @@ -32,6 +32,7 @@ from opentelemetry.test.globals_test import reset_trace_globals from opentelemetry.test.test_base import TestBase from opentelemetry.util.http import ( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS, OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST, OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE, _active_requests_count_attrs, @@ -529,24 +530,23 @@ def test_mark_span_internal_in_presence_of_span_from_other_framework(self): ) [email protected]( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS: ".*my-secret.*", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3,Regex-Test-Header-.*,Regex-Invalid-Test-Header-.*,.*my-secret.*", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3,my-custom-regex-header-.*,invalid-regex-header-.*,.*my-secret.*", + }, +) class TestHTTPAppWithCustomHeaders(TestBase): def setUp(self): super().setUp() - self.env_patch = patch.dict( - "os.environ", - { - OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3", - OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3", - }, - ) - self.env_patch.start() self.app = self._create_app() otel_fastapi.FastAPIInstrumentor().instrument_app(self.app) self.client = TestClient(self.app) def tearDown(self) -> None: super().tearDown() - self.env_patch.stop() with self.disable_logging(): otel_fastapi.FastAPIInstrumentor().uninstrument_app(self.app) @@ -559,6 +559,9 @@ async def _(): headers = { "custom-test-header-1": "test-header-value-1", "custom-test-header-2": "test-header-value-2", + "my-custom-regex-header-1": "my-custom-regex-value-1,my-custom-regex-value-2", + "My-Custom-Regex-Header-2": "my-custom-regex-value-3,my-custom-regex-value-4", + "My-Secret-Header": "My Secret Value", } content = {"message": "hello world"} return JSONResponse(content=content, headers=headers) @@ -573,12 +576,20 @@ def test_http_custom_request_headers_in_span_attributes(self): "http.request.header.custom_test_header_2": ( "test-header-value-2", ), + "http.request.header.regex_test_header_1": ("Regex Test Value 1",), + "http.request.header.regex_test_header_2": ( + "RegexTestValue2,RegexTestValue3", + ), + "http.request.header.my_secret_header": ("[REDACTED]",), } resp = self.client.get( "/foobar", headers={ "custom-test-header-1": "test-header-value-1", "custom-test-header-2": "test-header-value-2", + "Regex-Test-Header-1": "Regex Test Value 1", + "regex-test-header-2": "RegexTestValue2,RegexTestValue3", + "My-Secret-Header": "My Secret Value", }, ) self.assertEqual(200, resp.status_code) @@ -602,6 +613,9 @@ def test_http_custom_request_headers_not_in_span_attributes(self): headers={ "custom-test-header-1": "test-header-value-1", "custom-test-header-2": "test-header-value-2", + "Regex-Test-Header-1": "Regex Test Value 1", + "regex-test-header-2": "RegexTestValue2,RegexTestValue3", + "My-Secret-Header": "My Secret Value", }, ) self.assertEqual(200, resp.status_code) @@ -623,6 +637,13 @@ def test_http_custom_response_headers_in_span_attributes(self): "http.response.header.custom_test_header_2": ( "test-header-value-2", ), + "http.response.header.my_custom_regex_header_1": ( + "my-custom-regex-value-1,my-custom-regex-value-2", + ), + "http.response.header.my_custom_regex_header_2": ( + "my-custom-regex-value-3,my-custom-regex-value-4", + ), + "http.response.header.my_secret_header": ("[REDACTED]",), } resp = self.client.get("/foobar") self.assertEqual(200, resp.status_code) @@ -653,24 +674,23 @@ def test_http_custom_response_headers_not_in_span_attributes(self): self.assertNotIn(key, server_span.attributes) [email protected]( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS: ".*my-secret.*", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3,Regex-Test-Header-.*,Regex-Invalid-Test-Header-.*,.*my-secret.*", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3,my-custom-regex-header-.*,invalid-regex-header-.*,.*my-secret.*", + }, +) class TestWebSocketAppWithCustomHeaders(TestBase): def setUp(self): super().setUp() - self.env_patch = patch.dict( - "os.environ", - { - OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3", - OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3", - }, - ) - self.env_patch.start() self.app = self._create_app() otel_fastapi.FastAPIInstrumentor().instrument_app(self.app) self.client = TestClient(self.app) def tearDown(self) -> None: super().tearDown() - self.env_patch.stop() with self.disable_logging(): otel_fastapi.FastAPIInstrumentor().uninstrument_app(self.app) @@ -688,6 +708,12 @@ async def _(websocket: fastapi.WebSocket): "headers": [ (b"custom-test-header-1", b"test-header-value-1"), (b"custom-test-header-2", b"test-header-value-2"), + (b"Regex-Test-Header-1", b"Regex Test Value 1"), + ( + b"regex-test-header-2", + b"RegexTestValue2,RegexTestValue3", + ), + (b"My-Secret-Header", b"My Secret Value"), ], } ) @@ -727,6 +753,13 @@ def test_web_socket_custom_request_headers_in_span_attributes(self): self.assertSpanHasAttributes(server_span, expected) + @patch.dict( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS: ".*my-secret.*", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3,Regex-Test-Header-.*,Regex-Invalid-Test-Header-.*,.*my-secret.*", + }, + ) def test_web_socket_custom_request_headers_not_in_span_attributes(self): not_expected = { "http.request.header.custom_test_header_3": ( @@ -799,16 +832,15 @@ def test_web_socket_custom_response_headers_not_in_span_attributes(self): self.assertNotIn(key, server_span.attributes) [email protected]( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3", + }, +) class TestNonRecordingSpanWithCustomHeaders(TestBase): def setUp(self): super().setUp() - self.env_patch = patch.dict( - "os.environ", - { - OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3", - }, - ) - self.env_patch.start() self.app = fastapi.FastAPI() @self.app.get("/foobar")
Add more features for adding HTTP request / response headers to spans. I already have https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1172 open for this, and I'll be breaking it in to smaller pieces at @lzchen 's request. **Is your feature request related to a problem?** Currently, you can only provide a list of full HTTP request / response header names to be added to the span. There is also no capacity for header value redaction. **Describe the solution you'd like** It would be nice to be able to specify a regex or "all" to get all headers. Header value redaction is also a must-have for us. **Describe alternatives you've considered** I considered doing this in my application, but it makes more sense to add it here.
2022-10-24T18:09:36
open-telemetry/opentelemetry-python-contrib
1,404
open-telemetry__opentelemetry-python-contrib-1404
[ "1184" ]
47512c84b99ff5366492886821d3ba1b962e90f3
diff --git a/instrumentation/opentelemetry-instrumentation-starlette/src/opentelemetry/instrumentation/starlette/__init__.py b/instrumentation/opentelemetry-instrumentation-starlette/src/opentelemetry/instrumentation/starlette/__init__.py --- a/instrumentation/opentelemetry-instrumentation-starlette/src/opentelemetry/instrumentation/starlette/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-starlette/src/opentelemetry/instrumentation/starlette/__init__.py @@ -36,8 +36,9 @@ def home(request): Exclude lists ************* -To exclude certain URLs from being tracked, set the environment variable ``OTEL_PYTHON_STARLETTE_EXCLUDED_URLS`` -(or ``OTEL_PYTHON_EXCLUDED_URLS`` as fallback) with comma delimited regexes representing which URLs to exclude. +To exclude certain URLs from tracking, set the environment variable ``OTEL_PYTHON_STARLETTE_EXCLUDED_URLS`` +(or ``OTEL_PYTHON_EXCLUDED_URLS`` to cover all instrumentations) to a string of comma delimited regexes that match the +URLs. For example, @@ -50,9 +51,14 @@ def home(request): Request/Response hooks ********************** -Utilize request/response hooks to execute custom logic to be performed before/after performing a request. The server request hook takes in a server span and ASGI -scope object for every incoming request. The client request hook is called with the internal span and an ASGI scope which is sent as a dictionary for when the method receive is called. -The client response hook is called with the internal span and an ASGI event which is sent as a dictionary for when the method send is called. +This instrumentation supports request and response hooks. These are functions that get called +right after a span is created for a request and right before the span is finished for the response. + +- The server request hook is passed a server span and ASGI scope object for every incoming request. +- The client request hook is called with the internal span and an ASGI scope when the method ``receive`` is called. +- The client response hook is called with the internal span and an ASGI event when the method ``send`` is called. + +For example, .. code-block:: python @@ -70,54 +76,93 @@ def client_response_hook(span: Span, message: dict): Capture HTTP request and response headers ***************************************** -You can configure the agent to capture predefined HTTP headers as span attributes, according to the `semantic convention <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers>`_. +You can configure the agent to capture specified HTTP headers as span attributes, according to the +`semantic convention <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers>`_. Request headers *************** -To capture predefined HTTP request headers as span attributes, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST`` -to a comma-separated list of HTTP header names. +To capture HTTP request headers as span attributes, set the environment variable +``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST`` to a comma delimited list of HTTP header names. For example, - :: export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="content-type,custom_request_header" -will extract ``content-type`` and ``custom_request_header`` from request headers and add them as span attributes. +will extract ``content-type`` and ``custom_request_header`` from the request headers and add them as span attributes. + +Request header names in Starlette are case-insensitive. So, giving the header name as ``CUStom-Header`` in the +environment variable will capture the header named ``custom-header``. + +Regular expressions may also be used to match multiple headers that correspond to the given pattern. For example: +:: -It is recommended that you should give the correct names of the headers to be captured in the environment variable. -Request header names in starlette are case insensitive. So, giving header name as ``CUStom-Header`` in environment variable will be able capture header with name ``custom-header``. + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="Accept.*,X-.*" -The name of the added span attribute will follow the format ``http.request.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ). -The value of the attribute will be single item list containing all the header values. +Would match all request headers that start with ``Accept`` and ``X-``. -Example of the added span attribute, +Additionally, the special keyword ``all`` can be used to capture all request headers. +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="all" + +The name of the added span attribute will follow the format ``http.request.header.<header_name>`` where ``<header_name>`` +is the normalized HTTP header name (lowercase, with ``-`` replaced by ``_``). The value of the attribute will be a +single item list containing all the header values. + +For example: ``http.request.header.custom_request_header = ["<value1>,<value2>"]`` Response headers **************** -To capture predefined HTTP response headers as span attributes, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`` -to a comma-separated list of HTTP header names. +To capture HTTP response headers as span attributes, set the environment variable +``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`` to a comma delimited list of HTTP header names. For example, - :: export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="content-type,custom_response_header" -will extract ``content-type`` and ``custom_response_header`` from response headers and add them as span attributes. +will extract ``content-type`` and ``custom_response_header`` from the response headers and add them as span attributes. -It is recommended that you should give the correct names of the headers to be captured in the environment variable. -Response header names captured in starlette are case insensitive. So, giving header name as ``CUStomHeader`` in environment variable will be able capture header with name ``customheader``. +Response header names in Starlette are case-insensitive. So, giving the header name as ``CUStom-Header`` in the +environment variable will capture the header named ``custom-header``. -The name of the added span attribute will follow the format ``http.response.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ). -The value of the attribute will be single item list containing all the header values. +Regular expressions may also be used to match multiple headers that correspond to the given pattern. For example: +:: -Example of the added span attribute, + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="Content.*,X-.*" + +Would match all response headers that start with ``Content`` and ``X-``. + +Additionally, the special keyword ``all`` can be used to capture all response headers. +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="all" + +The name of the added span attribute will follow the format ``http.response.header.<header_name>`` where ``<header_name>`` +is the normalized HTTP header name (lowercase, with ``-`` replaced by ``_``). The value of the attribute will be a +single item list containing all the header values. + +For example: ``http.response.header.custom_response_header = ["<value1>,<value2>"]`` +Sanitizing headers +****************** +In order to prevent storing sensitive data such as personally identifiable information (PII), session keys, passwords, +etc, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS`` +to a comma delimited list of HTTP header names to be sanitized. Regexes may be used, and all header names will be +matched in a case-insensitive manner. + +For example, +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS=".*session.*,set-cookie" + +will replace the value of headers such as ``session-id`` and ``set-cookie`` with ``[REDACTED]`` in the span. + Note: - Environment variable names to capture http headers are still experimental, and thus are subject to change. + The environment variable names used to capture HTTP headers are still experimental, and thus are subject to change. API ---
diff --git a/instrumentation/opentelemetry-instrumentation-starlette/tests/test_starlette_instrumentation.py b/instrumentation/opentelemetry-instrumentation-starlette/tests/test_starlette_instrumentation.py --- a/instrumentation/opentelemetry-instrumentation-starlette/tests/test_starlette_instrumentation.py +++ b/instrumentation/opentelemetry-instrumentation-starlette/tests/test_starlette_instrumentation.py @@ -38,6 +38,7 @@ set_tracer_provider, ) from opentelemetry.util.http import ( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS, OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST, OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE, _active_requests_count_attrs, @@ -384,21 +385,12 @@ def create_app(self): def setUp(self): super().setUp() - self.env_patch = patch.dict( - "os.environ", - { - OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3", - OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3", - }, - ) - self.env_patch.start() self._instrumentor = otel_starlette.StarletteInstrumentor() self._app = self.create_app() self._client = TestClient(self._app) def tearDown(self) -> None: super().tearDown() - self.env_patch.stop() with self.disable_logging(): self._instrumentor.uninstrument() @@ -413,6 +405,9 @@ def _(request): headers={ "custom-test-header-1": "test-header-value-1", "custom-test-header-2": "test-header-value-2", + "my-custom-regex-header-1": "my-custom-regex-value-1,my-custom-regex-value-2", + "My-Custom-Regex-Header-2": "my-custom-regex-value-3,my-custom-regex-value-4", + "my-secret-header": "my-secret-value", }, ) @@ -426,6 +421,15 @@ async def _(websocket: WebSocket) -> None: "headers": [ (b"custom-test-header-1", b"test-header-value-1"), (b"custom-test-header-2", b"test-header-value-2"), + ( + b"my-custom-regex-header-1", + b"my-custom-regex-value-1,my-custom-regex-value-2", + ), + ( + b"My-Custom-Regex-Header-2", + b"my-custom-regex-value-3,my-custom-regex-value-4", + ), + (b"my-secret-header", b"my-secret-value"), ], } ) @@ -437,6 +441,14 @@ async def _(websocket: WebSocket) -> None: return app [email protected]( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS: ".*my-secret.*", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3,Regex-Test-Header-.*,Regex-Invalid-Test-Header-.*,.*my-secret.*", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3,my-custom-regex-header-.*,invalid-regex-header-.*,.*my-secret.*", + }, +) class TestHTTPAppWithCustomHeaders(TestBaseWithCustomHeaders): def test_custom_request_headers_in_span_attributes(self): expected = { @@ -446,12 +458,20 @@ def test_custom_request_headers_in_span_attributes(self): "http.request.header.custom_test_header_2": ( "test-header-value-2", ), + "http.request.header.regex_test_header_1": ("Regex Test Value 1",), + "http.request.header.regex_test_header_2": ( + "RegexTestValue2,RegexTestValue3", + ), + "http.request.header.my_secret_header": ("[REDACTED]",), } resp = self._client.get( "/foobar", headers={ "custom-test-header-1": "test-header-value-1", "custom-test-header-2": "test-header-value-2", + "Regex-Test-Header-1": "Regex Test Value 1", + "regex-test-header-2": "RegexTestValue2,RegexTestValue3", + "My-Secret-Header": "My Secret Value", }, ) self.assertEqual(200, resp.status_code) @@ -464,6 +484,13 @@ def test_custom_request_headers_in_span_attributes(self): self.assertSpanHasAttributes(server_span, expected) + @patch.dict( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS: ".*my-secret.*", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3,Regex-Test-Header-.*,Regex-Invalid-Test-Header-.*,.*my-secret.*", + }, + ) def test_custom_request_headers_not_in_span_attributes(self): not_expected = { "http.request.header.custom_test_header_3": ( @@ -475,6 +502,9 @@ def test_custom_request_headers_not_in_span_attributes(self): headers={ "custom-test-header-1": "test-header-value-1", "custom-test-header-2": "test-header-value-2", + "Regex-Test-Header-1": "Regex Test Value 1", + "regex-test-header-2": "RegexTestValue2,RegexTestValue3", + "My-Secret-Header": "My Secret Value", }, ) self.assertEqual(200, resp.status_code) @@ -496,6 +526,13 @@ def test_custom_response_headers_in_span_attributes(self): "http.response.header.custom_test_header_2": ( "test-header-value-2", ), + "http.response.header.my_custom_regex_header_1": ( + "my-custom-regex-value-1,my-custom-regex-value-2", + ), + "http.response.header.my_custom_regex_header_2": ( + "my-custom-regex-value-3,my-custom-regex-value-4", + ), + "http.response.header.my_secret_header": ("[REDACTED]",), } resp = self._client.get("/foobar") self.assertEqual(200, resp.status_code) @@ -527,6 +564,14 @@ def test_custom_response_headers_not_in_span_attributes(self): self.assertNotIn(key, server_span.attributes) [email protected]( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS: ".*my-secret.*", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3,Regex-Test-Header-.*,Regex-Invalid-Test-Header-.*,.*my-secret.*", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3,my-custom-regex-header-.*,invalid-regex-header-.*,.*my-secret.*", + }, +) class TestWebSocketAppWithCustomHeaders(TestBaseWithCustomHeaders): def test_custom_request_headers_in_span_attributes(self): expected = { @@ -536,12 +581,20 @@ def test_custom_request_headers_in_span_attributes(self): "http.request.header.custom_test_header_2": ( "test-header-value-2", ), + "http.request.header.regex_test_header_1": ("Regex Test Value 1",), + "http.request.header.regex_test_header_2": ( + "RegexTestValue2,RegexTestValue3", + ), + "http.request.header.my_secret_header": ("[REDACTED]",), } with self._client.websocket_connect( "/foobar_web", headers={ "custom-test-header-1": "test-header-value-1", "custom-test-header-2": "test-header-value-2", + "Regex-Test-Header-1": "Regex Test Value 1", + "regex-test-header-2": "RegexTestValue2,RegexTestValue3", + "My-Secret-Header": "My Secret Value", }, ) as websocket: data = websocket.receive_json() @@ -566,6 +619,9 @@ def test_custom_request_headers_not_in_span_attributes(self): headers={ "custom-test-header-1": "test-header-value-1", "custom-test-header-2": "test-header-value-2", + "Regex-Test-Header-1": "Regex Test Value 1", + "regex-test-header-2": "RegexTestValue2,RegexTestValue3", + "My-Secret-Header": "My Secret Value", }, ) as websocket: data = websocket.receive_json() @@ -589,6 +645,13 @@ def test_custom_response_headers_in_span_attributes(self): "http.response.header.custom_test_header_2": ( "test-header-value-2", ), + "http.response.header.my_custom_regex_header_1": ( + "my-custom-regex-value-1,my-custom-regex-value-2", + ), + "http.response.header.my_custom_regex_header_2": ( + "my-custom-regex-value-3,my-custom-regex-value-4", + ), + "http.response.header.my_secret_header": ("[REDACTED]",), } with self._client.websocket_connect("/foobar_web") as websocket: data = websocket.receive_json() @@ -624,6 +687,14 @@ def test_custom_response_headers_not_in_span_attributes(self): self.assertNotIn(key, server_span.attributes) [email protected]( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS: ".*my-secret.*", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3,Regex-Test-Header-.*,Regex-Invalid-Test-Header-.*,.*my-secret.*", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3,my-custom-regex-header-.*,invalid-regex-header-.*,.*my-secret.*", + }, +) class TestNonRecordingSpanWithCustomHeaders(TestBaseWithCustomHeaders): def setUp(self): super().setUp()
Add more features for adding HTTP request / response headers to spans. I already have https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1172 open for this, and I'll be breaking it in to smaller pieces at @lzchen 's request. **Is your feature request related to a problem?** Currently, you can only provide a list of full HTTP request / response header names to be added to the span. There is also no capacity for header value redaction. **Describe the solution you'd like** It would be nice to be able to specify a regex or "all" to get all headers. Header value redaction is also a must-have for us. **Describe alternatives you've considered** I considered doing this in my application, but it makes more sense to add it here.
2022-10-24T18:51:52
open-telemetry/opentelemetry-python-contrib
1,411
open-telemetry__opentelemetry-python-contrib-1411
[ "1184" ]
f58d16b47f3414f8650d614a65d7b7d69e350307
diff --git a/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/__init__.py b/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/__init__.py --- a/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/__init__.py @@ -94,8 +94,9 @@ Exclude lists ************* -To exclude certain URLs from being tracked, set the environment variable ``OTEL_PYTHON_DJANGO_EXCLUDED_URLS`` -(or ``OTEL_PYTHON_EXCLUDED_URLS`` as fallback) with comma delimited regexes representing which URLs to exclude. +To exclude certain URLs from tracking, set the environment variable ``OTEL_PYTHON_DJANGO_EXCLUDED_URLS`` +(or ``OTEL_PYTHON_EXCLUDED_URLS`` to cover all instrumentations) to a string of comma delimited regexes that match the +URLs. For example, @@ -107,8 +108,8 @@ Request attributes ******************** -To extract certain attributes from Django's request object and use them as span attributes, set the environment variable ``OTEL_PYTHON_DJANGO_TRACED_REQUEST_ATTRS`` to a comma -delimited list of request attribute names. +To extract attributes from Django's request object and use them as span attributes, set the environment variable +``OTEL_PYTHON_DJANGO_TRACED_REQUEST_ATTRS`` to a comma delimited list of request attribute names. For example, @@ -116,14 +117,15 @@ export OTEL_PYTHON_DJANGO_TRACED_REQUEST_ATTRS='path_info,content_type' -will extract path_info and content_type attributes from every traced request and add them as span attritbues. +will extract the ``path_info`` and ``content_type`` attributes from every traced request and add them as span attributes. Django Request object reference: https://docs.djangoproject.com/en/3.1/ref/request-response/#attributes Request and Response hooks *************************** -The instrumentation supports specifying request and response hooks. These are functions that get called back by the instrumentation right after a Span is created for a request -and right before the span is finished while processing a response. The hooks can be configured as follows: +This instrumentation supports request and response hooks. These are functions that get called +right after a span is created for a request and right before the span is finished for the response. +The hooks can be configured as follows: .. code:: python @@ -140,50 +142,94 @@ def response_hook(span, request, response): Capture HTTP request and response headers ***************************************** -You can configure the agent to capture predefined HTTP headers as span attributes, according to the `semantic convention <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers>`_. +You can configure the agent to capture specified HTTP headers as span attributes, according to the +`semantic convention <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers>`_. Request headers *************** -To capture predefined HTTP request headers as span attributes, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST`` -to a comma-separated list of HTTP header names. +To capture HTTP request headers as span attributes, set the environment variable +``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST`` to a comma delimited list of HTTP header names. For example, :: - export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="content_type,custom_request_header" + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="content-type,custom_request_header" -will extract content_type and custom_request_header from request headers and add them as span attributes. +will extract ``content-type`` and ``custom_request_header`` from the request headers and add them as span attributes. -It is recommended that you should give the correct names of the headers to be captured in the environment variable. -Request header names in django are case insensitive. So, giving header name as ``CUStom_Header`` in environment variable will be able capture header with name ``custom-header``. +Request header names in Django are case-insensitive. So, giving the header name as ``CUStom-Header`` in the environment +variable will capture the header named ``custom-header``. -The name of the added span attribute will follow the format ``http.request.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ). -The value of the attribute will be single item list containing all the header values. +Regular expressions may also be used to match multiple headers that correspond to the given pattern. For example: +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="Accept.*,X-.*" + +Would match all request headers that start with ``Accept`` and ``X-``. + +To capture all request headers, set ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST`` to ``".*"``. +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST=".*" -Example of the added span attribute, +The name of the added span attribute will follow the format ``http.request.header.<header_name>`` where ``<header_name>`` +is the normalized HTTP header name (lowercase, with ``-`` replaced by ``_``). The value of the attribute will be a +single item list containing all the header values. + +For example: ``http.request.header.custom_request_header = ["<value1>,<value2>"]`` Response headers **************** -To capture predefined HTTP response headers as span attributes, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`` -to a comma-separated list of HTTP header names. +To capture HTTP response headers as span attributes, set the environment variable +``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`` to a comma delimited list of HTTP header names. For example, :: - export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="content_type,custom_response_header" + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="content-type,custom_response_header" + +will extract ``content-type`` and ``custom_response_header`` from the response headers and add them as span attributes. -will extract content_type and custom_response_header from response headers and add them as span attributes. +Response header names in Django are case-insensitive. So, giving the header name as ``CUStom-Header`` in the environment +variable will capture the header named ``custom-header``. -It is recommended that you should give the correct names of the headers to be captured in the environment variable. -Response header names captured in django are case insensitive. So, giving header name as ``CUStomHeader`` in environment variable will be able capture header with name ``customheader``. +Regular expressions may also be used to match multiple headers that correspond to the given pattern. For example: +:: -The name of the added span attribute will follow the format ``http.response.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ). -The value of the attribute will be single item list containing all the header values. + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="Content.*,X-.*" -Example of the added span attribute, +Would match all response headers that start with ``Content`` and ``X-``. + +To capture all response headers, set ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`` to ``".*"``. +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE=".*" + +The name of the added span attribute will follow the format ``http.response.header.<header_name>`` where ``<header_name>`` +is the normalized HTTP header name (lowercase, with ``-`` replaced by ``_``). The value of the attribute will be a +single item list containing all the header values. + +For example: ``http.response.header.custom_response_header = ["<value1>,<value2>"]`` +Sanitizing headers +****************** +In order to prevent storing sensitive data such as personally identifiable information (PII), session keys, passwords, +etc, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS`` +to a comma delimited list of HTTP header names to be sanitized. Regexes may be used, and all header names will be +matched in a case-insensitive manner. + +For example, +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS=".*session.*,set-cookie" + +will replace the value of headers such as ``session-id`` and ``set-cookie`` with ``[REDACTED]`` in the span. + +Note: + The environment variable names used to capture HTTP headers are still experimental, and thus are subject to change. + API ---
diff --git a/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware.py b/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware.py --- a/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware.py +++ b/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware.py @@ -48,6 +48,7 @@ format_trace_id, ) from opentelemetry.util.http import ( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS, OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST, OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE, _active_requests_count_attrs, @@ -530,6 +531,14 @@ def test_django_with_wsgi_instrumented(self): ) [email protected]( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS: ".*my-secret.*", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3,Regex-Test-Header-.*,Regex-Invalid-Test-Header-.*,.*my-secret.*", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3,my-custom-regex-header-.*,invalid-regex-header-.*,.*my-secret.*", + }, +) class TestMiddlewareWsgiWithCustomHeaders(WsgiTestBase): @classmethod def setUpClass(cls): @@ -542,18 +551,9 @@ def setUp(self): tracer_provider, exporter = self.create_tracer_provider() self.exporter = exporter _django_instrumentor.instrument(tracer_provider=tracer_provider) - self.env_patch = patch.dict( - "os.environ", - { - OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3", - OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3", - }, - ) - self.env_patch.start() def tearDown(self): super().tearDown() - self.env_patch.stop() teardown_test_environment() _django_instrumentor.uninstrument() @@ -570,10 +570,18 @@ def test_http_custom_request_headers_in_span_attributes(self): "http.request.header.custom_test_header_2": ( "test-header-value-2", ), + "http.request.header.regex_test_header_1": ("Regex Test Value 1",), + "http.request.header.regex_test_header_2": ( + "RegexTestValue2,RegexTestValue3", + ), + "http.request.header.my_secret_header": ("[REDACTED]",), } Client( HTTP_CUSTOM_TEST_HEADER_1="test-header-value-1", HTTP_CUSTOM_TEST_HEADER_2="test-header-value-2", + HTTP_REGEX_TEST_HEADER_1="Regex Test Value 1", + HTTP_REGEX_TEST_HEADER_2="RegexTestValue2,RegexTestValue3", + HTTP_MY_SECRET_HEADER="My Secret Value", ).get("/traced/") spans = self.exporter.get_finished_spans() self.assertEqual(len(spans), 1) @@ -607,6 +615,13 @@ def test_http_custom_response_headers_in_span_attributes(self): "http.response.header.custom_test_header_2": ( "test-header-value-2", ), + "http.response.header.my_custom_regex_header_1": ( + "my-custom-regex-value-1,my-custom-regex-value-2", + ), + "http.response.header.my_custom_regex_header_2": ( + "my-custom-regex-value-3,my-custom-regex-value-4", + ), + "http.response.header.my_secret_header": ("[REDACTED]",), } Client().get("/traced_custom_header/") spans = self.exporter.get_finished_spans() diff --git a/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware_asgi.py b/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware_asgi.py --- a/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware_asgi.py +++ b/instrumentation/opentelemetry-instrumentation-django/tests/test_middleware_asgi.py @@ -43,6 +43,7 @@ format_trace_id, ) from opentelemetry.util.http import ( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS, OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST, OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE, get_excluded_urls, @@ -424,6 +425,14 @@ async def test_tracer_provider_traced(self): ) [email protected]( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS: ".*my-secret.*", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3,Regex-Test-Header-.*,Regex-Invalid-Test-Header-.*,.*my-secret.*", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3,my-custom-regex-header-.*,invalid-regex-header-.*,.*my-secret.*", + }, +) class TestMiddlewareAsgiWithCustomHeaders(SimpleTestCase, TestBase): @classmethod def setUpClass(cls): @@ -437,18 +446,9 @@ def setUp(self): tracer_provider, exporter = self.create_tracer_provider() self.exporter = exporter _django_instrumentor.instrument(tracer_provider=tracer_provider) - self.env_patch = patch.dict( - "os.environ", - { - OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3", - OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3", - }, - ) - self.env_patch.start() def tearDown(self): super().tearDown() - self.env_patch.stop() teardown_test_environment() _django_instrumentor.uninstrument() @@ -465,12 +465,20 @@ async def test_http_custom_request_headers_in_span_attributes(self): "http.request.header.custom_test_header_2": ( "test-header-value-2", ), + "http.request.header.regex_test_header_1": ("Regex Test Value 1",), + "http.request.header.regex_test_header_2": ( + "RegexTestValue2,RegexTestValue3", + ), + "http.request.header.my_secret_header": ("[REDACTED]",), } await self.async_client.get( "/traced/", **{ "custom-test-header-1": "test-header-value-1", "custom-test-header-2": "test-header-value-2", + "Regex-Test-Header-1": "Regex Test Value 1", + "regex-test-header-2": "RegexTestValue2,RegexTestValue3", + "My-Secret-Header": "My Secret Value", }, ) spans = self.exporter.get_finished_spans() @@ -510,6 +518,13 @@ async def test_http_custom_response_headers_in_span_attributes(self): "http.response.header.custom_test_header_2": ( "test-header-value-2", ), + "http.response.header.my_custom_regex_header_1": ( + "my-custom-regex-value-1,my-custom-regex-value-2", + ), + "http.response.header.my_custom_regex_header_2": ( + "my-custom-regex-value-3,my-custom-regex-value-4", + ), + "http.response.header.my_secret_header": ("[REDACTED]",), } await self.async_client.get("/traced_custom_header/") spans = self.exporter.get_finished_spans() diff --git a/instrumentation/opentelemetry-instrumentation-django/tests/views.py b/instrumentation/opentelemetry-instrumentation-django/tests/views.py --- a/instrumentation/opentelemetry-instrumentation-django/tests/views.py +++ b/instrumentation/opentelemetry-instrumentation-django/tests/views.py @@ -35,6 +35,13 @@ def response_with_custom_header(request): response = HttpResponse() response["custom-test-header-1"] = "test-header-value-1" response["custom-test-header-2"] = "test-header-value-2" + response[ + "my-custom-regex-header-1" + ] = "my-custom-regex-value-1,my-custom-regex-value-2" + response[ + "my-custom-regex-header-2" + ] = "my-custom-regex-value-3,my-custom-regex-value-4" + response["my-secret-header"] = "my-secret-value" return response
Add more features for adding HTTP request / response headers to spans. I already have https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1172 open for this, and I'll be breaking it in to smaller pieces at @lzchen 's request. **Is your feature request related to a problem?** Currently, you can only provide a list of full HTTP request / response header names to be added to the span. There is also no capacity for header value redaction. **Describe the solution you'd like** It would be nice to be able to specify a regex or "all" to get all headers. Header value redaction is also a must-have for us. **Describe alternatives you've considered** I considered doing this in my application, but it makes more sense to add it here.
2022-10-27T16:45:33
open-telemetry/opentelemetry-python-contrib
1,412
open-telemetry__opentelemetry-python-contrib-1412
[ "1184" ]
0dc16a41189183175de4ead3bd9cac8feede8d4a
diff --git a/instrumentation/opentelemetry-instrumentation-falcon/src/opentelemetry/instrumentation/falcon/__init__.py b/instrumentation/opentelemetry-instrumentation-falcon/src/opentelemetry/instrumentation/falcon/__init__.py --- a/instrumentation/opentelemetry-instrumentation-falcon/src/opentelemetry/instrumentation/falcon/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-falcon/src/opentelemetry/instrumentation/falcon/__init__.py @@ -19,15 +19,16 @@ * The Falcon resource and method name is used as the Span name. * The ``falcon.resource`` Span attribute is set so the matched resource. -* Error from Falcon resources are properly caught and recorded. +* Errors from Falcon resources are properly caught and recorded. Configuration ------------- Exclude lists ************* -To exclude certain URLs from being tracked, set the environment variable ``OTEL_PYTHON_FALCON_EXCLUDED_URLS`` -(or ``OTEL_PYTHON_EXCLUDED_URLS`` as fallback) with comma delimited regexes representing which URLs to exclude. +To exclude certain URLs from tracking, set the environment variable ``OTEL_PYTHON_FALCON_EXCLUDED_URLS`` +(or ``OTEL_PYTHON_EXCLUDED_URLS`` to cover all instrumentations) to a string of comma delimited regexes that match the +URLs. For example, @@ -39,8 +40,8 @@ Request attributes ******************** -To extract certain attributes from Falcon's request object and use them as span attributes, set the environment variable ``OTEL_PYTHON_FALCON_TRACED_REQUEST_ATTRS`` to a comma -delimited list of request attribute names. +To extract attributes from Falcon's request object and use them as span attributes, set the environment variable +``OTEL_PYTHON_FALCON_TRACED_REQUEST_ATTRS`` to a comma delimited list of request attribute names. For example, @@ -48,7 +49,7 @@ export OTEL_PYTHON_FALCON_TRACED_REQUEST_ATTRS='query_string,uri_template' -will extract query_string and uri_template attributes from every traced request and add them as span attritbues. +will extract the ``query_string`` and ``uri_template`` attributes from every traced request and add them as span attributes. Falcon Request object reference: https://falcon.readthedocs.io/en/stable/api/request_and_response.html#id1 @@ -73,8 +74,9 @@ def on_get(self, req, resp): Request and Response hooks *************************** -The instrumentation supports specifying request and response hooks. These are functions that get called back by the instrumentation right after a Span is created for a request -and right before the span is finished while processing a response. The hooks can be configured as follows: +This instrumentation supports request and response hooks. These are functions that get called +right after a span is created for a request and right before the span is finished for the response. +The hooks can be configured as follows: :: @@ -88,54 +90,93 @@ def response_hook(span, req, resp): Capture HTTP request and response headers ***************************************** -You can configure the agent to capture predefined HTTP headers as span attributes, according to the `semantic convention <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers>`_. +You can configure the agent to capture specified HTTP headers as span attributes, according to the +`semantic convention <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers>`_. Request headers *************** -To capture predefined HTTP request headers as span attributes, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST`` -to a comma-separated list of HTTP header names. +To capture HTTP request headers as span attributes, set the environment variable +``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST`` to a comma delimited list of HTTP header names. For example, - :: export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="content-type,custom_request_header" -will extract ``content-type`` and ``custom_request_header`` from request headers and add them as span attributes. +will extract ``content-type`` and ``custom_request_header`` from the request headers and add them as span attributes. + +Request header names in Falcon are case-insensitive and ``-`` characters are replaced by ``_``. So, giving the header +name as ``CUStom_Header`` in the environment variable will capture the header named ``custom-header``. + +Regular expressions may also be used to match multiple headers that correspond to the given pattern. For example: +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="Accept.*,X-.*" -It is recommended that you should give the correct names of the headers to be captured in the environment variable. -Request header names in falcon are case insensitive and - characters are replaced by _. So, giving header name as ``CUStom_Header`` in environment variable will be able capture header with name ``custom-header``. +Would match all request headers that start with ``Accept`` and ``X-``. -The name of the added span attribute will follow the format ``http.request.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ). -The value of the attribute will be single item list containing all the header values. +To capture all request headers, set ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST`` to ``".*"``. +:: -Example of the added span attribute, + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST=".*" + +The name of the added span attribute will follow the format ``http.request.header.<header_name>`` where ``<header_name>`` +is the normalized HTTP header name (lowercase, with ``-`` replaced by ``_``). The value of the attribute will be a +single item list containing all the header values. + +For example: ``http.request.header.custom_request_header = ["<value1>,<value2>"]`` Response headers **************** -To capture predefined HTTP response headers as span attributes, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`` -to a comma-separated list of HTTP header names. +To capture HTTP response headers as span attributes, set the environment variable +``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`` to a comma delimited list of HTTP header names. For example, - :: export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="content-type,custom_response_header" -will extract ``content-type`` and ``custom_response_header`` from response headers and add them as span attributes. +will extract ``content-type`` and ``custom_response_header`` from the response headers and add them as span attributes. + +Response header names in Falcon are case-insensitive. So, giving the header name as ``CUStom-Header`` in the environment +variable will capture the header named ``custom-header``. + +Regular expressions may also be used to match multiple headers that correspond to the given pattern. For example: +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="Content.*,X-.*" + +Would match all response headers that start with ``Content`` and ``X-``. -It is recommended that you should give the correct names of the headers to be captured in the environment variable. -Response header names captured in falcon are case insensitive. So, giving header name as ``CUStomHeader`` in environment variable will be able capture header with name ``customheader``. +To capture all response headers, set ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`` to ``".*"``. +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE=".*" -The name of the added span attribute will follow the format ``http.response.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ). -The value of the attribute will be single item list containing all the header values. +The name of the added span attribute will follow the format ``http.response.header.<header_name>`` where ``<header_name>`` +is the normalized HTTP header name (lowercase, with ``-`` replaced by ``_``). The value of the attribute will be a +single item list containing all the header values. -Example of the added span attribute, +For example: ``http.response.header.custom_response_header = ["<value1>,<value2>"]`` +Sanitizing headers +****************** +In order to prevent storing sensitive data such as personally identifiable information (PII), session keys, passwords, +etc, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS`` +to a comma delimited list of HTTP header names to be sanitized. Regexes may be used, and all header names will be +matched in a case-insensitive manner. + +For example, +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS=".*session.*,set-cookie" + +will replace the value of headers such as ``session-id`` and ``set-cookie`` with ``[REDACTED]`` in the span. + Note: - Environment variable names to capture http headers are still experimental, and thus are subject to change. + The environment variable names used to capture HTTP headers are still experimental, and thus are subject to change. API ---
diff --git a/instrumentation/opentelemetry-instrumentation-falcon/tests/app.py b/instrumentation/opentelemetry-instrumentation-falcon/tests/app.py --- a/instrumentation/opentelemetry-instrumentation-falcon/tests/app.py +++ b/instrumentation/opentelemetry-instrumentation-falcon/tests/app.py @@ -8,7 +8,13 @@ class HelloWorldResource: def _handle_request(self, _, resp): # pylint: disable=no-member resp.status = falcon.HTTP_201 - resp.body = "Hello World" + + _parsed_falcon_version = package_version.parse(falcon.__version__) + if _parsed_falcon_version < package_version.parse("3.0.0"): + # Falcon 1 and Falcon 2 + resp.body = "Hello World" + else: + resp.text = "Hello World" def on_get(self, req, resp): self._handle_request(req, resp) @@ -44,6 +50,15 @@ def on_get(self, _, resp): "my-custom-header", "my-custom-value-1,my-custom-header-2" ) resp.set_header("dont-capture-me", "test-value") + resp.set_header( + "my-custom-regex-header-1", + "my-custom-regex-value-1,my-custom-regex-value-2", + ) + resp.set_header( + "My-Custom-Regex-Header-2", + "my-custom-regex-value-3,my-custom-regex-value-4", + ) + resp.set_header("my-secret-header", "my-secret-value") def make_app(): diff --git a/instrumentation/opentelemetry-instrumentation-falcon/tests/test_falcon.py b/instrumentation/opentelemetry-instrumentation-falcon/tests/test_falcon.py --- a/instrumentation/opentelemetry-instrumentation-falcon/tests/test_falcon.py +++ b/instrumentation/opentelemetry-instrumentation-falcon/tests/test_falcon.py @@ -41,6 +41,7 @@ from opentelemetry.test.wsgitestutil import WsgiTestBase from opentelemetry.trace import StatusCode from opentelemetry.util.http import ( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS, OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST, OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE, ) @@ -421,8 +422,9 @@ def test_mark_span_internal_in_presence_of_span_from_other_framework(self): @patch.dict( "os.environ", { - OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,invalid-header", - OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "content-type,content-length,my-custom-header,invalid-header", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS: ".*my-secret.*", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,invalid-header,Regex-Test-Header-.*,Regex-Invalid-Test-Header-.*,.*my-secret.*", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "content-type,content-length,my-custom-header,invalid-header,my-custom-regex-header-.*,invalid-regex-header-.*,.*my-secret.*", }, ) class TestCustomRequestResponseHeaders(TestFalconBase): @@ -431,6 +433,9 @@ def test_custom_request_header_added_in_server_span(self): "Custom-Test-Header-1": "Test Value 1", "Custom-Test-Header-2": "TestValue2,TestValue3", "Custom-Test-Header-3": "TestValue4", + "Regex-Test-Header-1": "Regex Test Value 1", + "regex-test-header-2": "RegexTestValue2,RegexTestValue3", + "My-Secret-Header": "My Secret Value", } self.client().simulate_request( method="GET", path="/hello", headers=headers @@ -443,6 +448,11 @@ def test_custom_request_header_added_in_server_span(self): "http.request.header.custom_test_header_2": ( "TestValue2,TestValue3", ), + "http.request.header.regex_test_header_1": ("Regex Test Value 1",), + "http.request.header.regex_test_header_2": ( + "RegexTestValue2,RegexTestValue3", + ), + "http.request.header.my_secret_header": ("[REDACTED]",), } not_expected = { "http.request.header.custom_test_header_3": ("TestValue4",), @@ -459,6 +469,9 @@ def test_custom_request_header_not_added_in_internal_span(self): headers = { "Custom-Test-Header-1": "Test Value 1", "Custom-Test-Header-2": "TestValue2,TestValue3", + "Regex-Test-Header-1": "Regex Test Value 1", + "regex-test-header-2": "RegexTestValue2,RegexTestValue3", + "My-Secret-Header": "My Secret Value", } self.client().simulate_request( method="GET", path="/hello", headers=headers @@ -470,6 +483,13 @@ def test_custom_request_header_not_added_in_internal_span(self): "http.request.header.custom_test_header_2": ( "TestValue2,TestValue3", ), + "http.request.header.regex_test_header_1": ( + "Regex Test Value 1", + ), + "http.request.header.regex_test_header_2": ( + "RegexTestValue2,RegexTestValue3", + ), + "http.request.header.my_secret_header": ("[REDACTED]",), } self.assertEqual(span.kind, trace.SpanKind.INTERNAL) for key, _ in not_expected.items(): @@ -494,6 +514,13 @@ def test_custom_response_header_added_in_server_span(self): "http.response.header.my_custom_header": ( "my-custom-value-1,my-custom-header-2", ), + "http.response.header.my_custom_regex_header_1": ( + "my-custom-regex-value-1,my-custom-regex-value-2", + ), + "http.response.header.my_custom_regex_header_2": ( + "my-custom-regex-value-3,my-custom-regex-value-4", + ), + "http.response.header.my_secret_header": ("[REDACTED]",), } not_expected = { "http.response.header.dont_capture_me": ("test-value",) @@ -524,6 +551,13 @@ def test_custom_response_header_not_added_in_internal_span(self): "http.response.header.my_custom_header": ( "my-custom-value-1,my-custom-header-2", ), + "http.response.header.my_custom_regex_header_1": ( + "my-custom-regex-value-1,my-custom-regex-value-2", + ), + "http.response.header.my_custom_regex_header_2": ( + "my-custom-regex-value-3,my-custom-regex-value-4", + ), + "http.response.header.my_secret_header": ("[REDACTED]",), } self.assertEqual(span.kind, trace.SpanKind.INTERNAL) for key, _ in not_expected.items():
Add more features for adding HTTP request / response headers to spans. I already have https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1172 open for this, and I'll be breaking it in to smaller pieces at @lzchen 's request. **Is your feature request related to a problem?** Currently, you can only provide a list of full HTTP request / response header names to be added to the span. There is also no capacity for header value redaction. **Describe the solution you'd like** It would be nice to be able to specify a regex or "all" to get all headers. Header value redaction is also a must-have for us. **Describe alternatives you've considered** I considered doing this in my application, but it makes more sense to add it here.
2022-10-27T16:48:21
open-telemetry/opentelemetry-python-contrib
1,413
open-telemetry__opentelemetry-python-contrib-1413
[ "1184" ]
ff8852024915f40f83bcf348d23c909c5803b3eb
diff --git a/instrumentation/opentelemetry-instrumentation-flask/src/opentelemetry/instrumentation/flask/__init__.py b/instrumentation/opentelemetry-instrumentation-flask/src/opentelemetry/instrumentation/flask/__init__.py --- a/instrumentation/opentelemetry-instrumentation-flask/src/opentelemetry/instrumentation/flask/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-flask/src/opentelemetry/instrumentation/flask/__init__.py @@ -95,8 +95,9 @@ def hello(): Exclude lists ************* -To exclude certain URLs from being tracked, set the environment variable ``OTEL_PYTHON_FLASK_EXCLUDED_URLS`` -(or ``OTEL_PYTHON_EXCLUDED_URLS`` as fallback) with comma delimited regexes representing which URLs to exclude. +To exclude certain URLs from tracking, set the environment variable ``OTEL_PYTHON_FLASK_EXCLUDED_URLS`` +(or ``OTEL_PYTHON_EXCLUDED_URLS`` to cover all instrumentations) to a string of comma delimited regexes that match the +URLs. For example, @@ -106,7 +107,7 @@ def hello(): will exclude requests such as ``https://site/client/123/info`` and ``https://site/xyz/healthcheck``. -You can also pass the comma delimited regexes to the ``instrument_app`` method directly: +You can also pass comma delimited regexes directly to the ``instrument_app`` method: .. code-block:: python @@ -115,8 +116,15 @@ def hello(): Request/Response hooks ********************** -Utilize request/response hooks to execute custom logic to be performed before/after performing a request. Environ is an instance of WSGIEnvironment (flask.request.environ). -Response_headers is a list of key-value (tuples) representing the response headers returned from the response. +This instrumentation supports request and response hooks. These are functions that get called +right after a span is created for a request and right before the span is finished for the response. + +- The client request hook is called with the internal span and an instance of WSGIEnvironment (flask.request.environ) + when the method ``receive`` is called. +- The client response hook is called with the internal span, the status of the response and a list of key-value (tuples) + representing the response headers returned from the response when the method ``send`` is called. + +For example, .. code-block:: python @@ -130,58 +138,97 @@ def response_hook(span: Span, status: str, response_headers: List): FlaskInstrumentation().instrument(request_hook=request_hook, response_hook=response_hook) -Flask Request object reference: https://flask.palletsprojects.com/en/2.0.x/api/#flask.Request +Flask Request object reference: https://flask.palletsprojects.com/en/2.1.x/api/#flask.Request Capture HTTP request and response headers ***************************************** -You can configure the agent to capture predefined HTTP headers as span attributes, according to the `semantic convention <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers>`_. +You can configure the agent to capture specified HTTP headers as span attributes, according to the +`semantic convention <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers>`_. Request headers *************** -To capture predefined HTTP request headers as span attributes, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST`` -to a comma-separated list of HTTP header names. +To capture HTTP request headers as span attributes, set the environment variable +``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST`` to a comma delimited list of HTTP header names. For example, - :: export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="content-type,custom_request_header" -will extract ``content-type`` and ``custom_request_header`` from request headers and add them as span attributes. +will extract ``content-type`` and ``custom_request_header`` from the request headers and add them as span attributes. + +Request header names in Flask are case-insensitive and ``-`` characters are replaced by ``_``. So, giving the header +name as ``CUStom_Header`` in the environment variable will capture the header named ``custom-header``. + +Regular expressions may also be used to match multiple headers that correspond to the given pattern. For example: +:: -It is recommended that you should give the correct names of the headers to be captured in the environment variable. -Request header names in flask are case insensitive and - characters are replaced by _. So, giving header name as ``CUStom_Header`` in environment variable will be able capture header with name ``custom-header``. + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="Accept.*,X-.*" -The name of the added span attribute will follow the format ``http.request.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ). -The value of the attribute will be single item list containing all the header values. +Would match all request headers that start with ``Accept`` and ``X-``. -Example of the added span attribute, +To capture all request headers, set ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST`` to ``".*"``. +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST=".*" + +The name of the added span attribute will follow the format ``http.request.header.<header_name>`` where ``<header_name>`` +is the normalized HTTP header name (lowercase, with ``-`` replaced by ``_``). The value of the attribute will be a +single item list containing all the header values. + +For example: ``http.request.header.custom_request_header = ["<value1>,<value2>"]`` Response headers **************** -To capture predefined HTTP response headers as span attributes, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`` -to a comma-separated list of HTTP header names. +To capture HTTP response headers as span attributes, set the environment variable +``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`` to a comma delimited list of HTTP header names. For example, - :: export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="content-type,custom_response_header" -will extract ``content-type`` and ``custom_response_header`` from response headers and add them as span attributes. +will extract ``content-type`` and ``custom_response_header`` from the response headers and add them as span attributes. -It is recommended that you should give the correct names of the headers to be captured in the environment variable. -Response header names captured in flask are case insensitive. So, giving header name as ``CUStomHeader`` in environment variable will be able capture header with name ``customheader``. +Response header names in Flask are case-insensitive. So, giving the header name as ``CUStom-Header`` in the environment +variable will capture the header named ``custom-header``. -The name of the added span attribute will follow the format ``http.response.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ). -The value of the attribute will be single item list containing all the header values. +Regular expressions may also be used to match multiple headers that correspond to the given pattern. For example: +:: -Example of the added span attribute, + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="Content.*,X-.*" + +Would match all response headers that start with ``Content`` and ``X-``. + +To capture all response headers, set ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`` to ``".*"``. +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE=".*" + +The name of the added span attribute will follow the format ``http.response.header.<header_name>`` where ``<header_name>`` +is the normalized HTTP header name (lowercase, with ``-`` replaced by ``_``). The value of the attribute will be a +single item list containing all the header values. + +For example: ``http.response.header.custom_response_header = ["<value1>,<value2>"]`` +Sanitizing headers +****************** +In order to prevent storing sensitive data such as personally identifiable information (PII), session keys, passwords, +etc, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS`` +to a comma delimited list of HTTP header names to be sanitized. Regexes may be used, and all header names will be +matched in a case-insensitive manner. + +For example, +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS=".*session.*,set-cookie" + +will replace the value of headers such as ``session-id`` and ``set-cookie`` with ``[REDACTED]`` in the span. + Note: - Environment variable names to capture http headers are still experimental, and thus are subject to change. + The environment variable names used to capture HTTP headers are still experimental, and thus are subject to change. API ---
diff --git a/instrumentation/opentelemetry-instrumentation-flask/tests/base_test.py b/instrumentation/opentelemetry-instrumentation-flask/tests/base_test.py --- a/instrumentation/opentelemetry-instrumentation-flask/tests/base_test.py +++ b/instrumentation/opentelemetry-instrumentation-flask/tests/base_test.py @@ -42,6 +42,13 @@ def _custom_response_headers(): resp.headers[ "my-custom-header" ] = "my-custom-value-1,my-custom-header-2" + resp.headers[ + "my-custom-regex-header-1" + ] = "my-custom-regex-value-1,my-custom-regex-value-2" + resp.headers[ + "My-Custom-Regex-Header-2" + ] = "my-custom-regex-value-3,my-custom-regex-value-4" + resp.headers["my-secret-header"] = "my-secret-value" return resp def _common_initialization(self): diff --git a/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py b/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py --- a/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py +++ b/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py @@ -36,7 +36,12 @@ from opentelemetry.sdk.resources import Resource from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.test.wsgitestutil import WsgiTestBase -from opentelemetry.util.http import get_excluded_urls +from opentelemetry.util.http import ( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS, + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST, + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE, + get_excluded_urls, +) # pylint: disable=import-error from .base_test import InstrumentationTest @@ -558,18 +563,18 @@ def test_mark_span_internal_in_presence_of_span_from_other_framework(self): ) [email protected]( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS: ".*my-secret.*", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3,Regex-Test-Header-.*,Regex-Invalid-Test-Header-.*,.*my-secret.*", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "content-type,content-length,my-custom-header,invalid-header,my-custom-regex-header-.*,invalid-regex-header-.*,.*my-secret.*", + }, +) class TestCustomRequestResponseHeaders(InstrumentationTest, WsgiTestBase): def setUp(self): super().setUp() - self.env_patch = patch.dict( - "os.environ", - { - "OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST": "Custom-Test-Header-1,Custom-Test-Header-2,Custom-Test-Header-3", - "OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE": "content-type,content-length,my-custom-header,invalid-header", - }, - ) - self.env_patch.start() self.app = Flask(__name__) FlaskInstrumentor().instrument_app(self.app) @@ -577,7 +582,6 @@ def setUp(self): def tearDown(self): super().tearDown() - self.env_patch.stop() with self.disable_logging(): FlaskInstrumentor().uninstrument_app(self.app) @@ -585,6 +589,9 @@ def test_custom_request_header_added_in_server_span(self): headers = { "Custom-Test-Header-1": "Test Value 1", "Custom-Test-Header-2": "TestValue2,TestValue3", + "Regex-Test-Header-1": "Regex Test Value 1", + "regex-test-header-2": "RegexTestValue2,RegexTestValue3", + "My-Secret-Header": "My Secret Value", } resp = self.client.get("/hello/123", headers=headers) self.assertEqual(200, resp.status_code) @@ -594,6 +601,11 @@ def test_custom_request_header_added_in_server_span(self): "http.request.header.custom_test_header_2": ( "TestValue2,TestValue3", ), + "http.request.header.regex_test_header_1": ("Regex Test Value 1",), + "http.request.header.regex_test_header_2": ( + "RegexTestValue2,RegexTestValue3", + ), + "http.request.header.my_secret_header": ("[REDACTED]",), } self.assertEqual(span.kind, trace.SpanKind.SERVER) self.assertSpanHasAttributes(span, expected) @@ -604,6 +616,9 @@ def test_custom_request_header_not_added_in_internal_span(self): headers = { "Custom-Test-Header-1": "Test Value 1", "Custom-Test-Header-2": "TestValue2,TestValue3", + "Regex-Test-Header-1": "Regex Test Value 1", + "regex-test-header-2": "RegexTestValue2,RegexTestValue3", + "My-Secret-Header": "My Secret Value", } resp = self.client.get("/hello/123", headers=headers) self.assertEqual(200, resp.status_code) @@ -613,6 +628,13 @@ def test_custom_request_header_not_added_in_internal_span(self): "http.request.header.custom_test_header_2": ( "TestValue2,TestValue3", ), + "http.request.header.regex_test_header_1": ( + "Regex Test Value 1", + ), + "http.request.header.regex_test_header_2": ( + "RegexTestValue2,RegexTestValue3", + ), + "http.request.header.my_secret_header": ("[REDACTED]",), } self.assertEqual(span.kind, trace.SpanKind.INTERNAL) for key, _ in not_expected.items(): @@ -630,6 +652,13 @@ def test_custom_response_header_added_in_server_span(self): "http.response.header.my_custom_header": ( "my-custom-value-1,my-custom-header-2", ), + "http.response.header.my_custom_regex_header_1": ( + "my-custom-regex-value-1,my-custom-regex-value-2", + ), + "http.response.header.my_custom_regex_header_2": ( + "my-custom-regex-value-3,my-custom-regex-value-4", + ), + "http.response.header.my_secret_header": ("[REDACTED]",), } self.assertEqual(span.kind, trace.SpanKind.SERVER) self.assertSpanHasAttributes(span, expected) @@ -648,6 +677,13 @@ def test_custom_response_header_not_added_in_internal_span(self): "http.response.header.my_custom_header": ( "my-custom-value-1,my-custom-header-2", ), + "http.response.header.my_custom_regex_header_1": ( + "my-custom-regex-value-1,my-custom-regex-value-2", + ), + "http.response.header.my_custom_regex_header_2": ( + "my-custom-regex-value-3,my-custom-regex-value-4", + ), + "http.response.header.my_secret_header": ("[REDACTED]",), } self.assertEqual(span.kind, trace.SpanKind.INTERNAL) for key, _ in not_expected.items():
Add more features for adding HTTP request / response headers to spans. I already have https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1172 open for this, and I'll be breaking it in to smaller pieces at @lzchen 's request. **Is your feature request related to a problem?** Currently, you can only provide a list of full HTTP request / response header names to be added to the span. There is also no capacity for header value redaction. **Describe the solution you'd like** It would be nice to be able to specify a regex or "all" to get all headers. Header value redaction is also a must-have for us. **Describe alternatives you've considered** I considered doing this in my application, but it makes more sense to add it here.
2022-10-27T16:50:19
open-telemetry/opentelemetry-python-contrib
1,414
open-telemetry__opentelemetry-python-contrib-1414
[ "1184" ]
4383551135b01a7a4eb38b2dd8fe9ecd20566f03
diff --git a/instrumentation/opentelemetry-instrumentation-pyramid/src/opentelemetry/instrumentation/pyramid/__init__.py b/instrumentation/opentelemetry-instrumentation-pyramid/src/opentelemetry/instrumentation/pyramid/__init__.py --- a/instrumentation/opentelemetry-instrumentation-pyramid/src/opentelemetry/instrumentation/pyramid/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-pyramid/src/opentelemetry/instrumentation/pyramid/__init__.py @@ -55,7 +55,7 @@ --------------------------------- If you use Method 2 and then set tweens for your application with the ``pyramid.tweens`` setting, -you need to add ``opentelemetry.instrumentation.pyramid.trace_tween_factory`` explicitly to the list, +you need to explicitly add ``opentelemetry.instrumentation.pyramid.trace_tween_factory`` to the list, *as well as* instrumenting the config as shown above. For example: @@ -79,8 +79,9 @@ Exclude lists ************* -To exclude certain URLs from being tracked, set the environment variable ``OTEL_PYTHON_PYRAMID_EXCLUDED_URLS`` -(or ``OTEL_PYTHON_EXCLUDED_URLS`` as fallback) with comma delimited regexes representing which URLs to exclude. +To exclude certain URLs from tracking, set the environment variable ``OTEL_PYTHON_PYRAMID_EXCLUDED_URLS`` +(or ``OTEL_PYTHON_EXCLUDED_URLS`` to cover all instrumentations) to a string of comma delimited regexes that match the +URLs. For example, @@ -92,54 +93,93 @@ Capture HTTP request and response headers ***************************************** -You can configure the agent to capture predefined HTTP headers as span attributes, according to the `semantic convention <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers>`_. +You can configure the agent to capture specified HTTP headers as span attributes, according to the +`semantic convention <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers>`_. Request headers *************** -To capture predefined HTTP request headers as span attributes, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST`` -to a comma-separated list of HTTP header names. +To capture HTTP request headers as span attributes, set the environment variable +``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST`` to a comma delimited list of HTTP header names. For example, - :: export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="content-type,custom_request_header" -will extract ``content-type`` and ``custom_request_header`` from request headers and add them as span attributes. +will extract ``content-type`` and ``custom_request_header`` from the request headers and add them as span attributes. + +Request header names in Pyramid are case-insensitive and ``-`` characters are replaced by ``_``. So, giving the header +name as ``CUStom_Header`` in the environment variable will capture the header named ``custom-header``. + +Regular expressions may also be used to match multiple headers that correspond to the given pattern. For example: +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="Accept.*,X-.*" + +Would match all request headers that start with ``Accept`` and ``X-``. -It is recommended that you should give the correct names of the headers to be captured in the environment variable. -Request header names in pyramid are case insensitive and - characters are replaced by _. So, giving header name as ``CUStom_Header`` in environment variable will be able capture header with name ``custom-header``. +To capture all request headers, set ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST`` to ``".*"``. +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST=".*" -The name of the added span attribute will follow the format ``http.request.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ). -The value of the attribute will be single item list containing all the header values. +The name of the added span attribute will follow the format ``http.request.header.<header_name>`` where ``<header_name>`` +is the normalized HTTP header name (lowercase, with ``-`` replaced by ``_``). The value of the attribute will be a +single item list containing all the header values. -Example of the added span attribute, +For example: ``http.request.header.custom_request_header = ["<value1>,<value2>"]`` Response headers **************** -To capture predefined HTTP response headers as span attributes, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`` -to a comma-separated list of HTTP header names. +To capture HTTP response headers as span attributes, set the environment variable +``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`` to a comma delimited list of HTTP header names. For example, - :: export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="content-type,custom_response_header" -will extract ``content-type`` and ``custom_response_header`` from response headers and add them as span attributes. +will extract ``content-type`` and ``custom_response_header`` from the response headers and add them as span attributes. + +Response header names in Pyramid are case-insensitive. So, giving the header name as ``CUStom-Header`` in the environment +variable will capture the header named ``custom-header``. + +Regular expressions may also be used to match multiple headers that correspond to the given pattern. For example: +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="Content.*,X-.*" + +Would match all response headers that start with ``Content`` and ``X-``. -It is recommended that you should give the correct names of the headers to be captured in the environment variable. -Response header names captured in pyramid are case insensitive. So, giving header name as ``CUStomHeader`` in environment variable will be able capture header with name ``customheader``. +To capture all response headers, set ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`` to ``".*"``. +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE=".*" -The name of the added span attribute will follow the format ``http.response.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ). -The value of the attribute will be single item list containing all the header values. +The name of the added span attribute will follow the format ``http.response.header.<header_name>`` where ``<header_name>`` +is the normalized HTTP header name (lowercase, with ``-`` replaced by ``_``). The value of the attribute will be a +single item list containing all the header values. -Example of the added span attribute, +For example: ``http.response.header.custom_response_header = ["<value1>,<value2>"]`` +Sanitizing headers +****************** +In order to prevent storing sensitive data such as personally identifiable information (PII), session keys, passwords, +etc, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS`` +to a comma delimited list of HTTP header names to be sanitized. Regexes may be used, and all header names will be +matched in a case-insensitive manner. + +For example, +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS=".*session.*,set-cookie" + +will replace the value of headers such as ``session-id`` and ``set-cookie`` with ``[REDACTED]`` in the span. + Note: - Environment variable names to capture http headers are still experimental, and thus are subject to change. + The environment variable names used to capture HTTP headers are still experimental, and thus are subject to change. API ---
diff --git a/instrumentation/opentelemetry-instrumentation-pyramid/tests/pyramid_base_test.py b/instrumentation/opentelemetry-instrumentation-pyramid/tests/pyramid_base_test.py --- a/instrumentation/opentelemetry-instrumentation-pyramid/tests/pyramid_base_test.py +++ b/instrumentation/opentelemetry-instrumentation-pyramid/tests/pyramid_base_test.py @@ -40,6 +40,9 @@ def _custom_response_header_endpoint(request): "content-type": "text/plain; charset=utf-8", "content-length": "7", "my-custom-header": "my-custom-value-1,my-custom-header-2", + "my-custom-regex-header-1": "my-custom-regex-value-1,my-custom-regex-value-2", + "My-Custom-Regex-Header-2": "my-custom-regex-value-3,my-custom-regex-value-4", + "my-secret-header": "my-secret-value", "dont-capture-me": "test-value", } return Response("Testing", headers=headers) diff --git a/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_automatic.py b/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_automatic.py --- a/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_automatic.py +++ b/instrumentation/opentelemetry-instrumentation-pyramid/tests/test_automatic.py @@ -28,6 +28,7 @@ from opentelemetry.trace import SpanKind from opentelemetry.trace.status import StatusCode from opentelemetry.util.http import ( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS, OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST, OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE, _active_requests_count_attrs, @@ -285,24 +286,23 @@ def test_with_existing_span(self): ) [email protected]( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS: ".*my-secret.*", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,invalid-header,Regex-Test-Header-.*,Regex-Invalid-Test-Header-.*,.*my-secret.*", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "content-type,content-length,my-custom-header,invalid-header,my-custom-regex-header-.*,invalid-regex-header-.*,.*my-secret.*", + }, +) class TestCustomRequestResponseHeaders(InstrumentationTest, WsgiTestBase): def setUp(self): super().setUp() PyramidInstrumentor().instrument() self.config = Configurator() self._common_initialization(self.config) - self.env_patch = patch.dict( - "os.environ", - { - OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,invalid-header", - OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "content-type,content-length,my-custom-header,invalid-header", - }, - ) - self.env_patch.start() def tearDown(self) -> None: super().tearDown() - self.env_patch.stop() with self.disable_logging(): PyramidInstrumentor().uninstrument() @@ -311,6 +311,9 @@ def test_custom_request_header_added_in_server_span(self): "Custom-Test-Header-1": "Test Value 1", "Custom-Test-Header-2": "TestValue2,TestValue3", "Custom-Test-Header-3": "TestValue4", + "Regex-Test-Header-1": "Regex Test Value 1", + "regex-test-header-2": "RegexTestValue2,RegexTestValue3", + "My-Secret-Header": "My Secret Value", } resp = self.client.get("/hello/123", headers=headers) self.assertEqual(200, resp.status_code) @@ -320,6 +323,11 @@ def test_custom_request_header_added_in_server_span(self): "http.request.header.custom_test_header_2": ( "TestValue2,TestValue3", ), + "http.request.header.regex_test_header_1": ("Regex Test Value 1",), + "http.request.header.regex_test_header_2": ( + "RegexTestValue2,RegexTestValue3", + ), + "http.request.header.my_secret_header": ("[REDACTED]",), } not_expected = { "http.request.header.custom_test_header_3": ("TestValue4",), @@ -361,6 +369,13 @@ def test_custom_response_header_added_in_server_span(self): "http.response.header.my_custom_header": ( "my-custom-value-1,my-custom-header-2", ), + "http.response.header.my_custom_regex_header_1": ( + "my-custom-regex-value-1,my-custom-regex-value-2", + ), + "http.response.header.my_custom_regex_header_2": ( + "my-custom-regex-value-3,my-custom-regex-value-4", + ), + "http.response.header.my_secret_header": ("[REDACTED]",), } not_expected = { "http.response.header.dont_capture_me": ("test-value",) @@ -390,6 +405,14 @@ def test_custom_response_header_not_added_in_internal_span(self): self.assertNotIn(key, span.attributes) [email protected]( + "os.environ", + { + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS: ".*my-secret.*", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,invalid-header,Regex-Test-Header-.*,Regex-Invalid-Test-Header-.*,.*my-secret.*", + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "content-type,content-length,my-custom-header,invalid-header,my-custom-regex-header-.*,invalid-regex-header-.*,.*my-secret.*", + }, +) class TestCustomHeadersNonRecordingSpan(InstrumentationTest, WsgiTestBase): def setUp(self): super().setUp() @@ -401,18 +424,9 @@ def setUp(self): PyramidInstrumentor().instrument() self.config = Configurator() self._common_initialization(self.config) - self.env_patch = patch.dict( - "os.environ", - { - OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST: "Custom-Test-Header-1,Custom-Test-Header-2,invalid-header", - OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE: "content-type,content-length,my-custom-header,invalid-header", - }, - ) - self.env_patch.start() def tearDown(self) -> None: super().tearDown() - self.env_patch.stop() with self.disable_logging(): PyramidInstrumentor().uninstrument()
Add more features for adding HTTP request / response headers to spans. I already have https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1172 open for this, and I'll be breaking it in to smaller pieces at @lzchen 's request. **Is your feature request related to a problem?** Currently, you can only provide a list of full HTTP request / response header names to be added to the span. There is also no capacity for header value redaction. **Describe the solution you'd like** It would be nice to be able to specify a regex or "all" to get all headers. Header value redaction is also a must-have for us. **Describe alternatives you've considered** I considered doing this in my application, but it makes more sense to add it here.
2022-10-27T16:53:37
open-telemetry/opentelemetry-python-contrib
1,424
open-telemetry__opentelemetry-python-contrib-1424
[ "1353" ]
f994e1463645d6e5fbd617fc534cbbf70f4383ef
diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py b/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py --- a/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py @@ -79,6 +79,9 @@ def trace_integration( tracer_provider: The :class:`opentelemetry.trace.TracerProvider` to use. If omitted the current configured one is used. capture_parameters: Configure if db.statement.parameters should be captured. + enable_commenter: Flag to enable/disable sqlcommenter. + db_api_integration_factory: The `DatabaseApiIntegration` to use. If none is passed the + default one is used. """ wrap_connect( __name__, @@ -121,6 +124,8 @@ def wrap_connect( use. If omitted the current configured one is used. capture_parameters: Configure if db.statement.parameters should be captured. enable_commenter: Flag to enable/disable sqlcommenter. + db_api_integration_factory: The `DatabaseApiIntegration` to use. If none is passed the + default one is used. commenter_options: Configurations for tags to be appended at the sql query. """ @@ -197,7 +202,7 @@ def instrument_connection( Returns: An instrumented connection. """ - if isinstance(connection, wrapt.ObjectProxy): + if isinstance(connection, _TracedConnectionProxy): _logger.warning("Connection already instrumented") return connection @@ -331,6 +336,14 @@ def __getattr__(self, name): object.__getattribute__(self, "_connection"), name ) + def __getattribute__(self, name): + if object.__getattribute__(self, name): + return object.__getattribute__(self, name) + + return object.__getattribute__( + object.__getattribute__(self, "_connection"), name + ) + def cursor(self, *args, **kwargs): return get_traced_cursor_proxy( self._connection.cursor(*args, **kwargs), db_api_integration
diff --git a/tests/opentelemetry-docker-tests/tests/pymysql/test_pymysql_functional.py b/tests/opentelemetry-docker-tests/tests/pymysql/test_pymysql_functional.py --- a/tests/opentelemetry-docker-tests/tests/pymysql/test_pymysql_functional.py +++ b/tests/opentelemetry-docker-tests/tests/pymysql/test_pymysql_functional.py @@ -109,3 +109,19 @@ def test_callproc(self): ): self._cursor.callproc("test", ()) self.validate_spans("test") + + def test_commit(self): + stmt = "INSERT INTO test (id) VALUES (%s)" + with self._tracer.start_as_current_span("rootSpan"): + data = (("4",), ("5",), ("6",)) + self._cursor.executemany(stmt, data) + self._connection.commit() + self.validate_spans("INSERT") + + def test_rollback(self): + stmt = "INSERT INTO test (id) VALUES (%s)" + with self._tracer.start_as_current_span("rootSpan"): + data = (("7",), ("8",), ("9",)) + self._cursor.executemany(stmt, data) + self._connection.rollback() + self.validate_spans("INSERT")
conn.commit() raise InterfaceError because connection instrument wrapper has no _sock member **Describe your environment** Describe any aspect of your environment relevant to the problem, including your Python version, [platform](https://docs.python.org/3/library/platform.html), version numbers of installed dependencies, information about your cloud hosting provider, etc. If you're reporting a problem with a specific version of a library in this repo, please check whether the problem has been fixed on main. instrumentation version: opentelemetry-instrumentation-pymysql 0.33b0 **Steps to reproduce** When using `opentelemetry-instrument` command to automatically instrument pymysql ``` conn = pymysql.connect(...) with conn.cursor() as cursor: cursor.execute(...) # run any insert statement conn.commit() # this line will trigger InterfaceError ``` Current bandaid solution: ``` conn = pymysql.connect(...) conn._sock = conn._connection._sock # add this line to work around with conn.cursor() as cursor: cursor.execute(...) conn.commit() # this line will no longer trigger InterfaceError ``` Tracing down the stack will show that on line 792 of the `pymysql/connections/.py`, the Exception will be thrown because self now refers to the wrapper instead of the internal connection object: ``` def _execute_command(self, command, sql): """ :raise InterfaceError: If the connection is closed. :raise ValueError: If no username was specified. """ if not self._sock: raise err.InterfaceError(0, "") ... ``` If I do not instrument pymysql then this will not happen.
@ocelotl I'm having this same issue and it appears to be caused by https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1097 This may also be the cause of #1213 Also, should this be changed? ``` diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py b/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py index 0645d4c5..8bca74dd 100644 --- a/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py @@ -197,7 +197,7 @@ def instrument_connection( Returns: An instrumented connection. """ - if isinstance(connection, wrapt.ObjectProxy): + if isinstance(connection, _TracedConnectionProxy): _logger.warning("Connection already instrumented") return connection ``` PyMySQL specific ```python # file: PyMySQL/pymysql/connections.py class Connection:     # ...     # class attribute     _sock = None     # ...     def __init__(self):         # ...         # instance attribute     # self._sock assigned to new socket by self.connect()     # ... ``` _sock is a class attribute, also an instance attribute, which is used by the method connection.commit and connection.close and others Before #1097 ```python # file: opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py class TracedConnectionProxy(wrapt.ObjectProxy):     def __init__(self, connection, *args, **kwargs):         wrapt.ObjectProxy.__init__(self, connection) ``` accessing self._sock via wrapt.ObjectProxy to the underlying **instance attribute connection._sock**, which is good. After #1097 ```python class TracedConnectionProxy(type(connection), _TracedConnectionProxy):     def __init__(self, connection):         self._connection = connection ``` self._sock is the **class attribute Connection._sock** (by inheriting type(connection)), which is bad, because Connection._sock is None @srikanthccv Any thoughts here? Will look into this, thanks for reporting :v: @ocelotl Would be great if the fix could make it in to the next release. I (and I'm sure many others) am blocked from upgrading until this is fixed.
2022-10-31T16:31:34
open-telemetry/opentelemetry-python-contrib
1,427
open-telemetry__opentelemetry-python-contrib-1427
[ "1395" ]
7acc336ccac3df54b70452577365f8fcdfc80276
diff --git a/instrumentation/opentelemetry-instrumentation-redis/src/opentelemetry/instrumentation/redis/util.py b/instrumentation/opentelemetry-instrumentation-redis/src/opentelemetry/instrumentation/redis/util.py --- a/instrumentation/opentelemetry-instrumentation-redis/src/opentelemetry/instrumentation/redis/util.py +++ b/instrumentation/opentelemetry-instrumentation-redis/src/opentelemetry/instrumentation/redis/util.py @@ -28,7 +28,6 @@ def _extract_conn_attributes(conn_kwargs): SpanAttributes.DB_SYSTEM: DbSystemValues.REDIS.value, } db = conn_kwargs.get("db", 0) - attributes[SpanAttributes.DB_NAME] = db attributes[SpanAttributes.DB_REDIS_DATABASE_INDEX] = db try: attributes[SpanAttributes.NET_PEER_NAME] = conn_kwargs.get(
diff --git a/tests/opentelemetry-docker-tests/tests/redis/test_redis_functional.py b/tests/opentelemetry-docker-tests/tests/redis/test_redis_functional.py --- a/tests/opentelemetry-docker-tests/tests/redis/test_redis_functional.py +++ b/tests/opentelemetry-docker-tests/tests/redis/test_redis_functional.py @@ -37,7 +37,9 @@ def tearDown(self): def _check_span(self, span, name): self.assertEqual(span.name, name) self.assertIs(span.status.status_code, trace.StatusCode.UNSET) - self.assertEqual(span.attributes.get(SpanAttributes.DB_NAME), 0) + self.assertEqual( + span.attributes.get(SpanAttributes.DB_REDIS_DATABASE_INDEX), 0 + ) self.assertEqual( span.attributes[SpanAttributes.NET_PEER_NAME], "localhost" ) @@ -209,7 +211,9 @@ def tearDown(self): def _check_span(self, span, name): self.assertEqual(span.name, name) self.assertIs(span.status.status_code, trace.StatusCode.UNSET) - self.assertEqual(span.attributes.get(SpanAttributes.DB_NAME), 0) + self.assertEqual( + span.attributes.get(SpanAttributes.DB_REDIS_DATABASE_INDEX), 0 + ) self.assertEqual( span.attributes[SpanAttributes.NET_PEER_NAME], "localhost" )
[opentelemetry-instrumentation-redis] Stop sending db.name argument or rename it to redis[0-15] Hi! I've been recently playing with OpenTelemetry for Python (Flask) application and noticed that for Redis **db.name** argument is send to OpenTelemetry collector which seems to be a number of database (integer). This seems to be incorrect as in Redis there is no db name concept (databases are numbered from 0 to 15). Technically, it shouldn't be any problem with that but it may break some OpenTelemetry backends which expects a real DB name not a number. I have done some additional debugging and found that for node.js and .NET **db.name** argument is not send to collector. Shouldn't we have some consistency here? **Describe your environment** $ python --version Python 3.8.13 $ $ pip list | grep 'opentelemetry\|redis' opentelemetry-api 1.13.0 opentelemetry-distro 0.34b0 opentelemetry-exporter-otlp 1.13.0 opentelemetry-exporter-otlp-proto-grpc 1.13.0 opentelemetry-exporter-otlp-proto-http 1.13.0 opentelemetry-instrumentation 0.34b0 opentelemetry-instrumentation-aws-lambda 0.34b0 opentelemetry-instrumentation-dbapi 0.34b0 opentelemetry-instrumentation-flask 0.34b0 opentelemetry-instrumentation-grpc 0.34b0 opentelemetry-instrumentation-jinja2 0.34b0 opentelemetry-instrumentation-logging 0.34b0 opentelemetry-instrumentation-redis 0.34b0 opentelemetry-instrumentation-requests 0.34b0 opentelemetry-instrumentation-sqlite3 0.34b0 opentelemetry-instrumentation-urllib 0.34b0 opentelemetry-instrumentation-urllib3 0.34b0 opentelemetry-instrumentation-wsgi 0.34b0 opentelemetry-propagator-aws-xray 1.0.1 opentelemetry-proto 1.13.0 opentelemetry-sdk 1.13.0 opentelemetry-semantic-conventions 0.34b0 opentelemetry-util-http 0.34b0 redis 4.3.4 **Steps to reproduce** Any Python app with connection to Redis will show this behavior. **What is the expected behavior?** Stop sending db.name argument or rename it to redis[0-15] **What is the actual behavior?** The db.name argument is send as a number of Redis database. **Additional context** Please see below some logs from OpenTelemetry collector for python and node.js to see a difference. ===> PYTHON EXAMPLE ScopeSpans #0 ScopeSpans SchemaURL: InstrumentationScope opentelemetry.instrumentation.redis 0.34b0 Span #0 Trace ID : 4bc10b43ab0a0d3042f38ebbb32baef1 Parent ID : 79e2aed933827894 ID : 22f4fba607e73a33 Name : HMSET Kind : SPAN_KIND_CLIENT Start time : 2022-10-21 09:40:50.606962566 +0000 UTC End time : 2022-10-21 09:40:50.609568624 +0000 UTC Status code : STATUS_CODE_UNSET Status message : Attributes: -> db.statement: STRING(HMSET person1-hash name jane age 20) -> db.system: STRING(redis) -> db.name: INT(0) -> db.redis.database_index: INT(0) -> net.peer.name: STRING(redis-svc) -> net.peer.port: STRING(6379) -> net.transport: STRING(ip_tcp) -> db.redis.args_length: INT(6) ===> NODEJS EXAMPLE ScopeSpans #0 ScopeSpans SchemaURL: InstrumentationScope @opentelemetry/instrumentation-redis-4 0.33.0 Span #0 Trace ID : 21a071f4d1d7c860ecb758398d304f60 Parent ID : 1bbf5328c079ceda ID : 13dc47b2521f7f82 Name : redis-GET Kind : SPAN_KIND_CLIENT Start time : 2022-10-21 09:47:16.9553723 +0000 UTC End time : 2022-10-21 09:47:16.957585 +0000 UTC Status code : STATUS_CODE_UNSET Status message : Attributes: -> db.system: STRING(redis) -> net.peer.name: STRING(redis-svc) -> net.peer.port: INT(6379) -> db.statement: STRING(GET) ResourceSpans #4 Resource SchemaURL: Resource labels: -> service.name: STRING(nodejs-redis) -> telemetry.sdk.language: STRING(nodejs) -> telemetry.sdk.name: STRING(opentelemetry) -> telemetry.sdk.version: STRING(0.24.0) I am happy to contribute to it by reviewing the code fix and testing the behavior. @svrnm @sanketmehta28
I guess the best way to provide this information is through `db.redis.database_index` than `db.name`. Feel free to send a pull request. Yes @luke6Lh43. This makes sense. I have verified the behavior and while instrumenting the redis, it tries to fetch the "db" attribute from connection_pool object and in case of its absence (which is true in case of redis), it will by default set to '0'. AFAIK this is not the right behavior (as reflected in jode js or .net agents). You should create a PR and send it for review. Thank you @sanketmehta28 and @srikanthccv for your comments! I will start working on it in upcoming days :)
2022-11-02T11:20:52
open-telemetry/opentelemetry-python-contrib
1,435
open-telemetry__opentelemetry-python-contrib-1435
[ "1487" ]
43d0c6cae377b2c7bc230f431c347a73034b441a
diff --git a/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py b/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py --- a/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py @@ -260,7 +260,8 @@ def get( return decoded def keys(self, carrier: dict) -> typing.List[str]: - return [_key.decode("utf8") for (_key, _value) in carrier] + headers = carrier.get("headers") or [] + return [_key.decode("utf8") for (_key, _value) in headers] asgi_getter = ASGIGetter()
diff --git a/instrumentation/opentelemetry-instrumentation-asgi/tests/test_getter.py b/instrumentation/opentelemetry-instrumentation-asgi/tests/test_getter.py --- a/instrumentation/opentelemetry-instrumentation-asgi/tests/test_getter.py +++ b/instrumentation/opentelemetry-instrumentation-asgi/tests/test_getter.py @@ -18,12 +18,18 @@ class TestASGIGetter(TestCase): - def test_get_none(self): + def test_get_none_empty_carrier(self): getter = ASGIGetter() carrier = {} val = getter.get(carrier, "test") self.assertIsNone(val) + def test_get_none_empty_headers(self): + getter = ASGIGetter() + carrier = {"headers": []} + val = getter.get(carrier, "test") + self.assertIsNone(val) + def test_get_(self): getter = ASGIGetter() carrier = {"headers": [(b"test-key", b"val")]} @@ -44,7 +50,22 @@ def test_get_(self): "Should be case insensitive", ) - def test_keys(self): + def test_keys_empty_carrier(self): getter = ASGIGetter() keys = getter.keys({}) self.assertEqual(keys, []) + + def test_keys_empty_headers(self): + getter = ASGIGetter() + keys = getter.keys({"headers": []}) + self.assertEqual(keys, []) + + def test_keys(self): + getter = ASGIGetter() + carrier = {"headers": [(b"test-key", b"val")]} + expected_val = ["test-key"] + self.assertEqual( + getter.keys(carrier), + expected_val, + "Should be equal", + )
ASGI Instrumentation ValueError: too many values to unpack (expected 2) during JaegerPropagator **Describe your environment** - python:3.11-slim docker image - OTEL ```bash opentelemetry-api 1.14.0 opentelemetry-exporter-jaeger-thrift 1.14.0 opentelemetry-instrumentation 0.35b0 opentelemetry-instrumentation-asgi 0.35b0 opentelemetry-instrumentation-fastapi 0.35b0 opentelemetry-propagator-jaeger 1.14.0 opentelemetry-sdk 1.14.0 opentelemetry-semantic-conventions 0.35b0 opentelemetry-util-http 0.35b0 ``` **Steps to reproduce** 1. Setup an upstream application that previously create the jaeger header during the original request(example: Traefik) 2. Set up JaegerPropagator and Instrumentation on FastAPI example Traefik config ``` traefik: image: traefik:2.6 restart: always command: --api.dashboard=true --providers.docker=true --providers.docker.exposedbydefault=false --entrypoints.web.address=:80 --entrypoints.web.http.redirections.entryPoint.to=websecure --entrypoints.web.http.redirections.entryPoint.scheme=https --entrypoints.websecure.address=:443 --accesslog=true --tracing.jaeger=true --tracing.jaeger.gen128Bit=true --tracing.jaeger.samplingServerURL=http://jaeger:5778/sampling --tracing.jaeger.samplingType=const --tracing.jaeger.samplingParam=1.0 --tracing.jaeger.localAgentHostPort=jaeger:6831 ports: - 80:80 - 443:443 volumes: - /var/run/docker.sock:/var/run/docker.sock:ro labels: - traefik.enable=true - traefik.http.routers.dashboard.rule=Host(`traefik.docker.localhost`) && (PathPrefix(`/api/`) || PathPrefix(`/dashboard/`)) - traefik.http.routers.dashboard.tls=true - traefik.http.routers.dashboard.service=api@internal svc: build: context: . command: tail -f /dev/null restart: always volumes: - .:/usr/src environment: - SQLALCHEMY_DEBUG_ECHO=true - OTEL_RESOURCE_ATTRIBUTES=service.name=svc - OTEL_EXPORTER_JAEGER_AGENT_HOST=jaeger - OTEL_EXPORTER_JAEGER_AGENT_PORT=6831 - OTEL_TRACES_SAMPLER=parentbased_always_on # - OTEL_TRACES_SAMPLER=parentbased_traceidratio # - OTEL_TRACES_SAMPLER_ARG=1.0 - OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST=x-forwarded-for,x-real-ip expose: - 80 labels: - traefik.enable=true - traefik.http.routers.svc.rule=Host(`api.docker.localhost`) && PathPrefix(`/`) - traefik.http.routers.svc.tls=true healthcheck: test: ["CMD", "curl", "-f", "http://localhost/health"] interval: 10s timeout: 10s retries: 3 start_period: 10s ``` ```python import fastapi from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor from opentelemetry import trace from opentelemetry.exporter.jaeger.thrift import JaegerExporter from opentelemetry.propagate import set_global_textmap from opentelemetry.propagators.jaeger import JaegerPropagator from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor set_global_textmap(JaegerPropagator()) provider = TracerProvider() span_processor = BatchSpanProcessor(JaegerExporter()) provider.add_span_processor(span_processor) trace.set_tracer_provider(provider) app = fastapi.FastAPI() @app.get("/health") async def health(): return {"message": "hello world"} FastAPIInstrumentor.instrument_app(app) ``` **What is the expected behavior?** If the tracing already propagates with the Jaeger header(example from Traefik as the reverse proxy and with tracing enabled), we should still have the trace propagated successfully in FastAPI Instrumentation. **What is the actual behavior?** now even with default swagger pages, it will have exceptions on opening. ofc, I have reverse proxy both API and Documents. - any request coming with the Jaeger header will have issues as below - any request that does not have a previous jaeger header will still be fine (because the asgi getter will have no issue with processing empty headers) ```python INFO: 172.20.0.7:55510 - "GET /docs HTTP/1.1" 500 Internal Server Error ERROR: Exception in ASGI application Traceback (most recent call last): File "/home/ssp-py-sdk/.local/lib/python3.11/site-packages/uvicorn/protocols/http/httptools_impl.py", line 419, in run_asgi result = await app( # type: ignore[func-returns-value] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ssp-py-sdk/.local/lib/python3.11/site-packages/uvicorn/middleware/proxy_headers.py", line 78, in __call__ return await self.app(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ssp-py-sdk/.local/lib/python3.11/site-packages/fastapi/applications.py", line 270, in __call__ await super().__call__(scope, receive, send) File "/home/ssp-py-sdk/.local/lib/python3.11/site-packages/starlette/applications.py", line 124, in __call__ await self.middleware_stack(scope, receive, send) File "/home/ssp-py-sdk/.local/lib/python3.11/site-packages/starlette/middleware/errors.py", line 184, in __call__ raise exc File "/home/ssp-py-sdk/.local/lib/python3.11/site-packages/starlette/middleware/errors.py", line 162, in __call__ await self.app(scope, receive, _send) File "/home/ssp-py-sdk/.local/lib/python3.11/site-packages/opentelemetry/instrumentation/asgi/__init__.py", line 531, in __call__ span, token = _start_internal_or_server_span( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ssp-py-sdk/.local/lib/python3.11/site-packages/opentelemetry/instrumentation/utils.py", line 111, in _start_internal_or_server_span ctx = extract(context_carrier, getter=context_getter) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ssp-py-sdk/.local/lib/python3.11/site-packages/opentelemetry/propagate/__init__.py", line 102, in extract return get_global_textmap().extract(carrier, context, getter=getter) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ssp-py-sdk/.local/lib/python3.11/site-packages/opentelemetry/propagators/jaeger/__init__.py", line 54, in extract context = self._extract_baggage(getter, carrier, context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ssp-py-sdk/.local/lib/python3.11/site-packages/opentelemetry/propagators/jaeger/__init__.py", line 119, in _extract_baggage for key in getter.keys(carrier) ^^^^^^^^^^^^^^^^^^^^ File "/home/ssp-py-sdk/.local/lib/python3.11/site-packages/opentelemetry/instrumentation/asgi/__init__.py", line 263, in keys return [_key.decode("utf8") for (_key, _value) in carrier] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ssp-py-sdk/.local/lib/python3.11/site-packages/opentelemetry/instrumentation/asgi/__init__.py", line 263, in <listcomp> return [_key.decode("utf8") for (_key, _value) in carrier] ^^^^^^^^^^^^^^ ``` **Additional context** I believe the issue from this specific line https://github.com/open-telemetry/opentelemetry-python-contrib/blob/main/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py#L263, and I can confirm the older version 0.34b0 with this impl https://github.com/open-telemetry/opentelemetry-python-contrib/blob/v0.34b0/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py#L217 have no issue.
2022-11-10T13:10:46
open-telemetry/opentelemetry-python-contrib
1,439
open-telemetry__opentelemetry-python-contrib-1439
[ "1438" ]
b701980ab8044e2f4c55607e3fc2c0a3cd2c2288
diff --git a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/instrumentor.py b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/instrumentor.py --- a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/instrumentor.py +++ b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/instrumentor.py @@ -47,7 +47,7 @@ class BaseInstrumentor(ABC): def __new__(cls, *args, **kwargs): if cls._instance is None: - cls._instance = object.__new__(cls, *args, **kwargs) + cls._instance = object.__new__(cls) return cls._instance
diff --git a/instrumentation/opentelemetry-instrumentation-system-metrics/tests/test_system_metrics.py b/instrumentation/opentelemetry-instrumentation-system-metrics/tests/test_system_metrics.py --- a/instrumentation/opentelemetry-instrumentation-system-metrics/tests/test_system_metrics.py +++ b/instrumentation/opentelemetry-instrumentation-system-metrics/tests/test_system_metrics.py @@ -61,11 +61,31 @@ def setUp(self): ) self._patch_net_connections.start() + # Reset the singleton class on each test run + SystemMetricsInstrumentor._instance = None + def tearDown(self): super().tearDown() self._patch_net_connections.stop() SystemMetricsInstrumentor().uninstrument() + def test_system_metrics_instrumentor_initialization(self): + try: + SystemMetricsInstrumentor() + SystemMetricsInstrumentor(config={}) + except Exception as error: # pylint: disable=broad-except + self.fail(f"Unexpected exception {error} raised") + + SystemMetricsInstrumentor._instance = None + + try: + SystemMetricsInstrumentor(config={}) + SystemMetricsInstrumentor() + except Exception as error: # pylint: disable=broad-except + self.fail(f"Unexpected exception {error} raised") + + SystemMetricsInstrumentor().instrument() + def test_system_metrics_instrument(self): reader = InMemoryMetricReader() meter_provider = MeterProvider(metric_readers=[reader]) @@ -103,6 +123,35 @@ def test_system_metrics_instrument(self): self.assertIn(observer, observer_names) observer_names.remove(observer) + def test_runtime_metrics_instrument(self): + runtime_config = { + "runtime.memory": ["rss", "vms"], + "runtime.cpu.time": ["user", "system"], + "runtime.gc_count": None, + } + + reader = InMemoryMetricReader() + meter_provider = MeterProvider(metric_readers=[reader]) + runtime_metrics = SystemMetricsInstrumentor(config=runtime_config) + runtime_metrics.instrument(meter_provider=meter_provider) + + metric_names = [] + for resource_metrics in reader.get_metrics_data().resource_metrics: + for scope_metrics in resource_metrics.scope_metrics: + for metric in scope_metrics.metrics: + metric_names.append(metric.name) + self.assertEqual(len(metric_names), 3) + + observer_names = [ + f"runtime.{self.implementation}.memory", + f"runtime.{self.implementation}.cpu_time", + f"runtime.{self.implementation}.gc_count", + ] + + for observer in metric_names: + self.assertIn(observer, observer_names) + observer_names.remove(observer) + def _assert_metrics(self, observer_name, reader, expected): assertions = 0 # pylint: disable=too-many-nested-blocks
System metrics instrumentation not working with custom defined configuration System metric instrumentation is not functional if configuration on which metrics to be exported is explicitly provided. As a minimal example, this code ```python from opentelemetry.metrics import set_meter_provider from opentelemetry.instrumentation.system_metrics import SystemMetricsInstrumentor from opentelemetry.sdk.metrics import MeterProvider from opentelemetry.sdk.metrics.export import ( ConsoleMetricExporter, PeriodicExportingMetricReader, ) exporter = ConsoleMetricExporter() set_meter_provider(MeterProvider([PeriodicExportingMetricReader(exporter)])) configuration = { "runtime.memory": ["rss", "vms"], "runtime.cpu.time": ["user", "system"], } SystemMetricsInstrumentor(config=configuration).instrument() ``` results in ``` Traceback (most recent call last): File ".../test.py", line 15, in <module> SystemMetricsInstrumentor(config=configuration).instrument() File ".../lib/python3.10/site-packages/opentelemetry/instrumentation/instrumentor.py", line 51, in __new__ cls._instance = object.__new__(cls, *args, **kwargs) TypeError: object.__new__() takes exactly one argument (the type to instantiate) ``` I am happy to look into fixing this. Removing `*args` and `**kwargs` in `opentelemetry/instrumentation/instrumentor.py:51` actually solves the issue here but I'd like to understand the implications as this implies changing the interface class.
2022-11-11T22:30:22
open-telemetry/opentelemetry-python-contrib
1,440
open-telemetry__opentelemetry-python-contrib-1440
[ "1368" ]
99e0b426350ab74cadb5fcb4c9504dee12e73773
diff --git a/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/__init__.py b/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/__init__.py --- a/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/__init__.py @@ -136,11 +136,16 @@ def _instrument(self, **kwargs): An instrumented engine if passed in as an argument or list of instrumented engines, None otherwise. """ tracer_provider = kwargs.get("tracer_provider") - _w("sqlalchemy", "create_engine", _wrap_create_engine(tracer_provider)) + enable_commenter = kwargs.get("enable_commenter", False) + _w( + "sqlalchemy", + "create_engine", + _wrap_create_engine(tracer_provider, enable_commenter), + ) _w( "sqlalchemy.engine", "create_engine", - _wrap_create_engine(tracer_provider), + _wrap_create_engine(tracer_provider, enable_commenter), ) _w( "sqlalchemy.engine.base", @@ -151,7 +156,7 @@ def _instrument(self, **kwargs): _w( "sqlalchemy.ext.asyncio", "create_async_engine", - _wrap_create_async_engine(tracer_provider), + _wrap_create_async_engine(tracer_provider, enable_commenter), ) if kwargs.get("engine") is not None: return EngineTracer( diff --git a/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/engine.py b/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/engine.py --- a/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/engine.py +++ b/instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/engine.py @@ -49,27 +49,29 @@ def _get_tracer(tracer_provider=None): ) -def _wrap_create_async_engine(tracer_provider=None): +def _wrap_create_async_engine(tracer_provider=None, enable_commenter=False): # pylint: disable=unused-argument def _wrap_create_async_engine_internal(func, module, args, kwargs): """Trace the SQLAlchemy engine, creating an `EngineTracer` object that will listen to SQLAlchemy events. """ engine = func(*args, **kwargs) - EngineTracer(_get_tracer(tracer_provider), engine.sync_engine) + EngineTracer( + _get_tracer(tracer_provider), engine.sync_engine, enable_commenter + ) return engine return _wrap_create_async_engine_internal -def _wrap_create_engine(tracer_provider=None): +def _wrap_create_engine(tracer_provider=None, enable_commenter=False): # pylint: disable=unused-argument def _wrap_create_engine_internal(func, module, args, kwargs): """Trace the SQLAlchemy engine, creating an `EngineTracer` object that will listen to SQLAlchemy events. """ engine = func(*args, **kwargs) - EngineTracer(_get_tracer(tracer_provider), engine) + EngineTracer(_get_tracer(tracer_provider), engine, enable_commenter) return engine return _wrap_create_engine_internal @@ -94,7 +96,7 @@ def _wrap_connect_internal(func, module, args, kwargs): class EngineTracer: def __init__( - self, tracer, engine, enable_commenter=True, commenter_options=None + self, tracer, engine, enable_commenter=False, commenter_options=None ): self.tracer = tracer self.engine = engine
diff --git a/instrumentation/opentelemetry-instrumentation-sqlalchemy/tests/test_sqlcommenter.py b/instrumentation/opentelemetry-instrumentation-sqlalchemy/tests/test_sqlcommenter.py --- a/instrumentation/opentelemetry-instrumentation-sqlalchemy/tests/test_sqlcommenter.py +++ b/instrumentation/opentelemetry-instrumentation-sqlalchemy/tests/test_sqlcommenter.py @@ -77,3 +77,30 @@ def test_sqlcommenter_flask_integration(self): self.caplog.records[-2].getMessage(), r"SELECT 1 /\*db_driver='(.*)',flask=1,traceparent='\d{1,2}-[a-zA-Z0-9_]{32}-[a-zA-Z0-9_]{16}-\d{1,2}'\*/;", ) + + def test_sqlcommenter_enabled_create_engine_after_instrumentation(self): + SQLAlchemyInstrumentor().instrument( + tracer_provider=self.tracer_provider, + enable_commenter=True, + ) + from sqlalchemy import create_engine # pylint: disable-all + + engine = create_engine("sqlite:///:memory:") + cnx = engine.connect() + cnx.execute("SELECT 1;").fetchall() + self.assertRegex( + self.caplog.records[-2].getMessage(), + r"SELECT 1 /\*db_driver='(.*)',traceparent='\d{1,2}-[a-zA-Z0-9_]{32}-[a-zA-Z0-9_]{16}-\d{1,2}'\*/;", + ) + + def test_sqlcommenter_disabled_create_engine_after_instrumentation(self): + SQLAlchemyInstrumentor().instrument( + tracer_provider=self.tracer_provider, + enable_commenter=False, + ) + from sqlalchemy import create_engine # pylint: disable-all + + engine = create_engine("sqlite:///:memory:") + cnx = engine.connect() + cnx.execute("SELECT 1;").fetchall() + self.assertEqual(self.caplog.records[-2].getMessage(), "SELECT 1;")
SQLAlchemy Instrumentation: `enable_commenter` can't be disabled. Based on the [documentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/sqlalchemy/sqlalchemy.html#usage), you'd assume that: ```python SQLAlchemyInstrumentor().instrument(enable_commenter=False) ``` Would enable instrumentation but disable the statement commenter, but it doesn't work. It looks like you can't disable the sql commenter unless you are providing the `engine` keyword as well, which requires you to have already created the engine at that point in your code path. It looks like the `enable_commenter` and related kwargs need to be passed to the `_wrap_create_engine` function?
>It looks like the enable_commenter and related kwargs need to be passed to the _wrap_create_engine function? Correct, and pass it to `EngineTracer` which enables commenter by default. hi, can you assign this to me? thanks :)
2022-11-13T15:30:48
open-telemetry/opentelemetry-python-contrib
1,460
open-telemetry__opentelemetry-python-contrib-1460
[ "1459" ]
be4ceec08cb1b3097d7aa25c4efc358ddd050bdb
diff --git a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py --- a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py +++ b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py @@ -81,7 +81,7 @@ "instrumentation": "opentelemetry-instrumentation-grpc==0.36b0.dev", }, "httpx": { - "library": "httpx >= 0.18.0", + "library": "httpx >= 0.18.0, <= 0.23.0", "instrumentation": "opentelemetry-instrumentation-httpx==0.36b0.dev", }, "jinja2": {
httpx tests failing on httpx==0.23.1
2022-11-18T14:35:49
open-telemetry/opentelemetry-python-contrib
1,510
open-telemetry__opentelemetry-python-contrib-1510
[ "1503" ]
5af3519f369e5cfa8d9a8928572b9d7bdcadf297
diff --git a/instrumentation/opentelemetry-instrumentation-urllib/src/opentelemetry/instrumentation/urllib/__init__.py b/instrumentation/opentelemetry-instrumentation-urllib/src/opentelemetry/instrumentation/urllib/__init__.py --- a/instrumentation/opentelemetry-instrumentation-urllib/src/opentelemetry/instrumentation/urllib/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-urllib/src/opentelemetry/instrumentation/urllib/__init__.py @@ -12,14 +12,12 @@ # See the License for the specific language governing permissions and # limitations under the License. - """ This library allows tracing HTTP requests made by the -`urllib https://docs.python.org/3/library/urllib.html>`_ library. +`urllib <https://docs.python.org/3/library/urllib>`_ library. Usage ----- - .. code-block:: python from urllib import request @@ -43,7 +41,7 @@ right after a Span is created for a request and right before the span is finished processing a response respectively. The hooks can be configured as follows: -..code:: python +.. code:: python # `request_obj` is an instance of urllib.request.Request def request_hook(span, request_obj):
Add readthedocs documentation for urlib instrumentation Part of [1491](https://github.com/open-telemetry/opentelemetry-python-contrib/issues/1491)
2022-12-20T14:07:15
open-telemetry/opentelemetry-python-contrib
1,512
open-telemetry__opentelemetry-python-contrib-1512
[ "1462" ]
e1a1bada1f717d739b17e8734da169ca3dcbc025
diff --git a/instrumentation/opentelemetry-instrumentation-pymongo/src/opentelemetry/instrumentation/pymongo/__init__.py b/instrumentation/opentelemetry-instrumentation-pymongo/src/opentelemetry/instrumentation/pymongo/__init__.py --- a/instrumentation/opentelemetry-instrumentation-pymongo/src/opentelemetry/instrumentation/pymongo/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-pymongo/src/opentelemetry/instrumentation/pymongo/__init__.py @@ -46,6 +46,7 @@ failed_hook (Callable) - a function with extra user-defined logic to be performed after the query returns with a failed response this function signature is: def failed_hook(span: Span, event: CommandFailedEvent) -> None +capture_statement (bool) - an optional value to enable capturing the database statement that is being executed for example: @@ -81,6 +82,9 @@ def failed_hook(span, event): from opentelemetry import context from opentelemetry.instrumentation.instrumentor import BaseInstrumentor from opentelemetry.instrumentation.pymongo.package import _instruments +from opentelemetry.instrumentation.pymongo.utils import ( + COMMAND_TO_ATTRIBUTE_MAPPING, +) from opentelemetry.instrumentation.pymongo.version import __version__ from opentelemetry.instrumentation.utils import _SUPPRESS_INSTRUMENTATION_KEY from opentelemetry.semconv.trace import DbSystemValues, SpanAttributes @@ -106,6 +110,7 @@ def __init__( request_hook: RequestHookT = dummy_callback, response_hook: ResponseHookT = dummy_callback, failed_hook: FailedHookT = dummy_callback, + capture_statement: bool = False, ): self._tracer = tracer self._span_dict = {} @@ -113,6 +118,7 @@ def __init__( self.start_hook = request_hook self.success_hook = response_hook self.failed_hook = failed_hook + self.capture_statement = capture_statement def started(self, event: monitoring.CommandStartedEvent): """Method to handle a pymongo CommandStartedEvent""" @@ -120,16 +126,13 @@ def started(self, event: monitoring.CommandStartedEvent): _SUPPRESS_INSTRUMENTATION_KEY ): return - command = event.command.get(event.command_name, "") - name = event.database_name - name += "." + event.command_name - statement = event.command_name - if command: - statement += " " + str(command) + command_name = event.command_name + span_name = f"{event.database_name}.{command_name}" + statement = self._get_statement_by_command_name(command_name, event) collection = event.command.get(event.command_name) try: - span = self._tracer.start_span(name, kind=SpanKind.CLIENT) + span = self._tracer.start_span(span_name, kind=SpanKind.CLIENT) if span.is_recording(): span.set_attribute( SpanAttributes.DB_SYSTEM, DbSystemValues.MONGODB.value @@ -196,6 +199,14 @@ def failed(self, event: monitoring.CommandFailedEvent): def _pop_span(self, event): return self._span_dict.pop(_get_span_dict_key(event), None) + def _get_statement_by_command_name(self, command_name, event): + statement = command_name + command_attribute = COMMAND_TO_ATTRIBUTE_MAPPING.get(command_name) + command = event.command.get(command_attribute) + if command and self.capture_statement: + statement += " " + str(command) + return statement + def _get_span_dict_key(event): if event.connection_id is not None: @@ -228,6 +239,7 @@ def _instrument(self, **kwargs): request_hook = kwargs.get("request_hook", dummy_callback) response_hook = kwargs.get("response_hook", dummy_callback) failed_hook = kwargs.get("failed_hook", dummy_callback) + capture_statement = kwargs.get("capture_statement") # Create and register a CommandTracer only the first time if self._commandtracer_instance is None: tracer = get_tracer(__name__, __version__, tracer_provider) @@ -237,6 +249,7 @@ def _instrument(self, **kwargs): request_hook=request_hook, response_hook=response_hook, failed_hook=failed_hook, + capture_statement=capture_statement, ) monitoring.register(self._commandtracer_instance) # If already created, just enable it diff --git a/instrumentation/opentelemetry-instrumentation-pymongo/src/opentelemetry/instrumentation/pymongo/utils.py b/instrumentation/opentelemetry-instrumentation-pymongo/src/opentelemetry/instrumentation/pymongo/utils.py new file mode 100644 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-pymongo/src/opentelemetry/instrumentation/pymongo/utils.py @@ -0,0 +1,20 @@ +# Copyright The OpenTelemetry Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +COMMAND_TO_ATTRIBUTE_MAPPING = { + "insert": "documents", + "delete": "deletes", + "update": "updates", + "find": "filter", +}
diff --git a/instrumentation/opentelemetry-instrumentation-pymongo/tests/test_pymongo.py b/instrumentation/opentelemetry-instrumentation-pymongo/tests/test_pymongo.py --- a/instrumentation/opentelemetry-instrumentation-pymongo/tests/test_pymongo.py +++ b/instrumentation/opentelemetry-instrumentation-pymongo/tests/test_pymongo.py @@ -64,7 +64,7 @@ def test_started(self): span.attributes[SpanAttributes.DB_NAME], "database_name" ) self.assertEqual( - span.attributes[SpanAttributes.DB_STATEMENT], "command_name find" + span.attributes[SpanAttributes.DB_STATEMENT], "command_name" ) self.assertEqual( span.attributes[SpanAttributes.NET_PEER_NAME], "test.com" diff --git a/tests/opentelemetry-docker-tests/tests/pymongo/test_pymongo_functional.py b/tests/opentelemetry-docker-tests/tests/pymongo/test_pymongo_functional.py --- a/tests/opentelemetry-docker-tests/tests/pymongo/test_pymongo_functional.py +++ b/tests/opentelemetry-docker-tests/tests/pymongo/test_pymongo_functional.py @@ -34,6 +34,7 @@ def setUp(self): self.instrumentor = PymongoInstrumentor() self.instrumentor.instrument() self.instrumentor._commandtracer_instance._tracer = self._tracer + self.instrumentor._commandtracer_instance.capture_statement = True client = MongoClient( MONGODB_HOST, MONGODB_PORT, serverSelectionTimeoutMS=2000 ) @@ -44,7 +45,7 @@ def tearDown(self): self.instrumentor.uninstrument() super().tearDown() - def validate_spans(self): + def validate_spans(self, expected_db_statement): spans = self.memory_exporter.get_finished_spans() self.assertEqual(len(spans), 2) for span in spans: @@ -72,14 +73,24 @@ def validate_spans(self): pymongo_span.attributes[SpanAttributes.DB_MONGODB_COLLECTION], MONGODB_COLLECTION_NAME, ) + self.assertEqual( + pymongo_span.attributes[SpanAttributes.DB_STATEMENT], + expected_db_statement, + ) def test_insert(self): """Should create a child span for insert""" with self._tracer.start_as_current_span("rootSpan"): - self._collection.insert_one( + insert_result = self._collection.insert_one( {"name": "testName", "value": "testValue"} ) - self.validate_spans() + insert_result_id = insert_result.inserted_id + + expected_db_statement = ( + f"insert [{{'name': 'testName', 'value': 'testValue', '_id': " + f"ObjectId('{insert_result_id}')}}]" + ) + self.validate_spans(expected_db_statement) def test_update(self): """Should create a child span for update""" @@ -87,19 +98,40 @@ def test_update(self): self._collection.update_one( {"name": "testName"}, {"$set": {"value": "someOtherValue"}} ) - self.validate_spans() + + expected_db_statement = ( + "update [SON([('q', {'name': 'testName'}), ('u', " + "{'$set': {'value': 'someOtherValue'}}), ('multi', False), ('upsert', False)])]" + ) + self.validate_spans(expected_db_statement) def test_find(self): """Should create a child span for find""" with self._tracer.start_as_current_span("rootSpan"): - self._collection.find_one() - self.validate_spans() + self._collection.find_one({"name": "testName"}) + + expected_db_statement = "find {'name': 'testName'}" + self.validate_spans(expected_db_statement) def test_delete(self): """Should create a child span for delete""" with self._tracer.start_as_current_span("rootSpan"): self._collection.delete_one({"name": "testName"}) - self.validate_spans() + + expected_db_statement = ( + "delete [SON([('q', {'name': 'testName'}), ('limit', 1)])]" + ) + self.validate_spans(expected_db_statement) + + def test_find_without_capture_statement(self): + """Should create a child span for find""" + self.instrumentor._commandtracer_instance.capture_statement = False + + with self._tracer.start_as_current_span("rootSpan"): + self._collection.find_one({"name": "testName"}) + + expected_db_statement = "find" + self.validate_spans(expected_db_statement) def test_uninstrument(self): # check that integration is working
mongo DB instrumentation doesn't capture `db.statement` properly According to the [specs](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/database.md#call-level-attributes) - `db.statement` should capture the entire request, and not only the command name. **Steps to reproduce** Instrument a client using PymongoInstrumentor. Send a request to the db. **What is the expected behavior?** Produce a span with a `db.statement` value containing the whole request. **What is the actual behavior?** Produce a span with `db.statement` containing only the request name. **Additional context** Another discussion [here](https://github.com/open-telemetry/opentelemetry-specification/issues/2907) Another thing that needs to be fixed is adding the ability to hide the `db.statement` value on demand, in order to hide sensitive data when needed. If you can, assign this to me - I would like to solve it :)
2022-12-20T15:44:24
open-telemetry/opentelemetry-python-contrib
1,515
open-telemetry__opentelemetry-python-contrib-1515
[ "1500" ]
9fbb1febfeee57f8694271563aa248fb7d884c98
diff --git a/instrumentation/opentelemetry-instrumentation-remoulade/src/opentelemetry/instrumentation/remoulade/__init__.py b/instrumentation/opentelemetry-instrumentation-remoulade/src/opentelemetry/instrumentation/remoulade/__init__.py --- a/instrumentation/opentelemetry-instrumentation-remoulade/src/opentelemetry/instrumentation/remoulade/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-remoulade/src/opentelemetry/instrumentation/remoulade/__init__.py @@ -16,13 +16,13 @@ Usage ----- -* Start broker backend +Start broker backend :: docker run -p 5672:5672 rabbitmq -* Run instrumented actor +Run instrumented actor .. code-block:: python
Add readthedocs documentation for remoulade instrumentation Part of [1491](https://github.com/open-telemetry/opentelemetry-python-contrib/issues/1491)
2022-12-21T09:28:01
open-telemetry/opentelemetry-python-contrib
1,534
open-telemetry__opentelemetry-python-contrib-1534
[ "1494" ]
f38eeb73df6a6f572f4bb894976b18a8af44d22c
diff --git a/instrumentation/opentelemetry-instrumentation-aws-lambda/src/opentelemetry/instrumentation/aws_lambda/__init__.py b/instrumentation/opentelemetry-instrumentation-aws-lambda/src/opentelemetry/instrumentation/aws_lambda/__init__.py --- a/instrumentation/opentelemetry-instrumentation-aws-lambda/src/opentelemetry/instrumentation/aws_lambda/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-aws-lambda/src/opentelemetry/instrumentation/aws_lambda/__init__.py @@ -13,7 +13,7 @@ # limitations under the License. """ -The opentelemetry-instrumentation-aws-lambda package provides an `Instrumentor` +The opentelemetry-instrumentation-aws-lambda package provides an Instrumentor to traces calls within a Python AWS Lambda function. Usage @@ -27,7 +27,6 @@ from opentelemetry.instrumentation.botocore import AwsBotocoreInstrumentor from opentelemetry.instrumentation.aws_lambda import AwsLambdaInstrumentor - # Enable instrumentation AwsBotocoreInstrumentor().instrument() AwsLambdaInstrumentor().instrument() @@ -47,8 +46,8 @@ def lambda_handler(event, context): tracer_provider (TracerProvider) - an optional tracer provider event_context_extractor (Callable) - a function that returns an OTel Trace - Context given the Lambda Event the AWS Lambda was invoked with - this function signature is: def event_context_extractor(lambda_event: Any) -> Context +Context given the Lambda Event the AWS Lambda was invoked with +this function signature is: def event_context_extractor(lambda_event: Any) -> Context for example: .. code:: python @@ -63,7 +62,10 @@ def custom_event_context_extractor(lambda_event): AwsLambdaInstrumentor().instrument( event_context_extractor=custom_event_context_extractor ) + +--- """ + import logging import os from importlib import import_module
Add readthedocs documentation for aws lambda instrumentation Part of [1491](https://github.com/open-telemetry/opentelemetry-python-contrib/issues/1491)
2022-12-25T10:39:05
open-telemetry/opentelemetry-python-contrib
1,540
open-telemetry__opentelemetry-python-contrib-1540
[ "1499" ]
426d6415908b6fb2a763abc0b50b72e42de3dea3
diff --git a/instrumentation/opentelemetry-instrumentation-pika/src/opentelemetry/instrumentation/pika/__init__.py b/instrumentation/opentelemetry-instrumentation-pika/src/opentelemetry/instrumentation/pika/__init__.py --- a/instrumentation/opentelemetry-instrumentation-pika/src/opentelemetry/instrumentation/pika/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-pika/src/opentelemetry/instrumentation/pika/__init__.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. """ -Instrument `pika` to trace RabbitMQ applications. +Instrument pika to trace RabbitMQ applications. Usage ----- @@ -63,7 +63,7 @@ PikaInstrumentor.instrument_channel(channel, tracer_provider=tracer_provider) * PikaInstrumentor also supports instrumenting with hooks that will be called when producing or consuming a message. - The hooks should be of type `Callable[[Span, bytes, BasicProperties], None]` + The hooks should be of type "Callable[[Span, bytes, BasicProperties], None]" where the first parameter is the span, the second parameter is the message body and the third parameter is the message properties
Add readthedocs documentation for pika instrumentation Part of [1491](https://github.com/open-telemetry/opentelemetry-python-contrib/issues/1491)
2022-12-26T14:26:18
open-telemetry/opentelemetry-python-contrib
1,541
open-telemetry__opentelemetry-python-contrib-1541
[ "1502" ]
abaa26381e587c7f795e6cc63db736731551a97d
diff --git a/instrumentation/opentelemetry-instrumentation-tortoiseorm/src/opentelemetry/instrumentation/tortoiseorm/__init__.py b/instrumentation/opentelemetry-instrumentation-tortoiseorm/src/opentelemetry/instrumentation/tortoiseorm/__init__.py --- a/instrumentation/opentelemetry-instrumentation-tortoiseorm/src/opentelemetry/instrumentation/tortoiseorm/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-tortoiseorm/src/opentelemetry/instrumentation/tortoiseorm/__init__.py @@ -13,7 +13,7 @@ # limitations under the License. """ -Instrument `tortoise-orm`_ to report SQL queries. +Instrument tortoise-orm to report SQL queries. Usage -----
Add readthedocs documentation tortoiseorm instrumentation Part of [1491](https://github.com/open-telemetry/opentelemetry-python-contrib/issues/1491)
2022-12-27T08:17:52
open-telemetry/opentelemetry-python-contrib
1,542
open-telemetry__opentelemetry-python-contrib-1542
[ "1497" ]
1f0dda9865b3c83e6dea2f2b127a2b0971853543
diff --git a/instrumentation/opentelemetry-instrumentation-elasticsearch/src/opentelemetry/instrumentation/elasticsearch/__init__.py b/instrumentation/opentelemetry-instrumentation-elasticsearch/src/opentelemetry/instrumentation/elasticsearch/__init__.py --- a/instrumentation/opentelemetry-instrumentation-elasticsearch/src/opentelemetry/instrumentation/elasticsearch/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-elasticsearch/src/opentelemetry/instrumentation/elasticsearch/__init__.py @@ -34,7 +34,7 @@ es.get(index='my-index', doc_type='my-type', id=1) Elasticsearch instrumentation prefixes operation names with the string "Elasticsearch". This -can be changed to a different string by either setting the `OTEL_PYTHON_ELASTICSEARCH_NAME_PREFIX` +can be changed to a different string by either setting the OTEL_PYTHON_ELASTICSEARCH_NAME_PREFIX environment variable or by passing the prefix as an argument to the instrumentor. For example, @@ -42,16 +42,15 @@ ElasticsearchInstrumentor("my-custom-prefix").instrument() - -The `instrument` method accepts the following keyword args: - +The instrument() method accepts the following keyword args: tracer_provider (TracerProvider) - an optional tracer provider request_hook (Callable) - a function with extra user-defined logic to be performed before performing the request - this function signature is: - def request_hook(span: Span, method: str, url: str, kwargs) +this function signature is: +def request_hook(span: Span, method: str, url: str, kwargs) + response_hook (Callable) - a function with extra user-defined logic to be performed after performing the request - this function signature is: - def response_hook(span: Span, response: dict) +this function signature is: +def response_hook(span: Span, response: dict) for example:
Add readthedocs documentation for elasticsearch instrumentation Part of [1491](https://github.com/open-telemetry/opentelemetry-python-contrib/issues/1491)
2022-12-27T09:14:35
open-telemetry/opentelemetry-python-contrib
1,552
open-telemetry__opentelemetry-python-contrib-1552
[ "1498" ]
3dc2f8ee30d7641345c747095849ae55f4834ef1
diff --git a/instrumentation/opentelemetry-instrumentation-kafka-python/src/opentelemetry/instrumentation/kafka/__init__.py b/instrumentation/opentelemetry-instrumentation-kafka-python/src/opentelemetry/instrumentation/kafka/__init__.py --- a/instrumentation/opentelemetry-instrumentation-kafka-python/src/opentelemetry/instrumentation/kafka/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-kafka-python/src/opentelemetry/instrumentation/kafka/__init__.py @@ -13,7 +13,7 @@ # limitations under the License. """ -Instrument `kafka-python` to report instrumentation-kafka produced and consumed messages +Instrument kafka-python to report instrumentation-kafka produced and consumed messages Usage ----- @@ -30,24 +30,21 @@ producer = KafkaProducer(bootstrap_servers=['localhost:9092']) producer.send('my-topic', b'raw_bytes') - # report a span of type consumer with the default settings - consumer = KafkaConsumer('my-topic', - group_id='my-group', - bootstrap_servers=['localhost:9092']) + consumer = KafkaConsumer('my-topic', group_id='my-group', bootstrap_servers=['localhost:9092']) for message in consumer: - # process message + # process message -The `_instrument` method accepts the following keyword args: +The _instrument() method accepts the following keyword args: tracer_provider (TracerProvider) - an optional tracer provider produce_hook (Callable) - a function with extra user-defined logic to be performed before sending the message - this function signature is: - def produce_hook(span: Span, args, kwargs) +this function signature is: +def produce_hook(span: Span, args, kwargs) consume_hook (Callable) - a function with extra user-defined logic to be performed after consuming a message - this function signature is: - def consume - _hook(span: Span, record: kafka.record.ABCRecord, args, kwargs) +this function signature is: +def consume_hook(span: Span, record: kafka.record.ABCRecord, args, kwargs) for example: + .. code: python from opentelemetry.instrumentation.kafka import KafkaInstrumentor from kafka import KafkaProducer, KafkaConsumer
Add readthedocs documentation for kafka python instrumentation Part of [1491](https://github.com/open-telemetry/opentelemetry-python-contrib/issues/1491)
2022-12-28T06:46:14