Skip to content

Commit ff412c6

Browse files
authored
Added aio-pika instrumentation (#1095)
1 parent ac84e99 commit ff412c6

File tree

24 files changed

+818
-1
lines changed

24 files changed

+818
-1
lines changed

.github/component_owners.yml

+3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
components:
22

3+
instrumentation/opentelemetry-instrumentation-aio-pika:
4+
- ofek1weiss
5+
36
instrumentation/opentelemetry-instrumentation-boto3sqs:
47
- oxeye-nikolay
58
- nikosokolik

.github/workflows/test.yml

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ on:
66
- 'release/*'
77
pull_request:
88
env:
9-
CORE_REPO_SHA: d4d7c67663cc22615748d632e1c8c5799e8eacae
9+
CORE_REPO_SHA: 25771ecdac685a5bf7ada1da21092d2061dbfc02
1010

1111
jobs:
1212
build:

CHANGELOG.md

+2
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
3838
([#1127](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1127))
3939
- Add metric instrumentation for WSGI
4040
([#1128](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1128))
41+
- `opentelemetry-instrumentation-aio-pika` added RabbitMQ aio-pika module instrumentation.
42+
([#1095](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1095))
4143
- `opentelemetry-instrumentation-requests` Restoring metrics in requests
4244
([#1110](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1110))
4345
- Integrated sqlcommenter plugin into opentelemetry-instrumentation-django

instrumentation/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11

22
| Instrumentation | Supported Packages | Metrics support |
33
| --------------- | ------------------ | --------------- |
4+
| [opentelemetry-instrumentation-aio-pika](./opentelemetry-instrumentation-aio-pika) | aio_pika ~= 7.2.0 | No
45
| [opentelemetry-instrumentation-aiohttp-client](./opentelemetry-instrumentation-aiohttp-client) | aiohttp ~= 3.0 | No
56
| [opentelemetry-instrumentation-aiopg](./opentelemetry-instrumentation-aiopg) | aiopg >= 0.13.0, < 1.3.0 | No
67
| [opentelemetry-instrumentation-asgi](./opentelemetry-instrumentation-asgi) | asgiref ~= 3.0 | No
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
OpenTelemetry Aio-pika Instrumentation
2+
======================================
3+
4+
|pypi|
5+
6+
.. |pypi| image:: https://badge.fury.io/py/opentelemetry-instrumentation-aio-pika.svg
7+
:target: https://pypi.org/project/opentelemetry-instrumentation-aio-pika/
8+
9+
This library allows tracing requests made by the Aio-pika library.
10+
11+
Installation
12+
------------
13+
14+
::
15+
16+
pip install opentelemetry-instrumentation-aio-pika
17+
18+
References
19+
----------
20+
21+
* `OpenTelemetry Aio-pika instrumentation <https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/aio-pika/aio-pika.html>`_
22+
* `OpenTelemetry Project <https://opentelemetry.io/>`_
23+
* `OpenTelemetry Python Examples <https://github.com/open-telemetry/opentelemetry-python/tree/main/docs/examples>`_
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# Copyright The OpenTelemetry Authors
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
#
15+
[metadata]
16+
name = opentelemetry-instrumentation-aio-pika
17+
description = OpenTelemetry Aio-pika instrumentation
18+
long_description = file: README.rst
19+
long_description_content_type = text/x-rst
20+
author = OpenTelemetry Authors
21+
author_email = [email protected]
22+
url = https://github.com/open-telemetry/opentelemetry-python-contrib/instrumentation/opentelemetry-instrumentation-aio-pika
23+
platforms = any
24+
license = Apache-2.0
25+
classifiers =
26+
Development Status :: 4 - Beta
27+
Intended Audience :: Developers
28+
License :: OSI Approved :: Apache Software License
29+
Programming Language :: Python
30+
Programming Language :: Python :: 3
31+
Programming Language :: Python :: 3.6
32+
Programming Language :: Python :: 3.7
33+
Programming Language :: Python :: 3.8
34+
Programming Language :: Python :: 3.9
35+
Programming Language :: Python :: 3.10
36+
37+
[options]
38+
python_requires = >=3.6
39+
package_dir=
40+
=src
41+
packages=find_namespace:
42+
43+
install_requires =
44+
opentelemetry-api ~= 1.5
45+
wrapt >= 1.0.0, < 2.0.0
46+
47+
[options.extras_require]
48+
test =
49+
pytest
50+
wrapt >= 1.0.0, < 2.0.0
51+
opentelemetry-test-utils == 0.31b0
52+
53+
[options.packages.find]
54+
where = src
55+
56+
[options.entry_points]
57+
opentelemetry_instrumentor =
58+
aio-pika = opentelemetry.instrumentation.aio_pika:AioPikaInstrumentor
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
# Copyright The OpenTelemetry Authors
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
16+
# DO NOT EDIT. THIS FILE WAS AUTOGENERATED FROM templates/instrumentation_setup.py.txt.
17+
# RUN `python scripts/generate_setup.py` TO REGENERATE.
18+
19+
20+
import distutils.cmd
21+
import json
22+
import os
23+
from configparser import ConfigParser
24+
25+
import setuptools
26+
27+
config = ConfigParser()
28+
config.read("setup.cfg")
29+
30+
# We provide extras_require parameter to setuptools.setup later which
31+
# overwrites the extras_require section from setup.cfg. To support extras_require
32+
# section in setup.cfg, we load it here and merge it with the extras_require param.
33+
extras_require = {}
34+
if "options.extras_require" in config:
35+
for key, value in config["options.extras_require"].items():
36+
extras_require[key] = [v for v in value.split("\n") if v.strip()]
37+
38+
BASE_DIR = os.path.dirname(__file__)
39+
PACKAGE_INFO = {}
40+
41+
VERSION_FILENAME = os.path.join(
42+
BASE_DIR,
43+
"src",
44+
"opentelemetry",
45+
"instrumentation",
46+
"aio_pika",
47+
"version.py",
48+
)
49+
with open(VERSION_FILENAME, encoding="utf-8") as f:
50+
exec(f.read(), PACKAGE_INFO)
51+
52+
PACKAGE_FILENAME = os.path.join(
53+
BASE_DIR,
54+
"src",
55+
"opentelemetry",
56+
"instrumentation",
57+
"aio_pika",
58+
"package.py",
59+
)
60+
with open(PACKAGE_FILENAME, encoding="utf-8") as f:
61+
exec(f.read(), PACKAGE_INFO)
62+
63+
# Mark any instruments/runtime dependencies as test dependencies as well.
64+
extras_require["instruments"] = PACKAGE_INFO["_instruments"]
65+
test_deps = extras_require.get("test", [])
66+
for dep in extras_require["instruments"]:
67+
test_deps.append(dep)
68+
69+
extras_require["test"] = test_deps
70+
71+
72+
class JSONMetadataCommand(distutils.cmd.Command):
73+
74+
description = (
75+
"print out package metadata as JSON. This is used by OpenTelemetry dev scripts to ",
76+
"auto-generate code in other places",
77+
)
78+
user_options = []
79+
80+
def initialize_options(self):
81+
pass
82+
83+
def finalize_options(self):
84+
pass
85+
86+
def run(self):
87+
metadata = {
88+
"name": config["metadata"]["name"],
89+
"version": PACKAGE_INFO["__version__"],
90+
"instruments": PACKAGE_INFO["_instruments"],
91+
}
92+
print(json.dumps(metadata))
93+
94+
95+
setuptools.setup(
96+
cmdclass={"meta": JSONMetadataCommand},
97+
version=PACKAGE_INFO["__version__"],
98+
extras_require=extras_require,
99+
)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# Copyright The OpenTelemetry Authors
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
"""
15+
Instrument `aio_pika` to trace RabbitMQ applications.
16+
17+
Usage
18+
-----
19+
20+
* Start broker backend
21+
22+
.. code-block:: python
23+
24+
docker run -p 5672:5672 rabbitmq
25+
26+
* Run instrumented task
27+
28+
.. code-block:: python
29+
30+
import asyncio
31+
32+
from aio_pika import Message, connect
33+
from opentelemetry.instrumentation.aio_pika import AioPikaInstrumentor
34+
35+
AioPikaInstrumentor().instrument()
36+
37+
38+
async def main() -> None:
39+
connection = await connect("amqp://guest:guest@localhost/")
40+
async with connection:
41+
channel = await connection.channel()
42+
queue = await channel.declare_queue("hello")
43+
await channel.default_exchange.publish(
44+
Message(b"Hello World!"),
45+
routing_key=queue.name,
46+
)
47+
48+
49+
if __name__ == "__main__":
50+
asyncio.run(main())
51+
52+
API
53+
---
54+
"""
55+
# pylint: disable=import-error
56+
57+
from .aio_pika_instrumentor import AioPikaInstrumentor
58+
from .version import __version__
59+
60+
__all__ = ["AioPikaInstrumentor", "__version__"]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
# Copyright The OpenTelemetry Authors
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
from typing import Any, Callable, Collection
15+
16+
import wrapt
17+
from aio_pika import Exchange, Queue
18+
from aio_pika.abc import AbstractIncomingMessage
19+
20+
from opentelemetry import trace
21+
from opentelemetry.instrumentation.aio_pika.callback_decorator import (
22+
CallbackDecorator,
23+
)
24+
from opentelemetry.instrumentation.aio_pika.package import _instruments
25+
from opentelemetry.instrumentation.aio_pika.publish_decorator import (
26+
PublishDecorator,
27+
)
28+
from opentelemetry.instrumentation.aio_pika.version import __version__
29+
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
30+
from opentelemetry.instrumentation.utils import unwrap
31+
from opentelemetry.trace import Tracer
32+
33+
_INSTRUMENTATION_MODULE_NAME = "opentelemetry.instrumentation.aio_pika"
34+
35+
36+
class AioPikaInstrumentor(BaseInstrumentor):
37+
@staticmethod
38+
def _instrument_queue(tracer: Tracer):
39+
async def wrapper(wrapped, instance, args, kwargs):
40+
async def consume(
41+
callback: Callable[[AbstractIncomingMessage], Any],
42+
*fargs,
43+
**fkwargs
44+
):
45+
decorated_callback = CallbackDecorator(
46+
tracer, instance
47+
).decorate(callback)
48+
return await wrapped(decorated_callback, *fargs, **fkwargs)
49+
50+
return await consume(*args, **kwargs)
51+
52+
wrapt.wrap_function_wrapper(Queue, "consume", wrapper)
53+
54+
@staticmethod
55+
def _instrument_exchange(tracer: Tracer):
56+
async def wrapper(wrapped, instance, args, kwargs):
57+
decorated_publish = PublishDecorator(tracer, instance).decorate(
58+
wrapped
59+
)
60+
return await decorated_publish(*args, **kwargs)
61+
62+
wrapt.wrap_function_wrapper(Exchange, "publish", wrapper)
63+
64+
def _instrument(self, **kwargs):
65+
tracer_provider = kwargs.get("tracer_provider", None)
66+
tracer = trace.get_tracer(
67+
_INSTRUMENTATION_MODULE_NAME, __version__, tracer_provider
68+
)
69+
self._instrument_queue(tracer)
70+
self._instrument_exchange(tracer)
71+
72+
@staticmethod
73+
def _uninstrument_queue():
74+
unwrap(Queue, "consume")
75+
76+
@staticmethod
77+
def _uninstrument_exchange():
78+
unwrap(Exchange, "publish")
79+
80+
def _uninstrument(self, **kwargs):
81+
self._uninstrument_queue()
82+
self._uninstrument_exchange()
83+
84+
def instrumentation_dependencies(self) -> Collection[str]:
85+
return _instruments

0 commit comments

Comments
 (0)