span.py 19 KB

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