diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index cdc0c744e..59e9cb234 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -748,6 +748,8 @@ If set to `True`, the agent won’t send any events to the APM Server, independe If set to `False`, the agent won’t instrument any code. This disables most of the tracing functionality, but can be useful to debug possible instrumentation issues. +For explicitly installed Starlette/FastAPI APM middleware, the transaction-ending framework hook remains enabled so HTTP transactions complete, including after error handling. Library instrumentation remains disabled. + ### `verify_server_cert` [config-verify-server-cert] diff --git a/elasticapm/contrib/starlette/__init__.py b/elasticapm/contrib/starlette/__init__.py index 1160b0de5..dad4757cd 100644 --- a/elasticapm/contrib/starlette/__init__.py +++ b/elasticapm/contrib/starlette/__init__.py @@ -47,6 +47,7 @@ from elasticapm.conf import constants from elasticapm.contrib.asyncio.traces import set_context from elasticapm.contrib.starlette.utils import get_body, get_data_from_request, get_data_from_response +from elasticapm.instrumentation.packages.asyncio.starlette import StarletteServerErrorMiddlewareInstrumentation from elasticapm.utils.disttracing import TraceParent from elasticapm.utils.encoding import long_field from elasticapm.utils.logging import get_logger @@ -161,8 +162,15 @@ def __init__(self, app: ASGIApp, client: Optional[Client] = None, **kwargs) -> N if not self.client: self.client = make_apm_client(**kwargs) - if self.client.config.instrument and self.client.config.enabled: - elasticapm.instrumentation.control.instrument() + if self.client.config.enabled: + if self.client.config.instrument: + elasticapm.instrumentation.control.instrument() + else: + # Explicit middleware still needs the outer transaction-ending + # hook, after Starlette's error handler has finished. + elasticapm.instrumentation.control.instrument( + instrumentation_classes=(StarletteServerErrorMiddlewareInstrumentation,) + ) # If we ever make this a general-use ASGI middleware we should use # `asgiref.compatibility.guarantee_single_callable(app)` here diff --git a/elasticapm/instrumentation/control.py b/elasticapm/instrumentation/control.py index 86662bade..f1cd031a9 100644 --- a/elasticapm/instrumentation/control.py +++ b/elasticapm/instrumentation/control.py @@ -36,13 +36,14 @@ _lock = threading.Lock() -def instrument() -> None: +def instrument(instrumentation_classes=None) -> None: """ - Instruments all registered methods/functions with a wrapper + Instruments registered methods/functions, optionally restricted to classes. """ with _lock: for obj in register.get_instrumentation_objects(): - obj.instrument() + if instrumentation_classes is None or isinstance(obj, instrumentation_classes): + obj.instrument() def uninstrument() -> None: diff --git a/tests/contrib/asyncio/starlette_instrument_disabled_tests.py b/tests/contrib/asyncio/starlette_instrument_disabled_tests.py new file mode 100644 index 000000000..d891f3aac --- /dev/null +++ b/tests/contrib/asyncio/starlette_instrument_disabled_tests.py @@ -0,0 +1,130 @@ +# BSD 3-Clause License +# +# Copyright (c) 2019, Elasticsearch BV +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# * Neither the name of the copyright holder nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import asyncio + +import pytest + +pytest.importorskip("starlette") + +from starlette.applications import Starlette +from starlette.requests import Request +from starlette.responses import PlainTextResponse, StreamingResponse +from starlette.routing import Route +from starlette.testclient import TestClient + +import elasticapm +from elasticapm.conf import constants +from elasticapm.contrib.starlette import ElasticAPM + +pytestmark = pytest.mark.starlette + + +@pytest.fixture(autouse=True) +def clean_instrumentation(): + elasticapm.uninstrument() + yield + elasticapm.uninstrument() + + +@pytest.mark.parametrize("framework", ["starlette", "fastapi"]) +@pytest.mark.parametrize("instrument", [False, True]) +@pytest.mark.parametrize("kind", ["success", "handled", "unhandled", "stream"]) +def test_transaction_completion_without_library_instrumentation(elasticapm_client, instrument, kind, framework, mocker): + elasticapm_client.config.update("1", instrument=instrument) + handler_ids = [] + + async def endpoint(request: Request): + assert elasticapm.get_transaction_id() + if kind in ("handled", "unhandled"): + raise ValueError("test failure") + if kind == "stream": + completed = len(elasticapm_client.events[constants.TRANSACTION]) + + async def chunks(): + for chunk in (b"a", b"b"): + assert elasticapm.get_transaction_id() + assert len(elasticapm_client.events[constants.TRANSACTION]) == completed + yield chunk + + return StreamingResponse(chunks()) + return PlainTextResponse("ok") + + async def error_handler(request, exc): + handler_ids.append(elasticapm.get_transaction_id()) + elasticapm.label(error_handler="visited") + return PlainTextResponse("handled", status_code=500) + + handlers = {Exception: error_handler} if kind == "handled" else {} + if framework == "fastapi": + app = pytest.importorskip("fastapi").FastAPI(exception_handlers=handlers) + app.add_api_route("/", endpoint) + else: + app = Starlette(routes=[Route("/", endpoint)], exception_handlers=handlers) + app.add_middleware(ElasticAPM, client=elasticapm_client) + with TestClient(app, raise_server_exceptions=False) as client: + end_transaction = mocker.spy(elasticapm_client, "end_transaction") + for _ in range(2): + response = client.get("/") + assert response.status_code == (500 if kind in ("handled", "unhandled") else 200) + assert end_transaction.call_count == 2 + transactions = elasticapm_client.events[constants.TRANSACTION] + assert len(transactions) == 2 + assert transactions[0]["id"] != transactions[1]["id"] + if kind == "handled": + assert handler_ids == [transaction["id"] for transaction in transactions] + assert all(t["context"]["tags"]["error_handler"] == "visited" for t in transactions) + if kind in ("handled", "unhandled"): + assert len(elasticapm_client.events[constants.ERROR]) == 2 + if kind == "stream": + assert response.content == b"ab" + + +@pytest.mark.parametrize("elasticapm_client", [{"instrument": False}, {"instrument": True}], indirect=True) +def test_library_instrumentation_respects_instrument_setting(elasticapm_client): + async def endpoint(request): + await asyncio.tasks.sleep(0) + return PlainTextResponse("ok") + + app = Starlette(routes=[Route("/", endpoint)]) + app.add_middleware(ElasticAPM, client=elasticapm_client) + with TestClient(app) as client: + assert client.get("/").status_code == 200 + assert hasattr(asyncio.tasks.sleep, "__wrapped__") == elasticapm_client.config.instrument + spans = elasticapm_client.events[constants.SPAN] + assert [span["name"] for span in spans] == (["asyncio.sleep"] if elasticapm_client.config.instrument else []) + assert len(elasticapm_client.events[constants.TRANSACTION]) == 1 + + +@pytest.mark.parametrize("elasticapm_client", [{"instrument": False, "enabled": False}], indirect=True) +def test_disabled_agent_does_not_install_lifecycle_hook(elasticapm_client, mocker): + instrument = mocker.patch("elasticapm.instrumentation.control.instrument") + ElasticAPM(Starlette(), client=elasticapm_client) + instrument.assert_not_called()