Skip to content

Commit fedd768

Browse files
committed
Fix CR comments and lint test failures
1 parent 12a4746 commit fedd768

File tree

7 files changed

+71
-73
lines changed

7 files changed

+71
-73
lines changed

Diff for: CHANGELOG.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1313
- `opentelemetry-sdk-extension-aws` Add AWS resource detectors to extension package
1414
([#586](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/586))
1515
- `opentelemetry-instrumentation-asgi`, `opentelemetry-instrumentation-aiohttp-client`, `openetelemetry-instrumentation-fastapi`,
16-
`opentelemetry-instrumentation-starlette`, `opentelemetry-instrumentation-urllib`, `opentelemetry-instrumentation-urllib3` Added `request_hook` and `response_hook` callbacks
16+
`opentelemetry-instrumentation-starlette`, `opentelemetry-instrumentation-urllib`, `opentelemetry-instrumentation-urllib3`,
17+
`opentelemetry-instrumentation-pika` Added `request_hook` and `response_hook` callbacks
1718
([#576](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/576))
1819

1920
### Changed

Diff for: instrumentation/opentelemetry-instrumentation-pika/src/opentelemetry/instrumentation/pika/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,6 @@
5454
---
5555
"""
5656

57-
57+
# pylint: disable=unused-argument
5858
from .pika_instrumentor import PikaInstrumentor
5959
from .version import __version__

Diff for: instrumentation/opentelemetry-instrumentation-pika/src/opentelemetry/instrumentation/pika/pika_instrumentor.py

+32-20
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from logging import getLogger
1515
from typing import Any, Callable, Collection, Dict, Optional
1616

17+
from pika.adapters import BlockingConnection
1718
from pika.channel import Channel
1819

1920
from opentelemetry import trace
@@ -24,25 +25,28 @@
2425
from opentelemetry.trace import Tracer, TracerProvider
2526

2627
_LOG = getLogger(__name__)
27-
CTX_KEY = "__otel_task_span"
28+
_CTX_KEY = "__otel_task_span"
2829

29-
FUNCTIONS_TO_UNINSTRUMENT = ["basic_publish"]
30+
_FUNCTIONS_TO_UNINSTRUMENT = ["basic_publish"]
3031

3132

3233
class PikaInstrumentor(BaseInstrumentor): # type: ignore
34+
# pylint: disable=attribute-defined-outside-init
3335
@staticmethod
3436
def _instrument_consumers(
3537
consumers_dict: Dict[str, Callable[..., Any]], tracer: Tracer
3638
) -> Any:
3739
for key, callback in consumers_dict.items():
38-
decorated_callback = utils.decorate_callback(callback, tracer, key)
40+
decorated_callback = utils._decorate_callback(
41+
callback, tracer, key
42+
)
3943
setattr(decorated_callback, "_original_callback", callback)
4044
consumers_dict[key] = decorated_callback
4145

4246
@staticmethod
4347
def _instrument_basic_publish(channel: Channel, tracer: Tracer) -> None:
4448
original_function = getattr(channel, "basic_publish")
45-
decorated_function = utils.decorate_basic_publish(
49+
decorated_function = utils._decorate_basic_publish(
4650
original_function, channel, tracer
4751
)
4852
setattr(decorated_function, "_original_function", original_function)
@@ -58,7 +62,7 @@ def _instrument_channel_functions(
5862

5963
@staticmethod
6064
def _uninstrument_channel_functions(channel: Channel) -> None:
61-
for function_name in FUNCTIONS_TO_UNINSTRUMENT:
65+
for function_name in _FUNCTIONS_TO_UNINSTRUMENT:
6266
if not hasattr(channel, function_name):
6367
continue
6468
function = getattr(channel, function_name)
@@ -69,30 +73,19 @@ def _uninstrument_channel_functions(channel: Channel) -> None:
6973
def instrument_channel(
7074
channel: Channel, tracer_provider: Optional[TracerProvider] = None,
7175
) -> None:
76+
tracer = trace.get_tracer(__name__, __version__, tracer_provider)
77+
channel.__setattr__("__opentelemetry_tracer", tracer)
7278
if not hasattr(channel, "_impl"):
7379
_LOG.error("Could not find implementation for provided channel!")
7480
return
75-
tracer = trace.get_tracer(__name__, __version__, tracer_provider)
76-
channel.__setattr__("__opentelemetry_tracer", tracer)
7781
if channel._impl._consumers:
7882
PikaInstrumentor._instrument_consumers(
7983
channel._impl._consumers, tracer
8084
)
8185
PikaInstrumentor._instrument_channel_functions(channel, tracer)
8286

83-
def _instrument(self, **kwargs: Dict[str, Any]) -> None:
84-
channel: Channel = kwargs.get("channel", None)
85-
if not channel or not isinstance(channel, Channel):
86-
return
87-
tracer_provider: TracerProvider = kwargs.get("tracer_provider", None)
88-
PikaInstrumentor.instrument_channel(
89-
channel, tracer_provider=tracer_provider
90-
)
91-
92-
def _uninstrument(self, **kwargs: Dict[str, Any]) -> None:
93-
channel: Channel = kwargs.get("channel", None)
94-
if not channel or not isinstance(channel, Channel):
95-
return
87+
@staticmethod
88+
def uninstrument_channel(channel: Channel) -> None:
9689
if not hasattr(channel, "_impl"):
9790
_LOG.error("Could not find implementation for provided channel!")
9891
return
@@ -101,5 +94,24 @@ def _uninstrument(self, **kwargs: Dict[str, Any]) -> None:
10194
channel._impl._consumers[key] = callback._original_callback
10295
PikaInstrumentor._uninstrument_channel_functions(channel)
10396

97+
def _decorate_channel_function(
98+
self, tracer_provider: Optional[TracerProvider]
99+
) -> None:
100+
self.original_channel_func = BlockingConnection.channel
101+
102+
def _wrapper(*args, **kwargs):
103+
channel = self.original_channel_func(*args, **kwargs)
104+
self.instrument_channel(channel, tracer_provider=tracer_provider)
105+
return channel
106+
107+
BlockingConnection.channel = _wrapper
108+
109+
def _instrument(self, **kwargs: Dict[str, Any]) -> None:
110+
tracer_provider: TracerProvider = kwargs.get("tracer_provider", None)
111+
self._decorate_channel_function(tracer_provider)
112+
113+
def _uninstrument(self, **kwargs: Dict[str, Any]) -> None:
114+
BlockingConnection.channel = self.original_channel_func
115+
104116
def instrumentation_dependencies(self) -> Collection[str]:
105117
return _instruments

Diff for: instrumentation/opentelemetry-instrumentation-pika/src/opentelemetry/instrumentation/pika/utils.py

+12-12
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
from opentelemetry.trace.span import Span
1515

1616

17-
class PikaGetter(Getter): # type: ignore
17+
class _PikaGetter(Getter): # type: ignore
1818
def get(self, carrier: CarrierT, key: str) -> Optional[List[str]]:
1919
value = carrier.get(key, None)
2020
if value is None:
@@ -25,10 +25,10 @@ def keys(self, carrier: CarrierT) -> List[str]:
2525
return []
2626

2727

28-
pika_getter = PikaGetter()
28+
_pika_getter = _PikaGetter()
2929

3030

31-
def decorate_callback(
31+
def _decorate_callback(
3232
callback: Callable[[Channel, Basic.Deliver, BasicProperties, bytes], Any],
3333
tracer: Tracer,
3434
task_name: str,
@@ -41,7 +41,7 @@ def decorated_callback(
4141
) -> Any:
4242
if not properties:
4343
properties = BasicProperties()
44-
span = get_span(
44+
span = _get_span(
4545
tracer,
4646
channel,
4747
properties,
@@ -56,7 +56,7 @@ def decorated_callback(
5656
return decorated_callback
5757

5858

59-
def decorate_basic_publish(
59+
def _decorate_basic_publish(
6060
original_function: Callable[[str, str, bytes, BasicProperties, bool], Any],
6161
channel: Channel,
6262
tracer: Tracer,
@@ -70,7 +70,7 @@ def decorated_function(
7070
) -> Any:
7171
if not properties:
7272
properties = BasicProperties()
73-
span = get_span(
73+
span = _get_span(
7474
tracer,
7575
channel,
7676
properties,
@@ -92,7 +92,7 @@ def decorated_function(
9292
return decorated_function
9393

9494

95-
def get_span(
95+
def _get_span(
9696
tracer: Tracer,
9797
channel: Channel,
9898
properties: BasicProperties,
@@ -101,29 +101,29 @@ def get_span(
101101
) -> Optional[Span]:
102102
if properties.headers is None:
103103
properties.headers = {}
104-
ctx = propagate.extract(properties.headers, getter=pika_getter)
104+
ctx = propagate.extract(properties.headers, getter=_pika_getter)
105105
if context.get_value("suppress_instrumentation") or context.get_value(
106106
_SUPPRESS_INSTRUMENTATION_KEY
107107
):
108108
print("Suppressing instrumentation!")
109109
return None
110110
task_name = properties.type if properties.type else task_name
111111
span = tracer.start_span(
112-
context=ctx, name=generate_span_name(task_name, operation)
112+
context=ctx, name=_generate_span_name(task_name, operation)
113113
)
114-
enrich_span(span, channel, properties, task_name, operation)
114+
_enrich_span(span, channel, properties, task_name, operation)
115115
return span
116116

117117

118-
def generate_span_name(
118+
def _generate_span_name(
119119
task_name: str, operation: Optional[MessagingOperationValues]
120120
) -> str:
121121
if not operation:
122122
return f"{task_name} send"
123123
return f"{task_name} {operation.value}"
124124

125125

126-
def enrich_span(
126+
def _enrich_span(
127127
span: Span,
128128
channel: Channel,
129129
properties: BasicProperties,

Diff for: instrumentation/opentelemetry-instrumentation-pika/tests/test_getter.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,12 @@
1313
# limitations under the License.
1414
from unittest import TestCase
1515

16-
from opentelemetry.instrumentation.pika.utils import PikaGetter
16+
from opentelemetry.instrumentation.pika.utils import _PikaGetter
1717

1818

1919
class TestPikaGetter(TestCase):
2020
def setUp(self) -> None:
21-
self.getter = PikaGetter()
21+
self.getter = _PikaGetter()
2222

2323
def test_get_none(self) -> None:
2424
carrier = {}

Diff for: instrumentation/opentelemetry-instrumentation-pika/tests/test_pika_instrumentation.py

+10-25
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
# limitations under the License.
1414
from unittest import TestCase, mock
1515

16-
from pika.adapters import BaseConnection
16+
from pika.adapters import BaseConnection, BlockingConnection
1717
from pika.channel import Channel
1818

1919
from opentelemetry.instrumentation.pika import PikaInstrumentor
@@ -27,31 +27,16 @@ def setUp(self) -> None:
2727
self.mock_callback = mock.MagicMock()
2828
self.channel._impl._consumers = {"mock_key": self.mock_callback}
2929

30-
@mock.patch(
31-
"opentelemetry.instrumentation.pika.PikaInstrumentor.instrument_channel"
32-
)
33-
@mock.patch(
34-
"opentelemetry.instrumentation.pika.PikaInstrumentor._uninstrument_channel_functions"
35-
)
36-
def test_instrument_api(
37-
self,
38-
uninstrument_channel_functions: mock.MagicMock,
39-
instrument_channel: mock.MagicMock,
40-
) -> None:
30+
def test_instrument_api(self) -> None:
31+
original_channel = BlockingConnection.channel
4132
instrumentation = PikaInstrumentor()
42-
instrumentation.instrument(channel=self.channel)
43-
instrument_channel.assert_called_once_with(
44-
self.channel, tracer_provider=None
45-
)
46-
self.channel._impl._consumers = {"mock_key": mock.MagicMock()}
47-
self.channel._impl._consumers[
48-
"mock_key"
49-
]._original_callback = self.mock_callback
50-
instrumentation.uninstrument(channel=self.channel)
51-
uninstrument_channel_functions.assert_called_once()
33+
instrumentation.instrument()
34+
self.assertTrue(hasattr(instrumentation, "original_channel_func"))
5235
self.assertEqual(
53-
self.channel._impl._consumers["mock_key"], self.mock_callback
36+
original_channel, instrumentation.original_channel_func
5437
)
38+
instrumentation.uninstrument(channel=self.channel)
39+
self.assertEqual(original_channel, BlockingConnection.channel)
5540

5641
@mock.patch(
5742
"opentelemetry.instrumentation.pika.PikaInstrumentor._instrument_channel_functions"
@@ -71,7 +56,7 @@ def test_instrument(
7156
instrument_consumers.assert_called_once()
7257
instrument_channel_functions.assert_called_once()
7358

74-
@mock.patch("opentelemetry.instrumentation.pika.utils.decorate_callback")
59+
@mock.patch("opentelemetry.instrumentation.pika.utils._decorate_callback")
7560
def test_instrument_consumers(
7661
self, decorate_callback: mock.MagicMock
7762
) -> None:
@@ -92,7 +77,7 @@ def test_instrument_consumers(
9277
)
9378

9479
@mock.patch(
95-
"opentelemetry.instrumentation.pika.utils.decorate_basic_publish"
80+
"opentelemetry.instrumentation.pika.utils._decorate_basic_publish"
9681
)
9782
def test_instrument_basic_publish(
9883
self, decorate_basic_publish: mock.MagicMock

Diff for: instrumentation/opentelemetry-instrumentation-pika/tests/test_utils.py

+12-12
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@
2121
class TestUtils(TestCase):
2222
@staticmethod
2323
@mock.patch("opentelemetry.context.get_value")
24-
@mock.patch("opentelemetry.instrumentation.pika.utils.generate_span_name")
25-
@mock.patch("opentelemetry.instrumentation.pika.utils.enrich_span")
24+
@mock.patch("opentelemetry.instrumentation.pika.utils._generate_span_name")
25+
@mock.patch("opentelemetry.instrumentation.pika.utils._enrich_span")
2626
@mock.patch("opentelemetry.propagate.extract")
2727
def test_get_span(
2828
extract: mock.MagicMock,
@@ -35,7 +35,7 @@ def test_get_span(
3535
properties = mock.MagicMock()
3636
task_name = "test.test"
3737
get_value.return_value = None
38-
span = utils.get_span(tracer, channel, properties, task_name)
38+
span = utils._get_span(tracer, channel, properties, task_name)
3939
extract.assert_called_once()
4040
generate_span_name.assert_called_once()
4141
tracer.start_span.assert_called_once_with(
@@ -48,8 +48,8 @@ def test_get_span(
4848
), "The returned span was not enriched using enrich_span!"
4949

5050
@mock.patch("opentelemetry.context.get_value")
51-
@mock.patch("opentelemetry.instrumentation.pika.utils.generate_span_name")
52-
@mock.patch("opentelemetry.instrumentation.pika.utils.enrich_span")
51+
@mock.patch("opentelemetry.instrumentation.pika.utils._generate_span_name")
52+
@mock.patch("opentelemetry.instrumentation.pika.utils._enrich_span")
5353
@mock.patch("opentelemetry.propagate.extract")
5454
def test_get_span_suppressed(
5555
self,
@@ -63,22 +63,22 @@ def test_get_span_suppressed(
6363
properties = mock.MagicMock()
6464
task_name = "test.test"
6565
get_value.return_value = True
66-
span = utils.get_span(tracer, channel, properties, task_name)
66+
span = utils._get_span(tracer, channel, properties, task_name)
6767
self.assertEqual(span, None)
6868
extract.assert_called_once()
6969
generate_span_name.assert_not_called()
7070

7171
def test_generate_span_name_no_operation(self) -> None:
7272
task_name = "test.test"
7373
operation = None
74-
span_name = utils.generate_span_name(task_name, operation)
74+
span_name = utils._generate_span_name(task_name, operation)
7575
self.assertEqual(span_name, f"{task_name} send")
7676

7777
def test_generate_span_name_with_operation(self) -> None:
7878
task_name = "test.test"
7979
operation = mock.MagicMock()
8080
operation.value = "process"
81-
span_name = utils.generate_span_name(task_name, operation)
81+
span_name = utils._generate_span_name(task_name, operation)
8282
self.assertEqual(span_name, f"{task_name} {operation.value}")
8383

8484
@staticmethod
@@ -87,7 +87,7 @@ def test_enrich_span_basic_values() -> None:
8787
properties = mock.MagicMock()
8888
task_destination = "test.test"
8989
span = mock.MagicMock(spec=Span)
90-
utils.enrich_span(span, channel, properties, task_destination)
90+
utils._enrich_span(span, channel, properties, task_destination)
9191
span.set_attribute.assert_has_calls(
9292
any_order=True,
9393
calls=[
@@ -121,7 +121,7 @@ def test_enrich_span_with_operation() -> None:
121121
task_destination = "test.test"
122122
operation = mock.MagicMock()
123123
span = mock.MagicMock(spec=Span)
124-
utils.enrich_span(
124+
utils._enrich_span(
125125
span, channel, properties, task_destination, operation
126126
)
127127
span.set_attribute.assert_has_calls(
@@ -137,7 +137,7 @@ def test_enrich_span_without_operation() -> None:
137137
properties = mock.MagicMock()
138138
task_destination = "test.test"
139139
span = mock.MagicMock(spec=Span)
140-
utils.enrich_span(span, channel, properties, task_destination)
140+
utils._enrich_span(span, channel, properties, task_destination)
141141
span.set_attribute.assert_has_calls(
142142
any_order=True,
143143
calls=[mock.call(SpanAttributes.MESSAGING_TEMP_DESTINATION, True)],
@@ -151,7 +151,7 @@ def test_enrich_span_unique_connection() -> None:
151151
span = mock.MagicMock(spec=Span)
152152
# We do this to create the behaviour of hasattr(channel.connection, "params") == False
153153
del channel.connection.params
154-
utils.enrich_span(span, channel, properties, task_destination)
154+
utils._enrich_span(span, channel, properties, task_destination)
155155
span.set_attribute.assert_has_calls(
156156
any_order=True,
157157
calls=[

0 commit comments

Comments
 (0)