span.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. # Copyright The OpenTelemetry Authors
  2. # SPDX-License-Identifier: Apache-2.0
  3. from __future__ import annotations
  4. import abc
  5. import logging
  6. import re
  7. import types as python_types
  8. import typing
  9. import warnings
  10. from collections.abc import Iterator, Mapping, Sequence
  11. from opentelemetry.trace.status import Status, StatusCode
  12. from opentelemetry.util import types
  13. # The key MUST begin with a lowercase letter or a digit,
  14. # and can only contain lowercase letters (a-z), digits (0-9),
  15. # underscores (_), dashes (-), asterisks (*), and forward slashes (/).
  16. # For multi-tenant vendor scenarios, an at sign (@) can be used to
  17. # prefix the vendor name. Vendors SHOULD set the tenant ID
  18. # at the beginning of the key.
  19. # key = ( lcalpha ) 0*255( lcalpha / DIGIT / "_" / "-"/ "*" / "/" )
  20. # key = ( lcalpha / DIGIT ) 0*240( lcalpha / DIGIT / "_" / "-"/ "*" / "/" ) "@" lcalpha 0*13( lcalpha / DIGIT / "_" / "-"/ "*" / "/" )
  21. # lcalpha = %x61-7A ; a-z
  22. _KEY_FORMAT = (
  23. r"[a-z][_0-9a-z\-\*\/]{0,255}|"
  24. r"[a-z0-9][_0-9a-z\-\*\/]{0,240}@[a-z][_0-9a-z\-\*\/]{0,13}"
  25. )
  26. _KEY_PATTERN = re.compile(_KEY_FORMAT)
  27. # The value is an opaque string containing up to 256 printable
  28. # ASCII [RFC0020] characters (i.e., the range 0x20 to 0x7E)
  29. # except comma (,) and (=).
  30. # value = 0*255(chr) nblk-chr
  31. # nblk-chr = %x21-2B / %x2D-3C / %x3E-7E
  32. # chr = %x20 / nblk-chr
  33. _VALUE_FORMAT = (
  34. r"[\x20-\x2b\x2d-\x3c\x3e-\x7e]{0,255}[\x21-\x2b\x2d-\x3c\x3e-\x7e]"
  35. )
  36. _VALUE_PATTERN = re.compile(_VALUE_FORMAT)
  37. _TRACECONTEXT_MAXIMUM_TRACESTATE_KEYS = 32
  38. _delimiter_pattern = re.compile(r"[ \t]*,[ \t]*")
  39. _member_pattern = re.compile(f"({_KEY_FORMAT})(=)({_VALUE_FORMAT})[ \t]*")
  40. _logger = logging.getLogger(__name__)
  41. def _is_valid_pair(key: str, value: str) -> bool:
  42. return (
  43. isinstance(key, str)
  44. and _KEY_PATTERN.fullmatch(key) is not None
  45. and isinstance(value, str)
  46. and _VALUE_PATTERN.fullmatch(value) is not None
  47. )
  48. class Span(abc.ABC):
  49. """A span represents a single operation within a trace."""
  50. @abc.abstractmethod
  51. def end(self, end_time: int | None = None) -> None:
  52. """Sets the current time as the span's end time.
  53. The span's end time is the wall time at which the operation finished.
  54. Only the first call to `end` should modify the span, and
  55. implementations are free to ignore or raise on further calls.
  56. """
  57. @abc.abstractmethod
  58. def get_span_context(self) -> SpanContext:
  59. """Gets the span's SpanContext.
  60. Get an immutable, serializable identifier for this span that can be
  61. used to create new child spans.
  62. Returns:
  63. A :class:`opentelemetry.trace.SpanContext` with a copy of this span's immutable state.
  64. """
  65. @abc.abstractmethod
  66. def set_attributes(
  67. self, attributes: Mapping[str, types.AttributeValue]
  68. ) -> None:
  69. """Sets Attributes.
  70. Sets Attributes with the key and value passed as arguments dict.
  71. Note: The behavior of `None` value attributes is undefined, and hence
  72. strongly discouraged. It is also preferred to set attributes at span
  73. creation, instead of calling this method later since samplers can only
  74. consider information already present during span creation.
  75. """
  76. @abc.abstractmethod
  77. def set_attribute(self, key: str, value: types.AttributeValue) -> None:
  78. """Sets an Attribute.
  79. Sets a single Attribute with the key and value passed as arguments.
  80. Note: The behavior of `None` value attributes is undefined, and hence
  81. strongly discouraged. It is also preferred to set attributes at span
  82. creation, instead of calling this method later since samplers can only
  83. consider information already present during span creation.
  84. """
  85. @abc.abstractmethod
  86. def add_event(
  87. self,
  88. name: str,
  89. attributes: types.Attributes = None,
  90. timestamp: int | None = None,
  91. ) -> None:
  92. """Adds an `Event`.
  93. Adds a single `Event` with the name and, optionally, a timestamp and
  94. attributes passed as arguments. Implementations should generate a
  95. timestamp if the `timestamp` argument is omitted.
  96. """
  97. def add_link( # pylint: disable=no-self-use
  98. self,
  99. context: SpanContext,
  100. attributes: types.Attributes = None,
  101. ) -> None:
  102. """Adds a `Link`.
  103. Adds a single `Link` with the `SpanContext` of the span to link to and,
  104. optionally, attributes passed as arguments. Implementations may ignore
  105. calls with an invalid span context if both attributes and TraceState
  106. are empty.
  107. Note: It is preferred to add links at span creation, instead of calling
  108. this method later since samplers can only consider information already
  109. present during span creation.
  110. """
  111. warnings.warn(
  112. "Span.add_link() not implemented and will be a no-op. "
  113. "Use opentelemetry-sdk >= 1.23 to add links after span creation"
  114. )
  115. @abc.abstractmethod
  116. def update_name(self, name: str) -> None:
  117. """Updates the `Span` name.
  118. This will override the name provided via :func:`opentelemetry.trace.Tracer.start_span`.
  119. Upon this update, any sampling behavior based on Span name will depend
  120. on the implementation.
  121. """
  122. @abc.abstractmethod
  123. def is_recording(self) -> bool:
  124. """Returns whether this span will be recorded.
  125. Returns true if this Span is active and recording information like
  126. events with the add_event operation and attributes using set_attribute.
  127. """
  128. @abc.abstractmethod
  129. def set_status(
  130. self,
  131. status: Status | StatusCode,
  132. description: str | None = None,
  133. ) -> None:
  134. """Sets the Status of the Span. If used, this will override the default
  135. Span status.
  136. """
  137. @abc.abstractmethod
  138. def record_exception(
  139. self,
  140. exception: BaseException,
  141. attributes: types.Attributes = None,
  142. timestamp: int | None = None,
  143. escaped: bool = False,
  144. ) -> None:
  145. """Records an exception as a span event."""
  146. def __enter__(self) -> Span:
  147. """Invoked when `Span` is used as a context manager.
  148. Returns the `Span` itself.
  149. """
  150. return self
  151. def __exit__(
  152. self,
  153. exc_type: type[BaseException] | None,
  154. exc_val: BaseException | None,
  155. exc_tb: python_types.TracebackType | None,
  156. ) -> None:
  157. """Ends context manager and calls `end` on the `Span`."""
  158. self.end()
  159. class TraceFlags(int):
  160. """A bitmask that represents options specific to the trace.
  161. Supported flags:
  162. - "sampled" (``0x01``): Indicates the trace may have been sampled upstream.
  163. - "random-trace-id" (``0x02``): Indicates the trace ID was generated
  164. randomly, with at least the 7 rightmost bytes (56 bits) selected with
  165. uniform distribution.
  166. See the `W3C Trace Context - Traceparent`_ spec for details.
  167. .. _W3C Trace Context - Traceparent:
  168. https://www.w3.org/TR/trace-context-2/#trace-flags
  169. """
  170. DEFAULT = 0x00
  171. SAMPLED = 0x01
  172. RANDOM_TRACE_ID = 0x02
  173. @classmethod
  174. def get_default(cls) -> TraceFlags:
  175. return cls(cls.DEFAULT)
  176. @property
  177. def sampled(self) -> bool:
  178. return bool(self & TraceFlags.SAMPLED)
  179. @property
  180. def random_trace_id(self) -> bool:
  181. return bool(self & TraceFlags.RANDOM_TRACE_ID)
  182. DEFAULT_TRACE_OPTIONS = TraceFlags.get_default()
  183. class TraceState(Mapping[str, str]):
  184. """A list of key-value pairs representing vendor-specific trace info.
  185. Keys and values are strings of up to 256 printable US-ASCII characters.
  186. Implementations should conform to the `W3C Trace Context - Tracestate`_
  187. spec, which describes additional restrictions on valid field values.
  188. .. _W3C Trace Context - Tracestate:
  189. https://www.w3.org/TR/trace-context/#tracestate-field
  190. """
  191. def __init__(
  192. self,
  193. entries: Sequence[tuple[str, str]] | None = None,
  194. ) -> None:
  195. self._dict = {} # type: dict[str, str]
  196. if entries is None:
  197. return
  198. if len(entries) > _TRACECONTEXT_MAXIMUM_TRACESTATE_KEYS:
  199. _logger.warning(
  200. "There can't be more than %s key/value pairs.",
  201. _TRACECONTEXT_MAXIMUM_TRACESTATE_KEYS,
  202. )
  203. return
  204. for key, value in entries:
  205. if _is_valid_pair(key, value):
  206. if key in self._dict:
  207. _logger.warning("Duplicate key: %s found.", key)
  208. continue
  209. self._dict[key] = value
  210. else:
  211. _logger.warning(
  212. "Invalid key/value pair (%s, %s) found.", key, value
  213. )
  214. def __contains__(self, item: object) -> bool:
  215. return item in self._dict
  216. def __getitem__(self, key: str) -> str:
  217. return self._dict[key]
  218. def __iter__(self) -> Iterator[str]:
  219. return iter(self._dict)
  220. def __len__(self) -> int:
  221. return len(self._dict)
  222. def __repr__(self) -> str:
  223. pairs = [
  224. f"{{key={key}, value={value}}}"
  225. for key, value in self._dict.items()
  226. ]
  227. return str(pairs)
  228. def add(self, key: str, value: str) -> TraceState:
  229. """Adds a key-value pair to tracestate. The provided pair should
  230. adhere to w3c tracestate identifiers format.
  231. Args:
  232. key: A valid tracestate key to add
  233. value: A valid tracestate value to add
  234. Returns:
  235. A new TraceState with the modifications applied.
  236. If the provided key-value pair is invalid or results in tracestate
  237. that violates tracecontext specification, they are discarded and
  238. same tracestate will be returned.
  239. """
  240. if not _is_valid_pair(key, value):
  241. _logger.warning(
  242. "Invalid key/value pair (%s, %s) found.", key, value
  243. )
  244. return self
  245. # There can be a maximum of 32 pairs
  246. if len(self) >= _TRACECONTEXT_MAXIMUM_TRACESTATE_KEYS:
  247. _logger.warning("There can't be more 32 key/value pairs.")
  248. return self
  249. # Duplicate entries are not allowed
  250. if key in self._dict:
  251. _logger.warning("The provided key %s already exists.", key)
  252. return self
  253. new_state = [(key, value)] + list(self._dict.items())
  254. return TraceState(new_state)
  255. def update(self, key: str, value: str) -> TraceState:
  256. """Updates a key-value pair in tracestate. The provided pair should
  257. adhere to w3c tracestate identifiers format.
  258. Args:
  259. key: A valid tracestate key to update
  260. value: A valid tracestate value to update for key
  261. Returns:
  262. A new TraceState with the modifications applied.
  263. If the provided key-value pair is invalid or results in tracestate
  264. that violates tracecontext specification, they are discarded and
  265. same tracestate will be returned.
  266. """
  267. if not _is_valid_pair(key, value):
  268. _logger.warning(
  269. "Invalid key/value pair (%s, %s) found.", key, value
  270. )
  271. return self
  272. prev_state = self._dict.copy()
  273. prev_state.pop(key, None)
  274. new_state = [(key, value), *prev_state.items()]
  275. return TraceState(new_state)
  276. def delete(self, key: str) -> TraceState:
  277. """Deletes a key-value from tracestate.
  278. Args:
  279. key: A valid tracestate key to remove key-value pair from tracestate
  280. Returns:
  281. A new TraceState with the modifications applied.
  282. If the provided key-value pair is invalid or results in tracestate
  283. that violates tracecontext specification, they are discarded and
  284. same tracestate will be returned.
  285. """
  286. if key not in self._dict:
  287. _logger.warning("The provided key %s doesn't exist.", key)
  288. return self
  289. prev_state = self._dict.copy()
  290. prev_state.pop(key)
  291. new_state = list(prev_state.items())
  292. return TraceState(new_state)
  293. def to_header(self) -> str:
  294. """Creates a w3c tracestate header from a TraceState.
  295. Returns:
  296. A string that adheres to the w3c tracestate
  297. header format.
  298. """
  299. return ",".join(key + "=" + value for key, value in self._dict.items())
  300. @classmethod
  301. def from_header(cls, header_list: list[str]) -> TraceState:
  302. """Parses one or more w3c tracestate header into a TraceState.
  303. Args:
  304. header_list: one or more w3c tracestate headers.
  305. Returns:
  306. A valid TraceState that contains values extracted from
  307. the tracestate header.
  308. If the format of one headers is illegal, all values will
  309. be discarded and an empty tracestate will be returned.
  310. If the number of keys is beyond the maximum, all values
  311. will be discarded and an empty tracestate will be returned.
  312. """
  313. pairs = {} # type: dict[str, str]
  314. for header in header_list:
  315. members: list[str] = re.split(_delimiter_pattern, header)
  316. for member in members:
  317. # empty members are valid, but no need to process further.
  318. if not member:
  319. continue
  320. match = _member_pattern.fullmatch(member)
  321. if not match:
  322. _logger.warning(
  323. "Member doesn't match the w3c identifiers format %s",
  324. member,
  325. )
  326. return cls()
  327. groups: tuple[str, ...] = match.groups()
  328. key, _eq, value = groups
  329. # duplicate keys are not legal in header
  330. if key in pairs:
  331. return cls()
  332. pairs[key] = value
  333. return cls(list(pairs.items()))
  334. @classmethod
  335. def get_default(cls) -> TraceState:
  336. return cls()
  337. def keys(self) -> typing.KeysView[str]:
  338. return self._dict.keys()
  339. def items(self) -> typing.ItemsView[str, str]:
  340. return self._dict.items()
  341. def values(self) -> typing.ValuesView[str]:
  342. return self._dict.values()
  343. DEFAULT_TRACE_STATE = TraceState.get_default()
  344. _TRACE_ID_MAX_VALUE = 2**128 - 1
  345. _SPAN_ID_MAX_VALUE = 2**64 - 1
  346. class SpanContext(tuple[int, int, bool, "TraceFlags", "TraceState", bool]):
  347. """The state of a Span to propagate between processes.
  348. This class includes the immutable attributes of a :class:`.Span` that must
  349. be propagated to a span's children and across process boundaries.
  350. Args:
  351. trace_id: The ID of the trace that this span belongs to.
  352. span_id: This span's ID.
  353. is_remote: True if propagated from a remote parent.
  354. trace_flags: Trace options to propagate.
  355. trace_state: Tracing-system-specific info to propagate.
  356. """
  357. def __new__(
  358. cls,
  359. trace_id: int,
  360. span_id: int,
  361. is_remote: bool,
  362. trace_flags: TraceFlags | None = DEFAULT_TRACE_OPTIONS,
  363. trace_state: TraceState | None = DEFAULT_TRACE_STATE,
  364. ) -> SpanContext:
  365. if trace_flags is None:
  366. trace_flags = DEFAULT_TRACE_OPTIONS
  367. if trace_state is None:
  368. trace_state = DEFAULT_TRACE_STATE
  369. is_valid = (
  370. INVALID_TRACE_ID < trace_id <= _TRACE_ID_MAX_VALUE
  371. and INVALID_SPAN_ID < span_id <= _SPAN_ID_MAX_VALUE
  372. )
  373. return tuple.__new__(
  374. cls,
  375. (trace_id, span_id, is_remote, trace_flags, trace_state, is_valid),
  376. )
  377. def __getnewargs__(
  378. self,
  379. ) -> tuple[int, int, bool, TraceFlags, TraceState]:
  380. return (
  381. self.trace_id,
  382. self.span_id,
  383. self.is_remote,
  384. self.trace_flags,
  385. self.trace_state,
  386. )
  387. @property
  388. def trace_id(self) -> int:
  389. return self[0] # pylint: disable=unsubscriptable-object
  390. @property
  391. def span_id(self) -> int:
  392. return self[1] # pylint: disable=unsubscriptable-object
  393. @property
  394. def is_remote(self) -> bool:
  395. return self[2] # pylint: disable=unsubscriptable-object
  396. @property
  397. def trace_flags(self) -> TraceFlags:
  398. return self[3] # pylint: disable=unsubscriptable-object
  399. @property
  400. def trace_state(self) -> TraceState:
  401. return self[4] # pylint: disable=unsubscriptable-object
  402. @property
  403. def is_valid(self) -> bool:
  404. return self[5] # pylint: disable=unsubscriptable-object
  405. def __setattr__(self, *args: str) -> None:
  406. _logger.debug(
  407. "Immutable type, ignoring call to set attribute", stack_info=True
  408. )
  409. def __delattr__(self, *args: str) -> None:
  410. _logger.debug(
  411. "Immutable type, ignoring call to set attribute", stack_info=True
  412. )
  413. def __repr__(self) -> str:
  414. return f"{type(self).__name__}(trace_id=0x{format_trace_id(self.trace_id)}, span_id=0x{format_span_id(self.span_id)}, trace_flags=0x{self.trace_flags:02x}, trace_state={self.trace_state!r}, is_remote={self.is_remote})"
  415. class NonRecordingSpan(Span):
  416. """The Span that is used when no Span implementation is available.
  417. All operations are no-op except context propagation.
  418. """
  419. def __init__(self, context: SpanContext) -> None:
  420. self._context = context
  421. def get_span_context(self) -> SpanContext:
  422. return self._context
  423. def is_recording(self) -> bool:
  424. return False
  425. def end(self, end_time: int | None = None) -> None:
  426. pass
  427. def set_attributes(
  428. self, attributes: Mapping[str, types.AttributeValue]
  429. ) -> None:
  430. pass
  431. def set_attribute(self, key: str, value: types.AttributeValue) -> None:
  432. pass
  433. def add_event(
  434. self,
  435. name: str,
  436. attributes: types.Attributes = None,
  437. timestamp: int | None = None,
  438. ) -> None:
  439. pass
  440. def add_link(
  441. self,
  442. context: SpanContext,
  443. attributes: types.Attributes = None,
  444. ) -> None:
  445. pass
  446. def update_name(self, name: str) -> None:
  447. pass
  448. def set_status(
  449. self,
  450. status: Status | StatusCode,
  451. description: str | None = None,
  452. ) -> None:
  453. pass
  454. def record_exception(
  455. self,
  456. exception: BaseException,
  457. attributes: types.Attributes = None,
  458. timestamp: int | None = None,
  459. escaped: bool = False,
  460. ) -> None:
  461. pass
  462. def __repr__(self) -> str:
  463. return f"NonRecordingSpan({self._context!r})"
  464. INVALID_SPAN_ID = 0x0000000000000000
  465. INVALID_TRACE_ID = 0x00000000000000000000000000000000
  466. INVALID_SPAN_CONTEXT = SpanContext(
  467. trace_id=INVALID_TRACE_ID,
  468. span_id=INVALID_SPAN_ID,
  469. is_remote=False,
  470. trace_flags=DEFAULT_TRACE_OPTIONS,
  471. trace_state=DEFAULT_TRACE_STATE,
  472. )
  473. INVALID_SPAN = NonRecordingSpan(INVALID_SPAN_CONTEXT)
  474. def format_trace_id(trace_id: int) -> str:
  475. """Convenience trace ID formatting method
  476. Args:
  477. trace_id: Trace ID int
  478. Returns:
  479. The trace ID (16 bytes) cast to a 32-character hexadecimal string
  480. """
  481. return format(trace_id, "032x")
  482. def format_span_id(span_id: int) -> str:
  483. """Convenience span ID formatting method
  484. Args:
  485. span_id: Span ID int
  486. Returns:
  487. The span ID (8 bytes) cast to a 16-character hexadecimal string
  488. """
  489. return format(span_id, "016x")