From f1804dd5eaa1482afae8ac13ff23b512d0435101 Mon Sep 17 00:00:00 2001 From: David Acevedo Date: Fri, 10 Mar 2023 18:51:58 -0500 Subject: [PATCH] Add graphql-core instrumentation --- .github/component_owners.yml | 3 + CHANGELOG.md | 5 + docs-requirements.txt | 1 + .../graphql_core/graphql_core.rst | 7 + instrumentation/README.md | 1 + .../LICENSE | 201 ++++++++++ .../README.rst | 24 ++ .../pyproject.toml | 58 +++ .../instrumentation/graphql_core/__init__.py | 368 ++++++++++++++++++ .../instrumentation/graphql_core/package.py | 16 + .../instrumentation/graphql_core/version.py | 15 + .../tests/__init__.py | 0 .../test_graphql_core_instrumentation.py | 164 ++++++++ .../pyproject.toml | 1 + .../instrumentation/bootstrap_gen.py | 4 + tox.ini | 7 + 16 files changed, 875 insertions(+) create mode 100644 docs/instrumentation/graphql_core/graphql_core.rst create mode 100644 instrumentation/opentelemetry-instrumentation-graphql-core/LICENSE create mode 100644 instrumentation/opentelemetry-instrumentation-graphql-core/README.rst create mode 100644 instrumentation/opentelemetry-instrumentation-graphql-core/pyproject.toml create mode 100644 instrumentation/opentelemetry-instrumentation-graphql-core/src/opentelemetry/instrumentation/graphql_core/__init__.py create mode 100644 instrumentation/opentelemetry-instrumentation-graphql-core/src/opentelemetry/instrumentation/graphql_core/package.py create mode 100644 instrumentation/opentelemetry-instrumentation-graphql-core/src/opentelemetry/instrumentation/graphql_core/version.py create mode 100644 instrumentation/opentelemetry-instrumentation-graphql-core/tests/__init__.py create mode 100644 instrumentation/opentelemetry-instrumentation-graphql-core/tests/test_graphql_core_instrumentation.py diff --git a/.github/component_owners.yml b/.github/component_owners.yml index 933dc7da13..55d3519cb7 100644 --- a/.github/component_owners.yml +++ b/.github/component_owners.yml @@ -10,6 +10,9 @@ components: - oxeye-nikolay - nikosokolik + instrumentation/opentelemetry-instrumentation-graphql-core: + - dacevedo12 + instrumentation/opentelemetry-instrumentation-kafka-python: - nozik diff --git a/CHANGELOG.md b/CHANGELOG.md index ce84cd8a67..fa3c369284 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## Unreleased +### Added + +- `opentelemetry-instrumentation-graphql-core` Initial release + ([#1719](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1719)) + ## Version 1.17.0/0.38b0 (2023-03-22) ### Added diff --git a/docs-requirements.txt b/docs-requirements.txt index 6d11d20198..0e6218cc23 100644 --- a/docs-requirements.txt +++ b/docs-requirements.txt @@ -30,6 +30,7 @@ confluent-kafka>= 1.8.2,< 2.0.0 elasticsearch>=2.0,<9.0 flask~=2.0 falcon~=2.0 +graphql-core~=3.0 grpcio~=1.27 kafka-python>=2.0,<3.0 mysql-connector-python~=8.0 diff --git a/docs/instrumentation/graphql_core/graphql_core.rst b/docs/instrumentation/graphql_core/graphql_core.rst new file mode 100644 index 0000000000..8047352749 --- /dev/null +++ b/docs/instrumentation/graphql_core/graphql_core.rst @@ -0,0 +1,7 @@ +OpenTelemetry GraphQL-core instrumentation +========================================== + +.. automodule:: opentelemetry.instrumentation.graphql_core + :members: + :undoc-members: + :show-inheritance: diff --git a/instrumentation/README.md b/instrumentation/README.md index 0cf12c9baa..0ff7492060 100644 --- a/instrumentation/README.md +++ b/instrumentation/README.md @@ -18,6 +18,7 @@ | [opentelemetry-instrumentation-falcon](./opentelemetry-instrumentation-falcon) | falcon >= 1.4.1, < 4.0.0 | Yes | [opentelemetry-instrumentation-fastapi](./opentelemetry-instrumentation-fastapi) | fastapi ~= 0.58 | Yes | [opentelemetry-instrumentation-flask](./opentelemetry-instrumentation-flask) | flask >= 1.0, < 3.0 | Yes +| [opentelemetry-instrumentation-graphql-core](./opentelemetry-instrumentation-graphql-core) | graphql-core ~= 3.0 | No | [opentelemetry-instrumentation-grpc](./opentelemetry-instrumentation-grpc) | grpcio ~= 1.27 | No | [opentelemetry-instrumentation-httpx](./opentelemetry-instrumentation-httpx) | httpx >= 0.18.0 | No | [opentelemetry-instrumentation-jinja2](./opentelemetry-instrumentation-jinja2) | jinja2 >= 2.7, < 4.0 | No diff --git a/instrumentation/opentelemetry-instrumentation-graphql-core/LICENSE b/instrumentation/opentelemetry-instrumentation-graphql-core/LICENSE new file mode 100644 index 0000000000..1ef7dad2c5 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-graphql-core/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright The OpenTelemetry Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/instrumentation/opentelemetry-instrumentation-graphql-core/README.rst b/instrumentation/opentelemetry-instrumentation-graphql-core/README.rst new file mode 100644 index 0000000000..a0ead89037 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-graphql-core/README.rst @@ -0,0 +1,24 @@ +OpenTelemetry GraphQL-core Tracing +================================== + +|pypi| + +.. |pypi| image:: https://badge.fury.io/py/opentelemetry-instrumentation-graphql-core.svg + :target: https://pypi.org/project/opentelemetry-instrumentation-graphql-core/ + +This library allows tracing requests made by the GraphQL-core library. + +Installation +------------ + +:: + + pip install opentelemetry-instrumentation-graphql-core + + +References +---------- + +* `OpenTelemetry GraphQL-core Tracing `_ +* `OpenTelemetry Project `_ +* `OpenTelemetry Python Examples `_ diff --git a/instrumentation/opentelemetry-instrumentation-graphql-core/pyproject.toml b/instrumentation/opentelemetry-instrumentation-graphql-core/pyproject.toml new file mode 100644 index 0000000000..5672a7e34e --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-graphql-core/pyproject.toml @@ -0,0 +1,58 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "opentelemetry-instrumentation-graphql-core" +dynamic = ["version"] +description = "OpenTelemetry GraphQL-core instrumentation" +readme = "README.rst" +license = "Apache-2.0" +requires-python = ">=3.7" +authors = [ + { name = "OpenTelemetry Authors", email = "cncf-opentelemetry-contributors@lists.cncf.io" }, +] +classifiers = [ + "Development Status :: 4 - Beta", + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", +] +dependencies = [ + "opentelemetry-api ~= 1.12", + "opentelemetry-instrumentation == 0.39b0.dev", + "opentelemetry-semantic-conventions == 0.39b0.dev", +] + +[project.optional-dependencies] +instruments = [ + "graphql-core ~= 3.0", +] +test = [ + "opentelemetry-instrumentation-graphql-core[instruments]", + "opentelemetry-test-utils == 0.39b0.dev", +] + +[project.entry-points.opentelemetry_instrumentor] +graphql-core = "opentelemetry.instrumentation.graphql_core:GraphQLCoreInstrumentor" + +[project.urls] +Homepage = "https://github.com/open-telemetry/opentelemetry-python-contrib/tree/main/instrumentation/opentelemetry-instrumentation-graphql-core" + +[tool.hatch.version] +path = "src/opentelemetry/instrumentation/graphql_core/version.py" + +[tool.hatch.build.targets.sdist] +include = [ + "/src", + "/tests", +] + +[tool.hatch.build.targets.wheel] +packages = ["src/opentelemetry"] diff --git a/instrumentation/opentelemetry-instrumentation-graphql-core/src/opentelemetry/instrumentation/graphql_core/__init__.py b/instrumentation/opentelemetry-instrumentation-graphql-core/src/opentelemetry/instrumentation/graphql_core/__init__.py new file mode 100644 index 0000000000..777ca54db8 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-graphql-core/src/opentelemetry/instrumentation/graphql_core/__init__.py @@ -0,0 +1,368 @@ +# 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. + +""" +Instrument `GraphQL-core`_ to trace the parsing, validation and execution of queries. + +There are two options for instrumenting code. The first option is to use the +``opentelemetry-instrument`` executable which will automatically +instrument your GraphQL-core client. The second is to programmatically enable +instrumentation via the following code: + +.. _GraphQL-core: https://pypi.org/project/graphql-core/ + +Usage +----- + +.. code:: python + + # Instrument GraphQL-core + from opentelemetry.instrumentation.graphql_core import GraphQLCoreInstrumentor + + GraphQLCoreInstrumentor().instrument() + + # This will create a span with GraphQL-specific attributes + from graphql import ( + GraphQLField, + GraphQLObjectType, + GraphQLSchema, + GraphQLString, + graphql, + ) + + def resolve_hello(parent, info): + return "Hello world!" + + schema = GraphQLSchema( + query=GraphQLObjectType( + name="RootQueryType", + fields={ + "hello": GraphQLField(GraphQLString, resolve=resolve_hello) + }, + ) + ) + + await graphql(schema, "{ hello }") + +API +--- +The `instrument` method accepts the following keyword args: + +tracer_provider (TracerProvider) - an optional tracer provider +skip_default_resolvers (Boolean) - whether to skip spans for default resolvers. True by default. + +for example: + +.. code: python + + # Instrument GraphQL-core + from opentelemetry.instrumentation.graphql_core import GraphQLCoreInstrumentor + + GraphQLCoreInstrumentor().instrument(skip_default_resolvers=False) +""" + +import importlib +import re +from typing import ( + Any, + Callable, + Collection, + Dict, + List, + Optional, + Tuple, + Union, + cast, +) + +import graphql +from graphql import ( + DocumentNode, + ExecutionContext, + FieldNode, + GraphQLError, + GraphQLField, + GraphQLFieldResolver, + GraphQLObjectType, + OperationDefinitionNode, + Source, + default_field_resolver, + get_operation_ast, +) +from graphql.execution.execute import get_field_def +from graphql.language.parser import SourceType + +try: + # Faster, but only available from 3.1.0 onwards + from graphql.pyutils import is_awaitable +except ImportError: + from inspect import isawaitable as is_awaitable + +from wrapt import wrap_function_wrapper + +from opentelemetry import context +from opentelemetry.instrumentation.graphql_core.package import _instruments +from opentelemetry.instrumentation.graphql_core.version import __version__ +from opentelemetry.instrumentation.instrumentor import BaseInstrumentor +from opentelemetry.instrumentation.utils import ( + _SUPPRESS_INSTRUMENTATION_KEY, + unwrap, +) +from opentelemetry.trace import Span, get_tracer + +graphql_module = importlib.import_module("graphql.graphql") +graphql_execute_module = importlib.import_module("graphql.execution.execute") + + +class GraphQLCoreInstrumentor(BaseInstrumentor): + """An instrumentor for GraphQL-core. + + See `BaseInstrumentor` + """ + + def __init__(self) -> None: + super().__init__() + self._tracer = None + self.skip_default_resolvers = False + + def instrumentation_dependencies(self) -> Collection[str]: + return _instruments + + def _instrument(self, **kwargs: Any) -> None: + self._tracer = get_tracer( + __name__, __version__, kwargs.get("tracer_provider") + ) + self.skip_default_resolvers = kwargs.get( + "skip_default_resolvers", True + ) + + wrap_function_wrapper( + graphql, + "parse", + self._patched_parse, + ) + wrap_function_wrapper( + graphql_module, + "parse", + self._patched_parse, + ) + wrap_function_wrapper( + graphql.validation, + "validate", + self._patched_validate, + ) + wrap_function_wrapper( + graphql, + "execute", + self._patched_execute, + ) + wrap_function_wrapper( + graphql_module, + "execute", + self._patched_execute, + ) + wrap_function_wrapper( + graphql, + "ExecutionContext.execute_field", + self._patched_execute_field, + ) + + def _uninstrument(self, **kwargs: Any) -> None: + unwrap(graphql, "parse") + unwrap(graphql_module, "parse") + unwrap(graphql.validation, "validate") + unwrap(graphql, "execute") + unwrap(graphql_module, "execute") + unwrap(ExecutionContext, "execute_field") + + def _patched_parse( + self, + original_func: Callable[..., Any], + _instance: Any, + args: Tuple[Any, ...], + kwargs: Dict[str, Any], + ) -> Any: + if context.get_value(_SUPPRESS_INSTRUMENTATION_KEY): + return original_func(*args, **kwargs) + + with self._tracer.start_as_current_span("graphql.parse") as span: + source_arg: SourceType = args[0] + _set_document_attr(span, source_arg) + + return original_func(*args, **kwargs) + + def _patched_validate( + self, + original_func: Callable[..., Any], + _instance: Any, + args: Tuple[Any, ...], + kwargs: Dict[str, Any], + ) -> Any: + if context.get_value(_SUPPRESS_INSTRUMENTATION_KEY): + return original_func(*args, **kwargs) + + with self._tracer.start_as_current_span("graphql.validate") as span: + document_arg: DocumentNode = args[1] + _set_document_attr(span, document_arg) + + errors = original_func(*args, **kwargs) + _set_errors(span, errors) + return errors + + def _patched_execute( + self, + original_func: Callable[..., Any], + _instance: Any, + args: Tuple[Any, ...], + kwargs: Dict[str, Any], + ) -> Any: + if context.get_value(_SUPPRESS_INSTRUMENTATION_KEY): + return original_func(*args, **kwargs) + + with self._tracer.start_as_current_span("graphql.execute") as span: + document_arg: DocumentNode = args[1] + _set_operation_attrs(span, document_arg) + result = original_func(*args, **kwargs) + + if is_awaitable(result): + + async def await_result() -> Any: + with self._tracer.start_as_current_span( + "graphql.execute.await" + ) as span: + _set_operation_attrs(span, document_arg) + async_result = await result + _set_errors(span, async_result.errors) + return async_result + + return await_result() + _set_errors(span, result.errors) + return result + + def _patched_execute_field( + self, + original_func: Callable[..., Any], + instance: ExecutionContext, + args: Tuple[Any, ...], + kwargs: Dict[str, Any], + ) -> Any: + if context.get_value(_SUPPRESS_INSTRUMENTATION_KEY): + return original_func(*args, **kwargs) + + parent_type_arg: GraphQLObjectType = args[0] + field_nodes_arg: List[FieldNode] = args[2] + field_node = field_nodes_arg[0] + field = get_field_def(instance.schema, parent_type_arg, field_node) + + if _should_skip_field( + field, instance.operation, self.skip_default_resolvers + ): + return original_func(*args, **kwargs) + + with self._tracer.start_as_current_span("graphql.resolve") as span: + _set_field_attrs(span, field_node) + result = original_func(*args, **kwargs) + + if is_awaitable(result): + + async def await_result() -> Any: + with self._tracer.start_as_current_span( + "graphql.resolve.await" + ) as span: + _set_field_attrs(span, field_node) + return await result + + return await_result() + return result + + +def _format_source(obj: Union[DocumentNode, Source, str]) -> str: + if isinstance(obj, str): + value = obj + elif isinstance(obj, Source): + value = obj.body + elif isinstance(obj, DocumentNode) and obj.loc: + value = obj.loc.source.body + else: + value = "" + + return re.sub(r"\s+", " ", value).strip() + + +def _set_document_attr( + span: Span, obj: Union[DocumentNode, Source, str] +) -> None: + source = _format_source(obj) + span.set_attribute("graphql.document", source) + + +def _set_operation_attrs(span: Span, document: DocumentNode) -> None: + _set_document_attr(span, document) + + operation_definition = get_operation_ast(document) + + if operation_definition: + span.set_attribute( + "graphql.operation.type", + operation_definition.operation.value, + ) + + if operation_definition.name: + span.set_attribute( + "graphql.operation.name", + operation_definition.name.value, + ) + + +def _set_errors(span: Span, errors: Optional[List[GraphQLError]]) -> None: + if errors: + for error in errors: + span.record_exception(error) + + +def _set_field_attrs(span: Span, field_node: FieldNode) -> None: + span.set_attribute("graphql.field.name", field_node.name.value) + + +def _is_default_resolver(resolver: Optional[GraphQLFieldResolver]) -> bool: + # pylint: disable=comparison-with-callable + return ( + # graphql-core + resolver is None + or resolver == default_field_resolver + # ariadne + or getattr(resolver, "_ariadne_alias_resolver", False) + # strawberry + or getattr(resolver, "_is_default", False) + ) + + +def _is_introspection_query(operation: OperationDefinitionNode) -> bool: + selections = operation.selection_set.selections + + if selections: + root_field = cast(FieldNode, selections[0]) + return root_field.name.value == "__schema" + return False + + +def _should_skip_field( + field: GraphQLField, + operation: OperationDefinitionNode, + skip_default_resolvers: bool, +) -> bool: + if _is_default_resolver(field.resolve): + return skip_default_resolvers + + return _is_introspection_query(operation) diff --git a/instrumentation/opentelemetry-instrumentation-graphql-core/src/opentelemetry/instrumentation/graphql_core/package.py b/instrumentation/opentelemetry-instrumentation-graphql-core/src/opentelemetry/instrumentation/graphql_core/package.py new file mode 100644 index 0000000000..07129e0b69 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-graphql-core/src/opentelemetry/instrumentation/graphql_core/package.py @@ -0,0 +1,16 @@ +# Copyright The OpenTelemetry Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +_instruments = ("graphql-core ~= 3.0",) diff --git a/instrumentation/opentelemetry-instrumentation-graphql-core/src/opentelemetry/instrumentation/graphql_core/version.py b/instrumentation/opentelemetry-instrumentation-graphql-core/src/opentelemetry/instrumentation/graphql_core/version.py new file mode 100644 index 0000000000..eb62a67e28 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-graphql-core/src/opentelemetry/instrumentation/graphql_core/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.39b0.dev" diff --git a/instrumentation/opentelemetry-instrumentation-graphql-core/tests/__init__.py b/instrumentation/opentelemetry-instrumentation-graphql-core/tests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/instrumentation/opentelemetry-instrumentation-graphql-core/tests/test_graphql_core_instrumentation.py b/instrumentation/opentelemetry-instrumentation-graphql-core/tests/test_graphql_core_instrumentation.py new file mode 100644 index 0000000000..5dc34bde94 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-graphql-core/tests/test_graphql_core_instrumentation.py @@ -0,0 +1,164 @@ +# Copyright The OpenTelemetry Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import asyncio + +from graphql import ( + GraphQLField, + GraphQLObjectType, + GraphQLSchema, + GraphQLString, + graphql, + graphql_sync, +) + +from opentelemetry.instrumentation.graphql_core import GraphQLCoreInstrumentor +from opentelemetry.test.test_base import TestBase + + +def async_call(coro): + loop = asyncio.get_event_loop() + return loop.run_until_complete(coro) + + +class TestGraphQLCoreInstrumentor(TestBase): + def setUp(self): + super().setUp() + GraphQLCoreInstrumentor().instrument() + + def tearDown(self): + super().tearDown() + GraphQLCoreInstrumentor().uninstrument() + + def test_graphql(self): + async def resolve_hello(parent, info): + await asyncio.sleep(0) + return "Hello world!" + + schema = GraphQLSchema( + query=GraphQLObjectType( + name="RootQueryType", + fields={ + "hello": GraphQLField(GraphQLString, resolve=resolve_hello) + }, + ) + ) + + result = async_call(graphql(schema, "query Test { hello }")) + self.assertEqual(result.errors, None) + self.assertEqual(result.data["hello"], "Hello world!") + + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 6) + + parse_span = spans[0] + self.assertEqual("graphql.parse", parse_span.name) + self.assertEqual( + "query Test { hello }", parse_span.attributes["graphql.document"] + ) + + validate_span = spans[1] + self.assertEqual("graphql.validate", validate_span.name) + self.assertEqual( + "query Test { hello }", + validate_span.attributes["graphql.document"], + ) + + resolve_span = spans[2] + self.assertEqual("graphql.resolve", resolve_span.name) + self.assertEqual( + "hello", resolve_span.attributes["graphql.field.name"] + ) + + execute_span = spans[3] + self.assertEqual("graphql.execute", execute_span.name) + self.assertEqual( + "query Test { hello }", execute_span.attributes["graphql.document"] + ) + self.assertEqual( + "query", execute_span.attributes["graphql.operation.type"] + ) + self.assertEqual( + "Test", execute_span.attributes["graphql.operation.name"] + ) + + resolve_await_span = spans[4] + self.assertEqual("graphql.resolve.await", resolve_await_span.name) + self.assertEqual( + "hello", resolve_await_span.attributes["graphql.field.name"] + ) + + execute_await_span = spans[5] + self.assertEqual("graphql.execute.await", execute_await_span.name) + self.assertEqual( + "query Test { hello }", + execute_await_span.attributes["graphql.document"], + ) + self.assertEqual( + "query", execute_await_span.attributes["graphql.operation.type"] + ) + self.assertEqual( + "Test", execute_await_span.attributes["graphql.operation.name"] + ) + + def test_graphql_sync(self): + def resolve_hello(parent, info): + return "Hello world!" + + schema = GraphQLSchema( + query=GraphQLObjectType( + name="RootQueryType", + fields={ + "hello": GraphQLField(GraphQLString, resolve=resolve_hello) + }, + ) + ) + + result = graphql_sync(schema, "query Test { hello }") + self.assertEqual(result.errors, None) + self.assertEqual(result.data["hello"], "Hello world!") + + spans = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans), 4) + + parse_span = spans[0] + self.assertEqual("graphql.parse", parse_span.name) + self.assertEqual( + "query Test { hello }", parse_span.attributes["graphql.document"] + ) + + validate_span = spans[1] + self.assertEqual("graphql.validate", validate_span.name) + self.assertEqual( + "query Test { hello }", + validate_span.attributes["graphql.document"], + ) + + resolve_span = spans[2] + self.assertEqual("graphql.resolve", resolve_span.name) + self.assertEqual( + "hello", resolve_span.attributes["graphql.field.name"] + ) + + execute_span = spans[3] + self.assertEqual("graphql.execute", execute_span.name) + self.assertEqual( + "query Test { hello }", execute_span.attributes["graphql.document"] + ) + self.assertEqual( + "query", execute_span.attributes["graphql.operation.type"] + ) + self.assertEqual( + "Test", execute_span.attributes["graphql.operation.name"] + ) diff --git a/opentelemetry-contrib-instrumentations/pyproject.toml b/opentelemetry-contrib-instrumentations/pyproject.toml index d05a7712ad..33e18a212b 100644 --- a/opentelemetry-contrib-instrumentations/pyproject.toml +++ b/opentelemetry-contrib-instrumentations/pyproject.toml @@ -46,6 +46,7 @@ dependencies = [ "opentelemetry-instrumentation-falcon==0.39b0.dev", "opentelemetry-instrumentation-fastapi==0.39b0.dev", "opentelemetry-instrumentation-flask==0.39b0.dev", + "opentelemetry-instrumentation-graphql-core==0.39b0.dev", "opentelemetry-instrumentation-grpc==0.39b0.dev", "opentelemetry-instrumentation-httpx==0.39b0.dev", "opentelemetry-instrumentation-jinja2==0.39b0.dev", diff --git a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py index b3f5c10e9a..2352163bad 100644 --- a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py +++ b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py @@ -76,6 +76,10 @@ "library": "flask >= 1.0, < 3.0", "instrumentation": "opentelemetry-instrumentation-flask==0.39b0.dev", }, + "graphql-core": { + "library": "graphql-core ~= 3.0", + "instrumentation": "opentelemetry-instrumentation-graphql-core==0.39b0.dev", + }, "grpcio": { "library": "grpcio ~= 1.27", "instrumentation": "opentelemetry-instrumentation-grpc==0.39b0.dev", diff --git a/tox.ini b/tox.ini index 3d73d37667..953f378592 100644 --- a/tox.ini +++ b/tox.ini @@ -150,6 +150,9 @@ envlist = py3{7,8,9,10,11}-test-instrumentation-wsgi pypy3-test-instrumentation-wsgi + ; opentelemetry-instrumentation-graphql-core + py3{7,8,9,10,11}-test-instrumentation-graphql-core + ; opentelemetry-instrumentation-grpc py3{7,8,9,10,11}-test-instrumentation-grpc @@ -299,6 +302,7 @@ changedir = test-instrumentation-flask: instrumentation/opentelemetry-instrumentation-flask/tests test-instrumentation-urllib: instrumentation/opentelemetry-instrumentation-urllib/tests test-instrumentation-urllib3: instrumentation/opentelemetry-instrumentation-urllib3/tests + test-instrumentation-graphql-core: instrumentation/opentelemetry-instrumentation-graphql-core/tests test-instrumentation-grpc: instrumentation/opentelemetry-instrumentation-grpc/tests test-instrumentation-jinja2: instrumentation/opentelemetry-instrumentation-jinja2/tests test-instrumentation-kafka-python: instrumentation/opentelemetry-instrumentation-kafka-python/tests @@ -354,6 +358,8 @@ commands_pre = confluent-kafka: pip install {toxinidir}/instrumentation/opentelemetry-instrumentation-confluent-kafka[test] + graphql-core: pip install {toxinidir}/instrumentation/opentelemetry-instrumentation-graphql-core[test] + grpc: pip install {toxinidir}/instrumentation/opentelemetry-instrumentation-grpc[test] falcon{1,2,3},flask,django{1,2,3,4},pyramid,tornado,starlette,fastapi,aiohttp,asgi,requests,urllib,urllib3,wsgi: pip install {toxinidir}/util/opentelemetry-util-http[test] @@ -504,6 +510,7 @@ commands_pre = python -m pip install -e {toxinidir}/instrumentation/opentelemetry-instrumentation-boto3sqs[test] python -m pip install -e {toxinidir}/instrumentation/opentelemetry-instrumentation-django[test] python -m pip install -e {toxinidir}/instrumentation/opentelemetry-instrumentation-starlette[test] + python -m pip install -e {toxinidir}/instrumentation/opentelemetry-instrumentation-graphql-core[test] python -m pip install -e {toxinidir}/instrumentation/opentelemetry-instrumentation-grpc[test] python -m pip install -e {toxinidir}/instrumentation/opentelemetry-instrumentation-falcon[test] python -m pip install -e {toxinidir}/instrumentation/opentelemetry-instrumentation-boto[test]