From b6492a7999ebf5bdbad3ff71ceab6288b63e3233 Mon Sep 17 00:00:00 2001 From: Allen Kim Date: Thu, 15 Feb 2024 06:44:17 +0900 Subject: [PATCH] Feature/asyncio instrumentation (#1943) * add asyncio instrumentation * add asyncio instrumentation * modify test configure * modify test configure * modify tox generate result * modify tox generate result * add python version check * modify test code * add CHANGELOG.md * add docs * modify pyproject.toml * modify pyproject.toml * Add comments mentioned in an issue #1919 * Add comments mentioned in an issue #1919 * add asyncio component owner * - Add instrumentation-asyncio metric. - Configure coroutines/to_thread func to apply trace via environment variables. - Apply trace to future using a boolean environment variable. * modify docs * modify docs * modify docs * modify docs * modify docs * modify test_code * modify test_code * modify test_code * modify asyncio version * modify asyncio version * update dependency * modified lint results * modified lint results * modified lint results * modified lint results * modified lint results * modified lint results * modified lint results * include feedback * include feedback * include feedback * modify docs test results * Update instrumentation/opentelemetry-instrumentation-asyncio/README.rst Co-authored-by: Aaron Abbott * Update instrumentation/opentelemetry-instrumentation-asyncio/README.rst Co-authored-by: Aaron Abbott * Update instrumentation/opentelemetry-instrumentation-asyncio/README.rst Co-authored-by: Aaron Abbott * Update instrumentation/opentelemetry-instrumentation-asyncio/README.rst Co-authored-by: Aaron Abbott * Update instrumentation/opentelemetry-instrumentation-asyncio/src/opentelemetry/instrumentation/asyncio/utils.py Co-authored-by: Aaron Abbott * Update instrumentation/opentelemetry-instrumentation-asyncio/src/opentelemetry/instrumentation/asyncio/utils.py Co-authored-by: Aaron Abbott * include feedback * include feedback * drop python 3.7 support * drop python 3.7 support * Removed from default_instrumentations * Recover --------- Co-authored-by: Diego Hurtado Co-authored-by: Aaron Abbott --- .github/component_owners.yml | 3 + CHANGELOG.md | 3 +- CONTRIBUTING.md | 2 +- docs/instrumentation/asyncio/asyncio.rst | 7 + instrumentation/README.md | 1 + .../LICENSE | 201 ++++++++++ .../README.rst | 110 +++++ .../pyproject.toml | 59 +++ .../instrumentation/asyncio/__init__.py | 375 ++++++++++++++++++ .../asyncio/environment_variables.py | 34 ++ .../instrumentation/asyncio/package.py | 15 + .../instrumentation/asyncio/utils.py | 67 ++++ .../instrumentation/asyncio/version.py | 15 + .../tests/__init__.py | 13 + .../tests/common_test_func.py | 48 +++ .../tests/test_asyncio_cancellation.py | 78 ++++ .../tests/test_asyncio_create_task.py | 52 +++ .../tests/test_asyncio_ensure_future.py | 91 +++++ .../tests/test_asyncio_gather.py | 53 +++ .../tests/test_asyncio_integration.py | 49 +++ .../test_asyncio_run_coroutine_threadsafe.py | 61 +++ .../tests/test_asyncio_taskgroup.py | 63 +++ .../tests/test_asyncio_to_thread.py | 73 ++++ .../tests/test_asyncio_utils.py | 44 ++ .../tests/test_asyncio_wait.py | 88 ++++ .../pyproject.toml | 1 + .../instrumentation/bootstrap_gen.py | 1 + tox.ini | 7 + 28 files changed, 1612 insertions(+), 2 deletions(-) create mode 100644 docs/instrumentation/asyncio/asyncio.rst create mode 100644 instrumentation/opentelemetry-instrumentation-asyncio/LICENSE create mode 100644 instrumentation/opentelemetry-instrumentation-asyncio/README.rst create mode 100644 instrumentation/opentelemetry-instrumentation-asyncio/pyproject.toml create mode 100644 instrumentation/opentelemetry-instrumentation-asyncio/src/opentelemetry/instrumentation/asyncio/__init__.py create mode 100644 instrumentation/opentelemetry-instrumentation-asyncio/src/opentelemetry/instrumentation/asyncio/environment_variables.py create mode 100644 instrumentation/opentelemetry-instrumentation-asyncio/src/opentelemetry/instrumentation/asyncio/package.py create mode 100644 instrumentation/opentelemetry-instrumentation-asyncio/src/opentelemetry/instrumentation/asyncio/utils.py create mode 100644 instrumentation/opentelemetry-instrumentation-asyncio/src/opentelemetry/instrumentation/asyncio/version.py create mode 100644 instrumentation/opentelemetry-instrumentation-asyncio/tests/__init__.py create mode 100644 instrumentation/opentelemetry-instrumentation-asyncio/tests/common_test_func.py create mode 100644 instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_cancellation.py create mode 100644 instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_create_task.py create mode 100644 instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_ensure_future.py create mode 100644 instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_gather.py create mode 100644 instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_integration.py create mode 100644 instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_run_coroutine_threadsafe.py create mode 100644 instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_taskgroup.py create mode 100644 instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_to_thread.py create mode 100644 instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_utils.py create mode 100644 instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_wait.py diff --git a/.github/component_owners.yml b/.github/component_owners.yml index e31fde9b48..3e8459ec59 100644 --- a/.github/component_owners.yml +++ b/.github/component_owners.yml @@ -67,3 +67,6 @@ components: instrumentation/opentelemetry-instrumentation-cassandra: - mattcontinisio + + instrumentation/opentelemetry-instrumentation-asyncio: + - bourbonkk diff --git a/CHANGELOG.md b/CHANGELOG.md index 868b4f3e0b..1a31f1a2d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,7 +23,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## Version 1.22.0/0.43b0 (2023-12-14) ### Added - +- `opentelemetry-instrumentation-asyncio` Add support for asyncio + ([#1919](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1943)) - `opentelemetry-instrumentation` Added Otel semantic convention opt-in mechanism ([#1987](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1987)) - `opentelemetry-instrumentation-httpx` Fix mixing async and non async hooks diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 329962955c..7c76634db7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -202,7 +202,7 @@ The continuation integration overrides that environment variable with as per the Below is a checklist of things to be mindful of when implementing a new instrumentation or working on a specific instrumentation. It is one of our goals as a community to keep the implementation specific details of instrumentations as similar across the board as possible for ease of testing and feature parity. It is also good to abstract as much common functionality as possible. - Follow semantic conventions - - The instrumentation should follow the semantic conventions defined [here](https://github.com/open-telemetry/opentelemetry-specification/tree/main/semantic_conventions) + - The instrumentation should follow the semantic conventions defined [here](https://github.com/open-telemetry/opentelemetry-specification/tree/main/specification/semantic-conventions.md) - Extends from [BaseInstrumentor](https://github.com/open-telemetry/opentelemetry-python-contrib/blob/main/opentelemetry-instrumentation/src/opentelemetry/instrumentation/instrumentor.py#L26) - Supports auto-instrumentation - Add an entry point (ex. https://github.com/open-telemetry/opentelemetry-python-contrib/blob/f045c43affff6ff1af8fa2f7514a4fdaca97dacf/instrumentation/opentelemetry-instrumentation-requests/pyproject.toml#L44) diff --git a/docs/instrumentation/asyncio/asyncio.rst b/docs/instrumentation/asyncio/asyncio.rst new file mode 100644 index 0000000000..4cbcc70f09 --- /dev/null +++ b/docs/instrumentation/asyncio/asyncio.rst @@ -0,0 +1,7 @@ +OpenTelemetry asyncio Instrumentation +============================================== + +.. automodule:: opentelemetry.instrumentation.asyncio + :members: + :undoc-members: + :show-inheritance: diff --git a/instrumentation/README.md b/instrumentation/README.md index 2d77e806c5..d5e201b135 100644 --- a/instrumentation/README.md +++ b/instrumentation/README.md @@ -6,6 +6,7 @@ | [opentelemetry-instrumentation-aiohttp-server](./opentelemetry-instrumentation-aiohttp-server) | aiohttp ~= 3.0 | No | [opentelemetry-instrumentation-aiopg](./opentelemetry-instrumentation-aiopg) | aiopg >= 0.13.0, < 2.0.0 | No | [opentelemetry-instrumentation-asgi](./opentelemetry-instrumentation-asgi) | asgiref ~= 3.0 | No +| [opentelemetry-instrumentation-asyncio](./opentelemetry-instrumentation-asyncio) | asyncio | No | [opentelemetry-instrumentation-asyncpg](./opentelemetry-instrumentation-asyncpg) | asyncpg >= 0.12.0 | No | [opentelemetry-instrumentation-aws-lambda](./opentelemetry-instrumentation-aws-lambda) | aws_lambda | No | [opentelemetry-instrumentation-boto](./opentelemetry-instrumentation-boto) | boto~=2.0 | No diff --git a/instrumentation/opentelemetry-instrumentation-asyncio/LICENSE b/instrumentation/opentelemetry-instrumentation-asyncio/LICENSE new file mode 100644 index 0000000000..1ef7dad2c5 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright The OpenTelemetry Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/instrumentation/opentelemetry-instrumentation-asyncio/README.rst b/instrumentation/opentelemetry-instrumentation-asyncio/README.rst new file mode 100644 index 0000000000..d78e846793 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/README.rst @@ -0,0 +1,110 @@ +OpenTelemetry asyncio Instrumentation +====================================== + +|pypi| + +.. |pypi| image:: https://badge.fury.io/py/opentelemetry-instrumentation-asyncio.svg + :target: https://pypi.org/project/opentelemetry-instrumentation-asyncio/ + +AsyncioInstrumentor: Tracing Requests Made by the Asyncio Library + + +The opentelemetry-instrumentation-asyncio package allows tracing asyncio applications. +It also includes metrics for duration and counts of coroutines and futures. Metrics are generated even if coroutines are not traced. + + +Set the names of coroutines you want to trace. +------------------------------------------------- +.. code:: bash + + export OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACE=coro_name,coro_name2,coro_name3 + +If you want to trace specific blocking functions executed with the ``to_thread`` function of asyncio, set the name of the functions in ``OTEL_PYTHON_ASYNCIO_TO_THREAD_FUNCTION_NAMES_TO_TRACE``. +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ +.. code:: bash + + export OTEL_PYTHON_ASYNCIO_TO_THREAD_FUNCTION_NAMES_TO_TRACE=func_name,func_name2,func_name3 + +You can enable tracing futures with ``OTEL_PYTHON_ASYNCIO_FUTURE_TRACE_ENABLED`` +----------------------------------------------------------------------------------------------- +.. code:: bash + + export OTEL_PYTHON_ASYNCIO_FUTURE_TRACE_ENABLED=true + +Run instrumented application +----------------------------- +1. coroutine +-------------------- +.. code:: python + + # export OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACE=sleep + + import asyncio + from opentelemetry.instrumentation.asyncio import AsyncioInstrumentor + + AsyncioInstrumentor().instrument() + + async def main(): + await asyncio.create_task(asyncio.sleep(0.1)) + + asyncio.run(main()) + +2. future +-------------------- +.. code:: python + + # export OTEL_PYTHON_ASYNCIO_FUTURE_TRACE_ENABLED=true + + loop = asyncio.get_event_loop() + + future = asyncio.Future() + future.set_result(1) + task = asyncio.ensure_future(future) + loop.run_until_complete(task) + +3. to_thread +-------------------- +.. code:: python + + # export OTEL_PYTHON_ASYNCIO_TO_THREAD_FUNCTION_NAMES_TO_TRACE=func + + import asyncio + from opentelemetry.instrumentation.asyncio import AsyncioInstrumentor + + AsyncioInstrumentor().instrument() + + async def main(): + await asyncio.to_thread(func) + + def func(): + pass + + asyncio.run(main()) + + +asyncio metric types +---------------------- + +* `asyncio.process.duration` (seconds) - Duration of asyncio process +* `asyncio.process.count` (count) - Number of asyncio process + + +API +--- + + + +Installation +------------ + +:: + + pip install opentelemetry-instrumentation-asyncio + + +References +----------- + +* `OpenTelemetry asyncio/ Tracing `_ +* `OpenTelemetry Project `_ +* `OpenTelemetry Python Examples `_ diff --git a/instrumentation/opentelemetry-instrumentation-asyncio/pyproject.toml b/instrumentation/opentelemetry-instrumentation-asyncio/pyproject.toml new file mode 100644 index 0000000000..0624714d99 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/pyproject.toml @@ -0,0 +1,59 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "opentelemetry-instrumentation-asyncio" +dynamic = ["version"] +description = "OpenTelemetry instrumentation for asyncio" +readme = "README.rst" +license = "Apache-2.0" +requires-python = ">=3.8" +authors = [ + { name = "OpenTelemetry Authors", email = "cncf-opentelemetry-contributors@lists.cncf.io" }, +] +classifiers = [ + "Development Status :: 4 - Beta", + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", +] +dependencies = [ + "opentelemetry-api ~= 1.14", + "opentelemetry-instrumentation == 0.44b0.dev", + "opentelemetry-semantic-conventions == 0.44b0.dev", + "opentelemetry-test-utils == 0.44b0.dev", + "wrapt >= 1.0.0, < 2.0.0", +] + +[project.optional-dependencies] +instruments = [] +test = [ + "opentelemetry-instrumentation-asyncio[instruments]", + "pytest", + "wrapt >= 1.0.0, < 2.0.0", + "pytest-asyncio", +] + +[project.entry-points.opentelemetry_instrumentor] +asyncio = "opentelemetry.instrumentation.asyncio:AsyncioInstrumentor" + +[project.urls] +Homepage = "https://github.com/open-telemetry/opentelemetry-python-contrib/tree/main/instrumentation/opentelemetry-instrumentation-asyncio" + +[tool.hatch.version] +path = "src/opentelemetry/instrumentation/asyncio/version.py" + +[tool.hatch.build.targets.sdist] +include = [ + "/src", + "/tests", +] + +[tool.hatch.build.targets.wheel] +packages = ["src/opentelemetry"] diff --git a/instrumentation/opentelemetry-instrumentation-asyncio/src/opentelemetry/instrumentation/asyncio/__init__.py b/instrumentation/opentelemetry-instrumentation-asyncio/src/opentelemetry/instrumentation/asyncio/__init__.py new file mode 100644 index 0000000000..68e3d0839f --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/src/opentelemetry/instrumentation/asyncio/__init__.py @@ -0,0 +1,375 @@ +# Copyright The OpenTelemetry Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +.. asyncio: https://github.com/python/asyncio + +The opentelemetry-instrumentation-asycnio package allows tracing asyncio applications. +The metric for coroutine, future, is generated even if there is no setting to generate a span. + +Run instrumented application +------------------------------ +1. coroutine +---------------- +.. code:: python + + # export OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACE=sleep + + import asyncio + from opentelemetry.instrumentation.asyncio import AsyncioInstrumentor + + AsyncioInstrumentor().instrument() + + async def main(): + await asyncio.create_task(asyncio.sleep(0.1)) + + asyncio.run(main()) + +2. future +------------ +.. code:: python + + # export OTEL_PYTHON_ASYNCIO_FUTURE_TRACE_ENABLED=true + + loop = asyncio.get_event_loop() + + future = asyncio.Future() + future.set_result(1) + task = asyncio.ensure_future(future) + loop.run_until_complete(task) + +3. to_thread +------------- +.. code:: python + + import asyncio + from opentelemetry.instrumentation.asyncio import AsyncioInstrumentor + + AsyncioInstrumentor().instrument() + + async def main(): + await asyncio.to_thread(func) + + def func(): + pass + + asyncio.run(main()) + + +asyncio metric types +--------------------- + +* asyncio.process.duration (seconds) - Duration of asyncio process +* asyncio.process.count (count) - Number of asyncio process + + +API +--- +""" +import asyncio +import sys +from asyncio import futures +from timeit import default_timer +from typing import Collection + +from wrapt import wrap_function_wrapper as _wrap + +from opentelemetry.instrumentation.asyncio.package import _instruments +from opentelemetry.instrumentation.asyncio.utils import ( + get_coros_to_trace, + get_future_trace_enabled, + get_to_thread_to_trace, +) +from opentelemetry.instrumentation.asyncio.version import __version__ +from opentelemetry.instrumentation.instrumentor import BaseInstrumentor +from opentelemetry.instrumentation.utils import unwrap +from opentelemetry.metrics import get_meter +from opentelemetry.trace import get_tracer +from opentelemetry.trace.status import Status, StatusCode + +ASYNCIO_PREFIX = "asyncio" + + +class AsyncioInstrumentor(BaseInstrumentor): + """ + An instrumentor for asyncio + + See `BaseInstrumentor` + """ + + methods_with_coroutine = [ + "create_task", + "ensure_future", + "wait_for", + "wait", + "as_completed", + "run_coroutine_threadsafe", + ] + + def __init__(self): + super().__init__() + self.process_duration_histogram = None + self.process_created_counter = None + + self._tracer = None + self._meter = None + self._coros_name_to_trace: set = set() + self._to_thread_name_to_trace: set = set() + self._future_active_enabled: bool = False + + def instrumentation_dependencies(self) -> Collection[str]: + return _instruments + + def _instrument(self, **kwargs): + self._tracer = get_tracer( + __name__, __version__, kwargs.get("tracer_provider") + ) + self._meter = get_meter( + __name__, __version__, kwargs.get("meter_provider") + ) + + self._coros_name_to_trace = get_coros_to_trace() + self._future_active_enabled = get_future_trace_enabled() + self._to_thread_name_to_trace = get_to_thread_to_trace() + + self.process_duration_histogram = self._meter.create_histogram( + name="asyncio.process.duration", + description="Duration of asyncio process", + unit="s", + ) + self.process_created_counter = self._meter.create_counter( + name="asyncio.process.created", + description="Number of asyncio process", + unit="{process}", + ) + + for method in self.methods_with_coroutine: + self.instrument_method_with_coroutine(method) + + self.instrument_gather() + self.instrument_to_thread() + self.instrument_taskgroup_create_task() + + def _uninstrument(self, **kwargs): + for method in self.methods_with_coroutine: + uninstrument_method_with_coroutine(method) + uninstrument_gather() + uninstrument_to_thread() + uninstrument_taskgroup_create_task() + + def instrument_method_with_coroutine(self, method_name: str): + """ + Instruments specified asyncio method. + """ + + def wrap_coro_or_future(method, instance, args, kwargs): + + # If the first argument is a coroutine or future, + # we decorate it with a span and return the task. + if args and len(args) > 0: + first_arg = args[0] + # Check if it's a coroutine or future and wrap it + if asyncio.iscoroutine(first_arg) or futures.isfuture( + first_arg + ): + args = (self.trace_item(first_arg),) + args[1:] + # Check if it's a list and wrap each item + elif isinstance(first_arg, list): + args = ( + [self.trace_item(item) for item in first_arg], + ) + args[1:] + return method(*args, **kwargs) + + _wrap(asyncio, method_name, wrap_coro_or_future) + + def instrument_gather(self): + def wrap_coros_or_futures(method, instance, args, kwargs): + if args and len(args) > 0: + # Check if it's a coroutine or future and wrap it + wrapped_args = tuple(self.trace_item(item) for item in args) + return method(*wrapped_args, **kwargs) + return method(*args, **kwargs) + + _wrap(asyncio, "gather", wrap_coros_or_futures) + + def instrument_to_thread(self) -> None: + # to_thread was added in Python 3.9 + if sys.version_info < (3, 9): + return + + def wrap_to_thread(method, instance, args, kwargs) -> None: + if args: + first_arg = args[0] + # Wrap the first argument + wrapped_first_arg = self.trace_to_thread(first_arg) + wrapped_args = (wrapped_first_arg,) + args[1:] + + return method(*wrapped_args, **kwargs) + return method(*args, **kwargs) + + _wrap(asyncio, "to_thread", wrap_to_thread) + + def instrument_taskgroup_create_task(self) -> None: + # TaskGroup.create_task was added in Python 3.11 + if sys.version_info < (3, 11): + return + + def wrap_taskgroup_create_task(method, instance, args, kwargs) -> None: + if args: + coro = args[0] + wrapped_coro = self.trace_coroutine(coro) + wrapped_args = (wrapped_coro,) + args[1:] + return method(*wrapped_args, **kwargs) + return method(*args, **kwargs) + + _wrap( + asyncio.TaskGroup, # pylint: disable=no-member + "create_task", + wrap_taskgroup_create_task, + ) + + def trace_to_thread(self, func: callable): + """Trace a function.""" + start = default_timer() + span = ( + self._tracer.start_span( + f"{ASYNCIO_PREFIX} to_thread-" + func.__name__ + ) + if func.__name__ in self._to_thread_name_to_trace + else None + ) + attr = {"type": "to_thread", "name": func.__name__} + exception = None + try: + attr["state"] = "finished" + return func + except Exception: + attr["state"] = "exception" + raise + finally: + self.record_process(start, attr, span, exception) + + def trace_item(self, coro_or_future): + """Trace a coroutine or future item.""" + # Task is already traced, return it + if isinstance(coro_or_future, asyncio.Task): + return coro_or_future + if asyncio.iscoroutine(coro_or_future): + return self.trace_coroutine(coro_or_future) + if futures.isfuture(coro_or_future): + return self.trace_future(coro_or_future) + return coro_or_future + + async def trace_coroutine(self, coro): + start = default_timer() + attr = { + "type": "coroutine", + "name": coro.__name__, + } + span = ( + self._tracer.start_span(f"{ASYNCIO_PREFIX} coro-" + coro.__name__) + if coro.__name__ in self._coros_name_to_trace + else None + ) + exception = None + try: + attr["state"] = "finished" + return await coro + # CancelledError is raised when a coroutine is cancelled + # before it has a chance to run. We don't want to record + # this as an error. + except asyncio.CancelledError: + attr["state"] = "cancelled" + except Exception as exc: + exception = exc + state = determine_state(exception) + attr["state"] = state + raise + finally: + self.record_process(start, attr, span, exception) + + def trace_future(self, future): + start = default_timer() + span = ( + self._tracer.start_span(f"{ASYNCIO_PREFIX} future") + if self._future_active_enabled + else None + ) + + def callback(f): + exception = f.exception() + attr = { + "type": "future", + } + state = determine_state(exception) + attr["state"] = state + self.record_process(start, attr, span, exception) + + future.add_done_callback(callback) + return future + + def record_process( + self, start: float, attr: dict, span=None, exception=None + ) -> None: + """ + Record the processing time, update histogram and counter, and handle span. + + :param start: Start time of the process. + :param attr: Attributes for the histogram and counter. + :param span: Optional span for tracing. + :param exception: Optional exception occurred during the process. + """ + duration = max(default_timer() - start, 0) + self.process_duration_histogram.record(duration, attr) + self.process_created_counter.add(1, attr) + + if span: + if span.is_recording() and exception: + span.set_status(Status(StatusCode.ERROR)) + span.record_exception(exception) + span.end() + + +def determine_state(exception: Exception) -> str: + if isinstance(exception, asyncio.CancelledError): + return "cancelled" + if isinstance(exception, asyncio.TimeoutError): + return "timeout" + if exception: + return "exception" + return "finished" + + +def uninstrument_taskgroup_create_task() -> None: + # TaskGroup.create_task was added in Python 3.11 + if sys.version_info < (3, 11): + return + unwrap(asyncio.TaskGroup, "create_task") # pylint: disable=no-member + + +def uninstrument_to_thread() -> None: + # to_thread was added in Python 3.9 + if sys.version_info < (3, 9): + return + unwrap(asyncio, "to_thread") + + +def uninstrument_gather() -> None: + unwrap(asyncio, "gather") + + +def uninstrument_method_with_coroutine(method_name: str) -> None: + """ + Uninstrument specified asyncio method. + """ + unwrap(asyncio, method_name) diff --git a/instrumentation/opentelemetry-instrumentation-asyncio/src/opentelemetry/instrumentation/asyncio/environment_variables.py b/instrumentation/opentelemetry-instrumentation-asyncio/src/opentelemetry/instrumentation/asyncio/environment_variables.py new file mode 100644 index 0000000000..7420ea362f --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/src/opentelemetry/instrumentation/asyncio/environment_variables.py @@ -0,0 +1,34 @@ +# Copyright The OpenTelemetry Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Enter the names of the coroutines to be traced through the environment variable below, separated by commas. +""" +OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACE = ( + "OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACE" +) + +""" +To determines whether the tracing feature for Future of Asyncio in Python is enabled or not. +""" +OTEL_PYTHON_ASYNCIO_FUTURE_TRACE_ENABLED = ( + "OTEL_PYTHON_ASYNCIO_FUTURE_TRACE_ENABLED" +) + +""" +Enter the names of the functions to be traced through the environment variable below, separated by commas. +""" +OTEL_PYTHON_ASYNCIO_TO_THREAD_FUNCTION_NAMES_TO_TRACE = ( + "OTEL_PYTHON_ASYNCIO_TO_THREAD_FUNCTION_NAMES_TO_TRACE" +) diff --git a/instrumentation/opentelemetry-instrumentation-asyncio/src/opentelemetry/instrumentation/asyncio/package.py b/instrumentation/opentelemetry-instrumentation-asyncio/src/opentelemetry/instrumentation/asyncio/package.py new file mode 100644 index 0000000000..484f6e9c58 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/src/opentelemetry/instrumentation/asyncio/package.py @@ -0,0 +1,15 @@ +# Copyright The OpenTelemetry Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +_instruments = tuple() diff --git a/instrumentation/opentelemetry-instrumentation-asyncio/src/opentelemetry/instrumentation/asyncio/utils.py b/instrumentation/opentelemetry-instrumentation-asyncio/src/opentelemetry/instrumentation/asyncio/utils.py new file mode 100644 index 0000000000..15c78ae1ce --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/src/opentelemetry/instrumentation/asyncio/utils.py @@ -0,0 +1,67 @@ +# Copyright The OpenTelemetry Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import os +from typing import Set + +# pylint: disable=no-name-in-module +from opentelemetry.instrumentation.asyncio.environment_variables import ( + OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACE, + OTEL_PYTHON_ASYNCIO_FUTURE_TRACE_ENABLED, + OTEL_PYTHON_ASYNCIO_TO_THREAD_FUNCTION_NAMES_TO_TRACE, +) + + +def separate_coro_names_by_comma(coro_names: str) -> Set[str]: + """ + Function to separate the coroutines to be traced by comma + """ + if coro_names is None: + return set() + return {coro_name.strip() for coro_name in coro_names.split(",")} + + +def get_coros_to_trace() -> set: + """ + Function to get the coroutines to be traced from the environment variable + """ + coro_names = os.getenv(OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACE) + return separate_coro_names_by_comma(coro_names) + + +def get_future_trace_enabled() -> bool: + """ + Function to get the future active enabled flag from the environment variable + default value is False + """ + return ( + os.getenv(OTEL_PYTHON_ASYNCIO_FUTURE_TRACE_ENABLED, "False").lower() + == "true" + ) + + +def get_to_thread_to_trace() -> set: + """ + Function to get the functions to be traced from the environment variable + """ + func_names = os.getenv( + OTEL_PYTHON_ASYNCIO_TO_THREAD_FUNCTION_NAMES_TO_TRACE + ) + return separate_coro_names_by_comma(func_names) + + +__all__ = [ + "get_coros_to_trace", + "get_future_trace_enabled", + "get_to_thread_to_trace", +] diff --git a/instrumentation/opentelemetry-instrumentation-asyncio/src/opentelemetry/instrumentation/asyncio/version.py b/instrumentation/opentelemetry-instrumentation-asyncio/src/opentelemetry/instrumentation/asyncio/version.py new file mode 100644 index 0000000000..ff896307c3 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/src/opentelemetry/instrumentation/asyncio/version.py @@ -0,0 +1,15 @@ +# Copyright The OpenTelemetry Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +__version__ = "0.44b0.dev" diff --git a/instrumentation/opentelemetry-instrumentation-asyncio/tests/__init__.py b/instrumentation/opentelemetry-instrumentation-asyncio/tests/__init__.py new file mode 100644 index 0000000000..b0a6f42841 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/tests/__init__.py @@ -0,0 +1,13 @@ +# Copyright The OpenTelemetry Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/instrumentation/opentelemetry-instrumentation-asyncio/tests/common_test_func.py b/instrumentation/opentelemetry-instrumentation-asyncio/tests/common_test_func.py new file mode 100644 index 0000000000..5d06641bc0 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/tests/common_test_func.py @@ -0,0 +1,48 @@ +# Copyright The OpenTelemetry Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import asyncio + + +async def async_func(): + await asyncio.sleep(0.1) + + +async def factorial(number: int): + factorial_value = 1 + for value in range(2, number + 1): + await asyncio.sleep(0) + factorial_value *= value + return factorial_value + + +async def cancellable_coroutine(): + await asyncio.sleep(2) + + +async def cancellation_coro(): + task = asyncio.create_task(cancellable_coroutine()) + + await asyncio.sleep(0.1) + task.cancel() + + await task + + +async def cancellation_create_task(): + await asyncio.create_task(cancellation_coro()) + + +async def ensure_future(): + await asyncio.ensure_future(asyncio.sleep(0)) diff --git a/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_cancellation.py b/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_cancellation.py new file mode 100644 index 0000000000..9172cd4458 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_cancellation.py @@ -0,0 +1,78 @@ +# Copyright The OpenTelemetry Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import asyncio +from unittest.mock import patch + +# pylint: disable=no-name-in-module +from opentelemetry.instrumentation.asyncio import AsyncioInstrumentor +from opentelemetry.instrumentation.asyncio.environment_variables import ( + OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACE, +) +from opentelemetry.test.test_base import TestBase +from opentelemetry.trace import SpanKind, get_tracer + +from .common_test_func import cancellation_create_task + + +class TestAsyncioCancel(TestBase): + @patch.dict( + "os.environ", + { + OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACE: "cancellation_coro, cancellable_coroutine" + }, + ) + def setUp(self): + super().setUp() + AsyncioInstrumentor().instrument() + self._tracer = get_tracer( + __name__, + ) + + def tearDown(self): + super().tearDown() + AsyncioInstrumentor().uninstrument() + + def test_cancel(self): + with self._tracer.start_as_current_span("root", kind=SpanKind.SERVER): + asyncio.run(cancellation_create_task()) + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 3) + self.assertEqual(spans[0].context.trace_id, spans[1].context.trace_id) + self.assertEqual(spans[2].context.trace_id, spans[1].context.trace_id) + + self.assertEqual(spans[0].name, "asyncio coro-cancellable_coroutine") + self.assertEqual(spans[1].name, "asyncio coro-cancellation_coro") + for metric in ( + self.memory_metrics_reader.get_metrics_data() + .resource_metrics[0] + .scope_metrics[0] + .metrics + ): + if metric.name == "asyncio.process.duration": + for point in metric.data.data_points: + self.assertEqual(point.attributes["type"], "coroutine") + self.assertIn( + point.attributes["name"], + ["cancellation_coro", "cancellable_coroutine"], + ) + if metric.name == "asyncio.process.created": + for point in metric.data.data_points: + self.assertEqual(point.attributes["type"], "coroutine") + self.assertIn( + point.attributes["name"], + ["cancellation_coro", "cancellable_coroutine"], + ) + self.assertIn( + point.attributes["state"], ["finished", "cancelled"] + ) diff --git a/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_create_task.py b/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_create_task.py new file mode 100644 index 0000000000..9df8d9d14b --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_create_task.py @@ -0,0 +1,52 @@ +# Copyright The OpenTelemetry Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import asyncio +from unittest.mock import patch + +# pylint: disable=no-name-in-module +from opentelemetry.instrumentation.asyncio import AsyncioInstrumentor +from opentelemetry.instrumentation.asyncio.environment_variables import ( + OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACE, +) +from opentelemetry.test.test_base import TestBase +from opentelemetry.trace import get_tracer + +from .common_test_func import factorial + + +class TestAsyncioCreateTask(TestBase): + @patch.dict( + "os.environ", {OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACE: "sleep"} + ) + def setUp(self): + super().setUp() + AsyncioInstrumentor().instrument() + self._tracer = get_tracer( + __name__, + ) + + def tearDown(self): + super().tearDown() + AsyncioInstrumentor().uninstrument() + + def test_asyncio_create_task(self): + async def async_func(): + await asyncio.create_task(asyncio.sleep(0)) + await asyncio.create_task(factorial(3)) + + asyncio.run(async_func()) + spans = self.memory_exporter.get_finished_spans() + + self.assertEqual(len(spans), 1) + self.assertEqual(spans[0].name, "asyncio coro-sleep") diff --git a/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_ensure_future.py b/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_ensure_future.py new file mode 100644 index 0000000000..4907aa4bf8 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_ensure_future.py @@ -0,0 +1,91 @@ +# Copyright The OpenTelemetry Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import asyncio +from unittest.mock import patch + +import pytest + +# pylint: disable=no-name-in-module +from opentelemetry.instrumentation.asyncio import AsyncioInstrumentor +from opentelemetry.instrumentation.asyncio.environment_variables import ( + OTEL_PYTHON_ASYNCIO_FUTURE_TRACE_ENABLED, +) +from opentelemetry.test.test_base import TestBase +from opentelemetry.trace import get_tracer + +from .common_test_func import async_func + + +class TestAsyncioEnsureFuture(TestBase): + @patch.dict( + "os.environ", {OTEL_PYTHON_ASYNCIO_FUTURE_TRACE_ENABLED: "true"} + ) + def setUp(self): + super().setUp() + AsyncioInstrumentor().instrument() + self._tracer = get_tracer( + __name__, + ) + + def tearDown(self): + super().tearDown() + AsyncioInstrumentor().uninstrument() + + @pytest.mark.asyncio + def test_asyncio_loop_ensure_future(self): + """ + async_func is not traced because it is not set in the environment variable + """ + + async def test(): + task = asyncio.ensure_future(async_func()) + await task + + asyncio.run(test()) + + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 0) + + @pytest.mark.asyncio + def test_asyncio_ensure_future_with_future(self): + async def test(): + with self._tracer.start_as_current_span("root"): + future = asyncio.Future() + future.set_result(1) + task = asyncio.ensure_future(future) + await task + + asyncio.run(test()) + + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 2) + for span in spans: + if span.name == "root": + self.assertEqual(span.parent, None) + if span.name == "asyncio future": + self.assertNotEqual(span.parent.trace_id, 0) + + for metric in ( + self.memory_metrics_reader.get_metrics_data() + .resource_metrics[0] + .scope_metrics[0] + .metrics + ): + if metric.name == "asyncio.process.duration": + for point in metric.data.data_points: + self.assertEqual(point.attributes["type"], "future") + if metric.name == "asyncio.process.created": + for point in metric.data.data_points: + self.assertEqual(point.attributes["type"], "future") + self.assertEqual(point.attributes["state"], "finished") diff --git a/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_gather.py b/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_gather.py new file mode 100644 index 0000000000..395b46b698 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_gather.py @@ -0,0 +1,53 @@ +# Copyright The OpenTelemetry Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import asyncio +from unittest.mock import patch + +# pylint: disable=no-name-in-module +from opentelemetry.instrumentation.asyncio import AsyncioInstrumentor +from opentelemetry.instrumentation.asyncio.environment_variables import ( + OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACE, +) +from opentelemetry.test.test_base import TestBase +from opentelemetry.trace import get_tracer + +from .common_test_func import factorial + + +class TestAsyncioGather(TestBase): + @patch.dict( + "os.environ", + {OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACE: "factorial"}, + ) + def setUp(self): + super().setUp() + AsyncioInstrumentor().instrument() + self._tracer = get_tracer( + __name__, + ) + + def tearDown(self): + super().tearDown() + AsyncioInstrumentor().uninstrument() + + def test_asyncio_gather(self): + async def gather_factorial(): + await asyncio.gather(factorial(2), factorial(3), factorial(4)) + + asyncio.run(gather_factorial()) + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 3) + self.assertEqual(spans[0].name, "asyncio coro-factorial") + self.assertEqual(spans[1].name, "asyncio coro-factorial") + self.assertEqual(spans[2].name, "asyncio coro-factorial") diff --git a/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_integration.py b/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_integration.py new file mode 100644 index 0000000000..7f4723ec24 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_integration.py @@ -0,0 +1,49 @@ +# Copyright The OpenTelemetry Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import asyncio +from unittest.mock import patch + +# pylint: disable=no-name-in-module +from opentelemetry.instrumentation.asyncio import AsyncioInstrumentor +from opentelemetry.instrumentation.asyncio.environment_variables import ( + OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACE, +) +from opentelemetry.test.test_base import TestBase +from opentelemetry.trace import get_tracer + +from .common_test_func import ensure_future + + +class TestAsyncioInstrumentor(TestBase): + def setUp(self): + super().setUp() + self._tracer = get_tracer( + __name__, + ) + + @patch.dict( + "os.environ", {OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACE: "sleep"} + ) + def test_asyncio_integration(self): + AsyncioInstrumentor().instrument() + + asyncio.run(ensure_future()) + spans = self.memory_exporter.get_finished_spans() + self.memory_exporter.clear() + assert spans + AsyncioInstrumentor().uninstrument() + + asyncio.run(ensure_future()) + spans = self.memory_exporter.get_finished_spans() + assert not spans diff --git a/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_run_coroutine_threadsafe.py b/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_run_coroutine_threadsafe.py new file mode 100644 index 0000000000..fdf4bcb353 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_run_coroutine_threadsafe.py @@ -0,0 +1,61 @@ +# Copyright The OpenTelemetry Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import asyncio +import threading +from concurrent.futures import ThreadPoolExecutor +from unittest.mock import patch + +# pylint: disable=no-name-in-module +from opentelemetry.instrumentation.asyncio import AsyncioInstrumentor +from opentelemetry.instrumentation.asyncio.environment_variables import ( + OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACE, +) +from opentelemetry.test.test_base import TestBase +from opentelemetry.trace import get_tracer + + +class TestRunCoroutineThreadSafe(TestBase): + @patch.dict( + "os.environ", {OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACE: "coro"} + ) + def setUp(self): + super().setUp() + AsyncioInstrumentor().instrument() + self.loop = asyncio.new_event_loop() + self.executor = ThreadPoolExecutor(max_workers=1) + self.loop.set_default_executor(self.executor) + self.thread = threading.Thread(target=self.loop.run_forever) + self.thread.start() + + self._tracer = get_tracer( + __name__, + ) + + def tearDown(self): + super().tearDown() + self.loop.call_soon_threadsafe(self.loop.stop) + self.thread.join() + self.loop.close() + + AsyncioInstrumentor().uninstrument() + + def test_run_coroutine_threadsafe(self): + async def coro(): + return 42 + + future = asyncio.run_coroutine_threadsafe(coro(), self.loop) + result = future.result(timeout=1) + self.assertEqual(result, 42) + spans = self.memory_exporter.get_finished_spans() + assert spans diff --git a/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_taskgroup.py b/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_taskgroup.py new file mode 100644 index 0000000000..e02f63aa42 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_taskgroup.py @@ -0,0 +1,63 @@ +# Copyright The OpenTelemetry Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import asyncio +import sys +from unittest.mock import patch + +# pylint: disable=no-name-in-module +from opentelemetry.instrumentation.asyncio import AsyncioInstrumentor +from opentelemetry.instrumentation.asyncio.environment_variables import ( + OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACE, +) +from opentelemetry.test.test_base import TestBase +from opentelemetry.trace import get_tracer + +from .common_test_func import async_func + +py11 = False +if sys.version_info >= (3, 11): + py11 = True + + +class TestAsyncioTaskgroup(TestBase): + @patch.dict( + "os.environ", + {OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACE: "async_func"}, + ) + def setUp(self): + super().setUp() + AsyncioInstrumentor().instrument() + self._tracer = get_tracer( + __name__, + ) + + def tearDown(self): + super().tearDown() + AsyncioInstrumentor().uninstrument() + + def test_task_group_create_task(self): + # TaskGroup is only available in Python 3.11+ + if not py11: + return + + async def main(): + async with asyncio.TaskGroup() as tg: # pylint: disable=no-member + for _ in range(10): + tg.create_task(async_func()) + + with self._tracer.start_as_current_span("root"): + asyncio.run(main()) + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 11) + self.assertEqual(spans[4].context.trace_id, spans[5].context.trace_id) diff --git a/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_to_thread.py b/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_to_thread.py new file mode 100644 index 0000000000..b53a6edc08 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_to_thread.py @@ -0,0 +1,73 @@ +# Copyright The OpenTelemetry Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import asyncio +import sys +from unittest.mock import patch + +# pylint: disable=no-name-in-module +from opentelemetry.instrumentation.asyncio import AsyncioInstrumentor +from opentelemetry.instrumentation.asyncio.environment_variables import ( + OTEL_PYTHON_ASYNCIO_TO_THREAD_FUNCTION_NAMES_TO_TRACE, +) +from opentelemetry.test.test_base import TestBase +from opentelemetry.trace import get_tracer + + +class TestAsyncioToThread(TestBase): + @patch.dict( + "os.environ", + {OTEL_PYTHON_ASYNCIO_TO_THREAD_FUNCTION_NAMES_TO_TRACE: "multiply"}, + ) + def setUp(self): + super().setUp() + AsyncioInstrumentor().instrument() + self._tracer = get_tracer( + __name__, + ) + + def tearDown(self): + super().tearDown() + AsyncioInstrumentor().uninstrument() + + def test_to_thread(self): + # to_thread is only available in Python 3.9+ + if sys.version_info >= (3, 9): + + def multiply(x, y): + return x * y + + async def to_thread(): + result = await asyncio.to_thread(multiply, 2, 3) + assert result == 6 + + with self._tracer.start_as_current_span("root"): + asyncio.run(to_thread()) + spans = self.memory_exporter.get_finished_spans() + + self.assertEqual(len(spans), 2) + assert spans[0].name == "asyncio to_thread-multiply" + for metric in ( + self.memory_metrics_reader.get_metrics_data() + .resource_metrics[0] + .scope_metrics[0] + .metrics + ): + if metric.name == "asyncio.process.duration": + for point in metric.data.data_points: + self.assertEqual(point.attributes["type"], "to_thread") + self.assertEqual(point.attributes["name"], "multiply") + if metric.name == "asyncio.process.created": + for point in metric.data.data_points: + self.assertEqual(point.attributes["type"], "to_thread") + self.assertEqual(point.attributes["name"], "multiply") diff --git a/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_utils.py b/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_utils.py new file mode 100644 index 0000000000..f3974e2d43 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_utils.py @@ -0,0 +1,44 @@ +# Copyright The OpenTelemetry Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from unittest import TestCase +from unittest.mock import patch + +# pylint: disable=no-name-in-module +from opentelemetry.instrumentation.asyncio.environment_variables import ( + OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACE, + OTEL_PYTHON_ASYNCIO_FUTURE_TRACE_ENABLED, +) +from opentelemetry.instrumentation.asyncio.utils import ( + get_coros_to_trace, + get_future_trace_enabled, +) + + +class TestAsyncioToThread(TestCase): + @patch.dict( + "os.environ", + { + OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACE: "test1,test2,test3 ,test4" + }, + ) + def test_separator(self): + self.assertEqual( + get_coros_to_trace(), {"test1", "test2", "test3", "test4"} + ) + + @patch.dict( + "os.environ", {OTEL_PYTHON_ASYNCIO_FUTURE_TRACE_ENABLED: "true"} + ) + def test_future_trace_enabled(self): + self.assertEqual(get_future_trace_enabled(), True) diff --git a/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_wait.py b/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_wait.py new file mode 100644 index 0000000000..77064aeafa --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_wait.py @@ -0,0 +1,88 @@ +# Copyright The OpenTelemetry Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import asyncio +import sys +from unittest.mock import patch + +# pylint: disable=no-name-in-module +from opentelemetry.instrumentation.asyncio import AsyncioInstrumentor +from opentelemetry.instrumentation.asyncio.environment_variables import ( + OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACE, +) +from opentelemetry.test.test_base import TestBase +from opentelemetry.trace import get_tracer + +from .common_test_func import async_func + + +class TestAsyncioWait(TestBase): + @patch.dict( + "os.environ", + {OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACE: "async_func"}, + ) + def setUp(self): + super().setUp() + AsyncioInstrumentor().instrument() + self._tracer = get_tracer( + __name__, + ) + + def tearDown(self): + super().tearDown() + AsyncioInstrumentor().uninstrument() + + def test_asyncio_wait_with_create_task(self): + async def main(): + if sys.version_info >= (3, 11): + # In Python 3.11, you can't send coroutines directly to asyncio.wait(). + # Instead, you must wrap them in asyncio.create_task(). + tasks = [ + asyncio.create_task(async_func()), + asyncio.create_task(async_func()), + ] + await asyncio.wait(tasks) + else: + await asyncio.wait([async_func(), async_func()]) + + asyncio.run(main()) + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 2) + + def test_asyncio_wait_for(self): + async def main(): + await asyncio.wait_for(async_func(), 1) + await asyncio.wait_for(async_func(), 1) + + asyncio.run(main()) + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 2) + + def test_asyncio_as_completed(self): + async def main(): + if sys.version_info >= (3, 11): + # In Python 3.11, you can't send coroutines directly to asyncio.as_completed(). + # Instead, you must wrap them in asyncio.create_task(). + tasks = [ + asyncio.create_task(async_func()), + asyncio.create_task(async_func()), + ] + for task in asyncio.as_completed(tasks): + await task + else: + for task in asyncio.as_completed([async_func(), async_func()]): + await task + + asyncio.run(main()) + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 2) diff --git a/opentelemetry-contrib-instrumentations/pyproject.toml b/opentelemetry-contrib-instrumentations/pyproject.toml index b954212b98..ff29864774 100644 --- a/opentelemetry-contrib-instrumentations/pyproject.toml +++ b/opentelemetry-contrib-instrumentations/pyproject.toml @@ -33,6 +33,7 @@ dependencies = [ "opentelemetry-instrumentation-aiohttp-server==0.44b0.dev", "opentelemetry-instrumentation-aiopg==0.44b0.dev", "opentelemetry-instrumentation-asgi==0.44b0.dev", + "opentelemetry-instrumentation-asyncio==0.44b0.dev", "opentelemetry-instrumentation-asyncpg==0.44b0.dev", "opentelemetry-instrumentation-aws-lambda==0.44b0.dev", "opentelemetry-instrumentation-boto==0.44b0.dev", diff --git a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py index bf94b44d25..92ac4d9768 100644 --- a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py +++ b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py @@ -186,6 +186,7 @@ }, ] default_instrumentations = [ + "opentelemetry-instrumentation-asyncio==0.44b0.dev", "opentelemetry-instrumentation-aws-lambda==0.44b0.dev", "opentelemetry-instrumentation-dbapi==0.44b0.dev", "opentelemetry-instrumentation-logging==0.44b0.dev", diff --git a/tox.ini b/tox.ini index 3b921b9be1..74f785974d 100644 --- a/tox.ini +++ b/tox.ini @@ -230,6 +230,9 @@ envlist = py3{8,9,10,11}-test-instrumentation-confluent-kafka pypy3-test-instrumentation-confluent-kafka + ; opentelemetry-instrumentation-asyncio + py3{8,9,10,11}-test-instrumentation-asyncio + ; opentelemetry-instrumentation-cassandra py3{8,9,10,11}-test-instrumentation-cassandra pypy3-test-instrumentation-cassandra @@ -349,6 +352,7 @@ changedir = test-instrumentation-tortoiseorm: instrumentation/opentelemetry-instrumentation-tortoiseorm/tests test-instrumentation-wsgi: instrumentation/opentelemetry-instrumentation-wsgi/tests test-instrumentation-httpx-{18,21}: instrumentation/opentelemetry-instrumentation-httpx/tests + test-instrumentation-asyncio: instrumentation/opentelemetry-instrumentation-asyncio/tests test-util-http: util/opentelemetry-util-http/tests test-sdkextension-aws: sdk-extension/opentelemetry-sdk-extension-aws/tests test-resource-detector-container: resource/opentelemetry-resource-detector-container/tests @@ -465,6 +469,8 @@ commands_pre = elasticsearch-{2,5,6}: pip install {toxinidir}/opentelemetry-instrumentation[test] {toxinidir}/instrumentation/opentelemetry-instrumentation-elasticsearch[test] + asyncio: pip install {toxinidir}/instrumentation/opentelemetry-instrumentation-asyncio[test] + httpx-{18,21}: pip install {toxinidir}/instrumentation/opentelemetry-instrumentation-httpx[test] sdkextension-aws: pip install {toxinidir}/sdk-extension/opentelemetry-sdk-extension-aws[test] @@ -571,6 +577,7 @@ commands_pre = python -m pip install -e {toxinidir}/instrumentation/opentelemetry-instrumentation-httpx[test] python -m pip install -e {toxinidir}/instrumentation/opentelemetry-instrumentation-aws-lambda[test] python -m pip install -e {toxinidir}/instrumentation/opentelemetry-instrumentation-system-metrics[test] + python -m pip install -e {toxinidir}/instrumentation/opentelemetry-instrumentation-asyncio[test] python -m pip install -e {toxinidir}/exporter/opentelemetry-exporter-richconsole[test] # requires snappy headers to be available on the system python -m pip install -e {toxinidir}/sdk-extension/opentelemetry-sdk-extension-aws[test]