opentracing.py 29 KB

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