From 8fef469ab7ecde2050e3ec606e05568824f21a16 Mon Sep 17 00:00:00 2001 From: Leighton Chen Date: Mon, 3 Aug 2020 17:48:44 -0700 Subject: [PATCH 01/11] Rename db framework packages from "ext" to "instrumentation" (#966) --- .../CHANGELOG.md | 18 + .../LICENSE | 201 ++++++++++ .../MANIFEST.in | 9 + .../README.rst | 21 + .../setup.cfg | 52 +++ .../setup.py | 26 ++ .../instrumentation/dbapi/__init__.py | 369 ++++++++++++++++++ .../instrumentation/dbapi/version.py | 15 + .../tests/__init__.py | 0 .../tests/test_dbapi_integration.py | 199 ++++++++++ 10 files changed, 910 insertions(+) create mode 100644 instrumentation/opentelemetry-instrumentation-dbapi/CHANGELOG.md create mode 100644 instrumentation/opentelemetry-instrumentation-dbapi/LICENSE create mode 100644 instrumentation/opentelemetry-instrumentation-dbapi/MANIFEST.in create mode 100644 instrumentation/opentelemetry-instrumentation-dbapi/README.rst create mode 100644 instrumentation/opentelemetry-instrumentation-dbapi/setup.cfg create mode 100644 instrumentation/opentelemetry-instrumentation-dbapi/setup.py create mode 100644 instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py create mode 100644 instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/version.py create mode 100644 instrumentation/opentelemetry-instrumentation-dbapi/tests/__init__.py create mode 100644 instrumentation/opentelemetry-instrumentation-dbapi/tests/test_dbapi_integration.py diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/CHANGELOG.md b/instrumentation/opentelemetry-instrumentation-dbapi/CHANGELOG.md new file mode 100644 index 000000000..c0a38d855 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-dbapi/CHANGELOG.md @@ -0,0 +1,18 @@ +# Changelog + +## Unreleased + +- Change package name to opentelemetry-instrumentation-dbapi + ([#999](https://github.com/open-telemetry/opentelemetry-python/pull/999)) + +## 0.7b1 + +Released 2020-05-12 + +- Implement instrument_connection and uninstrument_connection ([#624](https://github.com/open-telemetry/opentelemetry-python/pull/624)) + +## 0.4a0 + +Released 2020-02-21 + +- Initial release \ No newline at end of file diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/LICENSE b/instrumentation/opentelemetry-instrumentation-dbapi/LICENSE new file mode 100644 index 000000000..261eeb9e9 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-dbapi/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-dbapi/MANIFEST.in b/instrumentation/opentelemetry-instrumentation-dbapi/MANIFEST.in new file mode 100644 index 000000000..aed3e3327 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-dbapi/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-dbapi/README.rst b/instrumentation/opentelemetry-instrumentation-dbapi/README.rst new file mode 100644 index 000000000..5137a1c1f --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-dbapi/README.rst @@ -0,0 +1,21 @@ +OpenTelemetry Database API instrumentation +========================================== + +|pypi| + +.. |pypi| image:: https://badge.fury.io/py/opentelemetry-instrumentation-dbapi.svg + :target: https://pypi.org/project/opentelemetry-instrumentation-dbapi/ + +Installation +------------ + +:: + + pip install opentelemetry-instrumentation-dbapi + + +References +---------- + +* `OpenTelemetry Database API Instrumentation `_ +* `OpenTelemetry Project `_ diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/setup.cfg b/instrumentation/opentelemetry-instrumentation-dbapi/setup.cfg new file mode 100644 index 000000000..29044f3ba --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-dbapi/setup.cfg @@ -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. +# +[metadata] +name = opentelemetry-instrumentation-dbapi +description = OpenTelemetry Database API instrumentation +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-dbapi +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 + Programming Language :: Python :: 3.4 + Programming Language :: Python :: 3.5 + Programming Language :: Python :: 3.6 + Programming Language :: Python :: 3.7 + Programming Language :: Python :: 3.8 + +[options] +python_requires = >=3.4 +package_dir= + =src +packages=find_namespace: +install_requires = + opentelemetry-api == 0.12.dev0 + opentelemetry-instrumentation == 0.12.dev0 + wrapt >= 1.0.0, < 2.0.0 + +[options.extras_require] +test = + opentelemetry-test == 0.12.dev0 + +[options.packages.find] +where = src diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/setup.py b/instrumentation/opentelemetry-instrumentation-dbapi/setup.py new file mode 100644 index 000000000..cfe98f389 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-dbapi/setup.py @@ -0,0 +1,26 @@ +# 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", "dbapi", "version.py" +) +PACKAGE_INFO = {} +with open(VERSION_FILENAME) as f: + exec(f.read(), PACKAGE_INFO) + +setuptools.setup(version=PACKAGE_INFO["__version__"]) diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py b/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py new file mode 100644 index 000000000..035c823bc --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py @@ -0,0 +1,369 @@ +# 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. + +""" +The trace integration with Database API supports libraries that follow the +Python Database API Specification v2.0. +``_ + +Usage +----- + +.. code-block:: python + + import mysql.connector + import pyodbc + + from opentelemetry import trace + from opentelemetry.instrumentation.dbapi import trace_integration + from opentelemetry.trace import TracerProvider + + trace.set_tracer_provider(TracerProvider()) + + # Ex: mysql.connector + trace_integration(mysql.connector, "connect", "mysql", "sql") + # Ex: pyodbc + trace_integration(pyodbc, "Connection", "odbc", "sql") + +API +--- +""" + +import functools +import logging +import typing + +import wrapt + +from opentelemetry import trace as trace_api +from opentelemetry.instrumentation.dbapi.version import __version__ +from opentelemetry.instrumentation.utils import unwrap +from opentelemetry.trace import SpanKind, TracerProvider, get_tracer +from opentelemetry.trace.status import Status, StatusCanonicalCode + +logger = logging.getLogger(__name__) + + +def trace_integration( + connect_module: typing.Callable[..., typing.Any], + connect_method_name: str, + database_component: str, + database_type: str = "", + connection_attributes: typing.Dict = None, + tracer_provider: typing.Optional[TracerProvider] = None, +): + """Integrate with DB API library. + https://www.python.org/dev/peps/pep-0249/ + + Args: + connect_module: Module name where connect method is available. + connect_method_name: The connect method name. + database_component: Database driver name or database name "JDBI", + "jdbc", "odbc", "postgreSQL". + database_type: The Database type. For any SQL database, "sql". + connection_attributes: Attribute names for database, port, host and + user in Connection object. + tracer_provider: The :class:`opentelemetry.trace.TracerProvider` to + use. If ommited the current configured one is used. + """ + wrap_connect( + __name__, + connect_module, + connect_method_name, + database_component, + database_type, + connection_attributes, + version=__version__, + tracer_provider=tracer_provider, + ) + + +def wrap_connect( + name: str, + connect_module: typing.Callable[..., typing.Any], + connect_method_name: str, + database_component: str, + database_type: str = "", + connection_attributes: typing.Dict = None, + version: str = "", + tracer_provider: typing.Optional[TracerProvider] = None, +): + """Integrate with DB API library. + https://www.python.org/dev/peps/pep-0249/ + + Args: + tracer: The :class:`opentelemetry.trace.Tracer` to use. + connect_module: Module name where connect method is available. + connect_method_name: The connect method name. + database_component: Database driver name or database name "JDBI", + "jdbc", "odbc", "postgreSQL". + database_type: The Database type. For any SQL database, "sql". + connection_attributes: Attribute names for database, port, host and + user in Connection object. + """ + + # pylint: disable=unused-argument + def wrap_connect_( + wrapped: typing.Callable[..., typing.Any], + instance: typing.Any, + args: typing.Tuple[typing.Any, typing.Any], + kwargs: typing.Dict[typing.Any, typing.Any], + ): + db_integration = DatabaseApiIntegration( + name, + database_component, + database_type=database_type, + connection_attributes=connection_attributes, + version=version, + tracer_provider=tracer_provider, + ) + return db_integration.wrapped_connection(wrapped, args, kwargs) + + try: + wrapt.wrap_function_wrapper( + connect_module, connect_method_name, wrap_connect_ + ) + except Exception as ex: # pylint: disable=broad-except + logger.warning("Failed to integrate with DB API. %s", str(ex)) + + +def unwrap_connect( + connect_module: typing.Callable[..., typing.Any], connect_method_name: str, +): + """Disable integration with DB API library. + https://www.python.org/dev/peps/pep-0249/ + + Args: + connect_module: Module name where the connect method is available. + connect_method_name: The connect method name. + """ + unwrap(connect_module, connect_method_name) + + +def instrument_connection( + name: str, + connection, + database_component: str, + database_type: str = "", + connection_attributes: typing.Dict = None, + version: str = "", + tracer_provider: typing.Optional[TracerProvider] = None, +): + """Enable instrumentation in a database connection. + + Args: + tracer: The :class:`opentelemetry.trace.Tracer` to use. + connection: The connection to instrument. + database_component: Database driver name or database name "JDBI", + "jdbc", "odbc", "postgreSQL". + database_type: The Database type. For any SQL database, "sql". + connection_attributes: Attribute names for database, port, host and + user in a connection object. + + Returns: + An instrumented connection. + """ + db_integration = DatabaseApiIntegration( + name, + database_component, + database_type, + connection_attributes=connection_attributes, + version=version, + tracer_provider=tracer_provider, + ) + db_integration.get_connection_attributes(connection) + return get_traced_connection_proxy(connection, db_integration) + + +def uninstrument_connection(connection): + """Disable instrumentation in a database connection. + + Args: + connection: The connection to uninstrument. + + Returns: + An uninstrumented connection. + """ + if isinstance(connection, wrapt.ObjectProxy): + return connection.__wrapped__ + + logger.warning("Connection is not instrumented") + return connection + + +class DatabaseApiIntegration: + def __init__( + self, + name: str, + database_component: str, + database_type: str = "sql", + connection_attributes=None, + version: str = "", + tracer_provider: typing.Optional[TracerProvider] = None, + ): + self.connection_attributes = connection_attributes + if self.connection_attributes is None: + self.connection_attributes = { + "database": "database", + "port": "port", + "host": "host", + "user": "user", + } + self._name = name + self._version = version + self._tracer_provider = tracer_provider + self.database_component = database_component + self.database_type = database_type + self.connection_props = {} + self.span_attributes = {} + self.name = "" + self.database = "" + + def get_tracer(self): + return get_tracer( + self._name, + instrumenting_library_version=self._version, + tracer_provider=self._tracer_provider, + ) + + def wrapped_connection( + self, + connect_method: typing.Callable[..., typing.Any], + args: typing.Tuple[typing.Any, typing.Any], + kwargs: typing.Dict[typing.Any, typing.Any], + ): + """Add object proxy to connection object. + """ + connection = connect_method(*args, **kwargs) + self.get_connection_attributes(connection) + return get_traced_connection_proxy(connection, self) + + def get_connection_attributes(self, connection): + # Populate span fields using connection + for key, value in self.connection_attributes.items(): + # Allow attributes nested in connection object + attribute = functools.reduce( + lambda attribute, attribute_value: getattr( + attribute, attribute_value, None + ), + value.split("."), + connection, + ) + if attribute: + self.connection_props[key] = attribute + self.name = self.database_component + self.database = self.connection_props.get("database", "") + if self.database: + # PyMySQL encodes names with utf-8 + if hasattr(self.database, "decode"): + self.database = self.database.decode(errors="ignore") + self.name += "." + self.database + user = self.connection_props.get("user") + if user is not None: + self.span_attributes["db.user"] = str(user) + host = self.connection_props.get("host") + if host is not None: + self.span_attributes["net.peer.name"] = host + port = self.connection_props.get("port") + if port is not None: + self.span_attributes["net.peer.port"] = port + + +def get_traced_connection_proxy( + connection, db_api_integration, *args, **kwargs +): + # pylint: disable=abstract-method + class TracedConnectionProxy(wrapt.ObjectProxy): + # pylint: disable=unused-argument + def __init__(self, connection, *args, **kwargs): + wrapt.ObjectProxy.__init__(self, connection) + + def cursor(self, *args, **kwargs): + return get_traced_cursor_proxy( + self.__wrapped__.cursor(*args, **kwargs), db_api_integration + ) + + return TracedConnectionProxy(connection, *args, **kwargs) + + +class TracedCursor: + def __init__(self, db_api_integration: DatabaseApiIntegration): + self._db_api_integration = db_api_integration + + def _populate_span( + self, span: trace_api.Span, *args: typing.Tuple[typing.Any, typing.Any] + ): + statement = args[0] if args else "" + span.set_attribute( + "component", self._db_api_integration.database_component + ) + span.set_attribute("db.type", self._db_api_integration.database_type) + span.set_attribute("db.instance", self._db_api_integration.database) + span.set_attribute("db.statement", statement) + + for ( + attribute_key, + attribute_value, + ) in self._db_api_integration.span_attributes.items(): + span.set_attribute(attribute_key, attribute_value) + + if len(args) > 1: + span.set_attribute("db.statement.parameters", str(args[1])) + + def traced_execution( + self, + query_method: typing.Callable[..., typing.Any], + *args: typing.Tuple[typing.Any, typing.Any], + **kwargs: typing.Dict[typing.Any, typing.Any] + ): + + with self._db_api_integration.get_tracer().start_as_current_span( + self._db_api_integration.name, kind=SpanKind.CLIENT + ) as span: + self._populate_span(span, *args) + try: + result = query_method(*args, **kwargs) + span.set_status(Status(StatusCanonicalCode.OK)) + return result + except Exception as ex: # pylint: disable=broad-except + span.set_status(Status(StatusCanonicalCode.UNKNOWN, str(ex))) + raise ex + + +def get_traced_cursor_proxy(cursor, db_api_integration, *args, **kwargs): + _traced_cursor = TracedCursor(db_api_integration) + + # pylint: disable=abstract-method + class TracedCursorProxy(wrapt.ObjectProxy): + + # pylint: disable=unused-argument + def __init__(self, cursor, *args, **kwargs): + wrapt.ObjectProxy.__init__(self, cursor) + + def execute(self, *args, **kwargs): + return _traced_cursor.traced_execution( + self.__wrapped__.execute, *args, **kwargs + ) + + def executemany(self, *args, **kwargs): + return _traced_cursor.traced_execution( + self.__wrapped__.executemany, *args, **kwargs + ) + + def callproc(self, *args, **kwargs): + return _traced_cursor.traced_execution( + self.__wrapped__.callproc, *args, **kwargs + ) + + return TracedCursorProxy(cursor, *args, **kwargs) diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/version.py b/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/version.py new file mode 100644 index 000000000..780a92b6a --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/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.12.dev0" diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/tests/__init__.py b/instrumentation/opentelemetry-instrumentation-dbapi/tests/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/tests/test_dbapi_integration.py b/instrumentation/opentelemetry-instrumentation-dbapi/tests/test_dbapi_integration.py new file mode 100644 index 000000000..299157033 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-dbapi/tests/test_dbapi_integration.py @@ -0,0 +1,199 @@ +# 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 logging +from unittest import mock + +from opentelemetry import trace as trace_api +from opentelemetry.instrumentation import dbapi +from opentelemetry.test.test_base import TestBase + + +class TestDBApiIntegration(TestBase): + def setUp(self): + super().setUp() + self.tracer = self.tracer_provider.get_tracer(__name__) + + def test_span_succeeded(self): + connection_props = { + "database": "testdatabase", + "server_host": "testhost", + "server_port": 123, + "user": "testuser", + } + connection_attributes = { + "database": "database", + "port": "server_port", + "host": "server_host", + "user": "user", + } + db_integration = dbapi.DatabaseApiIntegration( + self.tracer, "testcomponent", "testtype", connection_attributes + ) + mock_connection = db_integration.wrapped_connection( + mock_connect, {}, connection_props + ) + cursor = mock_connection.cursor() + cursor.execute("Test query", ("param1Value", False)) + spans_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans_list), 1) + span = spans_list[0] + self.assertEqual(span.name, "testcomponent.testdatabase") + self.assertIs(span.kind, trace_api.SpanKind.CLIENT) + + self.assertEqual(span.attributes["component"], "testcomponent") + self.assertEqual(span.attributes["db.type"], "testtype") + self.assertEqual(span.attributes["db.instance"], "testdatabase") + self.assertEqual(span.attributes["db.statement"], "Test query") + self.assertEqual( + span.attributes["db.statement.parameters"], + "('param1Value', False)", + ) + self.assertEqual(span.attributes["db.user"], "testuser") + self.assertEqual(span.attributes["net.peer.name"], "testhost") + self.assertEqual(span.attributes["net.peer.port"], 123) + self.assertIs( + span.status.canonical_code, + trace_api.status.StatusCanonicalCode.OK, + ) + + def test_span_failed(self): + db_integration = dbapi.DatabaseApiIntegration( + self.tracer, "testcomponent" + ) + mock_connection = db_integration.wrapped_connection( + mock_connect, {}, {} + ) + cursor = mock_connection.cursor() + with self.assertRaises(Exception): + cursor.execute("Test query", throw_exception=True) + + spans_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans_list), 1) + span = spans_list[0] + self.assertEqual(span.attributes["db.statement"], "Test query") + self.assertIs( + span.status.canonical_code, + trace_api.status.StatusCanonicalCode.UNKNOWN, + ) + self.assertEqual(span.status.description, "Test Exception") + + def test_executemany(self): + db_integration = dbapi.DatabaseApiIntegration( + self.tracer, "testcomponent" + ) + mock_connection = db_integration.wrapped_connection( + mock_connect, {}, {} + ) + cursor = mock_connection.cursor() + cursor.executemany("Test query") + spans_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans_list), 1) + span = spans_list[0] + self.assertEqual(span.attributes["db.statement"], "Test query") + + def test_callproc(self): + db_integration = dbapi.DatabaseApiIntegration( + self.tracer, "testcomponent" + ) + mock_connection = db_integration.wrapped_connection( + mock_connect, {}, {} + ) + cursor = mock_connection.cursor() + cursor.callproc("Test stored procedure") + spans_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans_list), 1) + span = spans_list[0] + self.assertEqual( + span.attributes["db.statement"], "Test stored procedure" + ) + + @mock.patch("opentelemetry.instrumentation.dbapi") + def test_wrap_connect(self, mock_dbapi): + dbapi.wrap_connect(self.tracer, mock_dbapi, "connect", "-") + connection = mock_dbapi.connect() + self.assertEqual(mock_dbapi.connect.call_count, 1) + self.assertIsInstance(connection.__wrapped__, mock.Mock) + + @mock.patch("opentelemetry.instrumentation.dbapi") + def test_unwrap_connect(self, mock_dbapi): + dbapi.wrap_connect(self.tracer, mock_dbapi, "connect", "-") + connection = mock_dbapi.connect() + self.assertEqual(mock_dbapi.connect.call_count, 1) + + dbapi.unwrap_connect(mock_dbapi, "connect") + connection = mock_dbapi.connect() + self.assertEqual(mock_dbapi.connect.call_count, 2) + self.assertIsInstance(connection, mock.Mock) + + def test_instrument_connection(self): + connection = mock.Mock() + # Avoid get_attributes failing because can't concatenate mock + connection.database = "-" + connection2 = dbapi.instrument_connection(self.tracer, connection, "-") + self.assertIs(connection2.__wrapped__, connection) + + def test_uninstrument_connection(self): + connection = mock.Mock() + # Set connection.database to avoid a failure because mock can't + # be concatenated + connection.database = "-" + connection2 = dbapi.instrument_connection(self.tracer, connection, "-") + self.assertIs(connection2.__wrapped__, connection) + + connection3 = dbapi.uninstrument_connection(connection2) + self.assertIs(connection3, connection) + + with self.assertLogs(level=logging.WARNING): + connection4 = dbapi.uninstrument_connection(connection) + self.assertIs(connection4, connection) + + +# pylint: disable=unused-argument +def mock_connect(*args, **kwargs): + database = kwargs.get("database") + server_host = kwargs.get("server_host") + server_port = kwargs.get("server_port") + user = kwargs.get("user") + return MockConnection(database, server_port, server_host, user) + + +class MockConnection: + def __init__(self, database, server_port, server_host, user): + self.database = database + self.server_port = server_port + self.server_host = server_host + self.user = user + + # pylint: disable=no-self-use + def cursor(self): + return MockCursor() + + +class MockCursor: + # pylint: disable=unused-argument, no-self-use + def execute(self, query, params=None, throw_exception=False): + if throw_exception: + raise Exception("Test Exception") + + # pylint: disable=unused-argument, no-self-use + def executemany(self, query, params=None, throw_exception=False): + if throw_exception: + raise Exception("Test Exception") + + # pylint: disable=unused-argument, no-self-use + def callproc(self, query, params=None, throw_exception=False): + if throw_exception: + raise Exception("Test Exception") From e2b3b6b6fb67d60656ab9a5f950782987cdf547d Mon Sep 17 00:00:00 2001 From: Leighton Chen Date: Tue, 4 Aug 2020 19:10:51 -0700 Subject: [PATCH 02/11] Rename remaining framework packages from "ext" to "instrumentation" (#969) --- .../opentelemetry-instrumentation-dbapi/CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/CHANGELOG.md b/instrumentation/opentelemetry-instrumentation-dbapi/CHANGELOG.md index c0a38d855..555b227db 100644 --- a/instrumentation/opentelemetry-instrumentation-dbapi/CHANGELOG.md +++ b/instrumentation/opentelemetry-instrumentation-dbapi/CHANGELOG.md @@ -3,7 +3,7 @@ ## Unreleased - Change package name to opentelemetry-instrumentation-dbapi - ([#999](https://github.com/open-telemetry/opentelemetry-python/pull/999)) + ([#966](https://github.com/open-telemetry/opentelemetry-python/pull/966)) ## 0.7b1 From 1107b97209dd4ce4d65a0a1c4de082015e2f3089 Mon Sep 17 00:00:00 2001 From: Leighton Chen Date: Sat, 15 Aug 2020 18:06:27 -0700 Subject: [PATCH 03/11] chore: 0.13.dev0 version update (#991) --- .../opentelemetry-instrumentation-dbapi/CHANGELOG.md | 4 ++++ .../opentelemetry-instrumentation-dbapi/setup.cfg | 6 +++--- .../src/opentelemetry/instrumentation/dbapi/version.py | 2 +- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/CHANGELOG.md b/instrumentation/opentelemetry-instrumentation-dbapi/CHANGELOG.md index 555b227db..bdb9236ac 100644 --- a/instrumentation/opentelemetry-instrumentation-dbapi/CHANGELOG.md +++ b/instrumentation/opentelemetry-instrumentation-dbapi/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +## Version 0.12b0 + +Released 2020-08-14 + - Change package name to opentelemetry-instrumentation-dbapi ([#966](https://github.com/open-telemetry/opentelemetry-python/pull/966)) diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/setup.cfg b/instrumentation/opentelemetry-instrumentation-dbapi/setup.cfg index 29044f3ba..2c7865934 100644 --- a/instrumentation/opentelemetry-instrumentation-dbapi/setup.cfg +++ b/instrumentation/opentelemetry-instrumentation-dbapi/setup.cfg @@ -40,13 +40,13 @@ package_dir= =src packages=find_namespace: install_requires = - opentelemetry-api == 0.12.dev0 - opentelemetry-instrumentation == 0.12.dev0 + opentelemetry-api == 0.13dev0 + opentelemetry-instrumentation == 0.13dev0 wrapt >= 1.0.0, < 2.0.0 [options.extras_require] test = - opentelemetry-test == 0.12.dev0 + opentelemetry-test == 0.13dev0 [options.packages.find] where = src diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/version.py b/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/version.py index 780a92b6a..9cc445d09 100644 --- a/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/version.py +++ b/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/version.py @@ -12,4 +12,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -__version__ = "0.12.dev0" +__version__ = "0.13dev0" From 33954ca03b007e99e7e07cfc805d0fb8c16f5780 Mon Sep 17 00:00:00 2001 From: Daniel <61800298+ffe4@users.noreply.github.com> Date: Wed, 2 Sep 2020 20:26:16 +0200 Subject: [PATCH 04/11] Add support for db cursors and connections in context managers (#1028) Here is an example snippet that will not report tracing without this patch: with psycopg2.connect(...) as conn, conn.cursor() as cursor: cursor.execute("select 1;") Co-authored-by: Carl Bordum Hansen --- .../CHANGELOG.md | 5 ++++- .../instrumentation/dbapi/__init__.py | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/CHANGELOG.md b/instrumentation/opentelemetry-instrumentation-dbapi/CHANGELOG.md index bdb9236ac..99e1e09b5 100644 --- a/instrumentation/opentelemetry-instrumentation-dbapi/CHANGELOG.md +++ b/instrumentation/opentelemetry-instrumentation-dbapi/CHANGELOG.md @@ -2,6 +2,9 @@ ## Unreleased +- bugfix: cursors and connections now produce spans when used with context managers + ([#1028](https://github.com/open-telemetry/opentelemetry-python/pull/1028)) + ## Version 0.12b0 Released 2020-08-14 @@ -19,4 +22,4 @@ Released 2020-05-12 Released 2020-02-21 -- Initial release \ No newline at end of file +- Initial release diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py b/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py index 035c823bc..551f71555 100644 --- a/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py @@ -294,6 +294,13 @@ def get_traced_connection_proxy( self.__wrapped__.cursor(*args, **kwargs), db_api_integration ) + def __enter__(self): + self.__wrapped__.__enter__() + return self + + def __exit__(self, *args, **kwargs): + self.__wrapped__.__exit__(*args, **kwargs) + return TracedConnectionProxy(connection, *args, **kwargs) @@ -366,4 +373,11 @@ def get_traced_cursor_proxy(cursor, db_api_integration, *args, **kwargs): self.__wrapped__.callproc, *args, **kwargs ) + def __enter__(self): + self.__wrapped__.__enter__() + return self + + def __exit__(self, *args, **kwargs): + self.__wrapped__.__exit__(*args, **kwargs) + return TracedCursorProxy(cursor, *args, **kwargs) From 82d0b14335cbea324f2c27167af4e2b31b139e7a Mon Sep 17 00:00:00 2001 From: alrex Date: Mon, 14 Sep 2020 15:11:56 -0700 Subject: [PATCH 05/11] dropping support for python 3.4 (#1099) * dropping support for python 3.4 --- .../opentelemetry-instrumentation-dbapi/CHANGELOG.md | 2 ++ instrumentation/opentelemetry-instrumentation-dbapi/setup.cfg | 3 +-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/CHANGELOG.md b/instrumentation/opentelemetry-instrumentation-dbapi/CHANGELOG.md index 99e1e09b5..5629a23aa 100644 --- a/instrumentation/opentelemetry-instrumentation-dbapi/CHANGELOG.md +++ b/instrumentation/opentelemetry-instrumentation-dbapi/CHANGELOG.md @@ -4,6 +4,8 @@ - bugfix: cursors and connections now produce spans when used with context managers ([#1028](https://github.com/open-telemetry/opentelemetry-python/pull/1028)) +- Drop support for Python 3.4 + ([#1099](https://github.com/open-telemetry/opentelemetry-python/pull/1099)) ## Version 0.12b0 diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/setup.cfg b/instrumentation/opentelemetry-instrumentation-dbapi/setup.cfg index 2c7865934..1ba131c8e 100644 --- a/instrumentation/opentelemetry-instrumentation-dbapi/setup.cfg +++ b/instrumentation/opentelemetry-instrumentation-dbapi/setup.cfg @@ -28,14 +28,13 @@ classifiers = License :: OSI Approved :: Apache Software License Programming Language :: Python Programming Language :: Python :: 3 - Programming Language :: Python :: 3.4 Programming Language :: Python :: 3.5 Programming Language :: Python :: 3.6 Programming Language :: Python :: 3.7 Programming Language :: Python :: 3.8 [options] -python_requires = >=3.4 +python_requires = >=3.5 package_dir= =src packages=find_namespace: From 8de04ac9968974890a02f27b3b7afe173c9a4cc9 Mon Sep 17 00:00:00 2001 From: alrex Date: Thu, 17 Sep 2020 08:23:52 -0700 Subject: [PATCH 06/11] release: updating changelogs and version to 0.13b0 (#1129) * updating changelogs and version to 0.13b0 --- .../opentelemetry-instrumentation-dbapi/CHANGELOG.md | 4 ++++ .../opentelemetry-instrumentation-dbapi/setup.cfg | 6 +++--- .../src/opentelemetry/instrumentation/dbapi/version.py | 2 +- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/CHANGELOG.md b/instrumentation/opentelemetry-instrumentation-dbapi/CHANGELOG.md index 5629a23aa..e110055da 100644 --- a/instrumentation/opentelemetry-instrumentation-dbapi/CHANGELOG.md +++ b/instrumentation/opentelemetry-instrumentation-dbapi/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +## Version 0.13b0 + +Released 2020-09-17 + - bugfix: cursors and connections now produce spans when used with context managers ([#1028](https://github.com/open-telemetry/opentelemetry-python/pull/1028)) - Drop support for Python 3.4 diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/setup.cfg b/instrumentation/opentelemetry-instrumentation-dbapi/setup.cfg index 1ba131c8e..fcf447183 100644 --- a/instrumentation/opentelemetry-instrumentation-dbapi/setup.cfg +++ b/instrumentation/opentelemetry-instrumentation-dbapi/setup.cfg @@ -39,13 +39,13 @@ package_dir= =src packages=find_namespace: install_requires = - opentelemetry-api == 0.13dev0 - opentelemetry-instrumentation == 0.13dev0 + opentelemetry-api == 0.13b0 + opentelemetry-instrumentation == 0.13b0 wrapt >= 1.0.0, < 2.0.0 [options.extras_require] test = - opentelemetry-test == 0.13dev0 + opentelemetry-test == 0.13b0 [options.packages.find] where = src diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/version.py b/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/version.py index 9cc445d09..2015e87c7 100644 --- a/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/version.py +++ b/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/version.py @@ -12,4 +12,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -__version__ = "0.13dev0" +__version__ = "0.13b0" From 23a011e5e73b3d135a643bc808c8155ecaf835ec Mon Sep 17 00:00:00 2001 From: alrex Date: Thu, 17 Sep 2020 12:21:39 -0700 Subject: [PATCH 07/11] chore: bump dev version (#1131) --- .../opentelemetry-instrumentation-dbapi/setup.cfg | 6 +++--- .../src/opentelemetry/instrumentation/dbapi/version.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/setup.cfg b/instrumentation/opentelemetry-instrumentation-dbapi/setup.cfg index fcf447183..fc1e3fb82 100644 --- a/instrumentation/opentelemetry-instrumentation-dbapi/setup.cfg +++ b/instrumentation/opentelemetry-instrumentation-dbapi/setup.cfg @@ -39,13 +39,13 @@ package_dir= =src packages=find_namespace: install_requires = - opentelemetry-api == 0.13b0 - opentelemetry-instrumentation == 0.13b0 + opentelemetry-api == 0.14.dev0 + opentelemetry-instrumentation == 0.14.dev0 wrapt >= 1.0.0, < 2.0.0 [options.extras_require] test = - opentelemetry-test == 0.13b0 + opentelemetry-test == 0.14.dev0 [options.packages.find] where = src diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/version.py b/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/version.py index 2015e87c7..0f9902789 100644 --- a/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/version.py +++ b/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/version.py @@ -12,4 +12,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -__version__ = "0.13b0" +__version__ = "0.14.dev0" From 362fe9c05eae68e5f4f71ade5c789da109a8739d Mon Sep 17 00:00:00 2001 From: Leighton Chen Date: Thu, 8 Oct 2020 15:25:20 -0400 Subject: [PATCH 08/11] Use is_recording flag in aiopg, asyncpg, dbapi, psycopg2, pymemcache, pymongo, redis, sqlalchemy instrumentations (#1212) --- .../instrumentation/dbapi/__init__.py | 10 ++++-- .../tests/test_dbapi_integration.py | 32 +++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py b/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py index 551f71555..0dcdd5ba6 100644 --- a/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py @@ -311,6 +311,8 @@ class TracedCursor: def _populate_span( self, span: trace_api.Span, *args: typing.Tuple[typing.Any, typing.Any] ): + if not span.is_recording(): + return statement = args[0] if args else "" span.set_attribute( "component", self._db_api_integration.database_component @@ -341,10 +343,14 @@ class TracedCursor: self._populate_span(span, *args) try: result = query_method(*args, **kwargs) - span.set_status(Status(StatusCanonicalCode.OK)) + if span.is_recording(): + span.set_status(Status(StatusCanonicalCode.OK)) return result except Exception as ex: # pylint: disable=broad-except - span.set_status(Status(StatusCanonicalCode.UNKNOWN, str(ex))) + if span.is_recording(): + span.set_status( + Status(StatusCanonicalCode.UNKNOWN, str(ex)) + ) raise ex diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/tests/test_dbapi_integration.py b/instrumentation/opentelemetry-instrumentation-dbapi/tests/test_dbapi_integration.py index 299157033..e342e15aa 100644 --- a/instrumentation/opentelemetry-instrumentation-dbapi/tests/test_dbapi_integration.py +++ b/instrumentation/opentelemetry-instrumentation-dbapi/tests/test_dbapi_integration.py @@ -69,6 +69,38 @@ class TestDBApiIntegration(TestBase): trace_api.status.StatusCanonicalCode.OK, ) + def test_span_not_recording(self): + connection_props = { + "database": "testdatabase", + "server_host": "testhost", + "server_port": 123, + "user": "testuser", + } + connection_attributes = { + "database": "database", + "port": "server_port", + "host": "server_host", + "user": "user", + } + mock_tracer = mock.Mock() + mock_span = mock.Mock() + mock_span.is_recording.return_value = False + mock_tracer.start_span.return_value = mock_span + mock_tracer.use_span.return_value.__enter__ = mock_span + mock_tracer.use_span.return_value.__exit__ = True + db_integration = dbapi.DatabaseApiIntegration( + mock_tracer, "testcomponent", "testtype", connection_attributes + ) + mock_connection = db_integration.wrapped_connection( + mock_connect, {}, connection_props + ) + cursor = mock_connection.cursor() + cursor.execute("Test query", ("param1Value", False)) + self.assertFalse(mock_span.is_recording()) + self.assertTrue(mock_span.is_recording.called) + self.assertFalse(mock_span.set_attribute.called) + self.assertFalse(mock_span.set_status.called) + def test_span_failed(self): db_integration = dbapi.DatabaseApiIntegration( self.tracer, "testcomponent" From 20a3a160bbaf53a8b0abb83b998cd4e065f9c454 Mon Sep 17 00:00:00 2001 From: Leighton Chen Date: Tue, 13 Oct 2020 14:38:09 -0400 Subject: [PATCH 09/11] chore: bump dev version (#1235) --- .../opentelemetry-instrumentation-dbapi/setup.cfg | 6 +++--- .../src/opentelemetry/instrumentation/dbapi/version.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/setup.cfg b/instrumentation/opentelemetry-instrumentation-dbapi/setup.cfg index fc1e3fb82..e644d253a 100644 --- a/instrumentation/opentelemetry-instrumentation-dbapi/setup.cfg +++ b/instrumentation/opentelemetry-instrumentation-dbapi/setup.cfg @@ -39,13 +39,13 @@ package_dir= =src packages=find_namespace: install_requires = - opentelemetry-api == 0.14.dev0 - opentelemetry-instrumentation == 0.14.dev0 + opentelemetry-api == 0.15.dev0 + opentelemetry-instrumentation == 0.15.dev0 wrapt >= 1.0.0, < 2.0.0 [options.extras_require] test = - opentelemetry-test == 0.14.dev0 + opentelemetry-test == 0.15.dev0 [options.packages.find] where = src diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/version.py b/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/version.py index 0f9902789..e7b342d64 100644 --- a/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/version.py +++ b/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/version.py @@ -12,4 +12,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -__version__ = "0.14.dev0" +__version__ = "0.15.dev0" From 5cab8136f7426d55a02b59f310eaa562c75ca088 Mon Sep 17 00:00:00 2001 From: Leighton Chen Date: Wed, 28 Oct 2020 17:28:58 -0400 Subject: [PATCH 10/11] Change status codes from grpc status codes, remove setting status in instrumentations except on ERROR (#1282) --- .../src/opentelemetry/instrumentation/dbapi/__init__.py | 8 ++------ .../tests/test_dbapi_integration.py | 6 ++---- 2 files changed, 4 insertions(+), 10 deletions(-) diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py b/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py index 0dcdd5ba6..0047ab185 100644 --- a/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py @@ -50,7 +50,7 @@ from opentelemetry import trace as trace_api from opentelemetry.instrumentation.dbapi.version import __version__ from opentelemetry.instrumentation.utils import unwrap from opentelemetry.trace import SpanKind, TracerProvider, get_tracer -from opentelemetry.trace.status import Status, StatusCanonicalCode +from opentelemetry.trace.status import Status, StatusCode logger = logging.getLogger(__name__) @@ -343,14 +343,10 @@ class TracedCursor: self._populate_span(span, *args) try: result = query_method(*args, **kwargs) - if span.is_recording(): - span.set_status(Status(StatusCanonicalCode.OK)) return result except Exception as ex: # pylint: disable=broad-except if span.is_recording(): - span.set_status( - Status(StatusCanonicalCode.UNKNOWN, str(ex)) - ) + span.set_status(Status(StatusCode.ERROR, str(ex))) raise ex diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/tests/test_dbapi_integration.py b/instrumentation/opentelemetry-instrumentation-dbapi/tests/test_dbapi_integration.py index e342e15aa..f2abb8b6d 100644 --- a/instrumentation/opentelemetry-instrumentation-dbapi/tests/test_dbapi_integration.py +++ b/instrumentation/opentelemetry-instrumentation-dbapi/tests/test_dbapi_integration.py @@ -65,8 +65,7 @@ class TestDBApiIntegration(TestBase): self.assertEqual(span.attributes["net.peer.name"], "testhost") self.assertEqual(span.attributes["net.peer.port"], 123) self.assertIs( - span.status.canonical_code, - trace_api.status.StatusCanonicalCode.OK, + span.status.status_code, trace_api.status.StatusCode.UNSET, ) def test_span_not_recording(self): @@ -117,8 +116,7 @@ class TestDBApiIntegration(TestBase): span = spans_list[0] self.assertEqual(span.attributes["db.statement"], "Test query") self.assertIs( - span.status.canonical_code, - trace_api.status.StatusCanonicalCode.UNKNOWN, + span.status.status_code, trace_api.status.StatusCode.ERROR, ) self.assertEqual(span.status.description, "Test Exception") From bbae639118f70eba14722be164b6cd41c73aa757 Mon Sep 17 00:00:00 2001 From: alrex Date: Mon, 2 Nov 2020 09:00:06 -0800 Subject: [PATCH 11/11] [pre-release] Update changelogs, version [0.15b0] (#1320) --- .../opentelemetry-instrumentation-dbapi/setup.cfg | 6 +++--- .../src/opentelemetry/instrumentation/dbapi/version.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/setup.cfg b/instrumentation/opentelemetry-instrumentation-dbapi/setup.cfg index e644d253a..b42a03867 100644 --- a/instrumentation/opentelemetry-instrumentation-dbapi/setup.cfg +++ b/instrumentation/opentelemetry-instrumentation-dbapi/setup.cfg @@ -39,13 +39,13 @@ package_dir= =src packages=find_namespace: install_requires = - opentelemetry-api == 0.15.dev0 - opentelemetry-instrumentation == 0.15.dev0 + opentelemetry-api == 0.15b0 + opentelemetry-instrumentation == 0.15b0 wrapt >= 1.0.0, < 2.0.0 [options.extras_require] test = - opentelemetry-test == 0.15.dev0 + opentelemetry-test == 0.15b0 [options.packages.find] where = src diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/version.py b/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/version.py index e7b342d64..ff494d225 100644 --- a/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/version.py +++ b/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/version.py @@ -12,4 +12,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -__version__ = "0.15.dev0" +__version__ = "0.15b0"