From b3965d09fa323db392e6505256e450d5c1f21d7b Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Tue, 14 Nov 2023 00:11:50 -0600 Subject: [PATCH 01/12] Clean up use of suppress_instrumentation in context and fix httpx bug --- .../pyproject.toml | 1 + .../instrumentation/aio_pika/utils.py | 9 --------- .../instrumentation/httpx/__init__.py | 6 +++--- .../instrumentation/pika/utils.py | 6 ++---- .../opentelemetry/instrumentation/utils.py | 20 +++++++++++++++++-- 5 files changed, 24 insertions(+), 18 deletions(-) delete mode 100644 instrumentation/opentelemetry-instrumentation-aio-pika/src/opentelemetry/instrumentation/aio_pika/utils.py diff --git a/instrumentation/opentelemetry-instrumentation-aio-pika/pyproject.toml b/instrumentation/opentelemetry-instrumentation-aio-pika/pyproject.toml index 237c812215..067fe05551 100644 --- a/instrumentation/opentelemetry-instrumentation-aio-pika/pyproject.toml +++ b/instrumentation/opentelemetry-instrumentation-aio-pika/pyproject.toml @@ -26,6 +26,7 @@ classifiers = [ ] dependencies = [ "opentelemetry-api ~= 1.5", + "opentelemetry-instrumentation == 0.42b0.dev", "wrapt >= 1.0.0, < 2.0.0", ] diff --git a/instrumentation/opentelemetry-instrumentation-aio-pika/src/opentelemetry/instrumentation/aio_pika/utils.py b/instrumentation/opentelemetry-instrumentation-aio-pika/src/opentelemetry/instrumentation/aio_pika/utils.py deleted file mode 100644 index fb94ddf468..0000000000 --- a/instrumentation/opentelemetry-instrumentation-aio-pika/src/opentelemetry/instrumentation/aio_pika/utils.py +++ /dev/null @@ -1,9 +0,0 @@ -from opentelemetry import context - - -def is_instrumentation_enabled() -> bool: - if context.get_value("suppress_instrumentation") or context.get_value( - context._SUPPRESS_INSTRUMENTATION_KEY - ): - return False - return True diff --git a/instrumentation/opentelemetry-instrumentation-httpx/src/opentelemetry/instrumentation/httpx/__init__.py b/instrumentation/opentelemetry-instrumentation-httpx/src/opentelemetry/instrumentation/httpx/__init__.py index 53542e7ef3..ecee204fc8 100644 --- a/instrumentation/opentelemetry-instrumentation-httpx/src/opentelemetry/instrumentation/httpx/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-httpx/src/opentelemetry/instrumentation/httpx/__init__.py @@ -200,7 +200,7 @@ async def async_response_hook(span, request, response): from opentelemetry.instrumentation.httpx.package import _instruments from opentelemetry.instrumentation.httpx.version import __version__ from opentelemetry.instrumentation.instrumentor import BaseInstrumentor -from opentelemetry.instrumentation.utils import http_status_to_status_code +from opentelemetry.instrumentation.utils import http_status_to_status_code, is_http_instrumentation_enabled from opentelemetry.propagate import inject from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.trace import SpanKind, TracerProvider, get_tracer @@ -347,7 +347,7 @@ def handle_request( httpx.Response, ]: """Add request info to span.""" - if context.get_value("suppress_instrumentation"): + if not is_http_instrumentation_enabled(): return self._transport.handle_request(*args, **kwargs) method, url, headers, stream, extensions = _extract_parameters( @@ -440,7 +440,7 @@ async def handle_async_request( httpx.Response, ]: """Add request info to span.""" - if context.get_value("suppress_instrumentation"): + if not is_http_instrumentation_enabled(): return await self._transport.handle_async_request(*args, **kwargs) method, url, headers, stream, extensions = _extract_parameters( diff --git a/instrumentation/opentelemetry-instrumentation-pika/src/opentelemetry/instrumentation/pika/utils.py b/instrumentation/opentelemetry-instrumentation-pika/src/opentelemetry/instrumentation/pika/utils.py index 881149dbac..6dab4fdfa9 100644 --- a/instrumentation/opentelemetry-instrumentation-pika/src/opentelemetry/instrumentation/pika/utils.py +++ b/instrumentation/opentelemetry-instrumentation-pika/src/opentelemetry/instrumentation/pika/utils.py @@ -5,7 +5,7 @@ from pika.spec import Basic, BasicProperties from opentelemetry import context, propagate, trace -from opentelemetry.instrumentation.utils import _SUPPRESS_INSTRUMENTATION_KEY +from opentelemetry.instrumentation.utils import is_instrumentation_enabled from opentelemetry.propagators.textmap import CarrierT, Getter from opentelemetry.semconv.trace import ( MessagingOperationValues, @@ -135,9 +135,7 @@ def _get_span( span_kind: SpanKind, operation: Optional[MessagingOperationValues] = None, ) -> Optional[Span]: - if context.get_value("suppress_instrumentation") or context.get_value( - _SUPPRESS_INSTRUMENTATION_KEY - ): + if not is_instrumentation_enabled(): return None task_name = properties.type if properties.type else task_name span = tracer.start_span( diff --git a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/utils.py b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/utils.py index 35a55a1279..72e1c13f5e 100644 --- a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/utils.py +++ b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/utils.py @@ -20,9 +20,7 @@ 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 from opentelemetry.trace.propagation.tracecontext import ( @@ -152,3 +150,21 @@ def _python_path_without_directory(python_path, directory, path_separator): "", python_path, ) + + +def is_instrumentation_enabled() -> bool: + if ( + context.get_value("suppress_instrumentation") + or + context.get_value(context._SUPPRESS_INSTRUMENTATION_KEY) # type: ignore + ): + return False + return True + + +def is_http_instrumentation_enabled() -> bool: + return ( + is_http_instrumentation_enabled() + and not + context.get_value(context._SUPPRESS_HTTP_INSTRUMENTATION_KEY) # type: ignore + ) From f45a3a858c1d627e078c751911111f7ce4137512 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Tue, 14 Nov 2023 09:18:32 -0600 Subject: [PATCH 02/12] Clean up use of suppress_instrumentation in context and fix httpx bug --- .../aiohttp_client/__init__.py | 6 +-- .../tests/test_aiohttp_client_integration.py | 16 ++----- .../instrumentation/boto3sqs/__init__.py | 6 +-- .../instrumentation/botocore/__init__.py | 36 ++++++--------- .../tests/test_botocore_instrumentation.py | 19 ++------ .../instrumentation/cassandra/__init__.py | 9 +--- .../tests/test_cassandra_integration.py | 24 ++-------- .../tests/test_programmatic.py | 6 +-- .../instrumentation/grpc/_aio_client.py | 10 ++-- .../instrumentation/grpc/_client.py | 6 +-- .../tests/test_aio_client_interceptor.py | 30 ++---------- .../tests/test_client_interceptor.py | 30 ++---------- .../tests/test_client_interceptor_filter.py | 30 ++---------- .../instrumentation/httpx/__init__.py | 6 +-- .../instrumentation/pymongo/__init__.py | 14 ++---- .../tests/test_pymongo.py | 10 +--- .../instrumentation/requests/__init__.py | 38 +++++++-------- .../tests/test_requests_integration.py | 23 +++------- .../instrumentation/urllib/__init__.py | 32 +++++-------- .../tests/test_urllib_integration.py | 24 +++------- .../instrumentation/urllib3/__init__.py | 29 ++---------- .../tests/test_urllib3_integration.py | 21 ++++----- .../instrumentation/wsgi/__init__.py | 4 +- .../tests/test_wsgi_middleware.py | 14 ++---- .../opentelemetry/instrumentation/utils.py | 46 +++++++++++++++---- 25 files changed, 168 insertions(+), 321 deletions(-) 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 index ef3b667c98..9f842bde79 100644 --- 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 @@ -94,8 +94,8 @@ def response_hook(span: Span, params: typing.Union[ from opentelemetry.instrumentation.aiohttp_client.version import __version__ from opentelemetry.instrumentation.instrumentor import BaseInstrumentor from opentelemetry.instrumentation.utils import ( - _SUPPRESS_INSTRUMENTATION_KEY, http_status_to_status_code, + is_instrumentation_enabled, unwrap, ) from opentelemetry.propagate import inject @@ -179,7 +179,7 @@ async def on_request_start( trace_config_ctx: types.SimpleNamespace, params: aiohttp.TraceRequestStartParams, ): - if context_api.get_value(_SUPPRESS_INSTRUMENTATION_KEY): + if not is_instrumentation_enabled(): trace_config_ctx.span = None return @@ -282,7 +282,7 @@ def _instrument( # pylint:disable=unused-argument def instrumented_init(wrapped, instance, args, kwargs): - if context_api.get_value(_SUPPRESS_INSTRUMENTATION_KEY): + if not is_instrumentation_enabled(): return wrapped(*args, **kwargs) client_trace_configs = list(kwargs.get("trace_configs") or []) 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 index 50330b05be..6865b62020 100644 --- a/instrumentation/opentelemetry-instrumentation-aiohttp-client/tests/test_aiohttp_client_integration.py +++ b/instrumentation/opentelemetry-instrumentation-aiohttp-client/tests/test_aiohttp_client_integration.py @@ -33,7 +33,7 @@ from opentelemetry.instrumentation.aiohttp_client import ( AioHttpClientInstrumentor, ) -from opentelemetry.instrumentation.utils import _SUPPRESS_INSTRUMENTATION_KEY +from opentelemetry.instrumentation.utils import suppress_instrumentation from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.test.test_base import TestBase from opentelemetry.trace import Span, StatusCode @@ -512,25 +512,17 @@ async def uninstrument_request(server: aiohttp.test_utils.TestServer): self.assert_spans(1) def test_suppress_instrumentation(self): - token = context.attach( - context.set_value(_SUPPRESS_INSTRUMENTATION_KEY, True) - ) - try: + with suppress_instrumentation(): run_with_test_server( self.get_default_request(), self.URL, self.default_handler ) - finally: - context.detach(token) self.assert_spans(0) @staticmethod async def suppressed_request(server: aiohttp.test_utils.TestServer): async with aiohttp.test_utils.TestClient(server) as client: - token = context.attach( - context.set_value(_SUPPRESS_INSTRUMENTATION_KEY, True) - ) - await client.get(TestAioHttpClientInstrumentor.URL) - context.detach(token) + with suppress_instrumentation(): + await client.get(TestAioHttpClientInstrumentor.URL) def test_suppress_instrumentation_after_creation(self): run_with_test_server( diff --git a/instrumentation/opentelemetry-instrumentation-boto3sqs/src/opentelemetry/instrumentation/boto3sqs/__init__.py b/instrumentation/opentelemetry-instrumentation-boto3sqs/src/opentelemetry/instrumentation/boto3sqs/__init__.py index 137c570ac6..ee7f4a59a6 100644 --- a/instrumentation/opentelemetry-instrumentation-boto3sqs/src/opentelemetry/instrumentation/boto3sqs/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-boto3sqs/src/opentelemetry/instrumentation/boto3sqs/__init__.py @@ -38,7 +38,7 @@ from opentelemetry import context, propagate, trace from opentelemetry.instrumentation.instrumentor import BaseInstrumentor from opentelemetry.instrumentation.utils import ( - _SUPPRESS_INSTRUMENTATION_KEY, + is_instrumentation_enabled, unwrap, ) from opentelemetry.propagators.textmap import CarrierT, Getter, Setter @@ -218,7 +218,7 @@ def _create_processing_span( def _wrap_send_message(self, sqs_class: type) -> None: def send_wrapper(wrapped, instance, args, kwargs): - if context.get_value(_SUPPRESS_INSTRUMENTATION_KEY): + if not is_instrumentation_enabled(): return wrapped(*args, **kwargs) queue_url = kwargs.get("QueueUrl") # The method expect QueueUrl and Entries params, so if they are None, we call wrapped to receive the @@ -252,7 +252,7 @@ def send_batch_wrapper(wrapped, instance, args, kwargs): # The method expect QueueUrl and Entries params, so if they are None, we call wrapped to receive the # original exception if ( - context.get_value(_SUPPRESS_INSTRUMENTATION_KEY) + not is_instrumentation_enabled() or not queue_url or not entries ): diff --git a/instrumentation/opentelemetry-instrumentation-botocore/src/opentelemetry/instrumentation/botocore/__init__.py b/instrumentation/opentelemetry-instrumentation-botocore/src/opentelemetry/instrumentation/botocore/__init__.py index 686b040b13..6a4f337ec5 100644 --- a/instrumentation/opentelemetry-instrumentation-botocore/src/opentelemetry/instrumentation/botocore/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-botocore/src/opentelemetry/instrumentation/botocore/__init__.py @@ -87,9 +87,6 @@ def response_hook(span, service_name, operation_name, result): from wrapt import wrap_function_wrapper from opentelemetry import context as context_api - -# FIXME: fix the importing of this private attribute when the location of the _SUPPRESS_HTTP_INSTRUMENTATION_KEY is defined. -from opentelemetry.context import _SUPPRESS_HTTP_INSTRUMENTATION_KEY from opentelemetry.instrumentation.botocore.extensions import _find_extension from opentelemetry.instrumentation.botocore.extensions.types import ( _AwsSdkCallContext, @@ -98,7 +95,8 @@ def response_hook(span, service_name, operation_name, result): from opentelemetry.instrumentation.botocore.version import __version__ from opentelemetry.instrumentation.instrumentor import BaseInstrumentor from opentelemetry.instrumentation.utils import ( - _SUPPRESS_INSTRUMENTATION_KEY, + is_instrumentation_enabled, + suppress_http_instrumentation, unwrap, ) from opentelemetry.propagators.aws.aws_xray_propagator import AwsXRayPropagator @@ -171,7 +169,7 @@ def _patched_endpoint_prepare_request( # pylint: disable=too-many-branches def _patched_api_call(self, original_func, instance, args, kwargs): - if context_api.get_value(_SUPPRESS_INSTRUMENTATION_KEY): + if not is_instrumentation_enabled(): return original_func(*args, **kwargs) call_context = _determine_call_context(instance, args) @@ -200,25 +198,21 @@ def _patched_api_call(self, original_func, instance, args, kwargs): _safe_invoke(extension.before_service_call, span) self._call_request_hook(span, call_context) - token = context_api.attach( - context_api.set_value(_SUPPRESS_HTTP_INSTRUMENTATION_KEY, True) - ) - - result = None try: - result = original_func(*args, **kwargs) - except ClientError as error: - result = getattr(error, "response", None) - _apply_response_attributes(span, result) - _safe_invoke(extension.on_error, span, error) - raise - else: - _apply_response_attributes(span, result) - _safe_invoke(extension.on_success, span, result) + with suppress_http_instrumentation(): + result = None + try: + result = original_func(*args, **kwargs) + except ClientError as error: + result = getattr(error, "response", None) + _apply_response_attributes(span, result) + _safe_invoke(extension.on_error, span, error) + raise + else: + _apply_response_attributes(span, result) + _safe_invoke(extension.on_success, span, result) finally: - context_api.detach(token) _safe_invoke(extension.after_service_call) - self._call_response_hook(span, call_context, result) return result diff --git a/instrumentation/opentelemetry-instrumentation-botocore/tests/test_botocore_instrumentation.py b/instrumentation/opentelemetry-instrumentation-botocore/tests/test_botocore_instrumentation.py index 3d25dcbf2d..993faa97a4 100644 --- a/instrumentation/opentelemetry-instrumentation-botocore/tests/test_botocore_instrumentation.py +++ b/instrumentation/opentelemetry-instrumentation-botocore/tests/test_botocore_instrumentation.py @@ -27,14 +27,8 @@ ) from opentelemetry import trace as trace_api -from opentelemetry.context import ( - _SUPPRESS_HTTP_INSTRUMENTATION_KEY, - attach, - detach, - set_value, -) from opentelemetry.instrumentation.botocore import BotocoreInstrumentor -from opentelemetry.instrumentation.utils import _SUPPRESS_INSTRUMENTATION_KEY +from opentelemetry.instrumentation.utils import suppress_http_instrumentation, suppress_instrumentation from opentelemetry.propagate import get_global_textmap, set_global_textmap from opentelemetry.propagators.aws.aws_xray_propagator import TRACE_HEADER_KEY from opentelemetry.semconv.trace import SpanAttributes @@ -341,23 +335,16 @@ def check_headers(**kwargs): @mock_xray def test_suppress_instrumentation_xray_client(self): xray_client = self._make_client("xray") - token = attach(set_value(_SUPPRESS_INSTRUMENTATION_KEY, True)) - try: + with suppress_instrumentation(): xray_client.put_trace_segments(TraceSegmentDocuments=["str1"]) xray_client.put_trace_segments(TraceSegmentDocuments=["str2"]) - finally: - detach(token) self.assertEqual(0, len(self.get_finished_spans())) @mock_xray def test_suppress_http_instrumentation_xray_client(self): - xray_client = self._make_client("xray") - token = attach(set_value(_SUPPRESS_HTTP_INSTRUMENTATION_KEY, True)) - try: + with suppress_http_instrumentation(): xray_client.put_trace_segments(TraceSegmentDocuments=["str1"]) xray_client.put_trace_segments(TraceSegmentDocuments=["str2"]) - finally: - detach(token) self.assertEqual(2, len(self.get_finished_spans())) @mock_s3 diff --git a/instrumentation/opentelemetry-instrumentation-cassandra/src/opentelemetry/instrumentation/cassandra/__init__.py b/instrumentation/opentelemetry-instrumentation-cassandra/src/opentelemetry/instrumentation/cassandra/__init__.py index 2a9239f152..a8dd1f6cbf 100644 --- a/instrumentation/opentelemetry-instrumentation-cassandra/src/opentelemetry/instrumentation/cassandra/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-cassandra/src/opentelemetry/instrumentation/cassandra/__init__.py @@ -70,10 +70,7 @@ def _traced_execute_async(func, instance, args, kwargs): if span.is_recording(): span.set_attribute(SpanAttributes.DB_NAME, instance.keyspace) span.set_attribute(SpanAttributes.DB_SYSTEM, "cassandra") - span.set_attribute( - SpanAttributes.NET_PEER_NAME, - instance.cluster.contact_points, - ) + span.set_attribute(SpanAttributes.NET_PEER_NAME, instance.cluster.contact_points) if include_db_statement: query = args[0] @@ -82,9 +79,7 @@ def _traced_execute_async(func, instance, args, kwargs): response = func(*args, **kwargs) return response - wrap_function_wrapper( - "cassandra.cluster", "Session.execute_async", _traced_execute_async - ) + wrap_function_wrapper("cassandra.cluster", "Session.execute_async", _traced_execute_async) class CassandraInstrumentor(BaseInstrumentor): diff --git a/instrumentation/opentelemetry-instrumentation-cassandra/tests/test_cassandra_integration.py b/instrumentation/opentelemetry-instrumentation-cassandra/tests/test_cassandra_integration.py index ed488ab07f..6977e1b2a2 100644 --- a/instrumentation/opentelemetry-instrumentation-cassandra/tests/test_cassandra_integration.py +++ b/instrumentation/opentelemetry-instrumentation-cassandra/tests/test_cassandra_integration.py @@ -46,25 +46,15 @@ def tearDown(self): def test_instrument_uninstrument(self): instrumentation = CassandraInstrumentor() instrumentation.instrument() - self.assertTrue( - isinstance( - cassandra.cluster.Session.execute_async, BoundFunctionWrapper - ) - ) + self.assertTrue(isinstance(cassandra.cluster.Session.execute_async, BoundFunctionWrapper)) instrumentation.uninstrument() - self.assertFalse( - isinstance( - cassandra.cluster.Session.execute_async, BoundFunctionWrapper - ) - ) + self.assertFalse(isinstance(cassandra.cluster.Session.execute_async, BoundFunctionWrapper)) @mock.patch("cassandra.cluster.Cluster.connect") @mock.patch("cassandra.cluster.Session.__init__") @mock.patch("cassandra.cluster.Session._create_response_future") - def test_instrumentor( - self, mock_create_response_future, mock_session_init, mock_connect - ): + def test_instrumentor(self, mock_create_response_future, mock_session_init, mock_connect): mock_create_response_future.return_value = mock.Mock() mock_session_init.return_value = None mock_connect.return_value = cassandra.cluster.Session() @@ -95,9 +85,7 @@ def test_instrumentor( @mock.patch("cassandra.cluster.Cluster.connect") @mock.patch("cassandra.cluster.Session.__init__") @mock.patch("cassandra.cluster.Session._create_response_future") - def test_custom_tracer_provider( - self, mock_create_response_future, mock_session_init, mock_connect - ): + def test_custom_tracer_provider(self, mock_create_response_future, mock_session_init, mock_connect): mock_create_response_future.return_value = mock.Mock() mock_session_init.return_value = None mock_connect.return_value = cassandra.cluster.Session() @@ -119,9 +107,7 @@ def test_custom_tracer_provider( @mock.patch("cassandra.cluster.Cluster.connect") @mock.patch("cassandra.cluster.Session.__init__") @mock.patch("cassandra.cluster.Session._create_response_future") - def test_instrument_connection_no_op_tracer_provider( - self, mock_create_response_future, mock_session_init, mock_connect - ): + def test_instrument_connection_no_op_tracer_provider(self, mock_create_response_future, mock_session_init, mock_connect): mock_create_response_future.return_value = mock.Mock() mock_session_init.return_value = None mock_connect.return_value = cassandra.cluster.Session() diff --git a/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py b/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py index 3bd2f74ba8..d903ef393b 100644 --- a/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py +++ b/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py @@ -327,9 +327,7 @@ def test_flask_metric_values(self): if isinstance(point, NumberDataPoint): self.assertEqual(point.value, 0) - def _assert_basic_metric( - self, expected_duration_attributes, expected_requests_count_attributes - ): + def _assert_basic_metric(self, expected_duration_attributes, expected_requests_count_attributes): 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: @@ -395,7 +393,7 @@ def test_basic_metric_nonstandard_http_method_success(self): ) @patch.dict( - "os.environ", + "os.environ", { OTEL_PYTHON_INSTRUMENTATION_HTTP_CAPTURE_ALL_METHODS: "1", }, diff --git a/instrumentation/opentelemetry-instrumentation-grpc/src/opentelemetry/instrumentation/grpc/_aio_client.py b/instrumentation/opentelemetry-instrumentation-grpc/src/opentelemetry/instrumentation/grpc/_aio_client.py index 5d5a5ccc46..8fc992be73 100644 --- a/instrumentation/opentelemetry-instrumentation-grpc/src/opentelemetry/instrumentation/grpc/_aio_client.py +++ b/instrumentation/opentelemetry-instrumentation-grpc/src/opentelemetry/instrumentation/grpc/_aio_client.py @@ -19,12 +19,11 @@ import grpc from grpc.aio import ClientCallDetails -from opentelemetry import context from opentelemetry.instrumentation.grpc._client import ( OpenTelemetryClientInterceptor, _carrier_setter, ) -from opentelemetry.instrumentation.utils import _SUPPRESS_INSTRUMENTATION_KEY +from opentelemetry.instrumentation.utils import is_instrumentation_enabled from opentelemetry.propagate import inject from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.trace.status import Status, StatusCode @@ -139,9 +138,10 @@ async def _wrap_stream_response(self, span, call): span.end() def tracing_skipped(self, client_call_details): - return context.get_value( - _SUPPRESS_INSTRUMENTATION_KEY - ) or not self.rpc_matches_filters(client_call_details) + return ( + not is_instrumentation_enabled() + or not self.rpc_matches_filters(client_call_details) + ) def rpc_matches_filters(self, client_call_details): return self._filter is None or self._filter(client_call_details) diff --git a/instrumentation/opentelemetry-instrumentation-grpc/src/opentelemetry/instrumentation/grpc/_client.py b/instrumentation/opentelemetry-instrumentation-grpc/src/opentelemetry/instrumentation/grpc/_client.py index b966fff4db..0a4f8df866 100644 --- a/instrumentation/opentelemetry-instrumentation-grpc/src/opentelemetry/instrumentation/grpc/_client.py +++ b/instrumentation/opentelemetry-instrumentation-grpc/src/opentelemetry/instrumentation/grpc/_client.py @@ -28,7 +28,7 @@ from opentelemetry import context, trace from opentelemetry.instrumentation.grpc import grpcext from opentelemetry.instrumentation.grpc._utilities import RpcInfo -from opentelemetry.instrumentation.utils import _SUPPRESS_INSTRUMENTATION_KEY +from opentelemetry.instrumentation.utils import is_instrumentation_enabled from opentelemetry.propagate import inject from opentelemetry.propagators.textmap import Setter from opentelemetry.semconv.trace import SpanAttributes @@ -123,7 +123,7 @@ def _trace_result(self, span, rpc_info, result): return result def _intercept(self, request, metadata, client_info, invoker): - if context.get_value(_SUPPRESS_INSTRUMENTATION_KEY): + if not is_instrumentation_enabled(): return invoker(request, metadata) if not metadata: @@ -219,7 +219,7 @@ def _intercept_server_stream( def intercept_stream( self, request_or_iterator, metadata, client_info, invoker ): - if context.get_value(_SUPPRESS_INSTRUMENTATION_KEY): + if not is_instrumentation_enabled(): return invoker(request_or_iterator, metadata) if self._filter is not None and not self._filter(client_info): diff --git a/instrumentation/opentelemetry-instrumentation-grpc/tests/test_aio_client_interceptor.py b/instrumentation/opentelemetry-instrumentation-grpc/tests/test_aio_client_interceptor.py index 6ca5ce92d5..ad95711aa1 100644 --- a/instrumentation/opentelemetry-instrumentation-grpc/tests/test_aio_client_interceptor.py +++ b/instrumentation/opentelemetry-instrumentation-grpc/tests/test_aio_client_interceptor.py @@ -39,7 +39,7 @@ def run(self, result=None): from opentelemetry.instrumentation.grpc._aio_client import ( UnaryUnaryAioClientInterceptor, ) -from opentelemetry.instrumentation.utils import _SUPPRESS_INSTRUMENTATION_KEY +from opentelemetry.instrumentation.utils import suppress_instrumentation from opentelemetry.propagate import get_global_textmap, set_global_textmap from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.test.mock_textmap import MockTextMapPropagator @@ -314,53 +314,33 @@ async def test_client_interceptor_trace_context_propagation(self): set_global_textmap(previous_propagator) async def test_unary_unary_with_suppress_key(self): - token = context.attach( - context.set_value(_SUPPRESS_INSTRUMENTATION_KEY, True) - ) - try: + with suppress_instrumentation(): response = await simple_method(self._stub) assert response.response_data == "data" spans = self.memory_exporter.get_finished_spans() self.assertEqual(len(spans), 0) - finally: - context.detach(token) async def test_unary_stream_with_suppress_key(self): - token = context.attach( - context.set_value(_SUPPRESS_INSTRUMENTATION_KEY, True) - ) - try: + with suppress_instrumentation(): async for response in server_streaming_method(self._stub): self.assertEqual(response.response_data, "data") spans = self.memory_exporter.get_finished_spans() self.assertEqual(len(spans), 0) - finally: - context.detach(token) async def test_stream_unary_with_suppress_key(self): - token = context.attach( - context.set_value(_SUPPRESS_INSTRUMENTATION_KEY, True) - ) - try: + with suppress_instrumentation(): response = await client_streaming_method(self._stub) assert response.response_data == "data" spans = self.memory_exporter.get_finished_spans() self.assertEqual(len(spans), 0) - finally: - context.detach(token) async def test_stream_stream_with_suppress_key(self): - token = context.attach( - context.set_value(_SUPPRESS_INSTRUMENTATION_KEY, True) - ) - try: + with suppress_instrumentation(): async for response in bidirectional_streaming_method(self._stub): self.assertEqual(response.response_data, "data") spans = self.memory_exporter.get_finished_spans() self.assertEqual(len(spans), 0) - finally: - context.detach(token) diff --git a/instrumentation/opentelemetry-instrumentation-grpc/tests/test_client_interceptor.py b/instrumentation/opentelemetry-instrumentation-grpc/tests/test_client_interceptor.py index 21d016d624..bd27e1974e 100644 --- a/instrumentation/opentelemetry-instrumentation-grpc/tests/test_client_interceptor.py +++ b/instrumentation/opentelemetry-instrumentation-grpc/tests/test_client_interceptor.py @@ -27,7 +27,7 @@ from opentelemetry.instrumentation.grpc.grpcext._interceptor import ( _UnaryClientInfo, ) -from opentelemetry.instrumentation.utils import _SUPPRESS_INSTRUMENTATION_KEY +from opentelemetry.instrumentation.utils import suppress_instrumentation from opentelemetry.propagate import get_global_textmap, set_global_textmap from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.test.mock_textmap import MockTextMapPropagator @@ -307,45 +307,25 @@ def invoker(request, metadata): set_global_textmap(previous_propagator) def test_unary_unary_with_suppress_key(self): - token = context.attach( - context.set_value(_SUPPRESS_INSTRUMENTATION_KEY, True) - ) - try: + with suppress_instrumentation(): simple_method(self._stub) spans = self.memory_exporter.get_finished_spans() - finally: - context.detach(token) self.assertEqual(len(spans), 0) def test_unary_stream_with_suppress_key(self): - token = context.attach( - context.set_value(_SUPPRESS_INSTRUMENTATION_KEY, True) - ) - try: + with suppress_instrumentation(): server_streaming_method(self._stub) spans = self.memory_exporter.get_finished_spans() - finally: - context.detach(token) self.assertEqual(len(spans), 0) def test_stream_unary_with_suppress_key(self): - token = context.attach( - context.set_value(_SUPPRESS_INSTRUMENTATION_KEY, True) - ) - try: + with suppress_instrumentation(): client_streaming_method(self._stub) spans = self.memory_exporter.get_finished_spans() - finally: - context.detach(token) self.assertEqual(len(spans), 0) def test_stream_stream_with_suppress_key(self): - token = context.attach( - context.set_value(_SUPPRESS_INSTRUMENTATION_KEY, True) - ) - try: + with suppress_instrumentation(): bidirectional_streaming_method(self._stub) spans = self.memory_exporter.get_finished_spans() - finally: - context.detach(token) self.assertEqual(len(spans), 0) diff --git a/instrumentation/opentelemetry-instrumentation-grpc/tests/test_client_interceptor_filter.py b/instrumentation/opentelemetry-instrumentation-grpc/tests/test_client_interceptor_filter.py index bfa20592ba..784529eb43 100644 --- a/instrumentation/opentelemetry-instrumentation-grpc/tests/test_client_interceptor_filter.py +++ b/instrumentation/opentelemetry-instrumentation-grpc/tests/test_client_interceptor_filter.py @@ -30,7 +30,7 @@ from opentelemetry.instrumentation.grpc.grpcext._interceptor import ( _UnaryClientInfo, ) -from opentelemetry.instrumentation.utils import _SUPPRESS_INSTRUMENTATION_KEY +from opentelemetry.instrumentation.utils import suppress_instrumentation from opentelemetry.propagate import get_global_textmap, set_global_textmap from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.test.mock_textmap import MockTextMapPropagator @@ -639,45 +639,25 @@ def invoker(request, metadata): set_global_textmap(previous_propagator) def test_unary_unary_with_suppress_key(self): - token = context.attach( - context.set_value(_SUPPRESS_INSTRUMENTATION_KEY, True) - ) - try: + with suppress_instrumentation(): simple_method(self._stub) spans = self.memory_exporter.get_finished_spans() - finally: - context.detach(token) self.assertEqual(len(spans), 0) def test_unary_stream_with_suppress_key(self): - token = context.attach( - context.set_value(_SUPPRESS_INSTRUMENTATION_KEY, True) - ) - try: + with suppress_instrumentation(): server_streaming_method(self._stub) spans = self.memory_exporter.get_finished_spans() - finally: - context.detach(token) self.assertEqual(len(spans), 0) def test_stream_unary_with_suppress_key(self): - token = context.attach( - context.set_value(_SUPPRESS_INSTRUMENTATION_KEY, True) - ) - try: + with suppress_instrumentation(): client_streaming_method(self._stub) spans = self.memory_exporter.get_finished_spans() - finally: - context.detach(token) self.assertEqual(len(spans), 0) def test_stream_stream_with_suppress_key(self): - token = context.attach( - context.set_value(_SUPPRESS_INSTRUMENTATION_KEY, True) - ) - try: + with suppress_instrumentation(): bidirectional_streaming_method(self._stub) spans = self.memory_exporter.get_finished_spans() - finally: - context.detach(token) self.assertEqual(len(spans), 0) diff --git a/instrumentation/opentelemetry-instrumentation-httpx/src/opentelemetry/instrumentation/httpx/__init__.py b/instrumentation/opentelemetry-instrumentation-httpx/src/opentelemetry/instrumentation/httpx/__init__.py index ecee204fc8..53542e7ef3 100644 --- a/instrumentation/opentelemetry-instrumentation-httpx/src/opentelemetry/instrumentation/httpx/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-httpx/src/opentelemetry/instrumentation/httpx/__init__.py @@ -200,7 +200,7 @@ async def async_response_hook(span, request, response): from opentelemetry.instrumentation.httpx.package import _instruments from opentelemetry.instrumentation.httpx.version import __version__ from opentelemetry.instrumentation.instrumentor import BaseInstrumentor -from opentelemetry.instrumentation.utils import http_status_to_status_code, is_http_instrumentation_enabled +from opentelemetry.instrumentation.utils import http_status_to_status_code from opentelemetry.propagate import inject from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.trace import SpanKind, TracerProvider, get_tracer @@ -347,7 +347,7 @@ def handle_request( httpx.Response, ]: """Add request info to span.""" - if not is_http_instrumentation_enabled(): + if context.get_value("suppress_instrumentation"): return self._transport.handle_request(*args, **kwargs) method, url, headers, stream, extensions = _extract_parameters( @@ -440,7 +440,7 @@ async def handle_async_request( httpx.Response, ]: """Add request info to span.""" - if not is_http_instrumentation_enabled(): + if context.get_value("suppress_instrumentation"): return await self._transport.handle_async_request(*args, **kwargs) method, url, headers, stream, extensions = _extract_parameters( diff --git a/instrumentation/opentelemetry-instrumentation-pymongo/src/opentelemetry/instrumentation/pymongo/__init__.py b/instrumentation/opentelemetry-instrumentation-pymongo/src/opentelemetry/instrumentation/pymongo/__init__.py index 041ff6b928..1f2c000036 100644 --- a/instrumentation/opentelemetry-instrumentation-pymongo/src/opentelemetry/instrumentation/pymongo/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-pymongo/src/opentelemetry/instrumentation/pymongo/__init__.py @@ -86,7 +86,7 @@ def failed_hook(span, event): COMMAND_TO_ATTRIBUTE_MAPPING, ) from opentelemetry.instrumentation.pymongo.version import __version__ -from opentelemetry.instrumentation.utils import _SUPPRESS_INSTRUMENTATION_KEY +from opentelemetry.instrumentation.utils import is_instrumentation_enabled from opentelemetry.semconv.trace import DbSystemValues, SpanAttributes from opentelemetry.trace import SpanKind, get_tracer from opentelemetry.trace.span import Span @@ -122,9 +122,7 @@ def __init__( def started(self, event: monitoring.CommandStartedEvent): """Method to handle a pymongo CommandStartedEvent""" - if not self.is_enabled or context.get_value( - _SUPPRESS_INSTRUMENTATION_KEY - ): + if not self.is_enabled or not is_instrumentation_enabled(): return command_name = event.command_name span_name = f"{event.database_name}.{command_name}" @@ -167,9 +165,7 @@ def started(self, event: monitoring.CommandStartedEvent): def succeeded(self, event: monitoring.CommandSucceededEvent): """Method to handle a pymongo CommandSucceededEvent""" - if not self.is_enabled or context.get_value( - _SUPPRESS_INSTRUMENTATION_KEY - ): + if not self.is_enabled or not is_instrumentation_enabled(): return span = self._pop_span(event) if span is None: @@ -185,9 +181,7 @@ def succeeded(self, event: monitoring.CommandSucceededEvent): def failed(self, event: monitoring.CommandFailedEvent): """Method to handle a pymongo CommandFailedEvent""" - if not self.is_enabled or context.get_value( - _SUPPRESS_INSTRUMENTATION_KEY - ): + if not (self.is_enabled and is_instrumentation_enabled()): 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 index 8eab3b701c..ba6597b588 100644 --- a/instrumentation/opentelemetry-instrumentation-pymongo/tests/test_pymongo.py +++ b/instrumentation/opentelemetry-instrumentation-pymongo/tests/test_pymongo.py @@ -20,7 +20,7 @@ CommandTracer, PymongoInstrumentor, ) -from opentelemetry.instrumentation.utils import _SUPPRESS_INSTRUMENTATION_KEY +from opentelemetry.instrumentation.utils import suppress_instrumentation from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.test.test_base import TestBase @@ -112,16 +112,10 @@ def test_suppression_key(self): mock_event.command.get = mock.Mock() mock_event.command.get.return_value = "dummy" - token = context.attach( - context.set_value(_SUPPRESS_INSTRUMENTATION_KEY, True) - ) - - try: + with suppress_instrumentation(): 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( diff --git a/instrumentation/opentelemetry-instrumentation-requests/src/opentelemetry/instrumentation/requests/__init__.py b/instrumentation/opentelemetry-instrumentation-requests/src/opentelemetry/instrumentation/requests/__init__.py index 0a8e4ee729..4c198596a2 100644 --- a/instrumentation/opentelemetry-instrumentation-requests/src/opentelemetry/instrumentation/requests/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-requests/src/opentelemetry/instrumentation/requests/__init__.py @@ -58,10 +58,6 @@ from requests.sessions import Session from requests.structures import CaseInsensitiveDict -from opentelemetry import context - -# FIXME: fix the importing of this private attribute when the location of the _SUPPRESS_HTTP_INSTRUMENTATION_KEY is defined. -from opentelemetry.context import _SUPPRESS_HTTP_INSTRUMENTATION_KEY from opentelemetry.instrumentation._semconv import ( _METRIC_ATTRIBUTES_CLIENT_DURATION_NAME, _SPAN_ATTRIBUTES_ERROR_TYPE, @@ -87,8 +83,9 @@ from opentelemetry.instrumentation.requests.package import _instruments from opentelemetry.instrumentation.requests.version import __version__ from opentelemetry.instrumentation.utils import ( - _SUPPRESS_INSTRUMENTATION_KEY, http_status_to_status_code, + is_http_instrumentation_enabled, + suppress_http_instrumentation, ) from opentelemetry.metrics import Histogram, get_meter from opentelemetry.propagate import inject @@ -149,9 +146,7 @@ def get_or_create_headers(): ) return request.headers - if context.get_value( - _SUPPRESS_INSTRUMENTATION_KEY - ) or context.get_value(_SUPPRESS_HTTP_INSTRUMENTATION_KEY): + if not is_http_instrumentation_enabled(): return wrapped_send(self, request, **kwargs) # See @@ -220,20 +215,19 @@ def get_or_create_headers(): headers = get_or_create_headers() inject(headers) - token = context.attach( - context.set_value(_SUPPRESS_HTTP_INSTRUMENTATION_KEY, True) - ) - - start_time = default_timer() - - try: - result = wrapped_send(self, request, **kwargs) # *** PROCEED - except Exception as exc: # pylint: disable=W0703 - exception = exc - result = getattr(exc, "response", None) - finally: - elapsed_time = max(default_timer() - start_time, 0) - context.detach(token) + with suppress_http_instrumentation(): + start_time = default_timer() + try: + result = wrapped_send( + self, request, **kwargs + ) # *** 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 + ) if isinstance(result, Response): span_attributes = {} diff --git a/instrumentation/opentelemetry-instrumentation-requests/tests/test_requests_integration.py b/instrumentation/opentelemetry-instrumentation-requests/tests/test_requests_integration.py index 11eada2589..b2cbade2c7 100644 --- a/instrumentation/opentelemetry-instrumentation-requests/tests/test_requests_integration.py +++ b/instrumentation/opentelemetry-instrumentation-requests/tests/test_requests_integration.py @@ -21,10 +21,8 @@ from requests.models import Response import opentelemetry.instrumentation.requests -from opentelemetry import context, trace +from opentelemetry import trace -# FIXME: fix the importing of this private attribute when the location of the _SUPPRESS_HTTP_INSTRUMENTATION_KEY is defined. -from opentelemetry.context import _SUPPRESS_HTTP_INSTRUMENTATION_KEY from opentelemetry.instrumentation._semconv import ( _OTEL_SEMCONV_STABILITY_OPT_IN_KEY, _SPAN_ATTRIBUTES_ERROR_TYPE, @@ -33,7 +31,10 @@ _OpenTelemetrySemanticConventionStability, ) from opentelemetry.instrumentation.requests import RequestsInstrumentor -from opentelemetry.instrumentation.utils import _SUPPRESS_INSTRUMENTATION_KEY +from opentelemetry.instrumentation.utils import ( + suppress_http_instrumentation, + suppress_instrumentation, +) from opentelemetry.propagate import get_global_textmap, set_global_textmap from opentelemetry.sdk import resources from opentelemetry.semconv.trace import SpanAttributes @@ -397,26 +398,16 @@ def test_uninstrument_session(self): self.assert_span() def test_suppress_instrumentation(self): - token = context.attach( - context.set_value(_SUPPRESS_INSTRUMENTATION_KEY, True) - ) - try: + with suppress_instrumentation(): result = self.perform_request(self.URL) self.assertEqual(result.text, "Hello!") - finally: - context.detach(token) self.assert_span(num_spans=0) def test_suppress_http_instrumentation(self): - token = context.attach( - context.set_value(_SUPPRESS_HTTP_INSTRUMENTATION_KEY, True) - ) - try: + with suppress_http_instrumentation(): result = self.perform_request(self.URL) self.assertEqual(result.text, "Hello!") - finally: - context.detach(token) self.assert_span(num_spans=0) diff --git a/instrumentation/opentelemetry-instrumentation-urllib/src/opentelemetry/instrumentation/urllib/__init__.py b/instrumentation/opentelemetry-instrumentation-urllib/src/opentelemetry/instrumentation/urllib/__init__.py index eca8fbda77..35d846e4a0 100644 --- a/instrumentation/opentelemetry-instrumentation-urllib/src/opentelemetry/instrumentation/urllib/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-urllib/src/opentelemetry/instrumentation/urllib/__init__.py @@ -85,15 +85,12 @@ def response_hook(span, request_obj, response) Request, ) -from opentelemetry import context - -# FIXME: fix the importing of this private attribute when the location of the _SUPPRESS_HTTP_INSTRUMENTATION_KEY is defined. -from opentelemetry.context import _SUPPRESS_HTTP_INSTRUMENTATION_KEY from opentelemetry.instrumentation.instrumentor import BaseInstrumentor from opentelemetry.instrumentation.urllib.package import _instruments from opentelemetry.instrumentation.urllib.version import __version__ from opentelemetry.instrumentation.utils import ( - _SUPPRESS_INSTRUMENTATION_KEY, + is_http_instrumentation_enabled, + suppress_http_instrumentation, http_status_to_status_code, ) from opentelemetry.metrics import Histogram, get_meter @@ -206,9 +203,7 @@ def call_wrapped(): def _instrumented_open_call( _, request, call_wrapped, get_or_create_headers ): # pylint: disable=too-many-locals - if context.get_value( - _SUPPRESS_INSTRUMENTATION_KEY - ) or context.get_value(_SUPPRESS_HTTP_INSTRUMENTATION_KEY): + if not is_http_instrumentation_enabled(): return call_wrapped() url = request.full_url @@ -236,18 +231,15 @@ def _instrumented_open_call( headers = get_or_create_headers() inject(headers) - 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, "file", None) - finally: - elapsed_time = round((default_timer() - start_time) * 1000) - context.detach(token) + with suppress_http_instrumentation(): + start_time = default_timer() + try: + result = call_wrapped() # *** PROCEED + except Exception as exc: # pylint: disable=W0703 + exception = exc + result = getattr(exc, "file", None) + finally: + elapsed_time = round((default_timer() - start_time) * 1000) if result is not None: code_ = result.getcode() diff --git a/instrumentation/opentelemetry-instrumentation-urllib/tests/test_urllib_integration.py b/instrumentation/opentelemetry-instrumentation-urllib/tests/test_urllib_integration.py index f27f594a30..36189e12c1 100644 --- a/instrumentation/opentelemetry-instrumentation-urllib/tests/test_urllib_integration.py +++ b/instrumentation/opentelemetry-instrumentation-urllib/tests/test_urllib_integration.py @@ -24,14 +24,14 @@ import httpretty import opentelemetry.instrumentation.urllib # pylint: disable=no-name-in-module,import-error -from opentelemetry import context, trace - -# FIXME: fix the importing of this private attribute when the location of the _SUPPRESS_HTTP_INSTRUMENTATION_KEY is defined. -from opentelemetry.context import _SUPPRESS_HTTP_INSTRUMENTATION_KEY +from opentelemetry import trace from opentelemetry.instrumentation.urllib import ( # pylint: disable=no-name-in-module,import-error URLLibInstrumentor, ) -from opentelemetry.instrumentation.utils import _SUPPRESS_INSTRUMENTATION_KEY +from opentelemetry.instrumentation.utils import ( + suppress_http_instrumentation, + suppress_instrumentation, +) from opentelemetry.propagate import get_global_textmap, set_global_textmap from opentelemetry.sdk import resources from opentelemetry.semconv.trace import SpanAttributes @@ -255,26 +255,16 @@ def test_uninstrument_session(self): self.assert_span() def test_suppress_instrumentation(self): - token = context.attach( - context.set_value(_SUPPRESS_INSTRUMENTATION_KEY, True) - ) - try: + with suppress_instrumentation(): result = self.perform_request(self.URL) self.assertEqual(result.read(), b"Hello!") - finally: - context.detach(token) self.assert_span(num_spans=0) def test_suppress_http_instrumentation(self): - token = context.attach( - context.set_value(_SUPPRESS_HTTP_INSTRUMENTATION_KEY, True) - ) - try: + with suppress_http_instrumentation(): result = self.perform_request(self.URL) self.assertEqual(result.read(), b"Hello!") - finally: - context.detach(token) self.assert_span(num_spans=0) diff --git a/instrumentation/opentelemetry-instrumentation-urllib3/src/opentelemetry/instrumentation/urllib3/__init__.py b/instrumentation/opentelemetry-instrumentation-urllib3/src/opentelemetry/instrumentation/urllib3/__init__.py index 5580cb529f..fe6fdf08f1 100644 --- a/instrumentation/opentelemetry-instrumentation-urllib3/src/opentelemetry/instrumentation/urllib3/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-urllib3/src/opentelemetry/instrumentation/urllib3/__init__.py @@ -88,16 +88,13 @@ def response_hook(span, request, response): import urllib3.connectionpool import wrapt -from opentelemetry import context - -# FIXME: fix the importing of this private attribute when the location of the _SUPPRESS_HTTP_INSTRUMENTATION_KEY is defined. -from opentelemetry.context import _SUPPRESS_HTTP_INSTRUMENTATION_KEY from opentelemetry.instrumentation.instrumentor import BaseInstrumentor from opentelemetry.instrumentation.urllib3.package import _instruments from opentelemetry.instrumentation.urllib3.version import __version__ from opentelemetry.instrumentation.utils import ( - _SUPPRESS_INSTRUMENTATION_KEY, http_status_to_status_code, + is_http_instrumentation_enabled, + suppress_http_instrumentation, unwrap, ) from opentelemetry.metrics import Histogram, get_meter @@ -224,7 +221,7 @@ def _instrument( excluded_urls: ExcludeList = None, ): def instrumented_urlopen(wrapped, instance, args, kwargs): - if _is_instrumentation_suppressed(): + if not is_http_instrumentation_enabled(): return wrapped(*args, **kwargs) url = _get_url(instance, args, kwargs, url_filter) @@ -248,7 +245,7 @@ def instrumented_urlopen(wrapped, instance, args, kwargs): request_hook(span, instance, headers, body) inject(headers) - with _suppress_further_instrumentation(): + with suppress_http_instrumentation(): start_time = default_timer() response = wrapped(*args, **kwargs) elapsed_time = round((default_timer() - start_time) * 1000) @@ -352,13 +349,6 @@ def _apply_response(span: Span, response: urllib3.response.HTTPResponse): span.set_status(Status(http_status_to_status_code(response.status))) -def _is_instrumentation_suppressed() -> bool: - return bool( - context.get_value(_SUPPRESS_INSTRUMENTATION_KEY) - or context.get_value(_SUPPRESS_HTTP_INSTRUMENTATION_KEY) - ) - - def _create_metric_attributes( instance: urllib3.connectionpool.HTTPConnectionPool, response: urllib3.response.HTTPResponse, @@ -382,16 +372,5 @@ def _create_metric_attributes( return metric_attributes -@contextlib.contextmanager -def _suppress_further_instrumentation(): - token = context.attach( - context.set_value(_SUPPRESS_HTTP_INSTRUMENTATION_KEY, True) - ) - try: - yield - finally: - context.detach(token) - - def _uninstrument(): unwrap(urllib3.connectionpool.HTTPConnectionPool, "urlopen") diff --git a/instrumentation/opentelemetry-instrumentation-urllib3/tests/test_urllib3_integration.py b/instrumentation/opentelemetry-instrumentation-urllib3/tests/test_urllib3_integration.py index 27e1b81269..966513d0e7 100644 --- a/instrumentation/opentelemetry-instrumentation-urllib3/tests/test_urllib3_integration.py +++ b/instrumentation/opentelemetry-instrumentation-urllib3/tests/test_urllib3_integration.py @@ -20,11 +20,11 @@ import urllib3.exceptions from opentelemetry import context, trace - -# FIXME: fix the importing of this private attribute when the location of the _SUPPRESS_HTTP_INSTRUMENTATION_KEY is defined. -from opentelemetry.context import _SUPPRESS_HTTP_INSTRUMENTATION_KEY from opentelemetry.instrumentation.urllib3 import URLLib3Instrumentor -from opentelemetry.instrumentation.utils import _SUPPRESS_INSTRUMENTATION_KEY +from opentelemetry.instrumentation.utils import ( + suppress_http_instrumentation, + suppress_instrumentation, +) from opentelemetry.propagate import get_global_textmap, set_global_textmap from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.test.mock_textmap import MockTextMapPropagator @@ -225,20 +225,17 @@ def test_uninstrument(self): URLLib3Instrumentor().instrument() def test_suppress_instrumentation(self): - suppression_keys = ( - _SUPPRESS_HTTP_INSTRUMENTATION_KEY, - _SUPPRESS_INSTRUMENTATION_KEY, + suppression_cms = ( + suppress_instrumentation, + suppress_http_instrumentation, ) - for key in suppression_keys: + for cm in suppression_cms: self.memory_exporter.clear() with self.subTest(key=key): - token = context.attach(context.set_value(key, True)) - try: + with cm(): response = self.perform_request(self.HTTP_URL) self.assertEqual(b"Hello!", response.data) - finally: - context.detach(token) self.assert_span(num_spans=0) diff --git a/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py b/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py index 87c73cc737..36fe69daec 100644 --- a/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py @@ -302,9 +302,7 @@ def collect_request_attributes(environ): """ result = { - SpanAttributes.HTTP_METHOD: sanitize_method( - environ.get("REQUEST_METHOD") - ), + SpanAttributes.HTTP_METHOD: sanitize_method(environ.get("REQUEST_METHOD")), SpanAttributes.HTTP_SERVER_NAME: environ.get("SERVER_NAME"), SpanAttributes.HTTP_SCHEME: environ.get("wsgi.url_scheme"), } diff --git a/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py b/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py index d71e584ca8..c1b5026cc7 100644 --- a/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py +++ b/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py @@ -287,26 +287,22 @@ def test_wsgi_metrics(self): self.assertTrue(number_data_point_seen and histogram_data_point_seen) def test_nonstandard_http_method(self): - self.environ["REQUEST_METHOD"] = "NONSTANDARD" + self.environ["REQUEST_METHOD"]= "NONSTANDARD" app = otel_wsgi.OpenTelemetryMiddleware(simple_wsgi) response = app(self.environ, self.start_response) - self.validate_response( - response, span_name="UNKNOWN /", http_method="UNKNOWN" - ) + self.validate_response(response, span_name="UNKNOWN /", http_method="UNKNOWN") @mock.patch.dict( - "os.environ", + "os.environ", { OTEL_PYTHON_INSTRUMENTATION_HTTP_CAPTURE_ALL_METHODS: "1", }, ) def test_nonstandard_http_method_allowed(self): - self.environ["REQUEST_METHOD"] = "NONSTANDARD" + self.environ["REQUEST_METHOD"]= "NONSTANDARD" app = otel_wsgi.OpenTelemetryMiddleware(simple_wsgi) response = app(self.environ, self.start_response) - self.validate_response( - response, span_name="NONSTANDARD /", http_method="NONSTANDARD" - ) + self.validate_response(response, span_name="NONSTANDARD /", http_method="NONSTANDARD") def test_default_span_name_missing_path_info(self): """Test that default span_names with missing path info.""" diff --git a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/utils.py b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/utils.py index 72e1c13f5e..b64cfbb0f5 100644 --- a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/utils.py +++ b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/utils.py @@ -13,9 +13,16 @@ # limitations under the License. import urllib.parse +from contextlib import contextmanager from re import escape, sub -from typing import Dict, Sequence +from typing import Dict, Iterable, Sequence +# pylint: disable=E0611 +# FIXME: fix the importing of these private attributes when the location of the _SUPPRESS_HTTP_INSTRUMENTATION_KEY is defined.= +from opentelemetry.context import ( + _SUPPRESS_HTTP_INSTRUMENTATION_KEY, + _SUPPRESS_INSTRUMENTATION_KEY, +) from wrapt import ObjectProxy from opentelemetry import context, trace @@ -153,18 +160,41 @@ def _python_path_without_directory(python_path, directory, path_separator): def is_instrumentation_enabled() -> bool: - if ( - context.get_value("suppress_instrumentation") - or - context.get_value(context._SUPPRESS_INSTRUMENTATION_KEY) # type: ignore - ): + if context.get_value(_SUPPRESS_INSTRUMENTATION_KEY): return False return True def is_http_instrumentation_enabled() -> bool: return ( - is_http_instrumentation_enabled() + is_instrumentation_enabled() and not - context.get_value(context._SUPPRESS_HTTP_INSTRUMENTATION_KEY) # type: ignore + context.get_value(_SUPPRESS_HTTP_INSTRUMENTATION_KEY) ) + + +@contextmanager +def _suppress_instrumentation(*keys: str) -> Iterable[None]: + """Suppress instrumentation within the context.""" + ctx = context.get_current() + for key in keys: + ctx = context.set_value(key, True, ctx) + token = context.attach(ctx) + try: + yield + finally: + context.detach(token) + + +@contextmanager +def suppress_instrumentation() -> Iterable[None]: + """Suppress instrumentation within the context.""" + with _suppress_instrumentation(_SUPPRESS_INSTRUMENTATION_KEY): + yield + + +@contextmanager +def suppress_http_instrumentation() -> Iterable[None]: + """Suppress instrumentation within the context.""" + with _suppress_instrumentation(_SUPPRESS_HTTP_INSTRUMENTATION_KEY): + yield From 195fb47e0215e4f8714a599e02c9d9b4ac1e0d50 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Tue, 14 Nov 2023 09:20:22 -0600 Subject: [PATCH 03/12] changelog --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 840cfd565a..1a7cbabbaa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ([#2002](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/2002)) - `opentelemetry-instrument-grpc` Fix arity of context.abort for AIO RPCs ([#2066](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/2066)) +- Consolidate instrumentation suppression mechanisms and fix bug in httpx instrumentation + ([#2061](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/2061)) ### Fixed From 2726e1989a891ba0b6f3fdf0caa958650d06a307 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Tue, 14 Nov 2023 09:40:35 -0600 Subject: [PATCH 04/12] fix tests --- .../tests/test_botocore_instrumentation.py | 1 + .../tests/test_urllib3_integration.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/instrumentation/opentelemetry-instrumentation-botocore/tests/test_botocore_instrumentation.py b/instrumentation/opentelemetry-instrumentation-botocore/tests/test_botocore_instrumentation.py index 993faa97a4..d617760037 100644 --- a/instrumentation/opentelemetry-instrumentation-botocore/tests/test_botocore_instrumentation.py +++ b/instrumentation/opentelemetry-instrumentation-botocore/tests/test_botocore_instrumentation.py @@ -342,6 +342,7 @@ def test_suppress_instrumentation_xray_client(self): @mock_xray def test_suppress_http_instrumentation_xray_client(self): + xray_client = self._make_client("xray") with suppress_http_instrumentation(): xray_client.put_trace_segments(TraceSegmentDocuments=["str1"]) xray_client.put_trace_segments(TraceSegmentDocuments=["str2"]) diff --git a/instrumentation/opentelemetry-instrumentation-urllib3/tests/test_urllib3_integration.py b/instrumentation/opentelemetry-instrumentation-urllib3/tests/test_urllib3_integration.py index 966513d0e7..50a2bfe3ad 100644 --- a/instrumentation/opentelemetry-instrumentation-urllib3/tests/test_urllib3_integration.py +++ b/instrumentation/opentelemetry-instrumentation-urllib3/tests/test_urllib3_integration.py @@ -232,7 +232,7 @@ def test_suppress_instrumentation(self): for cm in suppression_cms: self.memory_exporter.clear() - with self.subTest(key=key): + with self.subTest(cm=cm): with cm(): response = self.perform_request(self.HTTP_URL) self.assertEqual(b"Hello!", response.data) From 9d213ee0d20154ed2d6cb9bb4719e7ae45e56a4c Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Tue, 14 Nov 2023 11:40:22 -0600 Subject: [PATCH 05/12] fix import --- .../instrumentation/aio_pika/callback_decorator.py | 4 +--- .../opentelemetry/instrumentation/aio_pika/span_builder.py | 4 +--- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/instrumentation/opentelemetry-instrumentation-aio-pika/src/opentelemetry/instrumentation/aio_pika/callback_decorator.py b/instrumentation/opentelemetry-instrumentation-aio-pika/src/opentelemetry/instrumentation/aio_pika/callback_decorator.py index a2169b6d18..f10415bdd2 100644 --- a/instrumentation/opentelemetry-instrumentation-aio-pika/src/opentelemetry/instrumentation/aio_pika/callback_decorator.py +++ b/instrumentation/opentelemetry-instrumentation-aio-pika/src/opentelemetry/instrumentation/aio_pika/callback_decorator.py @@ -18,9 +18,7 @@ from opentelemetry import context, propagate, trace from opentelemetry.instrumentation.aio_pika.span_builder import SpanBuilder -from opentelemetry.instrumentation.aio_pika.utils import ( - is_instrumentation_enabled, -) +from opentelemetry.instrumentation.utils import is_instrumentation_enabled from opentelemetry.semconv.trace import MessagingOperationValues from opentelemetry.trace import Span, Tracer diff --git a/instrumentation/opentelemetry-instrumentation-aio-pika/src/opentelemetry/instrumentation/aio_pika/span_builder.py b/instrumentation/opentelemetry-instrumentation-aio-pika/src/opentelemetry/instrumentation/aio_pika/span_builder.py index 056f3dab25..b73afa62b3 100644 --- a/instrumentation/opentelemetry-instrumentation-aio-pika/src/opentelemetry/instrumentation/aio_pika/span_builder.py +++ b/instrumentation/opentelemetry-instrumentation-aio-pika/src/opentelemetry/instrumentation/aio_pika/span_builder.py @@ -15,9 +15,7 @@ from aio_pika.abc import AbstractChannel, AbstractMessage -from opentelemetry.instrumentation.aio_pika.utils import ( - is_instrumentation_enabled, -) +from opentelemetry.instrumentation.utils import is_instrumentation_enabled from opentelemetry.semconv.trace import ( MessagingOperationValues, SpanAttributes, From dcf8fb6c517f721564803d3cc0dd030fa619c34e Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Tue, 14 Nov 2023 11:55:22 -0600 Subject: [PATCH 06/12] fmt --- .../src/opentelemetry/instrumentation/utils.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/utils.py b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/utils.py index b64cfbb0f5..318aaeaa74 100644 --- a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/utils.py +++ b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/utils.py @@ -17,15 +17,16 @@ from re import escape, sub from typing import Dict, Iterable, Sequence +from wrapt import ObjectProxy + +from opentelemetry import context, trace + # pylint: disable=E0611 # FIXME: fix the importing of these private attributes when the location of the _SUPPRESS_HTTP_INSTRUMENTATION_KEY is defined.= from opentelemetry.context import ( _SUPPRESS_HTTP_INSTRUMENTATION_KEY, _SUPPRESS_INSTRUMENTATION_KEY, ) -from wrapt import ObjectProxy - -from opentelemetry import context, trace # pylint: disable=E0611 from opentelemetry.propagate import extract @@ -166,10 +167,8 @@ def is_instrumentation_enabled() -> bool: def is_http_instrumentation_enabled() -> bool: - return ( - is_instrumentation_enabled() - and not - context.get_value(_SUPPRESS_HTTP_INSTRUMENTATION_KEY) + return is_instrumentation_enabled() and not context.get_value( + _SUPPRESS_HTTP_INSTRUMENTATION_KEY ) From f09e3a92fd84f8ceb20ff757389f450924febed7 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Tue, 14 Nov 2023 12:00:35 -0600 Subject: [PATCH 07/12] update dep --- .../opentelemetry-instrumentation-aio-pika/pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/instrumentation/opentelemetry-instrumentation-aio-pika/pyproject.toml b/instrumentation/opentelemetry-instrumentation-aio-pika/pyproject.toml index 067fe05551..78674d1541 100644 --- a/instrumentation/opentelemetry-instrumentation-aio-pika/pyproject.toml +++ b/instrumentation/opentelemetry-instrumentation-aio-pika/pyproject.toml @@ -26,7 +26,7 @@ classifiers = [ ] dependencies = [ "opentelemetry-api ~= 1.5", - "opentelemetry-instrumentation == 0.42b0.dev", + "opentelemetry-instrumentation == 0.43b0.dev", "wrapt >= 1.0.0, < 2.0.0", ] From c9626a9b8af94e17914f36261349b0bd033af602 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Wed, 22 Nov 2023 17:29:08 -0600 Subject: [PATCH 08/12] lint --- .../instrumentation/botocore/__init__.py | 2 +- .../tests/test_botocore_instrumentation.py | 5 +++- .../instrumentation/cassandra/__init__.py | 9 +++++-- .../tests/test_cassandra_integration.py | 24 +++++++++++++++---- .../tests/test_programmatic.py | 6 +++-- .../instrumentation/urllib/__init__.py | 2 +- .../instrumentation/wsgi/__init__.py | 4 +++- .../tests/test_wsgi_middleware.py | 14 +++++++---- 8 files changed, 48 insertions(+), 18 deletions(-) diff --git a/instrumentation/opentelemetry-instrumentation-botocore/src/opentelemetry/instrumentation/botocore/__init__.py b/instrumentation/opentelemetry-instrumentation-botocore/src/opentelemetry/instrumentation/botocore/__init__.py index 6a4f337ec5..1053f3405a 100644 --- a/instrumentation/opentelemetry-instrumentation-botocore/src/opentelemetry/instrumentation/botocore/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-botocore/src/opentelemetry/instrumentation/botocore/__init__.py @@ -210,7 +210,7 @@ def _patched_api_call(self, original_func, instance, args, kwargs): raise else: _apply_response_attributes(span, result) - _safe_invoke(extension.on_success, span, result) + _safe_invoke(extension.on_success, span, result) finally: _safe_invoke(extension.after_service_call) self._call_response_hook(span, call_context, result) diff --git a/instrumentation/opentelemetry-instrumentation-botocore/tests/test_botocore_instrumentation.py b/instrumentation/opentelemetry-instrumentation-botocore/tests/test_botocore_instrumentation.py index d617760037..bb6d283399 100644 --- a/instrumentation/opentelemetry-instrumentation-botocore/tests/test_botocore_instrumentation.py +++ b/instrumentation/opentelemetry-instrumentation-botocore/tests/test_botocore_instrumentation.py @@ -28,7 +28,10 @@ from opentelemetry import trace as trace_api from opentelemetry.instrumentation.botocore import BotocoreInstrumentor -from opentelemetry.instrumentation.utils import suppress_http_instrumentation, suppress_instrumentation +from opentelemetry.instrumentation.utils import ( + suppress_http_instrumentation, + suppress_instrumentation, +) from opentelemetry.propagate import get_global_textmap, set_global_textmap from opentelemetry.propagators.aws.aws_xray_propagator import TRACE_HEADER_KEY from opentelemetry.semconv.trace import SpanAttributes diff --git a/instrumentation/opentelemetry-instrumentation-cassandra/src/opentelemetry/instrumentation/cassandra/__init__.py b/instrumentation/opentelemetry-instrumentation-cassandra/src/opentelemetry/instrumentation/cassandra/__init__.py index a8dd1f6cbf..2a9239f152 100644 --- a/instrumentation/opentelemetry-instrumentation-cassandra/src/opentelemetry/instrumentation/cassandra/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-cassandra/src/opentelemetry/instrumentation/cassandra/__init__.py @@ -70,7 +70,10 @@ def _traced_execute_async(func, instance, args, kwargs): if span.is_recording(): span.set_attribute(SpanAttributes.DB_NAME, instance.keyspace) span.set_attribute(SpanAttributes.DB_SYSTEM, "cassandra") - span.set_attribute(SpanAttributes.NET_PEER_NAME, instance.cluster.contact_points) + span.set_attribute( + SpanAttributes.NET_PEER_NAME, + instance.cluster.contact_points, + ) if include_db_statement: query = args[0] @@ -79,7 +82,9 @@ def _traced_execute_async(func, instance, args, kwargs): response = func(*args, **kwargs) return response - wrap_function_wrapper("cassandra.cluster", "Session.execute_async", _traced_execute_async) + wrap_function_wrapper( + "cassandra.cluster", "Session.execute_async", _traced_execute_async + ) class CassandraInstrumentor(BaseInstrumentor): diff --git a/instrumentation/opentelemetry-instrumentation-cassandra/tests/test_cassandra_integration.py b/instrumentation/opentelemetry-instrumentation-cassandra/tests/test_cassandra_integration.py index 6977e1b2a2..ed488ab07f 100644 --- a/instrumentation/opentelemetry-instrumentation-cassandra/tests/test_cassandra_integration.py +++ b/instrumentation/opentelemetry-instrumentation-cassandra/tests/test_cassandra_integration.py @@ -46,15 +46,25 @@ def tearDown(self): def test_instrument_uninstrument(self): instrumentation = CassandraInstrumentor() instrumentation.instrument() - self.assertTrue(isinstance(cassandra.cluster.Session.execute_async, BoundFunctionWrapper)) + self.assertTrue( + isinstance( + cassandra.cluster.Session.execute_async, BoundFunctionWrapper + ) + ) instrumentation.uninstrument() - self.assertFalse(isinstance(cassandra.cluster.Session.execute_async, BoundFunctionWrapper)) + self.assertFalse( + isinstance( + cassandra.cluster.Session.execute_async, BoundFunctionWrapper + ) + ) @mock.patch("cassandra.cluster.Cluster.connect") @mock.patch("cassandra.cluster.Session.__init__") @mock.patch("cassandra.cluster.Session._create_response_future") - def test_instrumentor(self, mock_create_response_future, mock_session_init, mock_connect): + def test_instrumentor( + self, mock_create_response_future, mock_session_init, mock_connect + ): mock_create_response_future.return_value = mock.Mock() mock_session_init.return_value = None mock_connect.return_value = cassandra.cluster.Session() @@ -85,7 +95,9 @@ def test_instrumentor(self, mock_create_response_future, mock_session_init, mock @mock.patch("cassandra.cluster.Cluster.connect") @mock.patch("cassandra.cluster.Session.__init__") @mock.patch("cassandra.cluster.Session._create_response_future") - def test_custom_tracer_provider(self, mock_create_response_future, mock_session_init, mock_connect): + def test_custom_tracer_provider( + self, mock_create_response_future, mock_session_init, mock_connect + ): mock_create_response_future.return_value = mock.Mock() mock_session_init.return_value = None mock_connect.return_value = cassandra.cluster.Session() @@ -107,7 +119,9 @@ def test_custom_tracer_provider(self, mock_create_response_future, mock_session_ @mock.patch("cassandra.cluster.Cluster.connect") @mock.patch("cassandra.cluster.Session.__init__") @mock.patch("cassandra.cluster.Session._create_response_future") - def test_instrument_connection_no_op_tracer_provider(self, mock_create_response_future, mock_session_init, mock_connect): + def test_instrument_connection_no_op_tracer_provider( + self, mock_create_response_future, mock_session_init, mock_connect + ): mock_create_response_future.return_value = mock.Mock() mock_session_init.return_value = None mock_connect.return_value = cassandra.cluster.Session() diff --git a/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py b/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py index d903ef393b..3bd2f74ba8 100644 --- a/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py +++ b/instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py @@ -327,7 +327,9 @@ def test_flask_metric_values(self): if isinstance(point, NumberDataPoint): self.assertEqual(point.value, 0) - def _assert_basic_metric(self, expected_duration_attributes, expected_requests_count_attributes): + def _assert_basic_metric( + self, expected_duration_attributes, expected_requests_count_attributes + ): 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: @@ -393,7 +395,7 @@ def test_basic_metric_nonstandard_http_method_success(self): ) @patch.dict( - "os.environ", + "os.environ", { OTEL_PYTHON_INSTRUMENTATION_HTTP_CAPTURE_ALL_METHODS: "1", }, diff --git a/instrumentation/opentelemetry-instrumentation-urllib/src/opentelemetry/instrumentation/urllib/__init__.py b/instrumentation/opentelemetry-instrumentation-urllib/src/opentelemetry/instrumentation/urllib/__init__.py index 35d846e4a0..3738c4d2c6 100644 --- a/instrumentation/opentelemetry-instrumentation-urllib/src/opentelemetry/instrumentation/urllib/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-urllib/src/opentelemetry/instrumentation/urllib/__init__.py @@ -89,9 +89,9 @@ def response_hook(span, request_obj, response) from opentelemetry.instrumentation.urllib.package import _instruments from opentelemetry.instrumentation.urllib.version import __version__ from opentelemetry.instrumentation.utils import ( + http_status_to_status_code, is_http_instrumentation_enabled, suppress_http_instrumentation, - http_status_to_status_code, ) from opentelemetry.metrics import Histogram, get_meter from opentelemetry.propagate import inject diff --git a/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py b/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py index 36fe69daec..87c73cc737 100644 --- a/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py @@ -302,7 +302,9 @@ def collect_request_attributes(environ): """ result = { - SpanAttributes.HTTP_METHOD: sanitize_method(environ.get("REQUEST_METHOD")), + SpanAttributes.HTTP_METHOD: sanitize_method( + environ.get("REQUEST_METHOD") + ), SpanAttributes.HTTP_SERVER_NAME: environ.get("SERVER_NAME"), SpanAttributes.HTTP_SCHEME: environ.get("wsgi.url_scheme"), } diff --git a/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py b/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py index c1b5026cc7..d71e584ca8 100644 --- a/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py +++ b/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py @@ -287,22 +287,26 @@ def test_wsgi_metrics(self): self.assertTrue(number_data_point_seen and histogram_data_point_seen) def test_nonstandard_http_method(self): - self.environ["REQUEST_METHOD"]= "NONSTANDARD" + self.environ["REQUEST_METHOD"] = "NONSTANDARD" app = otel_wsgi.OpenTelemetryMiddleware(simple_wsgi) response = app(self.environ, self.start_response) - self.validate_response(response, span_name="UNKNOWN /", http_method="UNKNOWN") + self.validate_response( + response, span_name="UNKNOWN /", http_method="UNKNOWN" + ) @mock.patch.dict( - "os.environ", + "os.environ", { OTEL_PYTHON_INSTRUMENTATION_HTTP_CAPTURE_ALL_METHODS: "1", }, ) def test_nonstandard_http_method_allowed(self): - self.environ["REQUEST_METHOD"]= "NONSTANDARD" + self.environ["REQUEST_METHOD"] = "NONSTANDARD" app = otel_wsgi.OpenTelemetryMiddleware(simple_wsgi) response = app(self.environ, self.start_response) - self.validate_response(response, span_name="NONSTANDARD /", http_method="NONSTANDARD") + self.validate_response( + response, span_name="NONSTANDARD /", http_method="NONSTANDARD" + ) def test_default_span_name_missing_path_info(self): """Test that default span_names with missing path info.""" From 5a1c58a65ae155dbefff2c302125ad102e89fe4e Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Mon, 27 Nov 2023 11:57:39 -0600 Subject: [PATCH 09/12] remove unused imports --- .../tests/test_aiohttp_client_integration.py | 1 - .../src/opentelemetry/instrumentation/botocore/__init__.py | 1 - .../src/opentelemetry/instrumentation/grpc/_client.py | 2 +- .../tests/test_aio_client_interceptor.py | 2 +- .../tests/test_client_interceptor.py | 2 +- .../tests/test_client_interceptor_filter.py | 2 +- .../src/opentelemetry/instrumentation/pymongo/__init__.py | 1 - .../opentelemetry-instrumentation-pymongo/tests/test_pymongo.py | 1 - .../src/opentelemetry/instrumentation/urllib3/__init__.py | 1 - .../tests/test_urllib3_integration.py | 2 +- 10 files changed, 5 insertions(+), 10 deletions(-) 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 index 6865b62020..2fa97f40b0 100644 --- a/instrumentation/opentelemetry-instrumentation-aiohttp-client/tests/test_aiohttp_client_integration.py +++ b/instrumentation/opentelemetry-instrumentation-aiohttp-client/tests/test_aiohttp_client_integration.py @@ -27,7 +27,6 @@ from http_server_mock import HttpServerMock from pkg_resources import iter_entry_points -from opentelemetry import context from opentelemetry import trace as trace_api from opentelemetry.instrumentation import aiohttp_client from opentelemetry.instrumentation.aiohttp_client import ( diff --git a/instrumentation/opentelemetry-instrumentation-botocore/src/opentelemetry/instrumentation/botocore/__init__.py b/instrumentation/opentelemetry-instrumentation-botocore/src/opentelemetry/instrumentation/botocore/__init__.py index 1053f3405a..7832d0b8fa 100644 --- a/instrumentation/opentelemetry-instrumentation-botocore/src/opentelemetry/instrumentation/botocore/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-botocore/src/opentelemetry/instrumentation/botocore/__init__.py @@ -86,7 +86,6 @@ def response_hook(span, service_name, operation_name, result): from botocore.exceptions import ClientError from wrapt import wrap_function_wrapper -from opentelemetry import context as context_api from opentelemetry.instrumentation.botocore.extensions import _find_extension from opentelemetry.instrumentation.botocore.extensions.types import ( _AwsSdkCallContext, diff --git a/instrumentation/opentelemetry-instrumentation-grpc/src/opentelemetry/instrumentation/grpc/_client.py b/instrumentation/opentelemetry-instrumentation-grpc/src/opentelemetry/instrumentation/grpc/_client.py index 0a4f8df866..e27c9e826f 100644 --- a/instrumentation/opentelemetry-instrumentation-grpc/src/opentelemetry/instrumentation/grpc/_client.py +++ b/instrumentation/opentelemetry-instrumentation-grpc/src/opentelemetry/instrumentation/grpc/_client.py @@ -25,7 +25,7 @@ import grpc -from opentelemetry import context, trace +from opentelemetry import trace from opentelemetry.instrumentation.grpc import grpcext from opentelemetry.instrumentation.grpc._utilities import RpcInfo from opentelemetry.instrumentation.utils import is_instrumentation_enabled diff --git a/instrumentation/opentelemetry-instrumentation-grpc/tests/test_aio_client_interceptor.py b/instrumentation/opentelemetry-instrumentation-grpc/tests/test_aio_client_interceptor.py index ad95711aa1..6b1006b8a3 100644 --- a/instrumentation/opentelemetry-instrumentation-grpc/tests/test_aio_client_interceptor.py +++ b/instrumentation/opentelemetry-instrumentation-grpc/tests/test_aio_client_interceptor.py @@ -31,7 +31,7 @@ def run(self, result=None): import pytest import opentelemetry.instrumentation.grpc -from opentelemetry import context, trace +from opentelemetry import trace from opentelemetry.instrumentation.grpc import ( GrpcAioInstrumentorClient, aio_client_interceptors, diff --git a/instrumentation/opentelemetry-instrumentation-grpc/tests/test_client_interceptor.py b/instrumentation/opentelemetry-instrumentation-grpc/tests/test_client_interceptor.py index bd27e1974e..2436aca40c 100644 --- a/instrumentation/opentelemetry-instrumentation-grpc/tests/test_client_interceptor.py +++ b/instrumentation/opentelemetry-instrumentation-grpc/tests/test_client_interceptor.py @@ -19,7 +19,7 @@ ) import opentelemetry.instrumentation.grpc -from opentelemetry import context, trace +from opentelemetry import trace from opentelemetry.instrumentation.grpc import GrpcInstrumentorClient from opentelemetry.instrumentation.grpc._client import ( OpenTelemetryClientInterceptor, diff --git a/instrumentation/opentelemetry-instrumentation-grpc/tests/test_client_interceptor_filter.py b/instrumentation/opentelemetry-instrumentation-grpc/tests/test_client_interceptor_filter.py index 784529eb43..9a9aefad59 100644 --- a/instrumentation/opentelemetry-instrumentation-grpc/tests/test_client_interceptor_filter.py +++ b/instrumentation/opentelemetry-instrumentation-grpc/tests/test_client_interceptor_filter.py @@ -22,7 +22,7 @@ ) import opentelemetry.instrumentation.grpc -from opentelemetry import context, trace +from opentelemetry import trace from opentelemetry.instrumentation.grpc import GrpcInstrumentorClient, filters from opentelemetry.instrumentation.grpc._client import ( OpenTelemetryClientInterceptor, diff --git a/instrumentation/opentelemetry-instrumentation-pymongo/src/opentelemetry/instrumentation/pymongo/__init__.py b/instrumentation/opentelemetry-instrumentation-pymongo/src/opentelemetry/instrumentation/pymongo/__init__.py index 1f2c000036..506669a5c6 100644 --- a/instrumentation/opentelemetry-instrumentation-pymongo/src/opentelemetry/instrumentation/pymongo/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-pymongo/src/opentelemetry/instrumentation/pymongo/__init__.py @@ -79,7 +79,6 @@ def failed_hook(span, event): 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.utils import ( diff --git a/instrumentation/opentelemetry-instrumentation-pymongo/tests/test_pymongo.py b/instrumentation/opentelemetry-instrumentation-pymongo/tests/test_pymongo.py index ba6597b588..5a8acfda31 100644 --- a/instrumentation/opentelemetry-instrumentation-pymongo/tests/test_pymongo.py +++ b/instrumentation/opentelemetry-instrumentation-pymongo/tests/test_pymongo.py @@ -14,7 +14,6 @@ from unittest import mock -from opentelemetry import context from opentelemetry import trace as trace_api from opentelemetry.instrumentation.pymongo import ( CommandTracer, diff --git a/instrumentation/opentelemetry-instrumentation-urllib3/src/opentelemetry/instrumentation/urllib3/__init__.py b/instrumentation/opentelemetry-instrumentation-urllib3/src/opentelemetry/instrumentation/urllib3/__init__.py index fe6fdf08f1..985f291199 100644 --- a/instrumentation/opentelemetry-instrumentation-urllib3/src/opentelemetry/instrumentation/urllib3/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-urllib3/src/opentelemetry/instrumentation/urllib3/__init__.py @@ -79,7 +79,6 @@ def response_hook(span, request, response): """ import collections.abc -import contextlib import io import typing from timeit import default_timer diff --git a/instrumentation/opentelemetry-instrumentation-urllib3/tests/test_urllib3_integration.py b/instrumentation/opentelemetry-instrumentation-urllib3/tests/test_urllib3_integration.py index 50a2bfe3ad..23124ea590 100644 --- a/instrumentation/opentelemetry-instrumentation-urllib3/tests/test_urllib3_integration.py +++ b/instrumentation/opentelemetry-instrumentation-urllib3/tests/test_urllib3_integration.py @@ -19,7 +19,7 @@ import urllib3 import urllib3.exceptions -from opentelemetry import context, trace +from opentelemetry import trace from opentelemetry.instrumentation.urllib3 import URLLib3Instrumentor from opentelemetry.instrumentation.utils import ( suppress_http_instrumentation, From ed728c2548b1f35e064d17cb9bed71284a4f6925 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Mon, 27 Nov 2023 16:05:51 -0600 Subject: [PATCH 10/12] apply lint --- .../src/opentelemetry/instrumentation/botocore/__init__.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/instrumentation/opentelemetry-instrumentation-botocore/src/opentelemetry/instrumentation/botocore/__init__.py b/instrumentation/opentelemetry-instrumentation-botocore/src/opentelemetry/instrumentation/botocore/__init__.py index 7832d0b8fa..36b973e318 100644 --- a/instrumentation/opentelemetry-instrumentation-botocore/src/opentelemetry/instrumentation/botocore/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-botocore/src/opentelemetry/instrumentation/botocore/__init__.py @@ -207,9 +207,8 @@ def _patched_api_call(self, original_func, instance, args, kwargs): _apply_response_attributes(span, result) _safe_invoke(extension.on_error, span, error) raise - else: - _apply_response_attributes(span, result) - _safe_invoke(extension.on_success, span, result) + _apply_response_attributes(span, result) + _safe_invoke(extension.on_success, span, result) finally: _safe_invoke(extension.after_service_call) self._call_response_hook(span, call_context, result) From 6feba0544e11133467cbce0e7097bdb8c15ca26a Mon Sep 17 00:00:00 2001 From: Diego Hurtado Date: Fri, 22 Dec 2023 16:14:56 -0600 Subject: [PATCH 11/12] Fix version for pika --- .../opentelemetry-instrumentation-aio-pika/pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/instrumentation/opentelemetry-instrumentation-aio-pika/pyproject.toml b/instrumentation/opentelemetry-instrumentation-aio-pika/pyproject.toml index 78674d1541..35a538b7a1 100644 --- a/instrumentation/opentelemetry-instrumentation-aio-pika/pyproject.toml +++ b/instrumentation/opentelemetry-instrumentation-aio-pika/pyproject.toml @@ -26,7 +26,7 @@ classifiers = [ ] dependencies = [ "opentelemetry-api ~= 1.5", - "opentelemetry-instrumentation == 0.43b0.dev", + "opentelemetry-instrumentation == 0.44b0.dev", "wrapt >= 1.0.0, < 2.0.0", ] From 17cf9d440c424220139e4516cd0b72d17918a310 Mon Sep 17 00:00:00 2001 From: Diego Hurtado Date: Fri, 22 Dec 2023 16:15:16 -0600 Subject: [PATCH 12/12] Fix lint --- .../tests/test_requests_integration.py | 1 - 1 file changed, 1 deletion(-) diff --git a/instrumentation/opentelemetry-instrumentation-requests/tests/test_requests_integration.py b/instrumentation/opentelemetry-instrumentation-requests/tests/test_requests_integration.py index b2cbade2c7..8817053068 100644 --- a/instrumentation/opentelemetry-instrumentation-requests/tests/test_requests_integration.py +++ b/instrumentation/opentelemetry-instrumentation-requests/tests/test_requests_integration.py @@ -22,7 +22,6 @@ import opentelemetry.instrumentation.requests from opentelemetry import trace - from opentelemetry.instrumentation._semconv import ( _OTEL_SEMCONV_STABILITY_OPT_IN_KEY, _SPAN_ATTRIBUTES_ERROR_TYPE,