def use_span(self, span: trace_api.Span, end_on_exit: bool = False) -> Iterator[trace_api.Span]: """See `opentelemetry.trace.Tracer.use_span`.""" try: span_snapshot = self.source.get_current_span() self.source._current_span_slot.set( # pylint:disable=protected-access span) try: yield span finally: self.source._current_span_slot.set( # pylint:disable=protected-access span_snapshot) except Exception as error: # pylint: disable=broad-except if (span.status is None and span._set_status_on_exception # pylint:disable=protected-access # noqa ): span.set_status( Status( canonical_code=StatusCanonicalCode.UNKNOWN, description="{}: {}".format( type(error).__name__, error), )) raise finally: if end_on_exit: span.end()
def _apply_response(span: Span, response: urllib3.response.HTTPResponse) -> None: if not span.is_recording(): return span.set_attribute("http.status_code", response.status) span.set_attribute("http.status_text", response.reason) span.set_status(Status(http_status_to_status_code(response.status)))
def use_span(self, span: trace_api.Span, end_on_exit: bool = False) -> Iterator[trace_api.Span]: try: token = context_api.attach(context_api.set_value(SPAN_KEY, span)) try: yield span finally: context_api.detach(token) except Exception as error: # pylint: disable=broad-except if (isinstance(span, Span) and span.status is None and span._set_status_on_exception # pylint:disable=protected-access # noqa ): span.set_status( Status( canonical_code=StatusCanonicalCode.UNKNOWN, description="{}: {}".format( type(error).__name__, error), )) raise finally: if end_on_exit: span.end()
def response_hook( span: Span, params: typing.Union[ aiohttp.TraceRequestEndParams, aiohttp.TraceRequestExceptionParams, ], ): span.set_attribute("response_hook_attr", "value")
def _set_attributes_from_cursor(span: trace.Span, vendor, cursor): """Attempt to set db connection attributes by introspecting the cursor.""" if vendor == "postgres": # pylint: disable=import-outside-toplevel from psycopg2.extensions import parse_dsn if hasattr(cursor, "connection") and hasattr(cursor.connection, "dsn"): dsn = getattr(cursor.connection, "dsn", None) if dsn: data = parse_dsn(dsn) span.set_attribute(_DB, data.get("dbname")) span.set_attribute(_HOST, data.get("host")) span.set_attribute(_PORT, int(data.get("port")))
def use_span(self, span: trace_api.Span, end_on_exit: bool = False) -> Iterator[trace_api.Span]: """See `opentelemetry.trace.Tracer.use_span`.""" try: span_snapshot = self._current_span_slot.get() self._current_span_slot.set(span) try: yield span finally: self._current_span_slot.set(span_snapshot) finally: if end_on_exit: span.end()
def _encode_span(self, span: Span, encoded_local_endpoint: Dict) -> Dict: context = span.get_span_context() encoded_span = { "traceId": self._encode_trace_id(context.trace_id), "id": self._encode_span_id(context.span_id), "name": span.name, "timestamp": self._nsec_to_usec_round(span.start_time), "duration": self._nsec_to_usec_round(span.end_time - span.start_time), } encoded_annotations = self._extract_annotations_from_events( span.events) if encoded_annotations is not None: for annotation in encoded_annotations: annotation["endpoint"] = encoded_local_endpoint encoded_span["annotations"] = encoded_annotations binary_annotations = self._extract_binary_annotations( span, encoded_local_endpoint) if binary_annotations: encoded_span["binaryAnnotations"] = binary_annotations debug = self._encode_debug(context) if debug: encoded_span["debug"] = debug parent_id = self._get_parent_id(span.parent) if parent_id is not None: encoded_span["parentId"] = self._encode_span_id(parent_id) return encoded_span
def _encode_span( self, span: Span, encoded_local_endpoint: zipkin_pb2.Endpoint ) -> zipkin_pb2.Span: context = span.get_span_context() # pylint: disable=no-member encoded_span = zipkin_pb2.Span( trace_id=self._encode_trace_id(context.trace_id), id=self._encode_span_id(context.span_id), name=span.name, timestamp=self._nsec_to_usec_round(span.start_time), duration=self._nsec_to_usec_round(span.end_time - span.start_time), local_endpoint=encoded_local_endpoint, kind=self.SPAN_KIND_MAP[span.kind], ) tags = self._extract_tags_from_span(span) if tags: encoded_span.tags.update(tags) annotations = self._encode_annotations(span.events) if annotations: encoded_span.annotations.extend(annotations) debug = self._encode_debug(context) if debug: encoded_span.debug = debug parent_id = self._get_parent_id(span.parent) if parent_id is not None: encoded_span.parent_id = self._encode_span_id(parent_id) return encoded_span
def use_span(self, span: trace_api.Span, end_on_exit: bool = False) -> Iterator[trace_api.Span]: """See `opentelemetry.trace.Tracer.use_span`.""" try: span_snapshot = self.source.get_current_span() self.source._current_span_slot.set( # pylint:disable=protected-access span) try: yield span finally: self.source._current_span_slot.set( # pylint:disable=protected-access span_snapshot) finally: if end_on_exit: span.end()
def _encode_span(self, span: Span, encoded_local_endpoint: Dict) -> Dict: context = span.get_span_context() encoded_span = { "traceId": self._encode_trace_id(context.trace_id), "id": self._encode_span_id(context.span_id), "name": span.name, "timestamp": self._nsec_to_usec_round(span.start_time), "duration": self._nsec_to_usec_round( span.end_time - span.start_time ), "localEndpoint": encoded_local_endpoint, "kind": self.SPAN_KIND_MAP[span.kind], } tags = self._extract_tags_from_span(span) if tags: encoded_span["tags"] = tags annotations = self._extract_annotations_from_events(span.events) if annotations: encoded_span["annotations"] = annotations debug = self._encode_debug(context) if debug: encoded_span["debug"] = debug parent_id = self._get_parent_id(span.parent) if parent_id is not None: encoded_span["parentId"] = self._encode_span_id(parent_id) return encoded_span
def _set_attributes_from_url(span: trace.Span, url): """Set connection tags from the url. return true if successful.""" if span.is_recording(): if url.host: span.set_attribute(_HOST, url.host) if url.port: span.set_attribute(_PORT, url.port) if url.database: span.set_attribute(_DB, url.database) if url.username: span.set_attribute(_USER, url.username) return bool(url.host)
def use_span( self, span: trace_api.Span, end_on_exit: bool = False, ) -> Iterator[trace_api.Span]: try: token = context_api.attach(context_api.set_value(SPAN_KEY, span)) try: yield span finally: context_api.detach(token) except Exception as exc: # pylint: disable=broad-except # Record the exception as an event if isinstance(span, Span) and span.is_recording(): # pylint:disable=protected-access if span._record_exception: span.record_exception(exc) # Records status if use_span is used # i.e. with tracer.start_as_current_span() as span: if (span.status.status_code is StatusCode.UNSET and span._set_status_on_exception): span.set_status( Status( status_code=StatusCode.ERROR, description="{}: {}".format( type(exc).__name__, exc), )) raise finally: if end_on_exit: span.end()
def add_tags(self, span: Span, info: GraphQLResolveInfo, kwargs: Dict[str, Any]): graphql_path = ".".join(map(str, get_path_from_info(info))) span.set_attribute("component", "graphql") span.set_attribute("graphql.parentType", info.parent_type.name) span.set_attribute("graphql.path", graphql_path) if kwargs: filtered_kwargs = self.filter_resolver_args(kwargs, info) for kwarg, value in filtered_kwargs.items(): span.set_attribute(f"graphql.param.{kwarg}", value)
def request_hook(self, span: Span, request): """django request hook before request is processed by app""" try: body = request.body span.update_name(f"{request.method} {span.name}") self.generic_request_handler(request.headers, body, span) full_url = request.build_absolute_uri() block_result = Registry().apply_filters(span, full_url, request.headers, body, TYPE_HTTP) if block_result: logger.debug('should block evaluated to true, aborting with 403') # since middleware chain is halted the status code is not set when blocked span.set_attribute('http.status_code', 403) span.end() raise PermissionDenied except PermissionDenied as permission_denied: raise permission_denied except Exception as err: # pylint:disable=W0703 logger.debug(constants.INST_RUNTIME_EXCEPTION_MSSG, 'django request hook', err, traceback.format_exc())
def use_span( self, span: trace_api.Span, end_on_exit: bool = False, record_exception: bool = True, ) -> Iterator[trace_api.Span]: try: token = context_api.attach(context_api.set_value(SPAN_KEY, span)) try: yield span finally: context_api.detach(token) except Exception as error: # pylint: disable=broad-except # pylint:disable=protected-access if isinstance(span, Span): if record_exception: span.record_exception(error) if span.status is None and span._set_status_on_exception: span.set_status( Status( canonical_code=getattr( error, EXCEPTION_STATUS_FIELD, StatusCanonicalCode.UNKNOWN, ), description="{}: {}".format( type(error).__name__, error), )) raise finally: if end_on_exit: span.end()
def inject( cls, span: trace.Span, set_in_carrier: httptextformat.Setter[_T], carrier: _T, ) -> None: context = span.get_context() if context == trace.INVALID_SPAN_CONTEXT: return traceparent_string = "00-{:032x}-{:016x}-{:02x}".format( context.trace_id, context.span_id, context.trace_options) set_in_carrier(carrier, cls._TRACEPARENT_HEADER_NAME, traceparent_string) if context.trace_state: tracestate_string = _format_tracestate(context.trace_state) set_in_carrier(carrier, cls._TRACESTATE_HEADER_NAME, tracestate_string)
def use_span( self, span: trace_api.Span, end_on_exit: bool = False, record_exception: bool = True, ) -> Iterator[trace_api.Span]: try: token = context_api.attach(context_api.set_value(SPAN_KEY, span)) try: yield span finally: context_api.detach(token) except Exception as error: # pylint: disable=broad-except # pylint:disable=protected-access if isinstance(span, Span): if record_exception: span.record_exception(error) # Records status if use_span is used # i.e. with tracer.start_as_current_span() as span: if ( span.status.status_code is StatusCode.UNSET and span._set_status_on_exception ): span.set_status( Status( status_code=getattr( error, EXCEPTION_STATUS_FIELD, StatusCode.ERROR, ), description="{}: {}".format( type(error).__name__, error ), ) ) raise finally: if end_on_exit: span.end()
def _populate_span(self, span: trace_api.Span, *args: typing.Tuple[typing.Any, typing.Any]): if not span.is_recording(): return statement = args[0] if args else "" span.set_attribute("component", self._db_api_integration.database_component) span.set_attribute("db.type", self._db_api_integration.database_type) span.set_attribute("db.instance", self._db_api_integration.database) span.set_attribute("db.statement", statement) for ( attribute_key, attribute_value, ) in self._db_api_integration.span_attributes.items(): span.set_attribute(attribute_key, attribute_value) if len(args) > 1: span.set_attribute("db.statement.parameters", str(args[1]))
def request_hook(span: Span, params: aiohttp.TraceRequestStartParams): span.update_name("{} - {}".format(params.method, params.url.path))
def _apply_response(span: Span, response: urllib3.response.HTTPResponse): if not span.is_recording(): return span.set_attribute(SpanAttributes.HTTP_STATUS_CODE, response.status) span.set_status(Status(http_status_to_status_code(response.status)))
def _enrich_span( span: Span, queue_name: str, queue_url: str, conversation_id: Optional[str] = None, operation: Optional[MessagingOperationValues] = None, message_id: Optional[str] = None, ) -> None: if not span.is_recording(): return span.set_attribute(SpanAttributes.MESSAGING_SYSTEM, "aws.sqs") span.set_attribute(SpanAttributes.MESSAGING_DESTINATION, queue_name) span.set_attribute( SpanAttributes.MESSAGING_DESTINATION_KIND, MessagingDestinationKindValues.QUEUE.value, ) span.set_attribute(SpanAttributes.MESSAGING_URL, queue_url) if operation: span.set_attribute(SpanAttributes.MESSAGING_OPERATION, operation.value) if conversation_id: span.set_attribute(SpanAttributes.MESSAGING_CONVERSATION_ID, conversation_id) if message_id: span.set_attribute(SpanAttributes.MESSAGING_MESSAGE_ID, message_id)
def _populate_span(self, span: trace_api.Span, cursor, *args: typing.Tuple[typing.Any, typing.Any]): if not span.is_recording(): return statement = self.get_statement(cursor, args) span.set_attribute("db.system", self._db_api_integration.database_system) span.set_attribute("db.name", self._db_api_integration.database) span.set_attribute("db.statement", statement) for ( attribute_key, attribute_value, ) in self._db_api_integration.span_attributes.items(): span.set_attribute(attribute_key, attribute_value) if self._db_api_integration.capture_parameters and len(args) > 1: span.set_attribute("db.statement.parameters", str(args[1]))
def request_hook(span: Span, params: aiohttp.TraceRequestStartParams): span.update_name(f"{params.method} - {params.url.path}")