opentracing.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  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 passing the
  68. operation name to ``trace``
  69. .. code-block:: python
  70. from synapse.logging.opentracing import trace
  71. @trace(opname="a_better_operation_name")
  72. def interesting_badly_named_function(*args, **kwargs):
  73. # Does all kinds of cool and expected things
  74. return something_usual_and_useful
  75. Setting Tags
  76. ------------
  77. To set a tag on the active span do
  78. .. code-block:: python
  79. from synapse.logging.opentracing import set_tag
  80. set_tag(tag_name, tag_value)
  81. There's a convenient decorator to tag all the args of the method. It uses
  82. inspection in order to use the formal parameter names prefixed with 'ARG_' as
  83. tag names. It uses kwarg names as tag names without the prefix.
  84. .. code-block:: python
  85. from synapse.logging.opentracing import tag_args
  86. @tag_args
  87. def set_fates(clotho, lachesis, atropos, father="Zues", mother="Themis"):
  88. pass
  89. set_fates("the story", "the end", "the act")
  90. # This will have the following tags
  91. # - ARG_clotho: "the story"
  92. # - ARG_lachesis: "the end"
  93. # - ARG_atropos: "the act"
  94. # - father: "Zues"
  95. # - mother: "Themis"
  96. Contexts and carriers
  97. ---------------------
  98. There are a selection of wrappers for injecting and extracting contexts from
  99. carriers provided. Unfortunately OpenTracing's three context injection
  100. techniques are not adequate for our inject of OpenTracing span-contexts into
  101. Twisted's http headers, EDU contents and our database tables. Also note that
  102. the binary encoding format mandated by OpenTracing is not actually implemented
  103. by jaeger_client v4.0.0 - it will silently noop.
  104. Please refer to the end of ``logging/opentracing.py`` for the available
  105. injection and extraction methods.
  106. Homeserver whitelisting
  107. -----------------------
  108. Most of the whitelist checks are encapsulated in the modules's injection
  109. and extraction method but be aware that using custom carriers or crossing
  110. unchartered waters will require the enforcement of the whitelist.
  111. ``logging/opentracing.py`` has a ``whitelisted_homeserver`` method which takes
  112. in a destination and compares it to the whitelist.
  113. Most injection methods take a 'destination' arg. The context will only be injected
  114. if the destination matches the whitelist or the destination is None.
  115. =======
  116. Gotchas
  117. =======
  118. - Checking whitelists on span propagation
  119. - Inserting pii
  120. - Forgetting to enter or exit a scope
  121. - Span source: make sure that the span you expect to be active across a
  122. function call really will be that one. Does the current function have more
  123. than one caller? Will all of those calling functions have be in a context
  124. with an active span?
  125. """
  126. import contextlib
  127. import enum
  128. import inspect
  129. import logging
  130. import re
  131. from functools import wraps
  132. from typing import (
  133. TYPE_CHECKING,
  134. Any,
  135. Callable,
  136. Collection,
  137. Dict,
  138. Generator,
  139. Iterable,
  140. List,
  141. Optional,
  142. Pattern,
  143. Type,
  144. TypeVar,
  145. Union,
  146. )
  147. import attr
  148. from typing_extensions import ParamSpec
  149. from twisted.internet import defer
  150. from twisted.web.http import Request
  151. from twisted.web.http_headers import Headers
  152. from synapse.config import ConfigError
  153. from synapse.util import json_decoder, json_encoder
  154. if TYPE_CHECKING:
  155. from synapse.http.site import SynapseRequest
  156. from synapse.server import HomeServer
  157. # Helper class
  158. class _DummyTagNames:
  159. """wrapper of opentracings tags. We need to have them if we
  160. want to reference them without opentracing around. Clearly they
  161. should never actually show up in a trace. `set_tags` overwrites
  162. these with the correct ones."""
  163. INVALID_TAG = "invalid-tag"
  164. COMPONENT = INVALID_TAG
  165. DATABASE_INSTANCE = INVALID_TAG
  166. DATABASE_STATEMENT = INVALID_TAG
  167. DATABASE_TYPE = INVALID_TAG
  168. DATABASE_USER = INVALID_TAG
  169. ERROR = INVALID_TAG
  170. HTTP_METHOD = INVALID_TAG
  171. HTTP_STATUS_CODE = INVALID_TAG
  172. HTTP_URL = INVALID_TAG
  173. MESSAGE_BUS_DESTINATION = INVALID_TAG
  174. PEER_ADDRESS = INVALID_TAG
  175. PEER_HOSTNAME = INVALID_TAG
  176. PEER_HOST_IPV4 = INVALID_TAG
  177. PEER_HOST_IPV6 = INVALID_TAG
  178. PEER_PORT = INVALID_TAG
  179. PEER_SERVICE = INVALID_TAG
  180. SAMPLING_PRIORITY = INVALID_TAG
  181. SERVICE = INVALID_TAG
  182. SPAN_KIND = INVALID_TAG
  183. SPAN_KIND_CONSUMER = INVALID_TAG
  184. SPAN_KIND_PRODUCER = INVALID_TAG
  185. SPAN_KIND_RPC_CLIENT = INVALID_TAG
  186. SPAN_KIND_RPC_SERVER = INVALID_TAG
  187. try:
  188. import opentracing
  189. import opentracing.tags
  190. tags = opentracing.tags
  191. except ImportError:
  192. opentracing = None # type: ignore[assignment]
  193. tags = _DummyTagNames # type: ignore[assignment]
  194. try:
  195. from jaeger_client import Config as JaegerConfig
  196. from synapse.logging.scopecontextmanager import LogContextScopeManager
  197. except ImportError:
  198. JaegerConfig = None # type: ignore
  199. LogContextScopeManager = None # type: ignore
  200. try:
  201. from rust_python_jaeger_reporter import Reporter
  202. # jaeger-client 4.7.0 requires that reporters inherit from BaseReporter, which
  203. # didn't exist before that version.
  204. try:
  205. from jaeger_client.reporter import BaseReporter
  206. except ImportError:
  207. class BaseReporter: # type: ignore[no-redef]
  208. pass
  209. @attr.s(slots=True, frozen=True, auto_attribs=True)
  210. class _WrappedRustReporter(BaseReporter):
  211. """Wrap the reporter to ensure `report_span` never throws."""
  212. _reporter: Reporter = attr.Factory(Reporter)
  213. def set_process(self, *args: Any, **kwargs: Any) -> None:
  214. return self._reporter.set_process(*args, **kwargs)
  215. def report_span(self, span: "opentracing.Span") -> None:
  216. try:
  217. return self._reporter.report_span(span)
  218. except Exception:
  219. logger.exception("Failed to report span")
  220. RustReporter: Optional[Type[_WrappedRustReporter]] = _WrappedRustReporter
  221. except ImportError:
  222. RustReporter = None
  223. logger = logging.getLogger(__name__)
  224. class SynapseTags:
  225. # The message ID of any to_device message processed
  226. TO_DEVICE_MESSAGE_ID = "to_device.message_id"
  227. # Whether the sync response has new data to be returned to the client.
  228. SYNC_RESULT = "sync.new_data"
  229. # incoming HTTP request ID (as written in the logs)
  230. REQUEST_ID = "request_id"
  231. # HTTP request tag (used to distinguish full vs incremental syncs, etc)
  232. REQUEST_TAG = "request_tag"
  233. # Text description of a database transaction
  234. DB_TXN_DESC = "db.txn_desc"
  235. # Uniqueish ID of a database transaction
  236. DB_TXN_ID = "db.txn_id"
  237. # The name of the external cache
  238. CACHE_NAME = "cache.name"
  239. class SynapseBaggage:
  240. FORCE_TRACING = "synapse-force-tracing"
  241. # Block everything by default
  242. # A regex which matches the server_names to expose traces for.
  243. # None means 'block everything'.
  244. _homeserver_whitelist: Optional[Pattern[str]] = None
  245. # Util methods
  246. class _Sentinel(enum.Enum):
  247. # defining a sentinel in this way allows mypy to correctly handle the
  248. # type of a dictionary lookup.
  249. sentinel = object()
  250. P = ParamSpec("P")
  251. R = TypeVar("R")
  252. def only_if_tracing(func: Callable[P, R]) -> Callable[P, Optional[R]]:
  253. """Executes the function only if we're tracing. Otherwise returns None."""
  254. @wraps(func)
  255. def _only_if_tracing_inner(*args: P.args, **kwargs: P.kwargs) -> Optional[R]:
  256. if opentracing:
  257. return func(*args, **kwargs)
  258. else:
  259. return None
  260. return _only_if_tracing_inner
  261. def ensure_active_span(message: str, ret=None):
  262. """Executes the operation only if opentracing is enabled and there is an active span.
  263. If there is no active span it logs message at the error level.
  264. Args:
  265. message: Message which fills in "There was no active span when trying to %s"
  266. in the error log if there is no active span and opentracing is enabled.
  267. ret (object): return value if opentracing is None or there is no active span.
  268. Returns (object): The result of the func or ret if opentracing is disabled or there
  269. was no active span.
  270. """
  271. def ensure_active_span_inner_1(func):
  272. @wraps(func)
  273. def ensure_active_span_inner_2(*args, **kwargs):
  274. if not opentracing:
  275. return ret
  276. if not opentracing.tracer.active_span:
  277. logger.error(
  278. "There was no active span when trying to %s."
  279. " Did you forget to start one or did a context slip?",
  280. message,
  281. stack_info=True,
  282. )
  283. return ret
  284. return func(*args, **kwargs)
  285. return ensure_active_span_inner_2
  286. return ensure_active_span_inner_1
  287. # Setup
  288. def init_tracer(hs: "HomeServer") -> None:
  289. """Set the whitelists and initialise the JaegerClient tracer"""
  290. global opentracing
  291. if not hs.config.tracing.opentracer_enabled:
  292. # We don't have a tracer
  293. opentracing = None # type: ignore[assignment]
  294. return
  295. if not opentracing or not JaegerConfig:
  296. raise ConfigError(
  297. "The server has been configured to use opentracing but opentracing is not "
  298. "installed."
  299. )
  300. # Pull out the jaeger config if it was given. Otherwise set it to something sensible.
  301. # See https://github.com/jaegertracing/jaeger-client-python/blob/master/jaeger_client/config.py
  302. set_homeserver_whitelist(hs.config.tracing.opentracer_whitelist)
  303. from jaeger_client.metrics.prometheus import PrometheusMetricsFactory
  304. config = JaegerConfig(
  305. config=hs.config.tracing.jaeger_config,
  306. service_name=f"{hs.config.server.server_name} {hs.get_instance_name()}",
  307. scope_manager=LogContextScopeManager(),
  308. metrics_factory=PrometheusMetricsFactory(),
  309. )
  310. # If we have the rust jaeger reporter available let's use that.
  311. if RustReporter:
  312. logger.info("Using rust_python_jaeger_reporter library")
  313. assert config.sampler is not None
  314. tracer = config.create_tracer(RustReporter(), config.sampler)
  315. opentracing.set_global_tracer(tracer)
  316. else:
  317. config.initialize_tracer()
  318. # Whitelisting
  319. @only_if_tracing
  320. def set_homeserver_whitelist(homeserver_whitelist: Iterable[str]) -> None:
  321. """Sets the homeserver whitelist
  322. Args:
  323. homeserver_whitelist: regexes specifying whitelisted homeservers
  324. """
  325. global _homeserver_whitelist
  326. if homeserver_whitelist:
  327. # Makes a single regex which accepts all passed in regexes in the list
  328. _homeserver_whitelist = re.compile(
  329. "({})".format(")|(".join(homeserver_whitelist))
  330. )
  331. @only_if_tracing
  332. def whitelisted_homeserver(destination: str) -> bool:
  333. """Checks if a destination matches the whitelist
  334. Args:
  335. destination
  336. """
  337. if _homeserver_whitelist:
  338. return _homeserver_whitelist.match(destination) is not None
  339. return False
  340. # Start spans and scopes
  341. # Could use kwargs but I want these to be explicit
  342. def start_active_span(
  343. operation_name: str,
  344. child_of: Optional[Union["opentracing.Span", "opentracing.SpanContext"]] = None,
  345. references: Optional[List["opentracing.Reference"]] = None,
  346. tags: Optional[Dict[str, str]] = None,
  347. start_time: Optional[float] = None,
  348. ignore_active_span: bool = False,
  349. finish_on_close: bool = True,
  350. *,
  351. tracer: Optional["opentracing.Tracer"] = None,
  352. ):
  353. """Starts an active opentracing span.
  354. Records the start time for the span, and sets it as the "active span" in the
  355. scope manager.
  356. Args:
  357. See opentracing.tracer
  358. Returns:
  359. scope (Scope) or contextlib.nullcontext
  360. """
  361. if opentracing is None:
  362. return contextlib.nullcontext() # type: ignore[unreachable]
  363. if tracer is None:
  364. # use the global tracer by default
  365. tracer = opentracing.tracer
  366. return tracer.start_active_span(
  367. operation_name,
  368. child_of=child_of,
  369. references=references,
  370. tags=tags,
  371. start_time=start_time,
  372. ignore_active_span=ignore_active_span,
  373. finish_on_close=finish_on_close,
  374. )
  375. def start_active_span_follows_from(
  376. operation_name: str,
  377. contexts: Collection,
  378. child_of: Optional[Union["opentracing.Span", "opentracing.SpanContext"]] = None,
  379. start_time: Optional[float] = None,
  380. *,
  381. inherit_force_tracing: bool = False,
  382. tracer: Optional["opentracing.Tracer"] = None,
  383. ):
  384. """Starts an active opentracing span, with additional references to previous spans
  385. Args:
  386. operation_name: name of the operation represented by the new span
  387. contexts: the previous spans to inherit from
  388. child_of: optionally override the parent span. If unset, the currently active
  389. span will be the parent. (If there is no currently active span, the first
  390. span in `contexts` will be the parent.)
  391. start_time: optional override for the start time of the created span. Seconds
  392. since the epoch.
  393. inherit_force_tracing: if set, and any of the previous contexts have had tracing
  394. forced, the new span will also have tracing forced.
  395. tracer: override the opentracing tracer. By default the global tracer is used.
  396. """
  397. if opentracing is None:
  398. return contextlib.nullcontext() # type: ignore[unreachable]
  399. references = [opentracing.follows_from(context) for context in contexts]
  400. scope = start_active_span(
  401. operation_name,
  402. child_of=child_of,
  403. references=references,
  404. start_time=start_time,
  405. tracer=tracer,
  406. )
  407. if inherit_force_tracing and any(
  408. is_context_forced_tracing(ctx) for ctx in contexts
  409. ):
  410. force_tracing(scope.span)
  411. return scope
  412. def start_active_span_from_edu(
  413. edu_content: Dict[str, Any],
  414. operation_name: str,
  415. references: Optional[List["opentracing.Reference"]] = None,
  416. tags: Optional[Dict[str, str]] = None,
  417. start_time: Optional[float] = None,
  418. ignore_active_span: bool = False,
  419. finish_on_close: bool = True,
  420. ) -> "opentracing.Scope":
  421. """
  422. Extracts a span context from an edu and uses it to start a new active span
  423. Args:
  424. edu_content: an edu_content with a `context` field whose value is
  425. canonical json for a dict which contains opentracing information.
  426. For the other args see opentracing.tracer
  427. """
  428. references = references or []
  429. if opentracing is None:
  430. return contextlib.nullcontext() # type: ignore[unreachable]
  431. carrier = json_decoder.decode(edu_content.get("context", "{}")).get(
  432. "opentracing", {}
  433. )
  434. context = opentracing.tracer.extract(opentracing.Format.TEXT_MAP, carrier)
  435. _references = [
  436. opentracing.child_of(span_context_from_string(x))
  437. for x in carrier.get("references", [])
  438. ]
  439. # For some reason jaeger decided not to support the visualization of multiple parent
  440. # spans or explicitly show references. I include the span context as a tag here as
  441. # an aid to people debugging but it's really not an ideal solution.
  442. references += _references
  443. scope = opentracing.tracer.start_active_span(
  444. operation_name,
  445. child_of=context,
  446. references=references,
  447. tags=tags,
  448. start_time=start_time,
  449. ignore_active_span=ignore_active_span,
  450. finish_on_close=finish_on_close,
  451. )
  452. scope.span.set_tag("references", carrier.get("references", []))
  453. return scope
  454. # Opentracing setters for tags, logs, etc
  455. @only_if_tracing
  456. def active_span() -> Optional["opentracing.Span"]:
  457. """Get the currently active span, if any"""
  458. return opentracing.tracer.active_span
  459. @ensure_active_span("set a tag")
  460. def set_tag(key: str, value: Union[str, bool, int, float]) -> None:
  461. """Sets a tag on the active span"""
  462. assert opentracing.tracer.active_span is not None
  463. opentracing.tracer.active_span.set_tag(key, value)
  464. @ensure_active_span("log")
  465. def log_kv(key_values: Dict[str, Any], timestamp: Optional[float] = None) -> None:
  466. """Log to the active span"""
  467. assert opentracing.tracer.active_span is not None
  468. opentracing.tracer.active_span.log_kv(key_values, timestamp)
  469. @ensure_active_span("set the traces operation name")
  470. def set_operation_name(operation_name: str) -> None:
  471. """Sets the operation name of the active span"""
  472. assert opentracing.tracer.active_span is not None
  473. opentracing.tracer.active_span.set_operation_name(operation_name)
  474. @only_if_tracing
  475. def force_tracing(
  476. span: Union["opentracing.Span", _Sentinel] = _Sentinel.sentinel
  477. ) -> None:
  478. """Force sampling for the active/given span and its children.
  479. Args:
  480. span: span to force tracing for. By default, the active span.
  481. """
  482. if isinstance(span, _Sentinel):
  483. span_to_trace = opentracing.tracer.active_span
  484. else:
  485. span_to_trace = span
  486. if span_to_trace is None:
  487. logger.error("No active span in force_tracing")
  488. return
  489. span_to_trace.set_tag(opentracing.tags.SAMPLING_PRIORITY, 1)
  490. # also set a bit of baggage, so that we have a way of figuring out if
  491. # it is enabled later
  492. span_to_trace.set_baggage_item(SynapseBaggage.FORCE_TRACING, "1")
  493. def is_context_forced_tracing(
  494. span_context: Optional["opentracing.SpanContext"],
  495. ) -> bool:
  496. """Check if sampling has been force for the given span context."""
  497. if span_context is None:
  498. return False
  499. return span_context.baggage.get(SynapseBaggage.FORCE_TRACING) is not None
  500. # Injection and extraction
  501. @ensure_active_span("inject the span into a header dict")
  502. def inject_header_dict(
  503. headers: Dict[bytes, List[bytes]],
  504. destination: Optional[str] = None,
  505. check_destination: bool = True,
  506. ) -> None:
  507. """
  508. Injects a span context into a dict of HTTP headers
  509. Args:
  510. headers: the dict to inject headers into
  511. destination: address of entity receiving the span context. Must be given unless
  512. check_destination is False. The context will only be injected if the
  513. destination matches the opentracing whitelist
  514. check_destination (bool): If false, destination will be ignored and the context
  515. will always be injected.
  516. Note:
  517. The headers set by the tracer are custom to the tracer implementation which
  518. should be unique enough that they don't interfere with any headers set by
  519. synapse or twisted. If we're still using jaeger these headers would be those
  520. here:
  521. https://github.com/jaegertracing/jaeger-client-python/blob/master/jaeger_client/constants.py
  522. """
  523. if check_destination:
  524. if destination is None:
  525. raise ValueError(
  526. "destination must be given unless check_destination is False"
  527. )
  528. if not whitelisted_homeserver(destination):
  529. return
  530. span = opentracing.tracer.active_span
  531. carrier: Dict[str, str] = {}
  532. assert span is not None
  533. opentracing.tracer.inject(span.context, opentracing.Format.HTTP_HEADERS, carrier)
  534. for key, value in carrier.items():
  535. headers[key.encode()] = [value.encode()]
  536. def inject_response_headers(response_headers: Headers) -> None:
  537. """Inject the current trace id into the HTTP response headers"""
  538. if not opentracing:
  539. return
  540. span = opentracing.tracer.active_span
  541. if not span:
  542. return
  543. # This is a bit implementation-specific.
  544. #
  545. # Jaeger's Spans have a trace_id property; other implementations (including the
  546. # dummy opentracing.span.Span which we use if init_tracer is not called) do not
  547. # expose it
  548. trace_id = getattr(span, "trace_id", None)
  549. if trace_id is not None:
  550. response_headers.addRawHeader("Synapse-Trace-Id", f"{trace_id:x}")
  551. @ensure_active_span("get the active span context as a dict", ret={})
  552. def get_active_span_text_map(destination: Optional[str] = None) -> Dict[str, str]:
  553. """
  554. Gets a span context as a dict. This can be used instead of manually
  555. injecting a span into an empty carrier.
  556. Args:
  557. destination: the name of the remote server.
  558. Returns:
  559. dict: the active span's context if opentracing is enabled, otherwise empty.
  560. """
  561. if destination and not whitelisted_homeserver(destination):
  562. return {}
  563. carrier: Dict[str, str] = {}
  564. assert opentracing.tracer.active_span is not None
  565. opentracing.tracer.inject(
  566. opentracing.tracer.active_span.context, opentracing.Format.TEXT_MAP, carrier
  567. )
  568. return carrier
  569. @ensure_active_span("get the span context as a string.", ret={})
  570. def active_span_context_as_string() -> str:
  571. """
  572. Returns:
  573. The active span context encoded as a string.
  574. """
  575. carrier: Dict[str, str] = {}
  576. if opentracing:
  577. assert opentracing.tracer.active_span is not None
  578. opentracing.tracer.inject(
  579. opentracing.tracer.active_span.context, opentracing.Format.TEXT_MAP, carrier
  580. )
  581. return json_encoder.encode(carrier)
  582. def span_context_from_request(request: Request) -> "Optional[opentracing.SpanContext]":
  583. """Extract an opentracing context from the headers on an HTTP request
  584. This is useful when we have received an HTTP request from another part of our
  585. system, and want to link our spans to those of the remote system.
  586. """
  587. if not opentracing:
  588. return None
  589. header_dict = {
  590. k.decode(): v[0].decode() for k, v in request.requestHeaders.getAllRawHeaders()
  591. }
  592. return opentracing.tracer.extract(opentracing.Format.HTTP_HEADERS, header_dict)
  593. @only_if_tracing
  594. def span_context_from_string(carrier: str) -> Optional["opentracing.SpanContext"]:
  595. """
  596. Returns:
  597. The active span context decoded from a string.
  598. """
  599. payload: Dict[str, str] = json_decoder.decode(carrier)
  600. return opentracing.tracer.extract(opentracing.Format.TEXT_MAP, payload)
  601. @only_if_tracing
  602. def extract_text_map(carrier: Dict[str, str]) -> Optional["opentracing.SpanContext"]:
  603. """
  604. Wrapper method for opentracing's tracer.extract for TEXT_MAP.
  605. Args:
  606. carrier: a dict possibly containing a span context.
  607. Returns:
  608. The active span context extracted from carrier.
  609. """
  610. return opentracing.tracer.extract(opentracing.Format.TEXT_MAP, carrier)
  611. # Tracing decorators
  612. def trace(func=None, opname: Optional[str] = None):
  613. """
  614. Decorator to trace a function.
  615. Sets the operation name to that of the function's or that given
  616. as operation_name. See the module's doc string for usage
  617. examples.
  618. """
  619. def decorator(func):
  620. if opentracing is None:
  621. return func # type: ignore[unreachable]
  622. _opname = opname if opname else func.__name__
  623. if inspect.iscoroutinefunction(func):
  624. @wraps(func)
  625. async def _trace_inner(*args, **kwargs):
  626. with start_active_span(_opname):
  627. return await func(*args, **kwargs)
  628. else:
  629. # The other case here handles both sync functions and those
  630. # decorated with inlineDeferred.
  631. @wraps(func)
  632. def _trace_inner(*args, **kwargs):
  633. scope = start_active_span(_opname)
  634. scope.__enter__()
  635. try:
  636. result = func(*args, **kwargs)
  637. if isinstance(result, defer.Deferred):
  638. def call_back(result: R) -> R:
  639. scope.__exit__(None, None, None)
  640. return result
  641. def err_back(result: R) -> R:
  642. scope.__exit__(None, None, None)
  643. return result
  644. result.addCallbacks(call_back, err_back)
  645. else:
  646. if inspect.isawaitable(result):
  647. logger.error(
  648. "@trace may not have wrapped %s correctly! "
  649. "The function is not async but returned a %s.",
  650. func.__qualname__,
  651. type(result).__name__,
  652. )
  653. scope.__exit__(None, None, None)
  654. return result
  655. except Exception as e:
  656. scope.__exit__(type(e), None, e.__traceback__)
  657. raise
  658. return _trace_inner
  659. if func:
  660. return decorator(func)
  661. else:
  662. return decorator
  663. def tag_args(func: Callable[P, R]) -> Callable[P, R]:
  664. """
  665. Tags all of the args to the active span.
  666. """
  667. if not opentracing:
  668. return func
  669. @wraps(func)
  670. def _tag_args_inner(*args: P.args, **kwargs: P.kwargs) -> R:
  671. argspec = inspect.getfullargspec(func)
  672. for i, arg in enumerate(argspec.args[1:]):
  673. set_tag("ARG_" + arg, args[i]) # type: ignore[index]
  674. set_tag("args", args[len(argspec.args) :]) # type: ignore[index]
  675. set_tag("kwargs", kwargs)
  676. return func(*args, **kwargs)
  677. return _tag_args_inner
  678. @contextlib.contextmanager
  679. def trace_servlet(
  680. request: "SynapseRequest", extract_context: bool = False
  681. ) -> Generator[None, None, None]:
  682. """Returns a context manager which traces a request. It starts a span
  683. with some servlet specific tags such as the request metrics name and
  684. request information.
  685. Args:
  686. request
  687. extract_context: Whether to attempt to extract the opentracing
  688. context from the request the servlet is handling.
  689. """
  690. if opentracing is None:
  691. yield # type: ignore[unreachable]
  692. return
  693. request_tags = {
  694. SynapseTags.REQUEST_ID: request.get_request_id(),
  695. tags.SPAN_KIND: tags.SPAN_KIND_RPC_SERVER,
  696. tags.HTTP_METHOD: request.get_method(),
  697. tags.HTTP_URL: request.get_redacted_uri(),
  698. tags.PEER_HOST_IPV6: request.getClientAddress().host,
  699. }
  700. request_name = request.request_metrics.name
  701. context = span_context_from_request(request) if extract_context else None
  702. # we configure the scope not to finish the span immediately on exit, and instead
  703. # pass the span into the SynapseRequest, which will finish it once we've finished
  704. # sending the response to the client.
  705. scope = start_active_span(request_name, child_of=context, finish_on_close=False)
  706. request.set_opentracing_span(scope.span)
  707. with scope:
  708. inject_response_headers(request.responseHeaders)
  709. try:
  710. yield
  711. finally:
  712. # We set the operation name again in case its changed (which happens
  713. # with JsonResource).
  714. scope.span.set_operation_name(request.request_metrics.name)
  715. # set the tags *after* the servlet completes, in case it decided to
  716. # prioritise the span (tags will get dropped on unprioritised spans)
  717. request_tags[
  718. SynapseTags.REQUEST_TAG
  719. ] = request.request_metrics.start_context.tag
  720. for k, v in request_tags.items():
  721. scope.span.set_tag(k, v)