mirror of
https://github.com/open-telemetry/opentelemetry-python-contrib.git
synced 2025-07-29 21:23:55 +08:00
Rename db framework packages from "ext" to "instrumentation" (#966)
This commit is contained in:
@ -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
|
201
instrumentation/opentelemetry-instrumentation-dbapi/LICENSE
Normal file
201
instrumentation/opentelemetry-instrumentation-dbapi/LICENSE
Normal file
@ -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.
|
@ -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
|
@ -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 <https://opentelemetry-python.readthedocs.io/en/latest/instrumentation/dbapi/dbapi.html>`_
|
||||
* `OpenTelemetry Project <https://opentelemetry.io/>`_
|
@ -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
|
26
instrumentation/opentelemetry-instrumentation-dbapi/setup.py
Normal file
26
instrumentation/opentelemetry-instrumentation-dbapi/setup.py
Normal file
@ -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__"])
|
@ -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.
|
||||
`<https://www.python.org/dev/peps/pep-0249/>`_
|
||||
|
||||
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)
|
@ -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"
|
@ -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")
|
Reference in New Issue
Block a user