diff --git a/sentry_sdk/consts.py b/sentry_sdk/consts.py index b1f4a0c5f6..8872453709 100644 --- a/sentry_sdk/consts.py +++ b/sentry_sdk/consts.py @@ -414,6 +414,12 @@ class SPANDATA: Example: "10.1.2.80" """ + CLOUD_REGION = "cloud.region" + """ + The geographical region the resource is running. + Example: "us-east-1" + """ + CODE_FILEPATH = "code.filepath" """ .. deprecated:: @@ -977,12 +983,24 @@ class SPANDATA: Example: "com.example.ExampleService/exampleMethod" """ + RPC_SERVICE = "rpc.service" + """ + The full (logical) name of the service being called, including its package name, if applicable. + Example: "myService.BestService" + """ + RPC_RESPONSE_STATUS_CODE = "rpc.response.status_code" """ Status code of the RPC returned by the RPC server or generated by the client. Example: "DEADLINE_EXCEEDED" """ + RPC_SYSTEM_NAME = "rpc.system.name" + """ + A string identifying the remoting system. + Example: "aws-api" + """ + SERVER_ADDRESS = "server.address" """ Name of the database host. @@ -1164,6 +1182,18 @@ class SPANDATA: Example: "prod" """ + SENTRY_OP = "sentry.op" + """ + The operation of a span. + Example: "http.client" + """ + + SENTRY_ORIGIN = "sentry.origin" + """ + The origin of the instrumentation (e.g. span, log, etc.) + Example: "auto.http.otel.fastify" + """ + SENTRY_RELEASE = "sentry.release" """ The Sentry release. diff --git a/sentry_sdk/integrations/boto3.py b/sentry_sdk/integrations/boto3.py deleted file mode 100644 index 18d7accf6d..0000000000 --- a/sentry_sdk/integrations/boto3.py +++ /dev/null @@ -1,269 +0,0 @@ -from functools import partial -from typing import TYPE_CHECKING - -import sentry_sdk -from sentry_sdk.consts import OP, SPANDATA -from sentry_sdk.integrations import DidNotEnable, Integration, _check_minimum_version -from sentry_sdk.traces import StreamedSpan -from sentry_sdk.tracing import BAGGAGE_HEADER_NAME, Span -from sentry_sdk.tracing_utils import ( - add_http_breadcrumb, - add_sentry_baggage_to_headers, - get_url_attributes, - has_span_streaming_enabled, - should_propagate_trace, -) -from sentry_sdk.utils import ( - capture_internal_exceptions, - parse_url, - parse_version, -) - -if TYPE_CHECKING: - from typing import Any, Dict, Optional, Type, Union - - from botocore.model import ServiceId - - -try: - from botocore import __version__ as BOTOCORE_VERSION - from botocore.awsrequest import AWSRequest - from botocore.client import BaseClient - from botocore.response import StreamingBody -except ImportError: - raise DidNotEnable("botocore is not installed") - - -class Boto3Integration(Integration): - identifier = "boto3" - origin = f"auto.http.{identifier}" - - @staticmethod - def setup_once() -> None: - version = parse_version(BOTOCORE_VERSION) - _check_minimum_version(Boto3Integration, version, "botocore") - - orig_init = BaseClient.__init__ - - def sentry_patched_init( - self: "BaseClient", *args: "Any", **kwargs: "Any" - ) -> None: - orig_init(self, *args, **kwargs) - meta = self.meta - service_id = meta.service_model.service_id - meta.events.register( - "request-created", - partial(_sentry_request_created, service_id=service_id), - ) - # run after other `before-sign` handlers, allowing it to see and preserve existing baggage. - meta.events.register_last("before-sign", _sentry_before_sign) - meta.events.register("after-call", _sentry_after_call) - meta.events.register("after-call-error", _sentry_after_call_error) - - BaseClient.__init__ = sentry_patched_init # type: ignore - - -def _sentry_request_created( - service_id: "ServiceId", request: "AWSRequest", operation_name: str, **kwargs: "Any" -) -> None: - description = "aws.%s.%s" % (service_id.hyphenize(), operation_name) - - client = sentry_sdk.get_client() - if client.get_integration(Boto3Integration) is None: - return - - parsed_url = None - if request.url is not None: - with capture_internal_exceptions(): - parsed_url = parse_url(request.url, sanitize=False) - - breadcrumb: "dict[str, Any]" = {} - - is_span_streaming_enabled = has_span_streaming_enabled(client.options) - span: "Union[Span, StreamedSpan, None]" = None - if is_span_streaming_enabled: - url_attributes = get_url_attributes(client, parsed_url) - breadcrumb.update(url_attributes) - - if request.method is not None: - breadcrumb[SPANDATA.HTTP_REQUEST_METHOD] = request.method - - if sentry_sdk.traces.get_current_span() is not None: - span = sentry_sdk.traces.start_span( - name=description, - attributes={ - "sentry.op": OP.HTTP_CLIENT, - "sentry.origin": Boto3Integration.origin, - SPANDATA.RPC_METHOD: f"{service_id}/{operation_name}", - }, - ) - span.set_attributes(url_attributes) - - if request.method is not None: - span.set_attribute(SPANDATA.HTTP_REQUEST_METHOD, request.method) - else: - span = sentry_sdk.start_span( - op=OP.HTTP_CLIENT, - name=description, - origin=Boto3Integration.origin, - ) - - if parsed_url: - span.set_data("aws.request.url", parsed_url.url) - span.set_data(SPANDATA.HTTP_QUERY, parsed_url.query) - span.set_data(SPANDATA.HTTP_FRAGMENT, parsed_url.fragment) - breadcrumb.update( - { - "aws.request.url": parsed_url.url, - SPANDATA.HTTP_QUERY: parsed_url.query, - SPANDATA.HTTP_FRAGMENT: parsed_url.fragment, - } - ) - - span.set_tag("aws.service_id", service_id.hyphenize()) - span.set_tag("aws.operation_name", operation_name) - if request.method is not None: - span.set_data(SPANDATA.HTTP_METHOD, request.method) - breadcrumb[SPANDATA.HTTP_METHOD] = request.method - - # We do it in order for subsequent http calls/retries be - # attached to this span. - span.__enter__() - - add_http_breadcrumb(None, breadcrumb) - - if span is not None: - # request.context is an open-ended data-structure - # where we can add anything useful in request life cycle. - request.context["_sentrysdk_span"] = span - - -def _sentry_before_sign( - request: "AWSRequest", signature_version: "Any", **kwargs: "Any" -) -> None: - client = sentry_sdk.get_client() - if client.get_integration(Boto3Integration) is None: - return - - with capture_internal_exceptions(): - # presigned requests are executed later by another caller. Adding propagation - # headers here would make those headers part of the signature, requiring the caller to reproduce the same values. - if isinstance(signature_version, str) and signature_version.endswith( - ("-query", "-presign-post") - ): - return - - if request.url is None or not should_propagate_trace(client, request.url): - return - - def _replace_header(request: "AWSRequest", key: str, value: str) -> None: - """ - Botocore's `HTTPHeaders` inherits from `email.message.Message`, where: - headers["foo"] = "old" - headers["foo"] = "new" - produces two fields: {"foo": "old", "foo": "new"}. So delete existing - fields before assigning replacement. - """ - if key in request.headers: - del request.headers[key] - request.headers[key] = value - - # use span associated with this botocore request - span = request.context.get("_sentrysdk_span") - - headers = sentry_sdk.get_current_scope().iter_trace_propagation_headers( - span=span - ) - for header_name, header_value in headers: - if header_name != BAGGAGE_HEADER_NAME: - # normal headers (e.g. `sentry-trace`) are non-shared, so replace stale values - _replace_header(request, header_name, header_value) - continue - - # merge existing `baggage` values under single header - existing_values = request.headers.get_all(BAGGAGE_HEADER_NAME, []) - combined_baggage = { - BAGGAGE_HEADER_NAME: ",".join(str(value) for value in existing_values) - } - # preserve third-party baggage, replace stale `sentry-*` values - add_sentry_baggage_to_headers(combined_baggage, header_value) - _replace_header( - request, BAGGAGE_HEADER_NAME, combined_baggage[BAGGAGE_HEADER_NAME] - ) - - -def _sentry_after_call( - context: "Dict[str, Any]", parsed: "Dict[str, Any]", **kwargs: "Any" -) -> None: - span: "Optional[Union[Span, StreamedSpan]]" = context.pop("_sentrysdk_span", None) - - # Span could be absent if the integration is disabled. - if span is None: - return - - span.__exit__(None, None, None) - - body = parsed.get("Body") - if not isinstance(body, StreamingBody): - return - - streaming_span: "Union[Span, StreamedSpan]" - if isinstance(span, StreamedSpan): - streaming_span = sentry_sdk.traces.start_span( - name=span.name, - parent_span=span, - attributes={ - "sentry.op": OP.HTTP_CLIENT_STREAM, - "sentry.origin": Boto3Integration.origin, - }, - ) - else: - streaming_span = span.start_child( - op=OP.HTTP_CLIENT_STREAM, - name=span.description, - origin=Boto3Integration.origin, - ) - - orig_read = body.read - orig_close = body.close - - def sentry_streaming_body_read(*args: "Any", **kwargs: "Any") -> bytes: - try: - ret = orig_read(*args, **kwargs) - if ret: - return ret - - if isinstance(streaming_span, StreamedSpan): - streaming_span.end() - else: - streaming_span.finish() - return ret - except Exception: - if isinstance(streaming_span, StreamedSpan): - streaming_span.end() - else: - streaming_span.finish() - raise - - body.read = sentry_streaming_body_read # type: ignore - - def sentry_streaming_body_close(*args: "Any", **kwargs: "Any") -> None: - if isinstance(streaming_span, StreamedSpan): - streaming_span.end() - else: - streaming_span.finish() - orig_close(*args, **kwargs) - - body.close = sentry_streaming_body_close # type: ignore - - -def _sentry_after_call_error( - context: "Dict[str, Any]", exception: "Type[BaseException]", **kwargs: "Any" -) -> None: - span: "Optional[Union[Span, StreamedSpan]]" = context.pop("_sentrysdk_span", None) - - # Span could be absent if the integration is disabled. - if span is None: - return - - span.__exit__(type(exception), exception, None) diff --git a/sentry_sdk/integrations/boto3/__init__.py b/sentry_sdk/integrations/boto3/__init__.py new file mode 100644 index 0000000000..66e7d208bd --- /dev/null +++ b/sentry_sdk/integrations/boto3/__init__.py @@ -0,0 +1,22 @@ +from sentry_sdk.integrations import DidNotEnable, Integration, _check_minimum_version +from sentry_sdk.utils import parse_version + +try: + from botocore import __version__ as BOTOCORE_VERSION +except ImportError: + raise DidNotEnable("botocore is not installed") + + +class Boto3Integration(Integration): + identifier = "boto3" + origin = f"auto.http.{identifier}" + + @staticmethod + def setup_once() -> None: + version = parse_version(BOTOCORE_VERSION) + _check_minimum_version(Boto3Integration, version, "botocore") + + # local import to avoid import cycle + from sentry_sdk.integrations.boto3._client import _patch_botocore_client + + _patch_botocore_client() diff --git a/sentry_sdk/integrations/boto3/_client.py b/sentry_sdk/integrations/boto3/_client.py new file mode 100644 index 0000000000..e05f424d39 --- /dev/null +++ b/sentry_sdk/integrations/boto3/_client.py @@ -0,0 +1,79 @@ +from typing import TYPE_CHECKING + +from botocore.client import BaseClient + +import sentry_sdk +from sentry_sdk.integrations.boto3 import Boto3Integration +from sentry_sdk.integrations.boto3._context import AwsCallContext +from sentry_sdk.integrations.boto3._instrumentation import ( + _finish_client_span, + _finish_client_span_with_error, + _sentry_before_sign, + _sentry_request_created, + _start_client_span, +) +from sentry_sdk.utils import capture_internal_exceptions + +if TYPE_CHECKING: + from typing import Any, Optional, Union + + from sentry_sdk.traces import StreamedSpan + from sentry_sdk.tracing import Span + + +def _patch_botocore_client() -> None: + orig_init = BaseClient.__init__ + orig_make_api_call = BaseClient._make_api_call # type: ignore + + def sentry_patched_init(self: "BaseClient", *args: "Any", **kwargs: "Any") -> None: + orig_init(self, *args, **kwargs) + meta = self.meta + meta.events.register("request-created", _sentry_request_created) + # run after other `before-sign` handlers so existing baggage is preserved. + meta.events.register_last("before-sign", _sentry_before_sign) + + def sentry_patched_make_api_call( + self: "BaseClient", operation_name: str, api_params: "Any" + ) -> "Any": + """ + Own the span lifecycle for one `_make_api_call()` invocation, including + all retries performed by botocore. + + Botocore's ``after-call-error`` event only surrounds ``_make_request``. + Wrapping ``_make_api_call`` also closes the span when parameter building, + serialization, or endpoint resolution fails before the request starts: + https://github.com/boto/botocore/blob/develop/botocore/client.py + + https://opentelemetry.io/docs/specs/semconv/rpc/rpc-spans/#rpc-client-span + """ + client = sentry_sdk.get_client() + if client.get_integration(Boto3Integration) is None: + return orig_make_api_call(self, operation_name, api_params) + + ctx: "Optional[AwsCallContext]" = None + span: "Optional[Union[Span, StreamedSpan]]" = None + + with capture_internal_exceptions(): + ctx = AwsCallContext(self, operation_name, api_params) + + if ctx is not None: + with capture_internal_exceptions(): + span = _start_client_span(ctx) + if span is not None: + span.__enter__() + + try: + parsed = orig_make_api_call(self, operation_name, api_params) + except BaseException as exc: + if span is not None: + with capture_internal_exceptions(): + _finish_client_span_with_error(span, exc) + raise + + if span is not None: + with capture_internal_exceptions(): + _finish_client_span(span, parsed) + return parsed + + BaseClient.__init__ = sentry_patched_init # type: ignore + BaseClient._make_api_call = sentry_patched_make_api_call # type: ignore diff --git a/sentry_sdk/integrations/boto3/_context.py b/sentry_sdk/integrations/boto3/_context.py new file mode 100644 index 0000000000..91cfc3db6c --- /dev/null +++ b/sentry_sdk/integrations/boto3/_context.py @@ -0,0 +1,38 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from typing import Any, Dict, Optional + + from botocore.client import BaseClient + + +class AwsCallContext: + __slots__ = ( + "service_name", + "service_id", + "service_id_hyphenized", + "operation_name", + "region_name", + "endpoint_url", + "params", + ) + + def __init__( + self, + client: "BaseClient", + operation_name: str, + params: "Any", + ) -> None: + client_meta = client.meta + service_model = client_meta.service_model + service_id = service_model.service_id + + # botocore's internal identifier, e.g. `apigateway`. + self.service_name: str = service_model.service_name + # modeled AWS service identity used in span names, e.g. `API Gateway`. + self.service_id: str = str(service_id) + self.service_id_hyphenized: str = service_id.hyphenize() + self.operation_name: str = operation_name + self.region_name: "Optional[str]" = getattr(client_meta, "region_name", None) + self.endpoint_url: "Optional[str]" = getattr(client_meta, "endpoint_url", None) + self.params: "Dict[str, Any]" = dict(params) if isinstance(params, dict) else {} diff --git a/sentry_sdk/integrations/boto3/_instrumentation.py b/sentry_sdk/integrations/boto3/_instrumentation.py new file mode 100644 index 0000000000..261f6feeba --- /dev/null +++ b/sentry_sdk/integrations/boto3/_instrumentation.py @@ -0,0 +1,337 @@ +from typing import TYPE_CHECKING +from urllib.parse import urlsplit + +from botocore.awsrequest import AWSRequest +from botocore.response import StreamingBody + +import sentry_sdk +from sentry_sdk.consts import OP, SPANDATA +from sentry_sdk.integrations.boto3 import Boto3Integration +from sentry_sdk.traces import StreamedSpan +from sentry_sdk.tracing import BAGGAGE_HEADER_NAME, Span +from sentry_sdk.tracing_utils import ( + add_http_breadcrumb, + add_sentry_baggage_to_headers, + get_url_attributes, + has_span_streaming_enabled, + should_propagate_trace, +) +from sentry_sdk.utils import ( + capture_internal_exceptions, + parse_url, +) + +if TYPE_CHECKING: + from typing import Any, Dict, Optional, Union + + from sentry_sdk._types import Attributes + from sentry_sdk.integrations.boto3._context import AwsCallContext + +_AWS_RPC_SYSTEM_NAME = "aws-api" + + +def _set_span_attributes( + span: "Union[Span, StreamedSpan]", attributes: "Attributes" +) -> None: + # streamed and legacy spans expose different attribute APIs. + if isinstance(span, StreamedSpan): + span.set_attributes(attributes) + return + + for key, value in attributes.items(): + span.set_data(key, value) + + +def _get_server_attributes(endpoint_url: "Optional[str]") -> "Attributes": + if not endpoint_url: + return {} + + default_ports = { + "http": 80, + "https": 443, + } + + try: + parsed_url = urlsplit(endpoint_url) + if parsed_url.scheme not in default_ports or not parsed_url.hostname: + return {} + + # `server.port` is only defined together with `server.address`. Infer the + # effective port when the configured HTTP(S) endpoint omits it. + # https://opentelemetry.io/docs/specs/semconv/rpc/rpc-spans/ + return { + SPANDATA.SERVER_ADDRESS: parsed_url.hostname, + SPANDATA.SERVER_PORT: parsed_url.port or default_ports[parsed_url.scheme], + } + + except (TypeError, UnicodeError, ValueError): + # Invalid client metadata must not prevent the AWS call from running. + return {} + + +def _get_client_attributes( + ctx: "AwsCallContext", +) -> "Attributes": + # The AWS SDK conventions define `rpc.service` as the modeled AWS service ID + # and `rpc.method` as the modeled operation name. Although the general RPC + # conventions now deprecate `rpc.service`, the AWS-specific convention still + # recommends both attributes and defines the span name as `Service.Operation`. + # https://opentelemetry.io/docs/specs/semconv/cloud-providers/aws-sdk/#aws-sdk-spans + attributes: "Attributes" = { + SPANDATA.RPC_METHOD: ctx.operation_name, + SPANDATA.RPC_SERVICE: ctx.service_id, + SPANDATA.RPC_SYSTEM_NAME: _AWS_RPC_SYSTEM_NAME, + } + + if ctx.region_name: + attributes[SPANDATA.CLOUD_REGION] = ctx.region_name + + attributes.update(_get_server_attributes(ctx.endpoint_url)) + return attributes + + +def _start_client_span( + ctx: "AwsCallContext", +) -> "Optional[Union[Span, StreamedSpan]]": + client = sentry_sdk.get_client() + if client.get_integration(Boto3Integration) is None: + return None + + # AWS client spans use `Service.Operation`, e.g. `DynamoDB.GetItem`. + # https://opentelemetry.io/docs/specs/semconv/cloud-providers/aws-sdk/#aws-sdk-spans + span_name = "%s.%s" % (ctx.service_id, ctx.operation_name) + attributes = _get_client_attributes(ctx) + span_op = OP.HTTP_CLIENT + span_origin = Boto3Integration.origin + + if has_span_streaming_enabled(client.options): + if sentry_sdk.traces.get_current_span() is None: + return None + + # `start_span()` evaluates `ignore_spans` against the initial attributes. + # https://opentelemetry.io/docs/specs/semconv/rpc/rpc-spans/#rpc-client-span + attributes.update( + { + SPANDATA.SENTRY_OP: span_op, + SPANDATA.SENTRY_ORIGIN: span_origin, + } + ) + return sentry_sdk.traces.start_span( + name=span_name, + attributes=attributes, + ) + + span = sentry_sdk.start_span( + name=span_name, + op=span_op, + origin=span_origin, + ) + _set_span_attributes(span, attributes) + span.set_tag("aws.service_id", ctx.service_id_hyphenized) + span.set_tag("aws.operation_name", ctx.operation_name) + return span + + +def _finish_client_span( + span: "Union[Span, StreamedSpan]", + parsed: "Dict[str, Any]", +) -> None: + span.__exit__(None, None, None) + + body = parsed.get("Body") + if not isinstance(body, StreamingBody): + return + + streaming_span: "Union[Span, StreamedSpan]" + if isinstance(span, StreamedSpan): + streaming_span = sentry_sdk.traces.start_span( + name=span.name, + parent_span=span, + attributes={ + SPANDATA.SENTRY_OP: OP.HTTP_CLIENT_STREAM, + SPANDATA.SENTRY_ORIGIN: Boto3Integration.origin, + }, + ) + else: + streaming_span = span.start_child( + op=OP.HTTP_CLIENT_STREAM, + name=span.description, + origin=Boto3Integration.origin, + ) + + orig_read = body.read + orig_close = body.close + + def sentry_streaming_body_read(*args: "Any", **kwargs: "Any") -> bytes: + try: + ret = orig_read(*args, **kwargs) + if ret: + return ret + + if isinstance(streaming_span, StreamedSpan): + streaming_span.end() + else: + streaming_span.finish() + return ret + except Exception: + if isinstance(streaming_span, StreamedSpan): + streaming_span.end() + else: + streaming_span.finish() + raise + + body.read = sentry_streaming_body_read # type: ignore + + def sentry_streaming_body_close(*args: "Any", **kwargs: "Any") -> None: + if isinstance(streaming_span, StreamedSpan): + streaming_span.end() + else: + streaming_span.finish() + orig_close(*args, **kwargs) + + body.close = sentry_streaming_body_close # type: ignore + + +def _finish_client_span_with_error( + span: "Union[Span, StreamedSpan]", + exception: "BaseException", +) -> None: + span.__exit__(type(exception), exception, exception.__traceback__) + + +def _set_request_attributes( + span: "Union[Span, StreamedSpan]", + request: "AWSRequest", +) -> None: + client = sentry_sdk.get_client() + + parsed_url = None + if request.url is not None: + with capture_internal_exceptions(): + parsed_url = parse_url(request.url, sanitize=False) + + if isinstance(span, StreamedSpan): + span.set_attributes(get_url_attributes(client, parsed_url)) + + if request.method is not None: + span.set_attribute(SPANDATA.HTTP_REQUEST_METHOD, request.method) + + return + + if parsed_url is not None: + span.set_data("aws.request.url", parsed_url.url) + span.set_data(SPANDATA.HTTP_QUERY, parsed_url.query) + span.set_data(SPANDATA.HTTP_FRAGMENT, parsed_url.fragment) + + if request.method is not None: + span.set_data(SPANDATA.HTTP_METHOD, request.method) + + +def _add_request_breadcrumb(request: "AWSRequest") -> None: + client = sentry_sdk.get_client() + + parsed_url = None + if request.url is not None: + with capture_internal_exceptions(): + parsed_url = parse_url(request.url, sanitize=False) + + breadcrumb: "dict[str, Any]" = {} + + if has_span_streaming_enabled(client.options): + breadcrumb.update(get_url_attributes(client, parsed_url)) + if request.method is not None: + breadcrumb[SPANDATA.HTTP_REQUEST_METHOD] = request.method + else: + if parsed_url is not None: + breadcrumb.update( + { + "aws.request.url": parsed_url.url, + SPANDATA.HTTP_QUERY: parsed_url.query, + SPANDATA.HTTP_FRAGMENT: parsed_url.fragment, + } + ) + + if request.method is not None: + breadcrumb[SPANDATA.HTTP_METHOD] = request.method + + add_http_breadcrumb(None, breadcrumb) + + +def _sentry_request_created( + request: "AWSRequest", operation_name: str, **kwargs: "Any" +) -> None: + """ + Enrich a single `AWSRequest` attempt. Botocore creates a + fresh `AWSRequest` on every retry. + https://github.com/boto/botocore/blob/develop/botocore/endpoint.py#L178-L202 + """ + client = sentry_sdk.get_client() + if client.get_integration(Boto3Integration) is None: + return + + with capture_internal_exceptions(): + _add_request_breadcrumb(request) + + if has_span_streaming_enabled(client.options): + span = sentry_sdk.traces.get_current_span() + else: + span = sentry_sdk.get_current_span() + if span is None: + return + + _set_request_attributes(span, request) + # each attempt has a fresh `request.context`; carry the active client span. + request.context["_sentrysdk_span"] = span + + +def _sentry_before_sign( + request: "AWSRequest", signature_version: "Any", **kwargs: "Any" +) -> None: + client = sentry_sdk.get_client() + if client.get_integration(Boto3Integration) is None: + return + + with capture_internal_exceptions(): + # presigned requests are executed later by another caller. Adding propagation + # headers here would make those headers part of the signature, requiring the caller to reproduce the same values. + if isinstance(signature_version, str) and signature_version.endswith( + ("-query", "-presign-post") + ): + return + + if request.url is None or not should_propagate_trace(client, request.url): + return + + def _replace_header(request: "AWSRequest", key: str, value: str) -> None: + """ + Botocore's `HTTPHeaders` inherits from `email.message.Message`, where: + headers["foo"] = "old" + headers["foo"] = "new" + produces two fields: {"foo": "old", "foo": "new"}. So delete existing + fields before assigning replacement. + """ + if key in request.headers: + del request.headers[key] + request.headers[key] = value + + # use span associated with this botocore request + span = request.context.get("_sentrysdk_span") + + headers = sentry_sdk.get_current_scope().iter_trace_propagation_headers( + span=span + ) + for header_name, header_value in headers: + if header_name != BAGGAGE_HEADER_NAME: + # normal headers (e.g. `sentry-trace`) are non-shared, so replace stale values + _replace_header(request, header_name, header_value) + continue + + # merge existing `baggage` values under single header + existing_values = request.headers.get_all(BAGGAGE_HEADER_NAME, []) + combined_baggage = { + BAGGAGE_HEADER_NAME: ",".join(str(value) for value in existing_values) + } + add_sentry_baggage_to_headers(combined_baggage, header_value) + _replace_header( + request, BAGGAGE_HEADER_NAME, combined_baggage[BAGGAGE_HEADER_NAME] + ) diff --git a/tests/integrations/boto3/test_client.py b/tests/integrations/boto3/test_client.py new file mode 100644 index 0000000000..6ddfd145e5 --- /dev/null +++ b/tests/integrations/boto3/test_client.py @@ -0,0 +1,400 @@ +import boto3 +import pytest +from botocore.awsrequest import AWSResponse +from botocore.config import Config +from botocore.exceptions import ClientError, EndpointConnectionError +from botocore.stub import Stubber + +import sentry_sdk +from sentry_sdk.consts import OP, SPANDATA +from sentry_sdk.integrations.boto3 import Boto3Integration +from tests.integrations.boto3.aws_mock import Body + +session = boto3.Session( # type: ignore[attr-defined] + aws_access_key_id="-", + aws_secret_access_key="-", + region_name="eu-north-1", +) + + +def test_public_api(): + assert Boto3Integration.__module__ == "sentry_sdk.integrations.boto3" + assert Boto3Integration.identifier == "boto3" + + +@pytest.fixture +def client_factory(sentry_init, monkeypatch, span_streaming): + sentry_init( + traces_sample_rate=1.0, + integrations=[Boto3Integration()], + trace_lifecycle="stream" if span_streaming else "static", + # avoid SDK's machine hostname being used as server name. + server_name="", + ) + # remove retry delay to speed up tests + monkeypatch.setattr("botocore.endpoint.time.sleep", lambda delay: None) + + def make_client(service_name="s3", attempt_count=1, **client_kwargs): + return session.client( + service_name, + config=Config( + # `total_max_attempts` includes the initial request. + retries={"total_max_attempts": attempt_count, "mode": "standard"} + ), + **client_kwargs, + ) + + return make_client + + +def _mock_responses(client, status_codes): + request_span_ids = [] + + def record_request(request, **kwargs): + span = request.context.get("_sentrysdk_span") + assert span is not None + request_span_ids.append(span.span_id) + + def respond(request, **kwargs): + # `request_created` runs before `before_send`, so use zero-based index for current + # attempt; `min(..., len(status_codes) - 1)` clamps to last status to avoid `IndexError`. + response_index = min(len(request_span_ids) - 1, len(status_codes) - 1) + return AWSResponse(request.url, status_codes[response_index], {}, Body(b"")) + + client.meta.events.register("request-created", record_request) + client.meta.events.register("before-send", respond) + return request_span_ids + + +def _capture_boto3_spans_by_op(invoke_client_method, capture_items, span_streaming): + items = capture_items() + + if span_streaming: + with sentry_sdk.traces.start_span(name="parent"): # type: ignore[attr-defined] + invoke_client_method() + + sentry_sdk.flush() + spans = [ + item.payload + for item in items + if item.type == "span" + and item.payload["attributes"].get(SPANDATA.SENTRY_ORIGIN) + == Boto3Integration.origin + ] + else: + with sentry_sdk.start_transaction(): + invoke_client_method() + + transaction = next(item.payload for item in items if item.type == "transaction") + spans = [ + span + for span in transaction["spans"] + if span["origin"] == Boto3Integration.origin + ] + + spans_by_op = {} + for span in spans: + op = ( + span["attributes"].get(SPANDATA.SENTRY_OP) if span_streaming else span["op"] + ) + spans_by_op.setdefault(op, []).append(span) + return spans_by_op + + +def _assert_span_finished(span, span_streaming): + finished_timestamp = "end_timestamp" if span_streaming else "timestamp" + assert span[finished_timestamp] is not None + + +def _assert_one_failed_span(spans, span_streaming): + assert len(spans) == 1 + assert spans[0]["status"] in ("error", "internal_error") + _assert_span_finished(spans[0], span_streaming) + + +def _capture_stubbed_client_span( + client, + method_name, + api_params, + capture_items, + span_streaming, +): + with Stubber(client) as stubber: + stubber.add_response(method_name, {}, api_params) + spans_by_op = _capture_boto3_spans_by_op( + lambda: getattr(client, method_name)(**api_params), + capture_items, + span_streaming, + ) + + client_spans = spans_by_op.get(OP.HTTP_CLIENT, []) + assert len(client_spans) == 1 + return client_spans[0] + + +def _span_attributes(span, span_streaming): + return span["attributes"] if span_streaming else span["data"] + + +@pytest.mark.parametrize( + ( + "service_name", + "method_name", + "api_params", + "span_name", + "rpc_service", + "rpc_method", + "endpoint_url", + "server_address", + "server_port", + ), + [ + ( + "s3", + "head_object", + {"Bucket": "bucket", "Key": "foo"}, + "S3.HeadObject", + "S3", + "HeadObject", + "http://localhost:4566", + "localhost", + 4566, + ), + ( + "events", + "list_event_buses", + {}, + "EventBridge.ListEventBuses", + "EventBridge", + "ListEventBuses", + None, + "events.eu-north-1.amazonaws.com", + 443, + ), + ], +) +@pytest.mark.parametrize("span_streaming", [True, False]) +def test_client_call_has_common_attributes( + capture_items, + client_factory, + span_streaming, + service_name, + method_name, + api_params, + span_name, + rpc_service, + rpc_method, + endpoint_url, + server_address, + server_port, +): + client = client_factory(service_name=service_name, endpoint_url=endpoint_url) + span = _capture_stubbed_client_span( + client, + method_name, + api_params, + capture_items, + span_streaming, + ) + attributes = _span_attributes(span, span_streaming) + + assert span["name" if span_streaming else "description"] == span_name + assert attributes[SPANDATA.RPC_SERVICE] == rpc_service + assert attributes[SPANDATA.RPC_METHOD] == rpc_method + assert attributes[SPANDATA.RPC_SYSTEM_NAME] == "aws-api" + assert attributes[SPANDATA.CLOUD_REGION] == "eu-north-1" + assert attributes[SPANDATA.SERVER_ADDRESS] == server_address + assert attributes[SPANDATA.SERVER_PORT] == server_port + + +def test_client_call_attributes_are_available_at_span_creation( + sentry_init, capture_items +): + # attribute-based filtering happens during span creation, at the same boundary + # where creation attributes are made available for sampling decisions. + sentry_init( + traces_sample_rate=1.0, + integrations=[Boto3Integration()], + trace_lifecycle="stream", + ignore_spans=[ + { + "attributes": { + SPANDATA.RPC_METHOD: "HeadObject", + SPANDATA.RPC_SERVICE: "S3", + SPANDATA.RPC_SYSTEM_NAME: "aws-api", + SPANDATA.SERVER_ADDRESS: "s3.eu-north-1.amazonaws.com", + SPANDATA.SERVER_PORT: 443, + } + } + ], + ) + client = session.client("s3") + items = capture_items("span") + + with Stubber(client) as stubber: + stubber.add_response("head_object", {}, {"Bucket": "bucket", "Key": "foo"}) + with sentry_sdk.traces.start_span(name="parent"): + client.head_object(Bucket="bucket", Key="foo") + + sentry_sdk.flush() + client_spans = [ + item.payload + for item in items + if item.payload["attributes"].get(SPANDATA.SENTRY_ORIGIN) + == Boto3Integration.origin + ] + assert client_spans == [] + + +def test_client_call_omits_missing_region( + sentry_init, + capture_items, + monkeypatch, +): + sentry_init( + traces_sample_rate=1.0, + integrations=[Boto3Integration()], + trace_lifecycle="stream", + server_name="", + ) + client = session.client("s3") + monkeypatch.setattr(client.meta.config, "region_name", None) + + span = _capture_stubbed_client_span( + client, + "head_object", + {"Bucket": "bucket", "Key": "foo"}, + capture_items, + span_streaming=True, + ) + + assert SPANDATA.CLOUD_REGION not in span["attributes"] + + +@pytest.mark.parametrize("span_streaming", [True, False]) +def test_retry_attempts_share_one_client_span( + capture_items, + client_factory, + span_streaming, +): + attempt_count = 3 + client = client_factory(attempt_count=attempt_count) + request_span_ids = _mock_responses(client, [500] * (attempt_count - 1) + [200]) + + spans_by_op = _capture_boto3_spans_by_op( + lambda: client.head_object(Bucket="bucket", Key="foo"), + capture_items, + span_streaming, + ) + client_spans = spans_by_op.get(OP.HTTP_CLIENT, []) + + assert len(request_span_ids) == attempt_count + # all `AWSRequest` instances created during retries reference the same client span. + assert len(set(request_span_ids)) == 1 + assert len(client_spans) == 1 + + +@pytest.mark.parametrize("span_streaming", [True, False]) +def test_retries_exhausted_has_one_failed_client_span( + capture_items, + client_factory, + span_streaming, +): + client = client_factory(attempt_count=2) + request_span_ids = _mock_responses(client, [500]) + + def attempt_failed_head_object_call(): + with pytest.raises(ClientError): + client.head_object(Bucket="bucket", Key="foo.pdf") + + spans_by_op = _capture_boto3_spans_by_op( + attempt_failed_head_object_call, capture_items, span_streaming + ) + client_spans = spans_by_op.get(OP.HTTP_CLIENT, []) + + assert len(request_span_ids) == 2 + assert len(set(request_span_ids)) == 1 + _assert_one_failed_span(client_spans, span_streaming) + + +@pytest.mark.parametrize( + "event_name", + [ + pytest.param("before-parameter-build"), + pytest.param("before-send"), + ], +) +@pytest.mark.parametrize("span_streaming", [True, False]) +def test_client_call_exception_is_unchanged_and_finishes_span( + capture_items, + client_factory, + span_streaming, + event_name, +): + client = client_factory() + if event_name == "before-send": + original_exception = EndpointConnectionError( + endpoint_url="https://s3.eu-north-1.amazonaws.com" + ) + else: + original_exception = ValueError("parameter processing failed") + + def raise_original_exception(**kwargs): + raise original_exception + + client.meta.events.register(event_name, raise_original_exception) + + def invoke_failing_client_method(): + with pytest.raises(type(original_exception)) as exc_info: + client.head_object(Bucket="bucket", Key="foo") + assert exc_info.value is original_exception + + spans_by_op = _capture_boto3_spans_by_op( + invoke_failing_client_method, capture_items, span_streaming + ) + client_spans = spans_by_op.get(OP.HTTP_CLIENT, []) + _assert_one_failed_span(client_spans, span_streaming) + + +@pytest.mark.parametrize("span_streaming", [True, False]) +def test_streaming_body_read_failure_finishes_stream_span( + capture_items, + client_factory, + span_streaming, +): + client = client_factory() + original_exception = OSError("stream read failed") + + class _FailingBody(Body): + def __init__(self, exception): + super().__init__(b"") + self._exception = exception + + def read(self, *args, **kwargs): + raise self._exception + + def respond(request, **kwargs): + return AWSResponse( + request.url, + 200, + {"content-length": "1"}, + _FailingBody(original_exception), + ) + + client.meta.events.register("before-send", respond) + + def invoke_client_method_and_read_body(): + body = client.get_object(Bucket="bucket", Key="foo")["Body"] + with pytest.raises(OSError) as exc_info: + body.read() + assert exc_info.value is original_exception + + spans_by_op = _capture_boto3_spans_by_op( + invoke_client_method_and_read_body, capture_items, span_streaming + ) + client_spans = spans_by_op.get(OP.HTTP_CLIENT, []) + stream_spans = spans_by_op.get(OP.HTTP_CLIENT_STREAM, []) + + assert len(client_spans) == 1 + assert len(stream_spans) == 1 + _assert_span_finished(stream_spans[0], span_streaming) diff --git a/tests/integrations/boto3/test_s3.py b/tests/integrations/boto3/test_s3.py index 9e6b296596..c687dcf471 100644 --- a/tests/integrations/boto3/test_s3.py +++ b/tests/integrations/boto3/test_s3.py @@ -53,7 +53,7 @@ def test_basic( assert len(spans) == 2 span = spans[0] assert span["attributes"]["sentry.op"] == "http.client" - assert span["name"] == "aws.s3.ListObjects" + assert span["name"] == "S3.ListObjects" else: events = capture_events() @@ -71,7 +71,7 @@ def test_basic( assert len(event["spans"]) == 1 (span,) = event["spans"] assert span["op"] == "http.client" - assert span["description"] == "aws.s3.ListObjects" + assert span["description"] == "S3.ListObjects" @pytest.mark.parametrize("send_default_pii", [True, False]) @@ -112,11 +112,12 @@ def test_streaming( span1 = spans[0] assert span1["attributes"]["sentry.op"] == "http.client" - assert span1["name"] == "aws.s3.GetObject" + assert span1["name"] == "S3.GetObject" expected_attrs = { "http.request.method": "GET", - "rpc.method": "S3/GetObject", + "rpc.method": "GetObject", + "rpc.service": "S3", "sentry.environment": "production", "sentry.op": "http.client", "sentry.origin": "auto.http.boto3", @@ -140,7 +141,7 @@ def test_streaming( span2 = spans[1] assert span2["attributes"]["sentry.op"] == "http.client.stream" - assert span2["name"] == "aws.s3.GetObject" + assert span2["name"] == "S3.GetObject" assert span2["parent_span_id"] == span1["span_id"] else: events = capture_events() @@ -161,7 +162,7 @@ def test_streaming( span1 = event["spans"][0] assert span1["op"] == "http.client" - assert span1["description"] == "aws.s3.GetObject" + assert span1["description"] == "S3.GetObject" assert span1["data"] == ApproxDict( { "http.method": "GET", @@ -173,7 +174,7 @@ def test_streaming( span2 = event["spans"][1] assert span2["op"] == "http.client.stream" - assert span2["description"] == "aws.s3.GetObject" + assert span2["description"] == "S3.GetObject" assert span2["parent_span_id"] == span1["span_id"] @@ -253,7 +254,7 @@ def test_omit_url_data_if_parsing_fails( items = capture_items("span") with mock.patch( - "sentry_sdk.integrations.boto3.parse_url", + "sentry_sdk.integrations.boto3._instrumentation.parse_url", side_effect=ValueError, ): with sentry_sdk.traces.start_span( @@ -272,7 +273,8 @@ def test_omit_url_data_if_parsing_fails( assert spans[0]["attributes"] == ApproxDict( { "http.request.method": "GET", - "rpc.method": "S3/ListObjects", + "rpc.method": "ListObjects", + "rpc.service": "S3", "sentry.environment": "production", "sentry.op": "http.client", "sentry.origin": "auto.http.boto3", @@ -294,7 +296,7 @@ def test_omit_url_data_if_parsing_fails( events = capture_events() with mock.patch( - "sentry_sdk.integrations.boto3.parse_url", + "sentry_sdk.integrations.boto3._instrumentation.parse_url", side_effect=ValueError, ): with sentry_sdk.start_transaction() as transaction, MockResponse(