diff --git a/instrumentation/opentelemetry-instrumentation-tornado/CHANGELOG.md b/instrumentation/opentelemetry-instrumentation-tornado/CHANGELOG.md new file mode 100644 index 00000000000..a2711d8a05d --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-tornado/CHANGELOG.md @@ -0,0 +1,5 @@ +# Changelog + +## Unreleased + +- Initial release. Supports Tornado 6.x on Python 3.5 and newer. diff --git a/instrumentation/opentelemetry-instrumentation-tornado/LICENSE b/instrumentation/opentelemetry-instrumentation-tornado/LICENSE new file mode 100644 index 00000000000..261eeb9e9f8 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-tornado/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 [yyyy] [name of copyright owner] + + 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-tornado/MANIFEST.in b/instrumentation/opentelemetry-instrumentation-tornado/MANIFEST.in new file mode 100644 index 00000000000..aed3e33273b --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-tornado/MANIFEST.in @@ -0,0 +1,9 @@ +graft src +graft tests +global-exclude *.pyc +global-exclude *.pyo +global-exclude __pycache__/* +include CHANGELOG.md +include MANIFEST.in +include README.rst +include LICENSE diff --git a/instrumentation/opentelemetry-instrumentation-tornado/README.rst b/instrumentation/opentelemetry-instrumentation-tornado/README.rst new file mode 100644 index 00000000000..d84fbd0412c --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-tornado/README.rst @@ -0,0 +1,39 @@ +OpenTelemetry Tornado Instrumentation +====================================== + +|pypi| + +.. |pypi| image:: https://badge.fury.io/py/opentelemetry-instrumentation-tornado.svg + :target: https://pypi.org/project/opentelemetry-instrumentation-tornado/ + +This library builds on the OpenTelemetry WSGI middleware to track web requests +in Tornado applications. + +Installation +------------ + +:: + + pip install opentelemetry-instrumentation-tornado + +Configuration +------------- + +The following environment variables are supported as configuration options: + +- OTEL_PYTHON_TORNADO_EXCLUDED_URLS + +A comma separated list of paths that should not be automatically traced. For example, if this is set to + +:: + + export OTEL_PYTHON_TORNADO_EXLUDED_URLS='/healthz,/ping' + +Then any requests made to ``/healthz`` and ``/ping`` will not be automatically traced. + + +References +---------- + +* `OpenTelemetry Tornado Instrumentation `_ +* `OpenTelemetry Project `_ diff --git a/instrumentation/opentelemetry-instrumentation-tornado/setup.cfg b/instrumentation/opentelemetry-instrumentation-tornado/setup.cfg new file mode 100644 index 00000000000..84510f19f98 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-tornado/setup.cfg @@ -0,0 +1,51 @@ +# 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. +# +[metadata] +name = opentelemetry-instrumentation-tornado +description = Tornado instrumentation for OpenTelemetry +long_description = file: README.rst +long_description_content_type = text/x-rst +author = OpenTelemetry Authors +author_email = cncf-opentelemetry-contributors@lists.cncf.io +url = https://github.com/open-telemetry/opentelemetry-python/tree/master/instrumentation/opentelemetry-instrumentation-tornado +platforms = any +license = Apache-2.0 +classifiers = + Development Status :: 4 - Beta + Intended Audience :: Developers + License :: OSI Approved :: Apache Software License + Programming Language :: Python + Programming Language :: Python :: 3.5 + Programming Language :: Python :: 3.6 + Programming Language :: Python :: 3.7 + Programming Language :: Python :: 3.8 + +[options] +python_requires = >=3.5 +package_dir= + =src +packages=find_namespace: +install_requires = + tornado >= 6.0 + opentelemetry-instrumentation == 0.13.dev0 + opentelemetry-api == 0.13.dev0 + +[options.extras_require] +test = + tornado >= 6.0 + opentelemetry-test == 0.13.dev0 + +[options.packages.find] +where = src diff --git a/instrumentation/opentelemetry-instrumentation-tornado/setup.py b/instrumentation/opentelemetry-instrumentation-tornado/setup.py new file mode 100644 index 00000000000..bd6814b50ee --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-tornado/setup.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 os + +import setuptools + +BASE_DIR = os.path.dirname(__file__) +VERSION_FILENAME = os.path.join( + BASE_DIR, + "src", + "opentelemetry", + "instrumentation", + "tornado", + "version.py", +) +PACKAGE_INFO = {} +with open(VERSION_FILENAME) as f: + exec(f.read(), PACKAGE_INFO) + +setuptools.setup( + version=PACKAGE_INFO["__version__"], + entry_points={ + "opentelemetry_instrumentor": [ + "tornado = opentelemetry.instrumentation.tornado:TornadoInstrumentor" + ] + }, +) diff --git a/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py b/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py new file mode 100644 index 00000000000..6379d841a03 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/__init__.py @@ -0,0 +1,263 @@ +# 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. + +""" +This library uses OpenTelemetry to track web requests in Tornado applications. + +Usage +----- + +.. code-block:: python + + import tornado.web + from opentelemetry.instrumentation.tornado import TornadoInstrumentor + + # apply tornado instrumentation + TornadoInstrumentor().instrument() + + class Handler(tornado.web.RequestHandler): + def get(self): + self.set_status(200) + + app = tornado.web.Application([(r"/", Handler)]) + app.listen(8080) + tornado.ioloop.IOLoop.current().start() +""" + +import inspect +import typing +from collections import namedtuple +from functools import partial, wraps +from logging import getLogger + +import tornado.web +import wrapt +from tornado.routing import Rule +from wrapt import wrap_function_wrapper + +from opentelemetry import configuration, context, propagators, trace +from opentelemetry.instrumentation.instrumentor import BaseInstrumentor +from opentelemetry.instrumentation.tornado.version import __version__ +from opentelemetry.instrumentation.utils import ( + http_status_to_canonical_code, + unwrap, +) +from opentelemetry.trace.status import Status +from opentelemetry.util import ExcludeList, time_ns + +from .client import fetch_async # pylint: disable=E0401 + +_logger = getLogger(__name__) +_TraceContext = namedtuple("TraceContext", ["activation", "span", "token"]) +_HANDLER_CONTEXT_KEY = "_otel_trace_context_key" +_OTEL_PATCHED_KEY = "_otel_patched_key" + + +def get_excluded_urls(): + urls = configuration.Configuration().TORNADO_EXCLUDED_URLS or "" + if urls: + urls = str.split(urls, ",") + return ExcludeList(urls) + + +_excluded_urls = get_excluded_urls() + + +class TornadoInstrumentor(BaseInstrumentor): + patched_handlers = [] + original_handler_new = None + + def _instrument(self, **kwargs): + """ + _instrument patches tornado.web.RequestHandler and tornado.httpclient.AsyncHTTPClient classes + to automatically instrument requests both received and sent by Tornado. + + We don't patch RequestHandler._execute as it causes some issues with contextvars based context. + Mainly the context fails to detach from within RequestHandler.on_finish() if it is attached inside + RequestHandler._execute. Same issue plagues RequestHandler.initialize. RequestHandler.prepare works + perfectly on the other hand as it executes in the same context as on_finish and log_exection which + are patched to finish a span after a request is served. + + However, we cannot just patch RequestHandler's prepare method because it is supposed to be overwridden + by sub-classes and since the parent prepare method does not do anything special, sub-classes don't + have to call super() when overriding the method. + + In order to work around this, we patch the __init__ method of RequestHandler and then dynamically patch + the prepare, on_finish and log_exception methods of the derived classes _only_ the first time we see them. + Note that the patch does not apply on every single __init__ call, only the first one for the enture + process lifetime. + """ + tracer_provider = kwargs.get("tracer_provider") + tracer = trace.get_tracer(__name__, __version__, tracer_provider) + + def handler_init(init, handler, args, kwargs): + cls = handler.__class__ + if patch_handler_class(tracer, cls): + self.patched_handlers.append(cls) + return init(*args, **kwargs) + + wrap_function_wrapper( + "tornado.web", "RequestHandler.__init__", handler_init + ) + wrap_function_wrapper( + "tornado.httpclient", + "AsyncHTTPClient.fetch", + partial(fetch_async, tracer), + ) + + def _uninstrument(self, **kwargs): + unwrap(tornado.web.RequestHandler, "__init__") + unwrap(tornado.httpclient.AsyncHTTPClient, "fetch") + for handler in self.patched_handlers: + unpatch_handler_class(handler) + self.patched_handlers = [] + + +def patch_handler_class(tracer, cls): + if getattr(cls, _OTEL_PATCHED_KEY, False): + return False + + setattr(cls, _OTEL_PATCHED_KEY, True) + _wrap(cls, "prepare", partial(_prepare, tracer)) + _wrap(cls, "on_finish", partial(_on_finish, tracer)) + _wrap(cls, "log_exception", partial(_log_exception, tracer)) + return True + + +def unpatch_handler_class(cls): + if not getattr(cls, _OTEL_PATCHED_KEY, False): + return + + unwrap(cls, "prepare") + unwrap(cls, "on_finish") + unwrap(cls, "log_exception") + delattr(cls, _OTEL_PATCHED_KEY) + + +def _wrap(cls, method_name, wrapper): + original = getattr(cls, method_name) + wrapper = wrapt.FunctionWrapper(original, wrapper) + wrapt.apply_patch(cls, method_name, wrapper) + + +def _prepare(tracer, func, handler, args, kwargs): + start_time = time_ns() + request = handler.request + if _excluded_urls.url_disabled(request.uri): + return func(*args, **kwargs) + _start_span(tracer, handler, start_time) + return func(*args, **kwargs) + + +def _on_finish(tracer, func, handler, args, kwargs): + _finish_span(tracer, handler) + return func(*args, **kwargs) + + +def _log_exception(tracer, func, handler, args, kwargs): + error = None + if len(args) == 3: + error = args[1] + + _finish_span(tracer, handler, error) + return func(*args, **kwargs) + + +def _get_header_from_request_headers( + headers: dict, header_name: str +) -> typing.List[str]: + header = headers.get(header_name) + return [header] if header else [] + + +def _get_attributes_from_request(request): + attrs = { + "component": "tornado", + "http.method": request.method, + "http.scheme": request.protocol, + "http.host": request.host, + "http.target": request.path, + } + + if request.host: + attrs["http.host"] = request.host + + if request.remote_ip: + attrs["net.peer.ip"] = request.remote_ip + + return attrs + + +def _get_operation_name(handler, request): + full_class_name = type(handler).__name__ + class_name = full_class_name.rsplit(".")[-1] + return "{0}.{1}".format(class_name, request.method.lower()) + + +def _start_span(tracer, handler, start_time) -> _TraceContext: + token = context.attach( + propagators.extract( + _get_header_from_request_headers, handler.request.headers, + ) + ) + span = tracer.start_span( + _get_operation_name(handler, handler.request), + kind=trace.SpanKind.SERVER, + attributes=_get_attributes_from_request(handler.request), + start_time=start_time, + ) + + activation = tracer.use_span(span, end_on_exit=True) + activation.__enter__() + ctx = _TraceContext(activation, span, token) + setattr(handler, _HANDLER_CONTEXT_KEY, ctx) + return ctx + + +def _finish_span(tracer, handler, error=None): + status_code = handler.get_status() + reason = getattr(handler, "_reason") + finish_args = (None, None, None) + ctx = getattr(handler, _HANDLER_CONTEXT_KEY, None) + + if error: + if isinstance(error, tornado.web.HTTPError): + status_code = error.status_code + if not ctx and status_code == 404: + ctx = _start_span(tracer, handler, time_ns()) + if status_code != 404: + finish_args = ( + type(error), + error, + getattr(error, "__traceback__", None), + ) + status_code = 500 + reason = None + + if not ctx: + return + + if reason: + ctx.span.set_attribute("http.status_text", reason) + ctx.span.set_attribute("http.status_code", status_code) + ctx.span.set_status( + Status( + canonical_code=http_status_to_canonical_code(status_code), + description=reason, + ) + ) + + ctx.activation.__exit__(*finish_args) + context.detach(ctx.token) + delattr(handler, _HANDLER_CONTEXT_KEY) diff --git a/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/client.py b/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/client.py new file mode 100644 index 00000000000..1fe8f58a2c7 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/client.py @@ -0,0 +1,79 @@ +import functools + +from tornado.httpclient import HTTPError, HTTPRequest + +from opentelemetry import propagators, trace +from opentelemetry.instrumentation.utils import http_status_to_canonical_code +from opentelemetry.trace.status import Status +from opentelemetry.util import time_ns + + +def _normalize_request(args, kwargs): + req = args[0] + if not isinstance(req, str): + return (args, kwargs) + + new_kwargs = {} + for param in ("callback", "raise_error"): + if param in kwargs: + new_kwargs[param] = kwargs.pop(param) + + req = HTTPRequest(req, **kwargs) + new_args = [req] + new_args.extend(args[1:]) + return (new_args, new_kwargs) + + +def fetch_async(tracer, func, _, args, kwargs): + start_time = time_ns() + + # Return immediately if no args were provided (error) + # or original_request is set (meaning we are in a redirect step). + if len(args) == 0 or hasattr(args[0], "original_request"): + return func(*args, **kwargs) + + # Force the creation of a HTTPRequest object if needed, + # so we can inject the context into the headers. + args, kwargs = _normalize_request(args, kwargs) + request = args[0] + + span = tracer.start_span( + request.method, + kind=trace.SpanKind.CLIENT, + attributes={ + "component": "tornado", + "http.url": request.url, + "http.method": request.method, + }, + start_time=start_time, + ) + + with tracer.use_span(span): + propagators.inject(type(request.headers).__setitem__, request.headers) + future = func(*args, **kwargs) + future.add_done_callback( + functools.partial(_finish_tracing_callback, span=span) + ) + return future + + +def _finish_tracing_callback(future, span): + status_code = None + description = None + exc = future.exception() + if exc: + if isinstance(exc, HTTPError): + status_code = exc.code + description = "{}: {}".format(type(exc).__name__, exc) + else: + status_code = future.result().code + + if status_code is not None: + span.set_attribute("http.status_code", status_code) + span.set_status( + Status( + canonical_code=http_status_to_canonical_code(status_code), + description=description, + ) + ) + span.end() diff --git a/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/version.py b/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/version.py new file mode 100644 index 00000000000..9cc445d09e1 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-tornado/src/opentelemetry/instrumentation/tornado/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.13dev0" diff --git a/instrumentation/opentelemetry-instrumentation-tornado/tests/__init__.py b/instrumentation/opentelemetry-instrumentation-tornado/tests/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/instrumentation/opentelemetry-instrumentation-tornado/tests/test_instrumentation.py b/instrumentation/opentelemetry-instrumentation-tornado/tests/test_instrumentation.py new file mode 100644 index 00000000000..2d5ffd00f78 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-tornado/tests/test_instrumentation.py @@ -0,0 +1,362 @@ +# 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.mock import patch + +from tornado.testing import AsyncHTTPTestCase + +from opentelemetry import trace +from opentelemetry.instrumentation.tornado import ( + TornadoInstrumentor, + patch_handler_class, + unpatch_handler_class, +) +from opentelemetry.test.test_base import TestBase +from opentelemetry.trace import SpanKind +from opentelemetry.util import ExcludeList + +from .tornado_test_app import ( + AsyncHandler, + DynamicHandler, + MainHandler, + make_app, +) + + +class TornadoTest(AsyncHTTPTestCase, TestBase): + def get_app(self): + tracer = trace.get_tracer(__name__) + app = make_app(tracer) + return app + + def setUp(self): + TornadoInstrumentor().instrument() + super().setUp() + + def tearDown(self): + TornadoInstrumentor().uninstrument() + super().tearDown() + + +class TestTornadoInstrumentor(TornadoTest): + def test_patch_references(self): + self.assertEqual(len(TornadoInstrumentor().patched_handlers), 0) + + self.fetch("/") + self.fetch("/async") + self.assertEqual( + TornadoInstrumentor().patched_handlers, [MainHandler, AsyncHandler] + ) + + self.fetch("/async") + self.fetch("/") + self.assertEqual( + TornadoInstrumentor().patched_handlers, [MainHandler, AsyncHandler] + ) + + TornadoInstrumentor().uninstrument() + self.assertEqual(TornadoInstrumentor().patched_handlers, []) + + def test_patch_applied_only_once(self): + tracer = trace.get_tracer(__name__) + self.assertTrue(patch_handler_class(tracer, AsyncHandler)) + self.assertFalse(patch_handler_class(tracer, AsyncHandler)) + self.assertFalse(patch_handler_class(tracer, AsyncHandler)) + unpatch_handler_class(AsyncHandler) + + +class TestTornadoInstrumentation(TornadoTest): + def test_http_calls(self): + methods = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"] + for method in methods: + self._test_http_method_call(method) + + def _test_http_method_call(self, method): + body = "" if method in ["POST", "PUT", "PATCH"] else None + response = self.fetch("/", method=method, body=body) + self.assertEqual(response.code, 201) + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 3) + + manual, server, client = self.sorted_spans(spans) + + self.assertEqual(manual.name, "manual") + self.assertEqual(manual.parent, server.context) + self.assertEqual(manual.context.trace_id, client.context.trace_id) + + self.assertEqual(server.name, "MainHandler." + method.lower()) + self.assertTrue(server.parent.is_remote) + self.assertNotEqual(server.parent, client.context) + self.assertEqual(server.parent.span_id, client.context.span_id) + self.assertEqual(server.context.trace_id, client.context.trace_id) + self.assertEqual(server.kind, SpanKind.SERVER) + self.assert_span_has_attributes( + server, + { + "component": "tornado", + "http.method": method, + "http.scheme": "http", + "http.host": "127.0.0.1:" + str(self.get_http_port()), + "http.target": "/", + "net.peer.ip": "127.0.0.1", + "http.status_text": "Created", + "http.status_code": 201, + }, + ) + + self.assertEqual(client.name, method) + self.assertFalse(client.context.is_remote) + self.assertIsNone(client.parent) + self.assertEqual(client.kind, SpanKind.CLIENT) + self.assert_span_has_attributes( + client, + { + "component": "tornado", + "http.url": self.get_url("/"), + "http.method": method, + "http.status_code": 201, + }, + ) + + self.memory_exporter.clear() + + def test_async_handler(self): + self._test_async_handler("/async", "AsyncHandler") + + def test_coroutine_handler(self): + self._test_async_handler("/cor", "CoroutineHandler") + + def _test_async_handler(self, url, handler_name): + response = self.fetch(url) + self.assertEqual(response.code, 201) + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 5) + + sub2, sub1, sub_wrapper, server, client = self.sorted_spans(spans) + + self.assertEqual(sub2.name, "sub-task-2") + self.assertEqual(sub2.parent, sub_wrapper.context) + self.assertEqual(sub2.context.trace_id, client.context.trace_id) + + self.assertEqual(sub1.name, "sub-task-1") + self.assertEqual(sub1.parent, sub_wrapper.context) + self.assertEqual(sub1.context.trace_id, client.context.trace_id) + + self.assertEqual(sub_wrapper.name, "sub-task-wrapper") + self.assertEqual(sub_wrapper.parent, server.context) + self.assertEqual(sub_wrapper.context.trace_id, client.context.trace_id) + + self.assertEqual(server.name, handler_name + ".get") + self.assertTrue(server.parent.is_remote) + self.assertNotEqual(server.parent, client.context) + self.assertEqual(server.parent.span_id, client.context.span_id) + self.assertEqual(server.context.trace_id, client.context.trace_id) + self.assertEqual(server.kind, SpanKind.SERVER) + self.assert_span_has_attributes( + server, + { + "component": "tornado", + "http.method": "GET", + "http.scheme": "http", + "http.host": "127.0.0.1:" + str(self.get_http_port()), + "http.target": url, + "net.peer.ip": "127.0.0.1", + "http.status_text": "Created", + "http.status_code": 201, + }, + ) + + self.assertEqual(client.name, "GET") + self.assertFalse(client.context.is_remote) + self.assertIsNone(client.parent) + self.assertEqual(client.kind, SpanKind.CLIENT) + self.assert_span_has_attributes( + client, + { + "component": "tornado", + "http.url": self.get_url(url), + "http.method": "GET", + "http.status_code": 201, + }, + ) + + def test_500(self): + response = self.fetch("/error") + self.assertEqual(response.code, 500) + + spans = self.sorted_spans(self.memory_exporter.get_finished_spans()) + self.assertEqual(len(spans), 2) + server, client = spans + + self.assertEqual(server.name, "BadHandler.get") + self.assertEqual(server.kind, SpanKind.SERVER) + self.assert_span_has_attributes( + server, + { + "component": "tornado", + "http.method": "GET", + "http.scheme": "http", + "http.host": "127.0.0.1:" + str(self.get_http_port()), + "http.target": "/error", + "net.peer.ip": "127.0.0.1", + "http.status_code": 500, + }, + ) + + self.assertEqual(client.name, "GET") + self.assertEqual(client.kind, SpanKind.CLIENT) + self.assert_span_has_attributes( + client, + { + "component": "tornado", + "http.url": self.get_url("/error"), + "http.method": "GET", + "http.status_code": 500, + }, + ) + + def test_404(self): + response = self.fetch("/missing-url") + self.assertEqual(response.code, 404) + + spans = self.sorted_spans(self.memory_exporter.get_finished_spans()) + self.assertEqual(len(spans), 2) + server, client = spans + + self.assertEqual(server.name, "ErrorHandler.get") + self.assertEqual(server.kind, SpanKind.SERVER) + self.assert_span_has_attributes( + server, + { + "component": "tornado", + "http.method": "GET", + "http.scheme": "http", + "http.host": "127.0.0.1:" + str(self.get_http_port()), + "http.target": "/missing-url", + "net.peer.ip": "127.0.0.1", + "http.status_text": "Not Found", + "http.status_code": 404, + }, + ) + + self.assertEqual(client.name, "GET") + self.assertEqual(client.kind, SpanKind.CLIENT) + self.assert_span_has_attributes( + client, + { + "component": "tornado", + "http.url": self.get_url("/missing-url"), + "http.method": "GET", + "http.status_code": 404, + }, + ) + + def test_dynamic_handler(self): + response = self.fetch("/dyna") + self.assertEqual(response.code, 404) + self.memory_exporter.clear() + + self._app.add_handlers(r".+", [(r"/dyna", DynamicHandler)]) + + response = self.fetch("/dyna") + self.assertEqual(response.code, 202) + + spans = self.sorted_spans(self.memory_exporter.get_finished_spans()) + self.assertEqual(len(spans), 2) + server, client = spans + + self.assertEqual(server.name, "DynamicHandler.get") + self.assertTrue(server.parent.is_remote) + self.assertNotEqual(server.parent, client.context) + self.assertEqual(server.parent.span_id, client.context.span_id) + self.assertEqual(server.context.trace_id, client.context.trace_id) + self.assertEqual(server.kind, SpanKind.SERVER) + self.assert_span_has_attributes( + server, + { + "component": "tornado", + "http.method": "GET", + "http.scheme": "http", + "http.host": "127.0.0.1:" + str(self.get_http_port()), + "http.target": "/dyna", + "net.peer.ip": "127.0.0.1", + "http.status_text": "Accepted", + "http.status_code": 202, + }, + ) + + self.assertEqual(client.name, "GET") + self.assertFalse(client.context.is_remote) + self.assertIsNone(client.parent) + self.assertEqual(client.kind, SpanKind.CLIENT) + self.assert_span_has_attributes( + client, + { + "component": "tornado", + "http.url": self.get_url("/dyna"), + "http.method": "GET", + "http.status_code": 202, + }, + ) + + @patch( + "opentelemetry.instrumentation.tornado._excluded_urls", + ExcludeList(["healthz", "ping"]), + ) + def test_exclude_lists(self): + def test_excluded(path): + self.fetch(path) + spans = self.sorted_spans( + self.memory_exporter.get_finished_spans() + ) + self.assertEqual(len(spans), 1) + client = spans[0] + self.assertEqual(client.name, "GET") + self.assertEqual(client.kind, SpanKind.CLIENT) + self.assert_span_has_attributes( + client, + { + "component": "tornado", + "http.url": self.get_url(path), + "http.method": "GET", + "http.status_code": 200, + }, + ) + self.memory_exporter.clear() + + test_excluded("/healthz") + test_excluded("/ping") + + +class TestTornadoUninstrument(TornadoTest): + def test_uninstrument(self): + response = self.fetch("/") + self.assertEqual(response.code, 201) + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 3) + manual, server, client = self.sorted_spans(spans) + self.assertEqual(manual.name, "manual") + self.assertEqual(server.name, "MainHandler.get") + self.assertEqual(client.name, "GET") + self.memory_exporter.clear() + + TornadoInstrumentor().uninstrument() + + response = self.fetch("/") + self.assertEqual(response.code, 201) + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 1) + manual = spans[0] + self.assertEqual(manual.name, "manual") diff --git a/instrumentation/opentelemetry-instrumentation-tornado/tests/tornado_test_app.py b/instrumentation/opentelemetry-instrumentation-tornado/tests/tornado_test_app.py new file mode 100644 index 00000000000..307dc60b76d --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-tornado/tests/tornado_test_app.py @@ -0,0 +1,99 @@ +# pylint: disable=W0223,R0201 + +import tornado.web +from tornado import gen + + +class AsyncHandler(tornado.web.RequestHandler): + async def get(self): + with self.application.tracer.start_as_current_span("sub-task-wrapper"): + await self.do_something1() + await self.do_something2() + self.set_status(201) + self.write("{}") + + async def do_something1(self): + with self.application.tracer.start_as_current_span("sub-task-1"): + tornado.gen.sleep(0.1) + + async def do_something2(self): + with self.application.tracer.start_as_current_span("sub-task-2"): + tornado.gen.sleep(0.1) + + +class CoroutineHandler(tornado.web.RequestHandler): + @gen.coroutine + def get(self): + with self.application.tracer.start_as_current_span("sub-task-wrapper"): + yield self.do_something1() + yield self.do_something2() + self.set_status(201) + self.write("{}") + + @gen.coroutine + def do_something1(self): + with self.application.tracer.start_as_current_span("sub-task-1"): + tornado.gen.sleep(0.1) + + @gen.coroutine + def do_something2(self): + with self.application.tracer.start_as_current_span("sub-task-2"): + tornado.gen.sleep(0.1) + + +class MainHandler(tornado.web.RequestHandler): + def _handler(self): + with self.application.tracer.start_as_current_span("manual"): + self.write("Hello, world") + self.set_status(201) + + def get(self): + return self._handler() + + def post(self): + return self._handler() + + def patch(self): + return self._handler() + + def delete(self): + return self._handler() + + def put(self): + return self._handler() + + def head(self): + return self._handler() + + def options(self): + return self._handler() + + +class BadHandler(tornado.web.RequestHandler): + def get(self): + raise NameError("some random name error") + + +class DynamicHandler(tornado.web.RequestHandler): + def get(self): + self.set_status(202) + + +class HealthCheckHandler(tornado.web.RequestHandler): + def get(self): + self.set_status(200) + + +def make_app(tracer): + app = tornado.web.Application( + [ + (r"/", MainHandler), + (r"/error", BadHandler), + (r"/cor", CoroutineHandler), + (r"/async", AsyncHandler), + (r"/healthz", HealthCheckHandler), + (r"/ping", HealthCheckHandler), + ] + ) + app.tracer = tracer + return app diff --git a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap.py b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap.py index c7022d9bc4d..d11535d31c3 100644 --- a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap.py +++ b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap.py @@ -49,6 +49,7 @@ "sqlalchemy": "opentelemetry-instrumentation-sqlalchemy>=0.8b0", "sqlite3": "opentelemetry-instrumentation-sqlite3>=0.11b0", "starlette": "opentelemetry-instrumentation-starlette>=0.11b0", + "tornado": "opentelemetry-instrumentation-tornado>=0.13b0", "wsgi": "opentelemetry-instrumentation-wsgi>=0.8b0", } @@ -78,6 +79,7 @@ "sqlalchemy": ("opentelemetry-instrumentation-sqlalchemy",), "sqlite3": ("opentelemetry-instrumentation-sqlite3",), "starlette": ("opentelemetry-instrumentation-starlette",), + "tornado": ("opentelemetry-instrumentation-tornado",), "wsgi": ("opentelemetry-instrumentation-wsgi",), } diff --git a/tests/util/src/opentelemetry/test/test_base.py b/tests/util/src/opentelemetry/test/test_base.py index e2d99c0acf3..e1dbc55e623 100644 --- a/tests/util/src/opentelemetry/test/test_base.py +++ b/tests/util/src/opentelemetry/test/test_base.py @@ -69,6 +69,13 @@ def assert_span_has_attributes(self, span, attributes): self.assertIn(key, span.attributes) self.assertEqual(val, span.attributes[key]) + def sorted_spans(self, spans): # pylint: disable=R0201 + return sorted( + spans, + key=lambda s: s._start_time, # pylint: disable=W0212 + reverse=True, + ) + @staticmethod def create_tracer_provider(**kwargs): """Helper to create a configured tracer provider. diff --git a/tox.ini b/tox.ini index 384c43725b4..b477d5ba740 100644 --- a/tox.ini +++ b/tox.ini @@ -169,6 +169,11 @@ envlist = ; instrumentation-system-metrics intentionally excluded from pypy3 ; known limitation: gc.get_count won't work under pypy + ; opentelemetry-instrumentation-tornado + ; instrumentation supports >=6 on Py 3.5 and above. + py3{5,6,7,8}-test-instrumentation-tornado + pypy3-test-instrumentation-tornado + lint py38-tracecontext py38-{mypy,mypyinstalled} @@ -229,6 +234,7 @@ changedir = test-instrumentation-sqlite3: instrumentation/opentelemetry-instrumentation-sqlite3/tests test-instrumentation-starlette: instrumentation/opentelemetry-instrumentation-starlette/tests test-instrumentation-system-metrics: instrumentation/opentelemetry-instrumentation-system-metrics/tests + test-instrumentation-tornado: instrumentation/opentelemetry-instrumentation-tornado/tests test-instrumentation-wsgi: instrumentation/opentelemetry-instrumentation-wsgi/tests test-exporter-jaeger: exporter/opentelemetry-exporter-jaeger/tests @@ -303,6 +309,8 @@ commands_pre = starlette: pip install {toxinidir}/instrumentation/opentelemetry-instrumentation-starlette[test] + tornado: pip install {toxinidir}/instrumentation/opentelemetry-instrumentation-tornado + jinja2: pip install {toxinidir}/instrumentation/opentelemetry-instrumentation-jinja2[test] aiohttp-client: pip install {toxinidir}/opentelemetry-sdk {toxinidir}/instrumentation/opentelemetry-instrumentation-aiohttp-client