diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 41f2aa08cb..90d3452f07 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -198,7 +198,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/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..c709513877 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/README.rst @@ -0,0 +1,24 @@ +OpenTelemetry asyncio Instrumentation +=========================== + +|pypi| + +.. |pypi| image:: https://badge.fury.io/py/opentelemetry-instrumentation-asyncio.svg + :target: https://pypi.org/project/opentelemetry-instrumentation-asyncio/ + +This library allows tracing requests made by the asyncio library. + +Installation +------------ + +:: + + pip install opentelemetry-instrumentation-asyncio + + +References +---------- + +* `OpenTelemetry asyncio/ Tracing /.html>`_ +* `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..0a4fb673c2 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/pyproject.toml @@ -0,0 +1,54 @@ +[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.7" +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.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", +] +dependencies = [ + "opentelemetry-api ~= 1.12", + "wrapt >= 1.0.0, < 2.0.0", +] + +[project.optional-dependencies] +test = [ + "opentelemetry-instrumentation-asyncio[instruments]", + "opentelemetry-test-utils == 0.41b0.dev", +] + +[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..3ae18a4cc2 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/src/opentelemetry/instrumentation/asyncio/__init__.py @@ -0,0 +1,221 @@ +# 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 + +Usage +----- + +.. code-block:: python + + import asyncio + from opentelemetry.instrumentation.asyncio import AsyncioInstrumentor + + AsyncioInstrumentor().instrument() + + async def main(): + await asyncio.create_task(asyncio.sleep(0.1)) + + asyncio.run(main()) + +API +--- +""" +import asyncio +import sys +from asyncio import futures +from typing import Collection + +from opentelemetry.trace import get_tracer +from opentelemetry.trace.status import Status, StatusCode +from wrapt import wrap_function_wrapper as _wrap + +from opentelemetry.instrumentation.asyncio.package import _instruments +from opentelemetry.instrumentation.asyncio.version import __version__ +from opentelemetry.instrumentation.instrumentor import BaseInstrumentor +from opentelemetry.instrumentation.utils import unwrap + +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._tracer = None + + def instrumentation_dependencies(self) -> Collection[str]: + return _instruments + + def _instrument(self, **kwargs): + tracer_provider = kwargs.get("tracer_provider") + self._tracer = get_tracer( + __name__, __version__, tracer_provider + ) + 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: + self.uninstrument_method_with_coroutine(method) + self.uninstrument_gather() + self.uninstrument_to_thread() + self.uninstrument_taskgroup_create_task() + + def instrument_method_with_coroutine(self, method_name): + """ + 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 uninstrument_method_with_coroutine(self, method_name): + """ + Uninstrument specified asyncio method. + """ + unwrap(asyncio, method_name) + + 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) + + _wrap(asyncio, "gather", wrap_coros_or_futures) + + def uninstrument_gather(self): + unwrap(asyncio, "gather") + + def instrument_to_thread(self): + def wrap_to_thread(method, instance, args, kwargs): + if args: + first_arg = args[0] + # Wrap the first argument + wrapped_first_arg = self.trace_func(first_arg) + wrapped_args = (wrapped_first_arg,) + args[1:] + + return method(*wrapped_args, **kwargs) + + _wrap(asyncio, "to_thread", wrap_to_thread) + + def uninstrument_to_thread(self): + unwrap(asyncio, "to_thread") + + def instrument_taskgroup_create_task(self): + if sys.version_info >= (3, 11): + def wrap_taskgroup_create_task(method, instance, args, kwargs): + if args: + coro = args[0] + wrapped_coro = self.trace_coroutine(coro) + wrapped_args = (wrapped_coro,) + args[1:] + return method(*wrapped_args, **kwargs) + + _wrap(asyncio.TaskGroup, "create_task", wrap_taskgroup_create_task) + + def uninstrument_taskgroup_create_task(self): + if sys.version_info >= (3, 11): + unwrap(asyncio.TaskGroup, "create_task") + + def trace_func(self, func): + """Trace a function.""" + with self._tracer.start_as_current_span(f"{ASYNCIO_PREFIX}to_thread_func-" + func.__name__) as span: + try: + return func + except Exception as exc: + span.set_status(Status(StatusCode.ERROR)) + span.record_exception(exc) + raise + + 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) + elif futures.isfuture(coro_or_future): + return self.trace_future(coro_or_future) + return coro_or_future + + async def trace_coroutine(self, coro): + + with self._tracer.start_as_current_span(f"{ASYNCIO_PREFIX}coro-" + coro.__name__) as span: + exception = None # Initialize the exception variable + try: + 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: + pass + except (asyncio.TimeoutError, + asyncio.InvalidStateError, + asyncio.SendfileNotAvailableError, + asyncio.IncompleteReadError, + asyncio.LimitOverrunError, + asyncio.BrokenBarrierError, + Exception) as exc: # General exception should be the last + exception = exc + raise + finally: + if span.is_recording() and exception: + span.set_status(Status(StatusCode.ERROR)) + span.record_exception(exception) + + def trace_future(self, future): + span = self._tracer.start_span(f"{ASYNCIO_PREFIX}" + future.__class__.__name__) + + def callback(f): + exception = f.exception() + if exception: + span.set_status(Status(StatusCode.ERROR)) + span.record_exception(exception) + span.end() + + future.add_done_callback(callback) + return future 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/version.py b/instrumentation/opentelemetry-instrumentation-asyncio/src/opentelemetry/instrumentation/asyncio/version.py new file mode 100644 index 0000000000..c2996671d6 --- /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.42b0.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..eacf7c9c0e --- /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. \ No newline at end of file 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..570136f52f --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/tests/common_test_func.py @@ -0,0 +1,50 @@ +# 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(1) + + +async def factorial(name, number): + f = 1 + for i in range(2, number + 1): + print(f"Task {name}: Compute factorial({number}), currently i={i}...") + await asyncio.sleep(0) + f *= i + print(f"Task {name}: factorial({number}) = {f}") + return f + + +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..c8419ecc02 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_cancellation.py @@ -0,0 +1,38 @@ +# 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 opentelemetry.test.test_base import TestBase +from opentelemetry.trace import get_tracer + +from .common_test_func import cancellation_create_task +from opentelemetry.instrumentation.asyncio import AsyncioInstrumentor + + +class TestAsyncioCancel(TestBase): + def setUp(self): + super().setUp() + AsyncioInstrumentor().instrument() + self._tracer = get_tracer( + __name__, + ) + + def tearDown(self): + super().tearDown() + AsyncioInstrumentor().uninstrument() + + def test_cancel(self): + asyncio.run(cancellation_create_task()) + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 2) 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..5d1edb40a2 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_create_task.py @@ -0,0 +1,40 @@ +# 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 opentelemetry.test.test_base import TestBase +from opentelemetry.trace import get_tracer + +from opentelemetry.instrumentation.asyncio import AsyncioInstrumentor + + +class TestAsyncioCreateTask(TestBase): + 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)) + + asyncio.run(async_func()) + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 1) 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..42ed1a1c29 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_ensure_future.py @@ -0,0 +1,57 @@ +# 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 pytest +from opentelemetry.test.test_base import TestBase +from opentelemetry.trace import get_tracer + +from opentelemetry.instrumentation.asyncio import AsyncioInstrumentor +from .common_test_func import async_func + + +class TestAsyncioEnsureFuture(TestBase): + 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): + loop = asyncio.get_event_loop() + task = asyncio.ensure_future(async_func()) + loop.run_until_complete(task) + + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 1) + self.assertEqual(spans[0].name, "asyncio.coro-async_func") + + @pytest.mark.asyncio + def test_asyncio_ensure_future_with_future(self): + loop = asyncio.get_event_loop() + + future = asyncio.Future() + future.set_result(1) + task = asyncio.ensure_future(future) + loop.run_until_complete(task) + + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 1) + self.assertEqual(spans[0].name, "asyncio.Future") 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..ea02612893 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_gather.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 + +from opentelemetry.test.test_base import TestBase +from opentelemetry.trace import get_tracer + +from .common_test_func import factorial +from opentelemetry.instrumentation.asyncio import AsyncioInstrumentor + + +class TestAsyncioGather(TestBase): + 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("A", 2), + factorial("B", 3), + factorial("C", 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..b10a327bc6 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_integration.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. +import asyncio + +from opentelemetry.test.test_base import TestBase +from opentelemetry.trace import get_tracer + +from .common_test_func import ensure_future +from opentelemetry.instrumentation.asyncio import AsyncioInstrumentor + + +class TestAsyncioInstrumentor(TestBase): + def setUp(self): + super().setUp() + self._tracer = get_tracer( + __name__, + ) + + def tearDown(self): + super().tearDown() + + 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..000168509f --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_run_coroutine_threadsafe.py @@ -0,0 +1,54 @@ +# 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 opentelemetry.test.test_base import TestBase +from opentelemetry.trace import get_tracer + +from opentelemetry.instrumentation.asyncio import AsyncioInstrumentor + + +class TestRunCoroutineThreadSafe(TestBase): + 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..6063972068 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_taskgroup.py @@ -0,0 +1,59 @@ +# 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 + +import aiotools +from opentelemetry.test.test_base import TestBase +from opentelemetry.trace import get_tracer + +from .common_test_func import async_func +from opentelemetry.instrumentation.asyncio import AsyncioInstrumentor + +py11 = False +if sys.version_info >= (3, 11): + py11 = True + + +class TestAsyncioTaskgroup(TestBase): + 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): + async def main(): + if py11: + async with asyncio.TaskGroup() as tg: + for _ in range(10): + tg.create_task(async_func()) + else: + async with aiotools.TaskGroup() as tg: + for _ in range(10): + tg.create_task(async_func()) + + asyncio.run(main()) + spans = self.memory_exporter.get_finished_spans() + assert spans + if py11: + self.assertEqual(len(spans), 10) + else: + # aiotools.TaskGroup is Out of scope of support. + self.assertEqual(len(spans), 0) 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..04afb945ff --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_to_thread.py @@ -0,0 +1,45 @@ +# 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 opentelemetry.test.test_base import TestBase +from opentelemetry.trace import get_tracer + +from opentelemetry.instrumentation.asyncio import AsyncioInstrumentor + + +class TestAsyncioToThread(TestBase): + def setUp(self): + super().setUp() + AsyncioInstrumentor().instrument() + self._tracer = get_tracer( + __name__, + ) + + def tearDown(self): + super().tearDown() + AsyncioInstrumentor().uninstrument() + + def test_to_thread(self): + def multiply(x, y): + return x * y + + async def to_thread(): + result = await asyncio.to_thread(multiply, 2, 3) + assert result == 6 + + asyncio.run(to_thread()) + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 1) + assert spans[0].name == "asyncio.to_thread_func-multiply" 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..070617ca94 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_wait.py @@ -0,0 +1,74 @@ +# 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 opentelemetry.test.test_base import TestBase +from opentelemetry.trace import get_tracer + +from .common_test_func import async_func +from opentelemetry.instrumentation.asyncio import AsyncioInstrumentor + + +class TestAsyncioWait(TestBase): + 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)