Skip to content

Commit 7758d5e

Browse files
committed
Move all key access to a single spot and deduplicate context managers
1 parent ba190a8 commit 7758d5e

File tree

31 files changed

+205
-319
lines changed

31 files changed

+205
-319
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: 17 additions & 22 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,22 @@ 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)
214+
finally:
215+
_safe_invoke(extension.after_service_call)
218216
finally:
219-
context_api.detach(token)
220-
_safe_invoke(extension.after_service_call)
221-
222217
self._call_response_hook(span, call_context, result)
223218

224219
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_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_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: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,9 @@
4343
from wrapt import wrap_function_wrapper
4444

4545
from opentelemetry import trace
46-
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
4746
from opentelemetry.instrumentation.cassandra.package import _instruments
4847
from opentelemetry.instrumentation.cassandra.version import __version__
48+
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
4949
from opentelemetry.instrumentation.utils import unwrap
5050
from opentelemetry.semconv.trace import SpanAttributes
5151

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

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ def add(x, y):
6363
from timeit import default_timer
6464
from typing import Collection, Iterable
6565

66+
from billiard import VERSION
6667
from billiard.einfo import ExceptionInfo
6768
from celery import signals # pylint: disable=no-name-in-module
6869

@@ -76,8 +77,6 @@ def add(x, y):
7677
from opentelemetry.propagators.textmap import Getter
7778
from opentelemetry.semconv.trace import SpanAttributes
7879
from opentelemetry.trace.status import Status, StatusCode
79-
from billiard import VERSION
80-
8180

8281
if VERSION >= (4, 0, 1):
8382
from billiard.einfo import ExceptionWithTraceback

instrumentation/opentelemetry-instrumentation-celery/src/opentelemetry/instrumentation/celery/utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@
1414

1515
import logging
1616

17-
from celery import registry # pylint: disable=no-name-in-module
1817
from billiard import VERSION
18+
from celery import registry # pylint: disable=no-name-in-module
1919

2020
from opentelemetry.semconv.trace import SpanAttributes
2121

instrumentation/opentelemetry-instrumentation-confluent-kafka/src/opentelemetry/instrumentation/confluent_kafka/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,8 +112,8 @@ def instrument_consumer(consumer: Consumer, tracer_provider=None)
112112
from .package import _instruments
113113
from .utils import (
114114
KafkaPropertiesExtractor,
115-
_end_current_consume_span,
116115
_create_new_consume_span,
116+
_end_current_consume_span,
117117
_enrich_span,
118118
_get_span_name,
119119
_kafka_getter,

instrumentation/opentelemetry-instrumentation-confluent-kafka/src/opentelemetry/instrumentation/confluent_kafka/utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@
22
from typing import List, Optional
33

44
from opentelemetry import context, propagate
5-
from opentelemetry.trace import SpanKind, Link
65
from opentelemetry.propagators import textmap
76
from opentelemetry.semconv.trace import (
87
MessagingDestinationKindValues,
98
MessagingOperationValues,
109
SpanAttributes,
1110
)
11+
from opentelemetry.trace import Link, SpanKind
1212

1313
_LOG = getLogger(__name__)
1414

instrumentation/opentelemetry-instrumentation-confluent-kafka/tests/test_instrumentation.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,6 @@
1414

1515
# pylint: disable=no-name-in-module
1616

17-
from opentelemetry.semconv.trace import (
18-
SpanAttributes,
19-
MessagingDestinationKindValues,
20-
)
21-
from opentelemetry.test.test_base import TestBase
22-
from .utils import MockConsumer, MockedMessage
23-
2417
from confluent_kafka import Consumer, Producer
2518

2619
from opentelemetry.instrumentation.confluent_kafka import (
@@ -32,6 +25,13 @@
3225
KafkaContextGetter,
3326
KafkaContextSetter,
3427
)
28+
from opentelemetry.semconv.trace import (
29+
MessagingDestinationKindValues,
30+
SpanAttributes,
31+
)
32+
from opentelemetry.test.test_base import TestBase
33+
34+
from .utils import MockConsumer, MockedMessage
3535

3636

3737
class TestConfluentKafka(TestBase):

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

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,6 @@
4040
OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS,
4141
OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST,
4242
OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE,
43-
OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE,
4443
OTEL_PYTHON_INSTRUMENTATION_HTTP_CAPTURE_ALL_METHODS,
4544
get_excluded_urls,
4645
)

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)