|
| 1 | +# Copyright The OpenTelemetry Authors |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import logging |
| 16 | +from datetime import datetime |
| 17 | +from typing import TYPE_CHECKING |
| 18 | + |
| 19 | +import wrapt |
| 20 | +from opencensus.trace.base_span import BaseSpan |
| 21 | +from opencensus.trace.span import SpanKind |
| 22 | +from opencensus.trace.status import Status |
| 23 | +from opencensus.trace.time_event import MessageEvent |
| 24 | + |
| 25 | +from opentelemetry import context, trace |
| 26 | + |
| 27 | +if TYPE_CHECKING: |
| 28 | + from opentelemetry.shim.opencensus._shim_tracer import ShimTracer |
| 29 | + |
| 30 | +_logger = logging.getLogger(__name__) |
| 31 | + |
| 32 | +# Copied from Java |
| 33 | +# https://github.com/open-telemetry/opentelemetry-java/blob/0d3a04669e51b33ea47b29399a7af00012d25ccb/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/SpanConverter.java#L24-L27 |
| 34 | +_MESSAGE_EVENT_ATTRIBUTE_KEY_TYPE = "message.event.type" |
| 35 | +_MESSAGE_EVENT_ATTRIBUTE_KEY_SIZE_UNCOMPRESSED = ( |
| 36 | + "message.event.size.uncompressed" |
| 37 | +) |
| 38 | +_MESSAGE_EVENT_ATTRIBUTE_KEY_SIZE_COMPRESSED = "message.event.size.compressed" |
| 39 | + |
| 40 | +_MESSAGE_EVENT_TYPE_STR_MAPPING = { |
| 41 | + 0: "TYPE_UNSPECIFIED", |
| 42 | + 1: "SENT", |
| 43 | + 2: "RECEIVED", |
| 44 | +} |
| 45 | + |
| 46 | + |
| 47 | +def _opencensus_time_to_nanos(timestamp: str) -> int: |
| 48 | + """Converts an OpenCensus formatted time string (ISO 8601 with Z) to time.time_ns style |
| 49 | + unix timestamp |
| 50 | + """ |
| 51 | + # format taken from |
| 52 | + # https://github.com/census-instrumentation/opencensus-python/blob/c38c71b9285e71de94d0185ff3c5bf65ee163345/opencensus/common/utils/__init__.py#L76 |
| 53 | + # |
| 54 | + # datetime.fromisoformat() does not work with the added "Z" until python 3.11 |
| 55 | + seconds_float = datetime.strptime( |
| 56 | + timestamp, "%Y-%m-%dT%H:%M:%S.%fZ" |
| 57 | + ).timestamp() |
| 58 | + return round(seconds_float * 1e9) |
| 59 | + |
| 60 | + |
| 61 | +# pylint: disable=abstract-method |
| 62 | +class ShimSpan(wrapt.ObjectProxy): |
| 63 | + def __init__( |
| 64 | + self, |
| 65 | + wrapped: BaseSpan, |
| 66 | + *, |
| 67 | + otel_span: trace.Span, |
| 68 | + shim_tracer: "ShimTracer", |
| 69 | + ) -> None: |
| 70 | + super().__init__(wrapped) |
| 71 | + self._self_otel_span = otel_span |
| 72 | + self._self_shim_tracer = shim_tracer |
| 73 | + self._self_token: object = None |
| 74 | + |
| 75 | + # Set a few values for BlankSpan members (they appear to be part of the "public" API |
| 76 | + # even though they are not documented in BaseSpan). Some instrumentations may use these |
| 77 | + # and not expect an AttributeError to be raised. Set values from OTel where possible |
| 78 | + # and let ObjectProxy defer to the wrapped BlankSpan otherwise. |
| 79 | + sc = self._self_otel_span.get_span_context() |
| 80 | + self.same_process_as_parent_span = not sc.is_remote |
| 81 | + self.span_id = sc.span_id |
| 82 | + |
| 83 | + def span(self, name="child_span"): |
| 84 | + return self._self_shim_tracer.start_span(name=name) |
| 85 | + |
| 86 | + def add_attribute(self, attribute_key, attribute_value): |
| 87 | + self._self_otel_span.set_attribute(attribute_key, attribute_value) |
| 88 | + |
| 89 | + def add_annotation(self, description, **attrs): |
| 90 | + self._self_otel_span.add_event(description, attrs) |
| 91 | + |
| 92 | + def add_message_event(self, message_event: MessageEvent): |
| 93 | + attrs = { |
| 94 | + _MESSAGE_EVENT_ATTRIBUTE_KEY_TYPE: _MESSAGE_EVENT_TYPE_STR_MAPPING[ |
| 95 | + message_event.type |
| 96 | + ], |
| 97 | + } |
| 98 | + if message_event.uncompressed_size_bytes is not None: |
| 99 | + attrs[ |
| 100 | + _MESSAGE_EVENT_ATTRIBUTE_KEY_SIZE_UNCOMPRESSED |
| 101 | + ] = message_event.uncompressed_size_bytes |
| 102 | + if message_event.compressed_size_bytes is not None: |
| 103 | + attrs[ |
| 104 | + _MESSAGE_EVENT_ATTRIBUTE_KEY_SIZE_COMPRESSED |
| 105 | + ] = message_event.compressed_size_bytes |
| 106 | + |
| 107 | + timestamp = _opencensus_time_to_nanos(message_event.timestamp) |
| 108 | + self._self_otel_span.add_event( |
| 109 | + str(message_event.id), |
| 110 | + attrs, |
| 111 | + timestamp=timestamp, |
| 112 | + ) |
| 113 | + |
| 114 | + # pylint: disable=no-self-use |
| 115 | + def add_link(self, link): |
| 116 | + """span links do not work with the shim because the OpenCensus Tracer does not accept |
| 117 | + links in start_span(). Same issue applies to SpanKind. Also see: |
| 118 | + https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/compatibility/opencensus.md#known-incompatibilities |
| 119 | + """ |
| 120 | + _logger.warning( |
| 121 | + "OpenTelemetry does not support links added after a span is created." |
| 122 | + ) |
| 123 | + |
| 124 | + @property |
| 125 | + def span_kind(self): |
| 126 | + """Setting span_kind does not work with the shim because the OpenCensus Tracer does not |
| 127 | + accept the param in start_span() and there's no way to set OTel span kind after |
| 128 | + start_span(). |
| 129 | + """ |
| 130 | + return SpanKind.UNSPECIFIED |
| 131 | + |
| 132 | + @span_kind.setter |
| 133 | + def span_kind(self, value): |
| 134 | + _logger.warning( |
| 135 | + "OpenTelemetry does not support setting span kind after a span is created." |
| 136 | + ) |
| 137 | + |
| 138 | + def set_status(self, status: Status): |
| 139 | + self._self_otel_span.set_status( |
| 140 | + trace.StatusCode.OK if status.is_ok else trace.StatusCode.ERROR, |
| 141 | + status.description, |
| 142 | + ) |
| 143 | + |
| 144 | + def finish(self): |
| 145 | + """Note this method does not pop the span from current context. Use Tracer.end_span() |
| 146 | + or a `with span: ...` statement (contextmanager) to do that. |
| 147 | + """ |
| 148 | + self._self_otel_span.end() |
| 149 | + |
| 150 | + def __enter__(self): |
| 151 | + self._self_otel_span.__enter__() |
| 152 | + return self |
| 153 | + |
| 154 | + # pylint: disable=arguments-differ |
| 155 | + def __exit__(self, exception_type, exception_value, traceback): |
| 156 | + self._self_otel_span.__exit__( |
| 157 | + exception_type, exception_value, traceback |
| 158 | + ) |
| 159 | + # OpenCensus Span.__exit__() calls Tracer.end_span() |
| 160 | + # https://github.com/census-instrumentation/opencensus-python/blob/2e08df591b507612b3968be8c2538dedbf8fab37/opencensus/trace/span.py#L390 |
| 161 | + # but that would cause the OTel span to be ended twice. Instead just detach it from |
| 162 | + # context directly. |
| 163 | + context.detach(self._self_token) |
0 commit comments