opentracing.py 28 KB

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