From 9a6375d1822cf94e712818c0e70fef6f0cbecaeb Mon Sep 17 00:00:00 2001 From: Cagri Yonca Date: Mon, 23 Nov 2026 15:26:28 +0100 Subject: [PATCH] feat(pika): add thread-safe channel instrumentation support Signed-off-by: Cagri Yonca --- src/instana/instrumentation/pika.py | 100 ++++++- tests/clients/test_pika.py | 405 +++++++++++++++++++++++++++- 2 files changed, 484 insertions(+), 21 deletions(-) diff --git a/src/instana/instrumentation/pika.py b/src/instana/instrumentation/pika.py index 75bb7a3d..a739558e 100644 --- a/src/instana/instrumentation/pika.py +++ b/src/instana/instrumentation/pika.py @@ -4,6 +4,7 @@ try: + import importlib.util import types from typing import ( TYPE_CHECKING, @@ -27,6 +28,7 @@ if TYPE_CHECKING: import pika.adapters.blocking_connection + import pika.adapters.thread_safe_connection import pika.channel import pika.connection @@ -57,6 +59,39 @@ def _extract_consumer_tags( span.set_attribute("sort", "consume") span.set_attribute("queue", queue) + def _get_pika_channel( + instance: Union[ + "pika.channel.Channel", "pika.adapters.thread_safe_connection.Channel" + ], + ) -> "pika.channel.Channel": + """Return the pika channel behind the given channel. + + The thread-safe channel (pika >= 1.5.0) keeps the pika channel in + `_channel`; every other caller already is a pika channel. + + :param instance: A pika channel or a thread-safe channel. + :return: The pika channel. + """ + return getattr(instance, "_channel", instance) + + def _get_consumer_connection( + instance: Union[ + "pika.adapters.blocking_connection.BlockingChannel", + "pika.adapters.thread_safe_connection.Channel", + ], + ) -> "pika.connection.Connection": + """Return the pika connection a consumer channel is bound to. + + The thread-safe channel (pika >= 1.5.0) exposes the pika channel in + `_channel`, the BlockingChannel the connection implementation. + + :param instance: A BlockingChannel or a thread-safe channel. + :return: The pika connection. + """ + if hasattr(instance, "_channel"): + return instance._channel.connection + return instance.connection._impl + @wrapt.patch_function_wrapper("pika.channel", "Channel.basic_publish") def basic_publish_with_instana( wrapped: Callable[..., pika.channel.Channel.basic_publish], @@ -90,7 +125,7 @@ def _bind_args( try: _extract_publisher_attributes( span, - conn=instance.connection, + conn=_get_pika_channel(instance).connection, routing_key=routing_key, exchange=exchange, ) @@ -130,14 +165,17 @@ def basic_get_with_instana( if not tracer: return wrapped(*args, **kwargs) - def _bind_args(*args: object, **kwargs: object) -> Tuple[object, ...]: + def _bind_args(*args: object, **kwargs: object) -> tuple[object, ...]: args = list(args) - queue = kwargs.pop("queue", None) or args.pop(0) - callback = ( - kwargs.pop("callback", None) - or kwargs.pop("on_message_callback", None) - or args.pop(0) - ) + queue = kwargs.pop("queue") if "queue" in kwargs else args.pop(0) + # `basic_consume` also takes a `callback` (Basic.ConsumeOk) next to + # `on_message_callback`, it must be passed through untouched. + if "on_message_callback" in kwargs: + callback = kwargs.pop("on_message_callback") + elif args: + callback = args.pop(0) + else: + callback = kwargs.pop("callback") return (queue, callback, tuple(args), kwargs) queue, callback, args, kwargs = _bind_args(*args, **kwargs) @@ -211,7 +249,7 @@ def _cb_wrapper( ) as span: try: _extract_consumer_tags( - span, conn=instance.connection._impl, queue=queue + span, conn=_get_consumer_connection(instance), queue=queue ) except Exception: logger.debug( @@ -306,6 +344,32 @@ def _BlockingChannel___init__( return ret + def _ThreadSafeChannel___init__( + wrapped: Callable[..., "pika.adapters.thread_safe_connection.Channel.__init__"], + instance: "pika.adapters.thread_safe_connection.Channel", + args: tuple[object, ...], + kwargs: dict[str, Any], + ) -> object: + """Trace the consumer callback at the thread-safe channel level. + + The callback is dispatched to a worker thread, so the wrapper of the + underlying pika channel is removed to avoid tracing it twice. + + :param wrapped: The original `Channel.__init__`. + :param instance: The thread-safe channel being initialized. + :param args: Positional arguments of `Channel.__init__`. + :param kwargs: Keyword arguments of `Channel.__init__`. + :return: The value returned by `Channel.__init__`. + """ + ret = wrapped(*args, **kwargs) + + if (impl := getattr(instance, "_channel", None)) and hasattr( + impl.basic_consume, "__wrapped__" + ): + impl.basic_consume = impl.basic_consume.__wrapped__ + + return ret + wrapt.wrap_function_wrapper( "pika.channel", "Channel.basic_get", basic_get_with_instana ) @@ -313,6 +377,24 @@ def _BlockingChannel___init__( "pika.channel", "Channel.basic_consume", basic_get_with_instana ) + # The thread-safe connection is only available since pika 1.5.0 + if importlib.util.find_spec("pika.adapters.thread_safe_connection"): + wrapt.wrap_function_wrapper( + "pika.adapters.thread_safe_connection", + "Channel.basic_publish", + basic_publish_with_instana, + ) + wrapt.wrap_function_wrapper( + "pika.adapters.thread_safe_connection", + "Channel.basic_consume", + basic_consume_with_instana, + ) + wrapt.wrap_function_wrapper( + "pika.adapters.thread_safe_connection", + "Channel.__init__", + _ThreadSafeChannel___init__, + ) + logger.debug("Instrumenting pika") except ImportError: pass diff --git a/tests/clients/test_pika.py b/tests/clients/test_pika.py index affd9284..c7c25d9f 100644 --- a/tests/clients/test_pika.py +++ b/tests/clients/test_pika.py @@ -2,9 +2,11 @@ # (c) Copyright Instana Inc. 2021 +import contextlib import threading import time -from typing import Generator, Optional +from types import SimpleNamespace +from typing import Callable, Generator, Optional import mock import pika @@ -14,6 +16,7 @@ import pytest from opentelemetry.trace.span import format_span_id +from instana.instrumentation import pika as pika_instrumentation from instana.singletons import agent, get_tracer from instana.util.ids import hex_id @@ -48,6 +51,37 @@ def _resource(self) -> Generator[None, None, None]: agent.options.allow_exit_as_root = False +@pytest.mark.parametrize( + "instance, expected", + [ + ("pika_channel", "pika_channel"), + ("thread_safe_channel", "pika_channel"), + ], +) +def test_get_pika_channel_resolves_pika_channel(instance, expected) -> None: + pika_channel = pika.channel.Channel(mock.Mock(), 1, mock.Mock()) + channels = { + "pika_channel": pika_channel, + "thread_safe_channel": SimpleNamespace(_channel=pika_channel), + } + + result = pika_instrumentation._get_pika_channel(channels[instance]) + + assert result is channels[expected] + + +@pytest.mark.parametrize( + "instance", + [ + SimpleNamespace(connection=SimpleNamespace(_impl="connection")), + SimpleNamespace(_channel=SimpleNamespace(connection="connection")), + ], + ids=["blocking_channel", "thread_safe_channel"], +) +def test_get_consumer_connection_resolves_pika_connection(instance) -> None: + assert pika_instrumentation._get_consumer_connection(instance) == "connection" + + class TestPikaBlockingChannel(_TestPika): @mock.patch("pika.channel.Channel", spec=pika.channel.Channel) def _create_obj( @@ -339,9 +373,28 @@ class TestPikaChannel(_TestPika): def _create_obj(self) -> pika.channel.Channel: return pika.channel.Channel(self.connection, 1, self._on_openok_callback) + @pytest.fixture + def sent_message(self, mocker) -> Callable[[], tuple[object, tuple[object, bytes]]]: + """Returns the (method, (properties, body)) that was handed over to pika.""" + if hasattr(pika.channel.Channel, "_marshal_publish"): + # pika >= 1.5.0 marshals the message on the connection + publish = self.connection._marshal_message + + def _sent_message() -> tuple[object, tuple[object, bytes]]: + publish.assert_called_once() + return publish.call_args.args[1:] + + else: + publish = mocker.patch("pika.channel.Channel._send_method") + + def _sent_message() -> tuple[object, tuple[object, bytes]]: + publish.assert_called_once() + return publish.call_args.args + + return _sent_message + @mock.patch("pika.spec.Basic.Publish") - @mock.patch("pika.channel.Channel._send_method") - def test_basic_publish(self, send_method, _unused) -> None: + def test_basic_publish(self, _unused, sent_message) -> None: self.obj._set_state(self.obj.OPEN) with self.tracer.start_as_current_span("testing"): @@ -372,7 +425,7 @@ def test_basic_publish(self, send_method, _unused) -> None: assert isinstance(rabbitmq_span.stack, list) assert len(rabbitmq_span.stack) > 0 - send_method.assert_called_once_with( + assert sent_message() == ( pika.spec.Basic.Publish(exchange="test.exchange", routing_key="test.queue"), ( pika.spec.BasicProperties( @@ -388,8 +441,7 @@ def test_basic_publish(self, send_method, _unused) -> None: ) @mock.patch("pika.spec.Basic.Publish") - @mock.patch("pika.channel.Channel._send_method") - def test_basic_publish_as_root_exit_span(self, send_method, _unused) -> None: + def test_basic_publish_as_root_exit_span(self, _unused, sent_message) -> None: agent.options.allow_exit_as_root = True self.obj._set_state(self.obj.OPEN) self.obj.basic_publish("test.exchange", "test.queue", "Hello!") @@ -414,7 +466,7 @@ def test_basic_publish_as_root_exit_span(self, send_method, _unused) -> None: assert isinstance(rabbitmq_span.stack, list) assert len(rabbitmq_span.stack) > 0 - send_method.assert_called_once_with( + assert sent_message() == ( pika.spec.Basic.Publish(exchange="test.exchange", routing_key="test.queue"), ( pika.spec.BasicProperties( @@ -430,8 +482,7 @@ def test_basic_publish_as_root_exit_span(self, send_method, _unused) -> None: ) @mock.patch("pika.spec.Basic.Publish") - @mock.patch("pika.channel.Channel._send_method") - def test_basic_publish_with_headers(self, send_method, _unused) -> None: + def test_basic_publish_with_headers(self, _unused, sent_message) -> None: self.obj._set_state(self.obj.OPEN) with self.tracer.start_as_current_span("testing"): @@ -447,7 +498,7 @@ def test_basic_publish_with_headers(self, send_method, _unused) -> None: rabbitmq_span = spans[0] - send_method.assert_called_once_with( + assert sent_message() == ( pika.spec.Basic.Publish(exchange="test.exchange", routing_key="test.queue"), ( pika.spec.BasicProperties( @@ -464,8 +515,7 @@ def test_basic_publish_with_headers(self, send_method, _unused) -> None: ) @mock.patch("pika.spec.Basic.Publish") - @mock.patch("pika.channel.Channel._send_method") - def test_basic_publish_tracing_off(self, send_method, _unused, mocker) -> None: + def test_basic_publish_tracing_off(self, _unused, mocker) -> None: mocker.patch( "instana.instrumentation.pika.get_tracer_tuple", return_value=(None, None, None), @@ -632,3 +682,334 @@ def test_basic_consume_with_trace_context(self, _unused) -> None: # A new span has been started assert rabbitmq_span.s assert rabbitmq_span.p != rabbitmq_span.s + + @mock.patch("pika.spec.Basic.Consume") + def test_basic_consume_with_consume_ok_callback(self, _unused) -> None: + self.obj._set_state(self.obj.OPEN) + + body = "Hello!" + properties = pika.BasicProperties() + + method_frame = pika.frame.Method( + 1, pika.spec.Basic.Deliver(consumer_tag="test") + ) + header_frame = pika.frame.Header(1, len(body), properties) + + cb = mock.Mock() + consume_ok_cb = mock.Mock() + + with mock.patch.object(pika.channel.Channel, "_rpc") as rpc: + self.obj.basic_consume( + queue="test.queue", + on_message_callback=cb, + consumer_tag="test", + callback=consume_ok_cb, + ) + + # The Basic.ConsumeOk callback is left untouched + assert rpc.call_args.args[1] == consume_ok_cb + + self.obj._on_deliver(method_frame, header_frame, body) + + spans = self.recorder.queued_spans() + assert len(spans) == 1 + + rabbitmq_span = spans[0] + assert rabbitmq_span.data["rabbitmq"]["sort"] == "consume" + assert rabbitmq_span.data["rabbitmq"]["queue"] == "test.queue" + + cb.assert_called_once_with(self.obj, method_frame.method, properties, body) + consume_ok_cb.assert_not_called() + + @mock.patch("pika.spec.Basic.Get") + def test_basic_get_with_empty_queue_name(self, _unused) -> None: + self.obj._set_state(self.obj.OPEN) + + body = "Hello!" + properties = pika.BasicProperties() + + method_frame = pika.frame.Method(1, pika.spec.Basic.GetOk) + header_frame = pika.frame.Header(1, len(body), properties) + + cb = mock.Mock() + + self.obj.basic_get(queue="", callback=cb) + self.obj._on_getok(method_frame, header_frame, body) + + spans = self.recorder.queued_spans() + assert len(spans) == 1 + assert spans[0].data["rabbitmq"]["sort"] == "consume" + + cb.assert_called_once_with(self.obj, pika.spec.Basic.GetOk, properties, body) + + +class TestPikaThreadSafeChannel(_TestPika): + def _create_obj(self) -> object: + thread_safe_connection = pytest.importorskip( + "pika.adapters.thread_safe_connection" + ) + + self.impl = pika.channel.Channel(self.connection, 1, self._on_openok_callback) + self.impl._set_state(self.impl.OPEN) + + wrapper = mock.MagicMock() + wrapper._closed_reason = None + wrapper._connection._error = None + + channel = thread_safe_connection.Channel(self.impl, wrapper) + # Run the consumer callbacks synchronously instead of on a worker thread + channel._consumer_work_pool.submit = lambda fn, *args: fn(*args) + return channel + + def test_basic_publish(self) -> None: + with self.tracer.start_as_current_span("testing"): + self.obj.basic_publish("test.exchange", "test.queue", "Hello!") + + spans = self.recorder.queued_spans() + assert len(spans) == 2 + + rabbitmq_span = spans[0] + test_span = spans[1] + + # Same traceId + assert test_span.t == rabbitmq_span.t + + # Parent relationships + assert rabbitmq_span.p == test_span.s + + # Error logging + assert not test_span.ec + assert not rabbitmq_span.ec + + # Span tags + assert rabbitmq_span.data["rabbitmq"]["exchange"] == "test.exchange" + assert rabbitmq_span.data["rabbitmq"]["sort"] == "publish" + assert rabbitmq_span.data["rabbitmq"]["address"] + assert rabbitmq_span.data["rabbitmq"]["key"] == "test.queue" + + # Context propagation + marshal_publish_args = self.connection._marshal_message.call_args.args + properties, body = marshal_publish_args[2] + assert body == b"Hello!" + assert properties.headers == { + "X-INSTANA-T": format_span_id(rabbitmq_span.t), + "X-INSTANA-S": format_span_id(rabbitmq_span.s), + "X-INSTANA-L": "1", + "Server-Timing": f"intid;desc={hex_id(rabbitmq_span.t)}", + } + + @mock.patch("pika.spec.Basic.Consume") + def test_basic_consume(self, _unused) -> None: + body = "Hello!" + instana_headers = { + "X-INSTANA-T": "0000000000000001", + "X-INSTANA-S": "0000000000000002", + "X-INSTANA-L": "1", + } + properties = pika.BasicProperties(headers=instana_headers) + + method_frame = pika.frame.Method( + 1, pika.spec.Basic.Deliver(consumer_tag="test") + ) + header_frame = pika.frame.Header(1, len(body), properties) + + cb = mock.Mock() + + with mock.patch.object(type(self.obj), "_blocking_rpc") as blocking_rpc: + blocking_rpc.return_value.method.consumer_tag = "test" + self.obj.basic_consume("test.queue", cb, consumer_tag="test") + + # Register the consumer on the pika channel, like the IOLoop thread would + send = blocking_rpc.call_args.args[1] + send(mock.Mock()) + + self.impl._on_deliver(method_frame, header_frame, body) + + # A single span covers the callback running on the worker thread + spans = self.recorder.queued_spans() + assert len(spans) == 1 + + rabbitmq_span = spans[0] + + # Trace context propagation + assert rabbitmq_span.t == int(instana_headers["X-INSTANA-T"]) + assert rabbitmq_span.p == int(instana_headers["X-INSTANA-S"]) + + # Error logging + assert not rabbitmq_span.ec + + # Span tags + assert rabbitmq_span.data["rabbitmq"]["sort"] == "consume" + assert rabbitmq_span.data["rabbitmq"]["address"] + assert rabbitmq_span.data["rabbitmq"]["queue"] == "test.queue" + + cb.assert_called_once_with(self.obj, method_frame.method, properties, body) + + def test_init_removes_pika_channel_consume_wrapper(self) -> None: + # The consumer callback is traced by the thread-safe channel only + assert not hasattr(self.impl.basic_consume, "__wrapped__") + + # Other pika channels keep their wrapper + other_channel = pika.channel.Channel(self.connection, 2, mock.Mock()) + assert hasattr(other_channel.basic_consume, "__wrapped__") + + def test_basic_publish_as_root_exit_span(self) -> None: + agent.options.allow_exit_as_root = True + + self.obj.basic_publish("test.exchange", "test.queue", "Hello!") + + spans = self.recorder.queued_spans() + assert len(spans) == 1 + + rabbitmq_span = spans[0] + + # Parent relationships + assert not rabbitmq_span.p + + # Error logging + assert not rabbitmq_span.ec + + # Span tags + assert rabbitmq_span.data["rabbitmq"]["exchange"] == "test.exchange" + assert rabbitmq_span.data["rabbitmq"]["sort"] == "publish" + assert rabbitmq_span.data["rabbitmq"]["key"] == "test.queue" + + def test_basic_publish_with_headers(self) -> None: + with self.tracer.start_as_current_span("testing"): + self.obj.basic_publish( + "test.exchange", + "test.queue", + "Hello!", + pika.BasicProperties(headers={"X-Custom-1": "test"}), + ) + + spans = self.recorder.queued_spans() + assert len(spans) == 2 + + rabbitmq_span = spans[0] + + properties, _ = self.connection._marshal_message.call_args.args[2] + assert properties.headers == { + "X-Custom-1": "test", + "X-INSTANA-T": format_span_id(rabbitmq_span.t), + "X-INSTANA-S": format_span_id(rabbitmq_span.s), + "X-INSTANA-L": "1", + "Server-Timing": f"intid;desc={hex_id(rabbitmq_span.t)}", + } + + def test_basic_publish_tracing_off(self, mocker) -> None: + mocker.patch( + "instana.instrumentation.pika.get_tracer_tuple", + return_value=(None, None, None), + ) + + with self.tracer.start_as_current_span("testing"): + self.obj.basic_publish("test.exchange", "test.queue", "Hello!") + + spans = self.recorder.queued_spans() + assert len(spans) == 1 + + # Span names are not "rabbitmq" + for span in spans: + assert span.n != "rabbitmq" + + # The message is published without trace context + properties, body = self.connection._marshal_message.call_args.args[2] + assert properties.headers is None + assert body == b"Hello!" + + def test_basic_publish_with_publisher_attributes_error(self, mocker) -> None: + mocker.patch( + "instana.instrumentation.pika._extract_publisher_attributes", + side_effect=Exception("test-error"), + ) + + with self.tracer.start_as_current_span("testing"): + self.obj.basic_publish("test.exchange", "test.queue", "Hello!") + + # The message is still published and traced + self.connection._marshal_message.assert_called_once() + + spans = self.recorder.queued_spans() + assert len(spans) == 2 + assert spans[0].n == "rabbitmq" + assert not spans[0].data["rabbitmq"]["sort"] + + def test_basic_publish_with_publish_error(self) -> None: + self.connection._marshal_message.side_effect = ValueError("test-error") + + with ( + self.tracer.start_as_current_span("testing"), + contextlib.suppress(ValueError), + ): + self.obj.basic_publish("test.exchange", "test.queue", "Hello!") + + spans = self.recorder.queued_spans() + assert len(spans) == 2 + + rabbitmq_span = spans[0] + assert rabbitmq_span.n == "rabbitmq" + assert rabbitmq_span.ec == 1 + + @mock.patch("pika.spec.Basic.Consume") + def test_basic_consume_with_callback_error(self, _unused) -> None: + body = "Hello!" + properties = pika.BasicProperties() + + method_frame = pika.frame.Method( + 1, pika.spec.Basic.Deliver(consumer_tag="test") + ) + header_frame = pika.frame.Header(1, len(body), properties) + + cb = mock.Mock(side_effect=ValueError("test-error")) + + with mock.patch.object(type(self.obj), "_blocking_rpc") as blocking_rpc: + blocking_rpc.return_value.method.consumer_tag = "test" + self.obj.basic_consume("test.queue", cb, consumer_tag="test") + + send = blocking_rpc.call_args.args[1] + send(mock.Mock()) + + with contextlib.suppress(ValueError): + self.impl._on_deliver(method_frame, header_frame, body) + + cb.assert_called_once_with(self.obj, method_frame.method, properties, body) + + spans = self.recorder.queued_spans() + assert len(spans) == 1 + assert spans[0].ec == 1 + + @mock.patch("pika.spec.Basic.Consume") + def test_basic_consume_with_consumer_attributes_error( + self, _unused, mocker + ) -> None: + mocker.patch( + "instana.instrumentation.pika._extract_consumer_tags", + side_effect=Exception("test-error"), + ) + + body = "Hello!" + properties = pika.BasicProperties() + + method_frame = pika.frame.Method( + 1, pika.spec.Basic.Deliver(consumer_tag="test") + ) + header_frame = pika.frame.Header(1, len(body), properties) + + cb = mock.Mock() + + with mock.patch.object(type(self.obj), "_blocking_rpc") as blocking_rpc: + blocking_rpc.return_value.method.consumer_tag = "test" + self.obj.basic_consume("test.queue", cb, consumer_tag="test") + + send = blocking_rpc.call_args.args[1] + send(mock.Mock()) + + self.impl._on_deliver(method_frame, header_frame, body) + + # The callback is still called and traced + cb.assert_called_once_with(self.obj, method_frame.method, properties, body) + + spans = self.recorder.queued_spans() + assert len(spans) == 1 + assert not spans[0].data["rabbitmq"]["sort"]