Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

1099 lignes
36 KiB

  1. # Copyright 2019 The Matrix.org Foundation C.I.C.
  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. # NOTE
  15. # This is a small wrapper around opentracing because opentracing is not currently
  16. # packaged downstream (specifically debian). Since opentracing instrumentation is
  17. # fairly invasive it was awkward to make it optional. As a result we opted to encapsulate
  18. # all opentracing state in these methods which effectively noop if opentracing is
  19. # not present. We should strongly consider encouraging the downstream distributers
  20. # to package opentracing and making opentracing a full dependency. In order to facilitate
  21. # this move the methods have work very similarly to opentracing's and it should only
  22. # be a matter of few regexes to move over to opentracing's access patterns proper.
  23. """
  24. ============================
  25. Using OpenTracing in Synapse
  26. ============================
  27. Python-specific tracing concepts are at https://opentracing.io/guides/python/.
  28. Note that Synapse wraps OpenTracing in a small module (this one) in order to make the
  29. OpenTracing dependency optional. That means that the access patterns are
  30. different to those demonstrated in the OpenTracing guides. However, it is
  31. still useful to know, especially if OpenTracing is included as a full dependency
  32. in the future or if you are modifying this module.
  33. OpenTracing is encapsulated so that
  34. no span objects from OpenTracing are exposed in Synapse's code. This allows
  35. OpenTracing to be easily disabled in Synapse and thereby have OpenTracing as
  36. an optional dependency. This does however limit the number of modifiable spans
  37. at any point in the code to one. From here out references to `opentracing`
  38. in the code snippets refer to the Synapses module.
  39. Most methods provided in the module have a direct correlation to those provided
  40. by opentracing. Refer to docs there for a more in-depth documentation on some of
  41. the args and methods.
  42. Tracing
  43. -------
  44. In Synapse it is not possible to start a non-active span. Spans can be started
  45. using the ``start_active_span`` method. This returns a scope (see
  46. OpenTracing docs) which is a context manager that needs to be entered and
  47. exited. This is usually done by using ``with``.
  48. .. code-block:: python
  49. from synapse.logging.opentracing import start_active_span
  50. with start_active_span("operation name"):
  51. # Do something we want to tracer
  52. Forgetting to enter or exit a scope will result in some mysterious and grievous log
  53. context errors.
  54. At anytime where there is an active span ``opentracing.set_tag`` can be used to
  55. set a tag on the current active span.
  56. Tracing functions
  57. -----------------
  58. Functions can be easily traced using decorators. The name of
  59. the function becomes the operation name for the span.
  60. .. code-block:: python
  61. from synapse.logging.opentracing import trace
  62. # Start a span using 'interesting_function' as the operation name
  63. @trace
  64. def interesting_function(*args, **kwargs):
  65. # Does all kinds of cool and expected things
  66. return something_usual_and_useful
  67. Operation names can be explicitly set for a function by using ``trace_with_opname``:
  68. .. code-block:: python
  69. from synapse.logging.opentracing import trace_with_opname
  70. @trace_with_opname("a_better_operation_name")
  71. def interesting_badly_named_function(*args, **kwargs):
  72. # Does all kinds of cool and expected things
  73. return something_usual_and_useful
  74. Setting Tags
  75. ------------
  76. To set a tag on the active span do
  77. .. code-block:: python
  78. from synapse.logging.opentracing import set_tag
  79. set_tag(tag_name, tag_value)
  80. There's a convenient decorator to tag all the args of the method. It uses
  81. inspection in order to use the formal parameter names prefixed with 'ARG_' as
  82. tag names. It uses kwarg names as tag names without the prefix.
  83. .. code-block:: python
  84. from synapse.logging.opentracing import tag_args
  85. @tag_args
  86. def set_fates(clotho, lachesis, atropos, father="Zues", mother="Themis"):
  87. pass
  88. set_fates("the story", "the end", "the act")
  89. # This will have the following tags
  90. # - ARG_clotho: "the story"
  91. # - ARG_lachesis: "the end"
  92. # - ARG_atropos: "the act"
  93. # - father: "Zues"
  94. # - mother: "Themis"
  95. Contexts and carriers
  96. ---------------------
  97. There are a selection of wrappers for injecting and extracting contexts from
  98. carriers provided. Unfortunately OpenTracing's three context injection
  99. techniques are not adequate for our inject of OpenTracing span-contexts into
  100. Twisted's http headers, EDU contents and our database tables. Also note that
  101. the binary encoding format mandated by OpenTracing is not actually implemented
  102. by jaeger_client v4.0.0 - it will silently noop.
  103. Please refer to the end of ``logging/opentracing.py`` for the available
  104. injection and extraction methods.
  105. Homeserver whitelisting
  106. -----------------------
  107. Most of the whitelist checks are encapsulated in the modules's injection
  108. and extraction method but be aware that using custom carriers or crossing
  109. unchartered waters will require the enforcement of the whitelist.
  110. ``logging/opentracing.py`` has a ``whitelisted_homeserver`` method which takes
  111. in a destination and compares it to the whitelist.
  112. Most injection methods take a 'destination' arg. The context will only be injected
  113. if the destination matches the whitelist or the destination is None.
  114. =======
  115. Gotchas
  116. =======
  117. - Checking whitelists on span propagation
  118. - Inserting pii
  119. - Forgetting to enter or exit a scope
  120. - Span source: make sure that the span you expect to be active across a
  121. function call really will be that one. Does the current function have more
  122. than one caller? Will all of those calling functions have be in a context
  123. with an active span?
  124. """
  125. import contextlib
  126. import enum
  127. import inspect
  128. import logging
  129. import re
  130. from functools import wraps
  131. from typing import (
  132. TYPE_CHECKING,
  133. Any,
  134. Awaitable,
  135. Callable,
  136. Collection,
  137. ContextManager,
  138. Dict,
  139. Generator,
  140. Iterable,
  141. List,
  142. Optional,
  143. Pattern,
  144. Type,
  145. TypeVar,
  146. Union,
  147. cast,
  148. overload,
  149. )
  150. import attr
  151. from typing_extensions import Concatenate, ParamSpec
  152. from twisted.internet import defer
  153. from twisted.web.http import Request
  154. from twisted.web.http_headers import Headers
  155. from synapse.config import ConfigError
  156. from synapse.util import json_decoder, json_encoder
  157. if TYPE_CHECKING:
  158. from synapse.http.site import SynapseRequest
  159. from synapse.server import HomeServer
  160. # Helper class
  161. # Matches the number suffix in an instance name like "matrix.org client_reader-8"
  162. STRIP_INSTANCE_NUMBER_SUFFIX_REGEX = re.compile(r"[_-]?\d+$")
  163. class _DummyTagNames:
  164. """wrapper of opentracings tags. We need to have them if we
  165. want to reference them without opentracing around. Clearly they
  166. should never actually show up in a trace. `set_tags` overwrites
  167. these with the correct ones."""
  168. INVALID_TAG = "invalid-tag"
  169. COMPONENT = INVALID_TAG
  170. DATABASE_INSTANCE = INVALID_TAG
  171. DATABASE_STATEMENT = INVALID_TAG
  172. DATABASE_TYPE = INVALID_TAG
  173. DATABASE_USER = INVALID_TAG
  174. ERROR = INVALID_TAG
  175. HTTP_METHOD = INVALID_TAG
  176. HTTP_STATUS_CODE = INVALID_TAG
  177. HTTP_URL = INVALID_TAG
  178. MESSAGE_BUS_DESTINATION = INVALID_TAG
  179. PEER_ADDRESS = INVALID_TAG
  180. PEER_HOSTNAME = INVALID_TAG
  181. PEER_HOST_IPV4 = INVALID_TAG
  182. PEER_HOST_IPV6 = INVALID_TAG
  183. PEER_PORT = INVALID_TAG
  184. PEER_SERVICE = INVALID_TAG
  185. SAMPLING_PRIORITY = INVALID_TAG
  186. SERVICE = INVALID_TAG
  187. SPAN_KIND = INVALID_TAG
  188. SPAN_KIND_CONSUMER = INVALID_TAG
  189. SPAN_KIND_PRODUCER = INVALID_TAG
  190. SPAN_KIND_RPC_CLIENT = INVALID_TAG
  191. SPAN_KIND_RPC_SERVER = INVALID_TAG
  192. try:
  193. import opentracing
  194. import opentracing.tags
  195. tags = opentracing.tags
  196. except ImportError:
  197. opentracing = None # type: ignore[assignment]
  198. tags = _DummyTagNames # type: ignore[assignment]
  199. try:
  200. from jaeger_client import Config as JaegerConfig
  201. from synapse.logging.scopecontextmanager import LogContextScopeManager
  202. except ImportError:
  203. JaegerConfig = None # type: ignore
  204. LogContextScopeManager = None # type: ignore
  205. try:
  206. from rust_python_jaeger_reporter import Reporter
  207. # jaeger-client 4.7.0 requires that reporters inherit from BaseReporter, which
  208. # didn't exist before that version.
  209. try:
  210. from jaeger_client.reporter import BaseReporter
  211. except ImportError:
  212. class BaseReporter: # type: ignore[no-redef]
  213. pass
  214. @attr.s(slots=True, frozen=True, auto_attribs=True)
  215. class _WrappedRustReporter(BaseReporter):
  216. """Wrap the reporter to ensure `report_span` never throws."""
  217. _reporter: Reporter = attr.Factory(Reporter)
  218. def set_process(self, *args: Any, **kwargs: Any) -> None:
  219. return self._reporter.set_process(*args, **kwargs)
  220. def report_span(self, span: "opentracing.Span") -> None:
  221. try:
  222. return self._reporter.report_span(span)
  223. except Exception:
  224. logger.exception("Failed to report span")
  225. RustReporter: Optional[Type[_WrappedRustReporter]] = _WrappedRustReporter
  226. except ImportError:
  227. RustReporter = None
  228. logger = logging.getLogger(__name__)
  229. class SynapseTags:
  230. # The message ID of any to_device EDU processed
  231. TO_DEVICE_EDU_ID = "to_device.edu_id"
  232. # Details about to-device messages
  233. TO_DEVICE_TYPE = "to_device.type"
  234. TO_DEVICE_SENDER = "to_device.sender"
  235. TO_DEVICE_RECIPIENT = "to_device.recipient"
  236. TO_DEVICE_RECIPIENT_DEVICE = "to_device.recipient_device"
  237. TO_DEVICE_MSGID = "to_device.msgid" # client-generated ID
  238. # Whether the sync response has new data to be returned to the client.
  239. SYNC_RESULT = "sync.new_data"
  240. INSTANCE_NAME = "instance_name"
  241. # incoming HTTP request ID (as written in the logs)
  242. REQUEST_ID = "request_id"
  243. # HTTP request tag (used to distinguish full vs incremental syncs, etc)
  244. REQUEST_TAG = "request_tag"
  245. # Text description of a database transaction
  246. DB_TXN_DESC = "db.txn_desc"
  247. # Uniqueish ID of a database transaction
  248. DB_TXN_ID = "db.txn_id"
  249. # The name of the external cache
  250. CACHE_NAME = "cache.name"
  251. # Boolean. Present on /v2/send_join requests, omitted from all others.
  252. # True iff partial state was requested and we provided (or intended to provide)
  253. # partial state in the response.
  254. SEND_JOIN_RESPONSE_IS_PARTIAL_STATE = "send_join.partial_state_response"
  255. # Used to tag function arguments
  256. #
  257. # Tag a named arg. The name of the argument should be appended to this prefix.
  258. FUNC_ARG_PREFIX = "ARG."
  259. # Tag extra variadic number of positional arguments (`def foo(first, second, *extras)`)
  260. FUNC_ARGS = "args"
  261. # Tag keyword args
  262. FUNC_KWARGS = "kwargs"
  263. # Some intermediate result that's interesting to the function. The label for
  264. # the result should be appended to this prefix.
  265. RESULT_PREFIX = "RESULT."
  266. class SynapseBaggage:
  267. FORCE_TRACING = "synapse-force-tracing"
  268. # Block everything by default
  269. # A regex which matches the server_names to expose traces for.
  270. # None means 'block everything'.
  271. _homeserver_whitelist: Optional[Pattern[str]] = None
  272. # Util methods
  273. class _Sentinel(enum.Enum):
  274. # defining a sentinel in this way allows mypy to correctly handle the
  275. # type of a dictionary lookup.
  276. sentinel = object()
  277. P = ParamSpec("P")
  278. R = TypeVar("R")
  279. T = TypeVar("T")
  280. def only_if_tracing(func: Callable[P, R]) -> Callable[P, Optional[R]]:
  281. """Executes the function only if we're tracing. Otherwise returns None."""
  282. @wraps(func)
  283. def _only_if_tracing_inner(*args: P.args, **kwargs: P.kwargs) -> Optional[R]:
  284. if opentracing:
  285. return func(*args, **kwargs)
  286. else:
  287. return None
  288. return _only_if_tracing_inner
  289. @overload
  290. def ensure_active_span(
  291. message: str,
  292. ) -> Callable[[Callable[P, R]], Callable[P, Optional[R]]]:
  293. ...
  294. @overload
  295. def ensure_active_span(
  296. message: str, ret: T
  297. ) -> Callable[[Callable[P, R]], Callable[P, Union[T, R]]]:
  298. ...
  299. def ensure_active_span(
  300. message: str, ret: Optional[T] = None
  301. ) -> Callable[[Callable[P, R]], Callable[P, Union[Optional[T], R]]]:
  302. """Executes the operation only if opentracing is enabled and there is an active span.
  303. If there is no active span it logs message at the error level.
  304. Args:
  305. message: Message which fills in "There was no active span when trying to %s"
  306. in the error log if there is no active span and opentracing is enabled.
  307. ret: return value if opentracing is None or there is no active span.
  308. Returns:
  309. The result of the func, falling back to ret if opentracing is disabled or there
  310. was no active span.
  311. """
  312. def ensure_active_span_inner_1(
  313. func: Callable[P, R]
  314. ) -> Callable[P, Union[Optional[T], R]]:
  315. @wraps(func)
  316. def ensure_active_span_inner_2(
  317. *args: P.args, **kwargs: P.kwargs
  318. ) -> Union[Optional[T], R]:
  319. if not opentracing:
  320. return ret
  321. if not opentracing.tracer.active_span:
  322. logger.error(
  323. "There was no active span when trying to %s."
  324. " Did you forget to start one or did a context slip?",
  325. message,
  326. stack_info=True,
  327. )
  328. return ret
  329. return func(*args, **kwargs)
  330. return ensure_active_span_inner_2
  331. return ensure_active_span_inner_1
  332. # Setup
  333. def init_tracer(hs: "HomeServer") -> None:
  334. """Set the whitelists and initialise the JaegerClient tracer"""
  335. global opentracing
  336. if not hs.config.tracing.opentracer_enabled:
  337. # We don't have a tracer
  338. opentracing = None # type: ignore[assignment]
  339. return
  340. if opentracing is None or JaegerConfig is None:
  341. raise ConfigError(
  342. "The server has been configured to use opentracing but opentracing is not "
  343. "installed."
  344. )
  345. # Pull out the jaeger config if it was given. Otherwise set it to something sensible.
  346. # See https://github.com/jaegertracing/jaeger-client-python/blob/master/jaeger_client/config.py
  347. set_homeserver_whitelist(hs.config.tracing.opentracer_whitelist)
  348. from jaeger_client.metrics.prometheus import PrometheusMetricsFactory
  349. # Instance names are opaque strings but by stripping off the number suffix,
  350. # we can get something that looks like a "worker type", e.g.
  351. # "client_reader-1" -> "client_reader" so we don't spread the traces across
  352. # so many services.
  353. instance_name_by_type = re.sub(
  354. STRIP_INSTANCE_NUMBER_SUFFIX_REGEX, "", hs.get_instance_name()
  355. )
  356. jaeger_config = hs.config.tracing.jaeger_config
  357. tags = jaeger_config.setdefault("tags", {})
  358. # tag the Synapse instance name so that it's an easy jumping
  359. # off point into the logs. Can also be used to filter for an
  360. # instance that is under load.
  361. tags[SynapseTags.INSTANCE_NAME] = hs.get_instance_name()
  362. config = JaegerConfig(
  363. config=jaeger_config,
  364. service_name=f"{hs.config.server.server_name} {instance_name_by_type}",
  365. scope_manager=LogContextScopeManager(),
  366. metrics_factory=PrometheusMetricsFactory(),
  367. )
  368. # If we have the rust jaeger reporter available let's use that.
  369. if RustReporter:
  370. logger.info("Using rust_python_jaeger_reporter library")
  371. assert config.sampler is not None
  372. tracer = config.create_tracer(RustReporter(), config.sampler)
  373. opentracing.set_global_tracer(tracer)
  374. else:
  375. config.initialize_tracer()
  376. # Whitelisting
  377. @only_if_tracing
  378. def set_homeserver_whitelist(homeserver_whitelist: Iterable[str]) -> None:
  379. """Sets the homeserver whitelist
  380. Args:
  381. homeserver_whitelist: regexes specifying whitelisted homeservers
  382. """
  383. global _homeserver_whitelist
  384. if homeserver_whitelist:
  385. # Makes a single regex which accepts all passed in regexes in the list
  386. _homeserver_whitelist = re.compile(
  387. "({})".format(")|(".join(homeserver_whitelist))
  388. )
  389. @only_if_tracing
  390. def whitelisted_homeserver(destination: str) -> bool:
  391. """Checks if a destination matches the whitelist
  392. Args:
  393. destination
  394. """
  395. if _homeserver_whitelist:
  396. return _homeserver_whitelist.match(destination) is not None
  397. return False
  398. # Start spans and scopes
  399. # Could use kwargs but I want these to be explicit
  400. def start_active_span(
  401. operation_name: str,
  402. child_of: Optional[Union["opentracing.Span", "opentracing.SpanContext"]] = None,
  403. references: Optional[List["opentracing.Reference"]] = None,
  404. tags: Optional[Dict[str, str]] = None,
  405. start_time: Optional[float] = None,
  406. ignore_active_span: bool = False,
  407. finish_on_close: bool = True,
  408. *,
  409. tracer: Optional["opentracing.Tracer"] = None,
  410. ) -> "opentracing.Scope":
  411. """Starts an active opentracing span.
  412. Records the start time for the span, and sets it as the "active span" in the
  413. scope manager.
  414. Args:
  415. See opentracing.tracer
  416. Returns:
  417. scope (Scope) or contextlib.nullcontext
  418. """
  419. if opentracing is None:
  420. return contextlib.nullcontext() # type: ignore[unreachable]
  421. if tracer is None:
  422. # use the global tracer by default
  423. tracer = opentracing.tracer
  424. return tracer.start_active_span(
  425. operation_name,
  426. child_of=child_of,
  427. references=references,
  428. tags=tags,
  429. start_time=start_time,
  430. ignore_active_span=ignore_active_span,
  431. finish_on_close=finish_on_close,
  432. )
  433. def start_active_span_follows_from(
  434. operation_name: str,
  435. contexts: Collection,
  436. child_of: Optional[Union["opentracing.Span", "opentracing.SpanContext"]] = None,
  437. start_time: Optional[float] = None,
  438. *,
  439. inherit_force_tracing: bool = False,
  440. tracer: Optional["opentracing.Tracer"] = None,
  441. ) -> "opentracing.Scope":
  442. """Starts an active opentracing span, with additional references to previous spans
  443. Args:
  444. operation_name: name of the operation represented by the new span
  445. contexts: the previous spans to inherit from
  446. child_of: optionally override the parent span. If unset, the currently active
  447. span will be the parent. (If there is no currently active span, the first
  448. span in `contexts` will be the parent.)
  449. start_time: optional override for the start time of the created span. Seconds
  450. since the epoch.
  451. inherit_force_tracing: if set, and any of the previous contexts have had tracing
  452. forced, the new span will also have tracing forced.
  453. tracer: override the opentracing tracer. By default the global tracer is used.
  454. """
  455. if opentracing is None:
  456. return contextlib.nullcontext() # type: ignore[unreachable]
  457. references = [opentracing.follows_from(context) for context in contexts]
  458. scope = start_active_span(
  459. operation_name,
  460. child_of=child_of,
  461. references=references,
  462. start_time=start_time,
  463. tracer=tracer,
  464. )
  465. if inherit_force_tracing and any(
  466. is_context_forced_tracing(ctx) for ctx in contexts
  467. ):
  468. force_tracing(scope.span)
  469. return scope
  470. def start_active_span_from_edu(
  471. edu_content: Dict[str, Any],
  472. operation_name: str,
  473. references: Optional[List["opentracing.Reference"]] = None,
  474. tags: Optional[Dict[str, str]] = None,
  475. start_time: Optional[float] = None,
  476. ignore_active_span: bool = False,
  477. finish_on_close: bool = True,
  478. ) -> "opentracing.Scope":
  479. """
  480. Extracts a span context from an edu and uses it to start a new active span
  481. Args:
  482. edu_content: an edu_content with a `context` field whose value is
  483. canonical json for a dict which contains opentracing information.
  484. For the other args see opentracing.tracer
  485. """
  486. references = references or []
  487. if opentracing is None:
  488. return contextlib.nullcontext() # type: ignore[unreachable]
  489. carrier = json_decoder.decode(edu_content.get("context", "{}")).get(
  490. "opentracing", {}
  491. )
  492. context = opentracing.tracer.extract(opentracing.Format.TEXT_MAP, carrier)
  493. _references = [
  494. opentracing.child_of(span_context_from_string(x))
  495. for x in carrier.get("references", [])
  496. ]
  497. # For some reason jaeger decided not to support the visualization of multiple parent
  498. # spans or explicitly show references. I include the span context as a tag here as
  499. # an aid to people debugging but it's really not an ideal solution.
  500. references += _references
  501. scope = opentracing.tracer.start_active_span(
  502. operation_name,
  503. child_of=context,
  504. references=references,
  505. tags=tags,
  506. start_time=start_time,
  507. ignore_active_span=ignore_active_span,
  508. finish_on_close=finish_on_close,
  509. )
  510. scope.span.set_tag("references", carrier.get("references", []))
  511. return scope
  512. # Opentracing setters for tags, logs, etc
  513. @only_if_tracing
  514. def active_span() -> Optional["opentracing.Span"]:
  515. """Get the currently active span, if any"""
  516. return opentracing.tracer.active_span
  517. @ensure_active_span("set a tag")
  518. def set_tag(key: str, value: Union[str, bool, int, float]) -> None:
  519. """Sets a tag on the active span"""
  520. assert opentracing.tracer.active_span is not None
  521. opentracing.tracer.active_span.set_tag(key, value)
  522. @ensure_active_span("log")
  523. def log_kv(key_values: Dict[str, Any], timestamp: Optional[float] = None) -> None:
  524. """Log to the active span"""
  525. assert opentracing.tracer.active_span is not None
  526. opentracing.tracer.active_span.log_kv(key_values, timestamp)
  527. @ensure_active_span("set the traces operation name")
  528. def set_operation_name(operation_name: str) -> None:
  529. """Sets the operation name of the active span"""
  530. assert opentracing.tracer.active_span is not None
  531. opentracing.tracer.active_span.set_operation_name(operation_name)
  532. @only_if_tracing
  533. def force_tracing(
  534. span: Union["opentracing.Span", _Sentinel] = _Sentinel.sentinel
  535. ) -> None:
  536. """Force sampling for the active/given span and its children.
  537. Args:
  538. span: span to force tracing for. By default, the active span.
  539. """
  540. if isinstance(span, _Sentinel):
  541. span_to_trace = opentracing.tracer.active_span
  542. else:
  543. span_to_trace = span
  544. if span_to_trace is None:
  545. logger.error("No active span in force_tracing")
  546. return
  547. span_to_trace.set_tag(opentracing.tags.SAMPLING_PRIORITY, 1)
  548. # also set a bit of baggage, so that we have a way of figuring out if
  549. # it is enabled later
  550. span_to_trace.set_baggage_item(SynapseBaggage.FORCE_TRACING, "1")
  551. def is_context_forced_tracing(
  552. span_context: Optional["opentracing.SpanContext"],
  553. ) -> bool:
  554. """Check if sampling has been force for the given span context."""
  555. if span_context is None:
  556. return False
  557. return span_context.baggage.get(SynapseBaggage.FORCE_TRACING) is not None
  558. # Injection and extraction
  559. @ensure_active_span("inject the span into a header dict")
  560. def inject_header_dict(
  561. headers: Dict[bytes, List[bytes]],
  562. destination: Optional[str] = None,
  563. check_destination: bool = True,
  564. ) -> None:
  565. """
  566. Injects a span context into a dict of HTTP headers
  567. Args:
  568. headers: the dict to inject headers into
  569. destination: address of entity receiving the span context. Must be given unless
  570. check_destination is False. The context will only be injected if the
  571. destination matches the opentracing whitelist
  572. check_destination: If false, destination will be ignored and the context
  573. will always be injected.
  574. Note:
  575. The headers set by the tracer are custom to the tracer implementation which
  576. should be unique enough that they don't interfere with any headers set by
  577. synapse or twisted. If we're still using jaeger these headers would be those
  578. here:
  579. https://github.com/jaegertracing/jaeger-client-python/blob/master/jaeger_client/constants.py
  580. """
  581. if check_destination:
  582. if destination is None:
  583. raise ValueError(
  584. "destination must be given unless check_destination is False"
  585. )
  586. if not whitelisted_homeserver(destination):
  587. return
  588. span = opentracing.tracer.active_span
  589. carrier: Dict[str, str] = {}
  590. assert span is not None
  591. opentracing.tracer.inject(span.context, opentracing.Format.HTTP_HEADERS, carrier)
  592. for key, value in carrier.items():
  593. headers[key.encode()] = [value.encode()]
  594. def inject_response_headers(response_headers: Headers) -> None:
  595. """Inject the current trace id into the HTTP response headers"""
  596. if not opentracing:
  597. return
  598. span = opentracing.tracer.active_span
  599. if not span:
  600. return
  601. # This is a bit implementation-specific.
  602. #
  603. # Jaeger's Spans have a trace_id property; other implementations (including the
  604. # dummy opentracing.span.Span which we use if init_tracer is not called) do not
  605. # expose it
  606. trace_id = getattr(span, "trace_id", None)
  607. if trace_id is not None:
  608. response_headers.addRawHeader("Synapse-Trace-Id", f"{trace_id:x}")
  609. @ensure_active_span(
  610. "get the active span context as a dict", ret=cast(Dict[str, str], {})
  611. )
  612. def get_active_span_text_map(destination: Optional[str] = None) -> Dict[str, str]:
  613. """
  614. Gets a span context as a dict. This can be used instead of manually
  615. injecting a span into an empty carrier.
  616. Args:
  617. destination: the name of the remote server.
  618. Returns:
  619. the active span's context if opentracing is enabled, otherwise empty.
  620. """
  621. if destination and not whitelisted_homeserver(destination):
  622. return {}
  623. carrier: Dict[str, str] = {}
  624. assert opentracing.tracer.active_span is not None
  625. opentracing.tracer.inject(
  626. opentracing.tracer.active_span.context, opentracing.Format.TEXT_MAP, carrier
  627. )
  628. return carrier
  629. @ensure_active_span("get the span context as a string.", ret={})
  630. def active_span_context_as_string() -> str:
  631. """
  632. Returns:
  633. The active span context encoded as a string.
  634. """
  635. carrier: Dict[str, str] = {}
  636. if opentracing:
  637. assert opentracing.tracer.active_span is not None
  638. opentracing.tracer.inject(
  639. opentracing.tracer.active_span.context, opentracing.Format.TEXT_MAP, carrier
  640. )
  641. return json_encoder.encode(carrier)
  642. def span_context_from_request(request: Request) -> "Optional[opentracing.SpanContext]":
  643. """Extract an opentracing context from the headers on an HTTP request
  644. This is useful when we have received an HTTP request from another part of our
  645. system, and want to link our spans to those of the remote system.
  646. """
  647. if not opentracing:
  648. return None
  649. header_dict = {
  650. k.decode(): v[0].decode() for k, v in request.requestHeaders.getAllRawHeaders()
  651. }
  652. return opentracing.tracer.extract(opentracing.Format.HTTP_HEADERS, header_dict)
  653. @only_if_tracing
  654. def span_context_from_string(carrier: str) -> Optional["opentracing.SpanContext"]:
  655. """
  656. Returns:
  657. The active span context decoded from a string.
  658. """
  659. payload: Dict[str, str] = json_decoder.decode(carrier)
  660. return opentracing.tracer.extract(opentracing.Format.TEXT_MAP, payload)
  661. @only_if_tracing
  662. def extract_text_map(carrier: Dict[str, str]) -> Optional["opentracing.SpanContext"]:
  663. """
  664. Wrapper method for opentracing's tracer.extract for TEXT_MAP.
  665. Args:
  666. carrier: a dict possibly containing a span context.
  667. Returns:
  668. The active span context extracted from carrier.
  669. """
  670. return opentracing.tracer.extract(opentracing.Format.TEXT_MAP, carrier)
  671. # Tracing decorators
  672. def _custom_sync_async_decorator(
  673. func: Callable[P, R],
  674. wrapping_logic: Callable[Concatenate[Callable[P, R], P], ContextManager[None]],
  675. ) -> Callable[P, R]:
  676. """
  677. Decorates a function that is sync or async (coroutines), or that returns a Twisted
  678. `Deferred`. The custom business logic of the decorator goes in `wrapping_logic`.
  679. Example usage:
  680. ```py
  681. # Decorator to time the function and log it out
  682. def duration(func: Callable[P, R]) -> Callable[P, R]:
  683. @contextlib.contextmanager
  684. def _wrapping_logic(func: Callable[P, R], *args: P.args, **kwargs: P.kwargs) -> Generator[None, None, None]:
  685. start_ts = time.time()
  686. try:
  687. yield
  688. finally:
  689. end_ts = time.time()
  690. duration = end_ts - start_ts
  691. logger.info("%s took %s seconds", func.__name__, duration)
  692. return _custom_sync_async_decorator(func, _wrapping_logic)
  693. ```
  694. Args:
  695. func: The function to be decorated
  696. wrapping_logic: The business logic of your custom decorator.
  697. This should be a ContextManager so you are able to run your logic
  698. before/after the function as desired.
  699. """
  700. if inspect.iscoroutinefunction(func):
  701. # For this branch, we handle async functions like `async def func() -> RInner`.
  702. # In this branch, R = Awaitable[RInner], for some other type RInner
  703. @wraps(func)
  704. async def _wrapper(
  705. *args: P.args, **kwargs: P.kwargs
  706. ) -> Any: # Return type is RInner
  707. # type-ignore: func() returns R, but mypy doesn't know that R is
  708. # Awaitable here.
  709. with wrapping_logic(func, *args, **kwargs): # type: ignore[arg-type]
  710. return await func(*args, **kwargs)
  711. else:
  712. # The other case here handles sync functions including those decorated with
  713. # `@defer.inlineCallbacks` or that return a `Deferred` or other `Awaitable`.
  714. @wraps(func)
  715. def _wrapper(*args: P.args, **kwargs: P.kwargs) -> Any:
  716. scope = wrapping_logic(func, *args, **kwargs)
  717. scope.__enter__()
  718. try:
  719. result = func(*args, **kwargs)
  720. if isinstance(result, defer.Deferred):
  721. def call_back(result: R) -> R:
  722. scope.__exit__(None, None, None)
  723. return result
  724. def err_back(result: R) -> R:
  725. # TODO: Pass the error details into `scope.__exit__(...)` for
  726. # consistency with the other paths.
  727. scope.__exit__(None, None, None)
  728. return result
  729. result.addCallbacks(call_back, err_back)
  730. elif inspect.isawaitable(result):
  731. async def wrap_awaitable() -> Any:
  732. try:
  733. assert isinstance(result, Awaitable)
  734. awaited_result = await result
  735. scope.__exit__(None, None, None)
  736. return awaited_result
  737. except Exception as e:
  738. scope.__exit__(type(e), None, e.__traceback__)
  739. raise
  740. # The original method returned an awaitable, eg. a coroutine, so we
  741. # create another awaitable wrapping it that calls
  742. # `scope.__exit__(...)`.
  743. return wrap_awaitable()
  744. else:
  745. # Just a simple sync function so we can just exit the scope and
  746. # return the result without any fuss.
  747. scope.__exit__(None, None, None)
  748. return result
  749. except Exception as e:
  750. scope.__exit__(type(e), None, e.__traceback__)
  751. raise
  752. return _wrapper # type: ignore[return-value]
  753. def trace_with_opname(
  754. opname: str,
  755. *,
  756. tracer: Optional["opentracing.Tracer"] = None,
  757. ) -> Callable[[Callable[P, R]], Callable[P, R]]:
  758. """
  759. Decorator to trace a function with a custom opname.
  760. See the module's doc string for usage examples.
  761. """
  762. @contextlib.contextmanager
  763. def _wrapping_logic(
  764. func: Callable[P, R], *args: P.args, **kwargs: P.kwargs
  765. ) -> Generator[None, None, None]:
  766. with start_active_span(opname, tracer=tracer):
  767. yield
  768. def _decorator(func: Callable[P, R]) -> Callable[P, R]:
  769. if not opentracing:
  770. return func
  771. return _custom_sync_async_decorator(func, _wrapping_logic)
  772. return _decorator
  773. def trace(func: Callable[P, R]) -> Callable[P, R]:
  774. """
  775. Decorator to trace a function.
  776. Sets the operation name to that of the function's name.
  777. See the module's doc string for usage examples.
  778. """
  779. return trace_with_opname(func.__name__)(func)
  780. def tag_args(func: Callable[P, R]) -> Callable[P, R]:
  781. """
  782. Decorator to tag all of the args to the active span.
  783. Args:
  784. func: `func` is assumed to be a method taking a `self` parameter, or a
  785. `classmethod` taking a `cls` parameter. In either case, a tag is not
  786. created for this parameter.
  787. """
  788. if not opentracing:
  789. return func
  790. # getfullargspec is somewhat expensive, so ensure it is only called a single
  791. # time (the function signature shouldn't change anyway).
  792. argspec = inspect.getfullargspec(func)
  793. @contextlib.contextmanager
  794. def _wrapping_logic(
  795. _func: Callable[P, R], *args: P.args, **kwargs: P.kwargs
  796. ) -> Generator[None, None, None]:
  797. # We use `[1:]` to skip the `self` object reference and `start=1` to
  798. # make the index line up with `argspec.args`.
  799. #
  800. # FIXME: We could update this to handle any type of function by ignoring the
  801. # first argument only if it's named `self` or `cls`. This isn't fool-proof
  802. # but handles the idiomatic cases.
  803. for i, arg in enumerate(args[1:], start=1):
  804. set_tag(SynapseTags.FUNC_ARG_PREFIX + argspec.args[i], str(arg))
  805. set_tag(SynapseTags.FUNC_ARGS, str(args[len(argspec.args) :]))
  806. set_tag(SynapseTags.FUNC_KWARGS, str(kwargs))
  807. yield
  808. return _custom_sync_async_decorator(func, _wrapping_logic)
  809. @contextlib.contextmanager
  810. def trace_servlet(
  811. request: "SynapseRequest", extract_context: bool = False
  812. ) -> Generator[None, None, None]:
  813. """Returns a context manager which traces a request. It starts a span
  814. with some servlet specific tags such as the request metrics name and
  815. request information.
  816. Args:
  817. request
  818. extract_context: Whether to attempt to extract the opentracing
  819. context from the request the servlet is handling.
  820. """
  821. if opentracing is None:
  822. yield # type: ignore[unreachable]
  823. return
  824. request_tags = {
  825. SynapseTags.REQUEST_ID: request.get_request_id(),
  826. tags.SPAN_KIND: tags.SPAN_KIND_RPC_SERVER,
  827. tags.HTTP_METHOD: request.get_method(),
  828. tags.HTTP_URL: request.get_redacted_uri(),
  829. tags.PEER_HOST_IPV6: request.get_client_ip_if_available(),
  830. }
  831. request_name = request.request_metrics.name
  832. context = span_context_from_request(request) if extract_context else None
  833. # we configure the scope not to finish the span immediately on exit, and instead
  834. # pass the span into the SynapseRequest, which will finish it once we've finished
  835. # sending the response to the client.
  836. scope = start_active_span(request_name, child_of=context, finish_on_close=False)
  837. request.set_opentracing_span(scope.span)
  838. with scope:
  839. inject_response_headers(request.responseHeaders)
  840. try:
  841. yield
  842. finally:
  843. # We set the operation name again in case its changed (which happens
  844. # with JsonResource).
  845. scope.span.set_operation_name(request.request_metrics.name)
  846. # Mypy seems to think that start_context.tag below can be Optional[str], but
  847. # that doesn't appear to be correct and works in practice.
  848. request_tags[
  849. SynapseTags.REQUEST_TAG
  850. ] = request.request_metrics.start_context.tag # type: ignore[assignment]
  851. # set the tags *after* the servlet completes, in case it decided to
  852. # prioritise the span (tags will get dropped on unprioritised spans)
  853. for k, v in request_tags.items():
  854. scope.span.set_tag(k, v)