opentracing.py 28 KB

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