Skip to content

Commit ef2c7cc

Browse files
committed
Clean up use of suppress_instrumentation in context and fix httpx bug
1 parent ba190a8 commit ef2c7cc

File tree

25 files changed

+166
-321
lines changed

25 files changed

+166
-321
lines changed

instrumentation/opentelemetry-instrumentation-aiohttp-client/src/opentelemetry/instrumentation/aiohttp_client/__init__.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -94,8 +94,8 @@ def response_hook(span: Span, params: typing.Union[
9494
from opentelemetry.instrumentation.aiohttp_client.version import __version__
9595
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
9696
from opentelemetry.instrumentation.utils import (
97-
_SUPPRESS_INSTRUMENTATION_KEY,
9897
http_status_to_status_code,
98+
is_instrumentation_enabled,
9999
unwrap,
100100
)
101101
from opentelemetry.propagate import inject
@@ -179,7 +179,7 @@ async def on_request_start(
179179
trace_config_ctx: types.SimpleNamespace,
180180
params: aiohttp.TraceRequestStartParams,
181181
):
182-
if context_api.get_value(_SUPPRESS_INSTRUMENTATION_KEY):
182+
if not is_instrumentation_enabled():
183183
trace_config_ctx.span = None
184184
return
185185

@@ -282,7 +282,7 @@ def _instrument(
282282

283283
# pylint:disable=unused-argument
284284
def instrumented_init(wrapped, instance, args, kwargs):
285-
if context_api.get_value(_SUPPRESS_INSTRUMENTATION_KEY):
285+
if not is_instrumentation_enabled():
286286
return wrapped(*args, **kwargs)
287287

288288
client_trace_configs = list(kwargs.get("trace_configs") or [])

instrumentation/opentelemetry-instrumentation-aiohttp-client/tests/test_aiohttp_client_integration.py

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
from opentelemetry.instrumentation.aiohttp_client import (
3333
AioHttpClientInstrumentor,
3434
)
35-
from opentelemetry.instrumentation.utils import _SUPPRESS_INSTRUMENTATION_KEY
35+
from opentelemetry.instrumentation.utils import suppress_instrumentation
3636
from opentelemetry.semconv.trace import SpanAttributes
3737
from opentelemetry.test.test_base import TestBase
3838
from opentelemetry.trace import Span, StatusCode
@@ -506,25 +506,17 @@ async def uninstrument_request(server: aiohttp.test_utils.TestServer):
506506
self.assert_spans(1)
507507

508508
def test_suppress_instrumentation(self):
509-
token = context.attach(
510-
context.set_value(_SUPPRESS_INSTRUMENTATION_KEY, True)
511-
)
512-
try:
509+
with suppress_instrumentation():
513510
run_with_test_server(
514511
self.get_default_request(), self.URL, self.default_handler
515512
)
516-
finally:
517-
context.detach(token)
518513
self.assert_spans(0)
519514

520515
@staticmethod
521516
async def suppressed_request(server: aiohttp.test_utils.TestServer):
522517
async with aiohttp.test_utils.TestClient(server) as client:
523-
token = context.attach(
524-
context.set_value(_SUPPRESS_INSTRUMENTATION_KEY, True)
525-
)
526-
await client.get(TestAioHttpClientInstrumentor.URL)
527-
context.detach(token)
518+
with suppress_instrumentation():
519+
await client.get(TestAioHttpClientInstrumentor.URL)
528520

529521
def test_suppress_instrumentation_after_creation(self):
530522
run_with_test_server(

instrumentation/opentelemetry-instrumentation-boto3sqs/src/opentelemetry/instrumentation/boto3sqs/__init__.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@
3838
from opentelemetry import context, propagate, trace
3939
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
4040
from opentelemetry.instrumentation.utils import (
41-
_SUPPRESS_INSTRUMENTATION_KEY,
41+
is_instrumentation_enabled,
4242
unwrap,
4343
)
4444
from opentelemetry.propagators.textmap import CarrierT, Getter, Setter
@@ -218,7 +218,7 @@ def _create_processing_span(
218218

219219
def _wrap_send_message(self, sqs_class: type) -> None:
220220
def send_wrapper(wrapped, instance, args, kwargs):
221-
if context.get_value(_SUPPRESS_INSTRUMENTATION_KEY):
221+
if not is_instrumentation_enabled():
222222
return wrapped(*args, **kwargs)
223223
queue_url = kwargs.get("QueueUrl")
224224
# 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):
252252
# The method expect QueueUrl and Entries params, so if they are None, we call wrapped to receive the
253253
# original exception
254254
if (
255-
context.get_value(_SUPPRESS_INSTRUMENTATION_KEY)
255+
not is_instrumentation_enabled()
256256
or not queue_url
257257
or not entries
258258
):

instrumentation/opentelemetry-instrumentation-botocore/src/opentelemetry/instrumentation/botocore/__init__.py

Lines changed: 15 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -87,9 +87,6 @@ def response_hook(span, service_name, operation_name, result):
8787
from wrapt import wrap_function_wrapper
8888

8989
from opentelemetry import context as context_api
90-
91-
# FIXME: fix the importing of this private attribute when the location of the _SUPPRESS_HTTP_INSTRUMENTATION_KEY is defined.
92-
from opentelemetry.context import _SUPPRESS_HTTP_INSTRUMENTATION_KEY
9390
from opentelemetry.instrumentation.botocore.extensions import _find_extension
9491
from opentelemetry.instrumentation.botocore.extensions.types import (
9592
_AwsSdkCallContext,
@@ -98,7 +95,8 @@ def response_hook(span, service_name, operation_name, result):
9895
from opentelemetry.instrumentation.botocore.version import __version__
9996
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
10097
from opentelemetry.instrumentation.utils import (
101-
_SUPPRESS_INSTRUMENTATION_KEY,
98+
is_instrumentation_enabled,
99+
suppress_http_instrumentation,
102100
unwrap,
103101
)
104102
from opentelemetry.propagators.aws.aws_xray_propagator import AwsXRayPropagator
@@ -171,7 +169,7 @@ def _patched_endpoint_prepare_request(
171169

172170
# pylint: disable=too-many-branches
173171
def _patched_api_call(self, original_func, instance, args, kwargs):
174-
if context_api.get_value(_SUPPRESS_INSTRUMENTATION_KEY):
172+
if not is_instrumentation_enabled():
175173
return original_func(*args, **kwargs)
176174

177175
call_context = _determine_call_context(instance, args)
@@ -200,25 +198,21 @@ def _patched_api_call(self, original_func, instance, args, kwargs):
200198
_safe_invoke(extension.before_service_call, span)
201199
self._call_request_hook(span, call_context)
202200

203-
token = context_api.attach(
204-
context_api.set_value(_SUPPRESS_HTTP_INSTRUMENTATION_KEY, True)
205-
)
206-
207-
result = None
208201
try:
209-
result = original_func(*args, **kwargs)
210-
except ClientError as error:
211-
result = getattr(error, "response", None)
212-
_apply_response_attributes(span, result)
213-
_safe_invoke(extension.on_error, span, error)
214-
raise
215-
else:
216-
_apply_response_attributes(span, result)
217-
_safe_invoke(extension.on_success, span, result)
202+
with suppress_http_instrumentation():
203+
result = None
204+
try:
205+
result = original_func(*args, **kwargs)
206+
except ClientError as error:
207+
result = getattr(error, "response", None)
208+
_apply_response_attributes(span, result)
209+
_safe_invoke(extension.on_error, span, error)
210+
raise
211+
else:
212+
_apply_response_attributes(span, result)
213+
_safe_invoke(extension.on_success, span, result)
218214
finally:
219-
context_api.detach(token)
220215
_safe_invoke(extension.after_service_call)
221-
222216
self._call_response_hook(span, call_context, result)
223217

224218
return result

instrumentation/opentelemetry-instrumentation-botocore/tests/test_botocore_instrumentation.py

Lines changed: 3 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -27,14 +27,8 @@
2727
)
2828

2929
from opentelemetry import trace as trace_api
30-
from opentelemetry.context import (
31-
_SUPPRESS_HTTP_INSTRUMENTATION_KEY,
32-
attach,
33-
detach,
34-
set_value,
35-
)
3630
from opentelemetry.instrumentation.botocore import BotocoreInstrumentor
37-
from opentelemetry.instrumentation.utils import _SUPPRESS_INSTRUMENTATION_KEY
31+
from opentelemetry.instrumentation.utils import suppress_http_instrumentation, suppress_instrumentation
3832
from opentelemetry.propagate import get_global_textmap, set_global_textmap
3933
from opentelemetry.propagators.aws.aws_xray_propagator import TRACE_HEADER_KEY
4034
from opentelemetry.semconv.trace import SpanAttributes
@@ -341,23 +335,16 @@ def check_headers(**kwargs):
341335
@mock_xray
342336
def test_suppress_instrumentation_xray_client(self):
343337
xray_client = self._make_client("xray")
344-
token = attach(set_value(_SUPPRESS_INSTRUMENTATION_KEY, True))
345-
try:
338+
with suppress_instrumentation():
346339
xray_client.put_trace_segments(TraceSegmentDocuments=["str1"])
347340
xray_client.put_trace_segments(TraceSegmentDocuments=["str2"])
348-
finally:
349-
detach(token)
350341
self.assertEqual(0, len(self.get_finished_spans()))
351342

352343
@mock_xray
353344
def test_suppress_http_instrumentation_xray_client(self):
354-
xray_client = self._make_client("xray")
355-
token = attach(set_value(_SUPPRESS_HTTP_INSTRUMENTATION_KEY, True))
356-
try:
345+
with suppress_http_instrumentation():
357346
xray_client.put_trace_segments(TraceSegmentDocuments=["str1"])
358347
xray_client.put_trace_segments(TraceSegmentDocuments=["str2"])
359-
finally:
360-
detach(token)
361348
self.assertEqual(2, len(self.get_finished_spans()))
362349

363350
@mock_s3

instrumentation/opentelemetry-instrumentation-cassandra/src/opentelemetry/instrumentation/cassandra/__init__.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -70,10 +70,7 @@ def _traced_execute_async(func, instance, args, kwargs):
7070
if span.is_recording():
7171
span.set_attribute(SpanAttributes.DB_NAME, instance.keyspace)
7272
span.set_attribute(SpanAttributes.DB_SYSTEM, "cassandra")
73-
span.set_attribute(
74-
SpanAttributes.NET_PEER_NAME,
75-
instance.cluster.contact_points,
76-
)
73+
span.set_attribute(SpanAttributes.NET_PEER_NAME, instance.cluster.contact_points)
7774

7875
if include_db_statement:
7976
query = args[0]
@@ -82,9 +79,7 @@ def _traced_execute_async(func, instance, args, kwargs):
8279
response = func(*args, **kwargs)
8380
return response
8481

85-
wrap_function_wrapper(
86-
"cassandra.cluster", "Session.execute_async", _traced_execute_async
87-
)
82+
wrap_function_wrapper("cassandra.cluster", "Session.execute_async", _traced_execute_async)
8883

8984

9085
class CassandraInstrumentor(BaseInstrumentor):

instrumentation/opentelemetry-instrumentation-cassandra/tests/test_cassandra_integration.py

Lines changed: 5 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -46,25 +46,15 @@ def tearDown(self):
4646
def test_instrument_uninstrument(self):
4747
instrumentation = CassandraInstrumentor()
4848
instrumentation.instrument()
49-
self.assertTrue(
50-
isinstance(
51-
cassandra.cluster.Session.execute_async, BoundFunctionWrapper
52-
)
53-
)
49+
self.assertTrue(isinstance(cassandra.cluster.Session.execute_async, BoundFunctionWrapper))
5450

5551
instrumentation.uninstrument()
56-
self.assertFalse(
57-
isinstance(
58-
cassandra.cluster.Session.execute_async, BoundFunctionWrapper
59-
)
60-
)
52+
self.assertFalse(isinstance(cassandra.cluster.Session.execute_async, BoundFunctionWrapper))
6153

6254
@mock.patch("cassandra.cluster.Cluster.connect")
6355
@mock.patch("cassandra.cluster.Session.__init__")
6456
@mock.patch("cassandra.cluster.Session._create_response_future")
65-
def test_instrumentor(
66-
self, mock_create_response_future, mock_session_init, mock_connect
67-
):
57+
def test_instrumentor(self, mock_create_response_future, mock_session_init, mock_connect):
6858
mock_create_response_future.return_value = mock.Mock()
6959
mock_session_init.return_value = None
7060
mock_connect.return_value = cassandra.cluster.Session()
@@ -95,9 +85,7 @@ def test_instrumentor(
9585
@mock.patch("cassandra.cluster.Cluster.connect")
9686
@mock.patch("cassandra.cluster.Session.__init__")
9787
@mock.patch("cassandra.cluster.Session._create_response_future")
98-
def test_custom_tracer_provider(
99-
self, mock_create_response_future, mock_session_init, mock_connect
100-
):
88+
def test_custom_tracer_provider(self, mock_create_response_future, mock_session_init, mock_connect):
10189
mock_create_response_future.return_value = mock.Mock()
10290
mock_session_init.return_value = None
10391
mock_connect.return_value = cassandra.cluster.Session()
@@ -119,9 +107,7 @@ def test_custom_tracer_provider(
119107
@mock.patch("cassandra.cluster.Cluster.connect")
120108
@mock.patch("cassandra.cluster.Session.__init__")
121109
@mock.patch("cassandra.cluster.Session._create_response_future")
122-
def test_instrument_connection_no_op_tracer_provider(
123-
self, mock_create_response_future, mock_session_init, mock_connect
124-
):
110+
def test_instrument_connection_no_op_tracer_provider(self, mock_create_response_future, mock_session_init, mock_connect):
125111
mock_create_response_future.return_value = mock.Mock()
126112
mock_session_init.return_value = None
127113
mock_connect.return_value = cassandra.cluster.Session()

instrumentation/opentelemetry-instrumentation-flask/tests/test_programmatic.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -328,9 +328,7 @@ def test_flask_metric_values(self):
328328
if isinstance(point, NumberDataPoint):
329329
self.assertEqual(point.value, 0)
330330

331-
def _assert_basic_metric(
332-
self, expected_duration_attributes, expected_requests_count_attributes
333-
):
331+
def _assert_basic_metric(self, expected_duration_attributes, expected_requests_count_attributes):
334332
metrics_list = self.memory_metrics_reader.get_metrics_data()
335333
for resource_metric in metrics_list.resource_metrics:
336334
for scope_metrics in resource_metric.scope_metrics:
@@ -396,7 +394,7 @@ def test_basic_metric_nonstandard_http_method_success(self):
396394
)
397395

398396
@patch.dict(
399-
"os.environ",
397+
"os.environ",
400398
{
401399
OTEL_PYTHON_INSTRUMENTATION_HTTP_CAPTURE_ALL_METHODS: "1",
402400
},

instrumentation/opentelemetry-instrumentation-grpc/src/opentelemetry/instrumentation/grpc/_aio_client.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,11 @@
1919
import grpc
2020
from grpc.aio import ClientCallDetails
2121

22-
from opentelemetry import context
2322
from opentelemetry.instrumentation.grpc._client import (
2423
OpenTelemetryClientInterceptor,
2524
_carrier_setter,
2625
)
27-
from opentelemetry.instrumentation.utils import _SUPPRESS_INSTRUMENTATION_KEY
26+
from opentelemetry.instrumentation.utils import is_instrumentation_enabled
2827
from opentelemetry.propagate import inject
2928
from opentelemetry.semconv.trace import SpanAttributes
3029
from opentelemetry.trace.status import Status, StatusCode
@@ -139,9 +138,10 @@ async def _wrap_stream_response(self, span, call):
139138
span.end()
140139

141140
def tracing_skipped(self, client_call_details):
142-
return context.get_value(
143-
_SUPPRESS_INSTRUMENTATION_KEY
144-
) or not self.rpc_matches_filters(client_call_details)
141+
return (
142+
not is_instrumentation_enabled()
143+
or not self.rpc_matches_filters(client_call_details)
144+
)
145145

146146
def rpc_matches_filters(self, client_call_details):
147147
return self._filter is None or self._filter(client_call_details)

instrumentation/opentelemetry-instrumentation-grpc/src/opentelemetry/instrumentation/grpc/_client.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
from opentelemetry import context, trace
2929
from opentelemetry.instrumentation.grpc import grpcext
3030
from opentelemetry.instrumentation.grpc._utilities import RpcInfo
31-
from opentelemetry.instrumentation.utils import _SUPPRESS_INSTRUMENTATION_KEY
31+
from opentelemetry.instrumentation.utils import is_instrumentation_enabled
3232
from opentelemetry.propagate import inject
3333
from opentelemetry.propagators.textmap import Setter
3434
from opentelemetry.semconv.trace import SpanAttributes
@@ -123,7 +123,7 @@ def _trace_result(self, span, rpc_info, result):
123123
return result
124124

125125
def _intercept(self, request, metadata, client_info, invoker):
126-
if context.get_value(_SUPPRESS_INSTRUMENTATION_KEY):
126+
if not is_instrumentation_enabled():
127127
return invoker(request, metadata)
128128

129129
if not metadata:
@@ -219,7 +219,7 @@ def _intercept_server_stream(
219219
def intercept_stream(
220220
self, request_or_iterator, metadata, client_info, invoker
221221
):
222-
if context.get_value(_SUPPRESS_INSTRUMENTATION_KEY):
222+
if not is_instrumentation_enabled():
223223
return invoker(request_or_iterator, metadata)
224224

225225
if self._filter is not None and not self._filter(client_info):

0 commit comments

Comments
 (0)