You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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