opentracing.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062
  1. # Copyright 2019 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # NOTE
  15. # This is a small wrapper around opentracing because opentracing is not currently
  16. # packaged downstream (specifically debian). Since opentracing instrumentation is
  17. # fairly invasive it was awkward to make it optional. As a result we opted to encapsulate
  18. # all opentracing state in these methods which effectively noop if opentracing is
  19. # not present. We should strongly consider encouraging the downstream distributers
  20. # to package opentracing and making opentracing a full dependency. In order to facilitate
  21. # this move the methods have work very similarly to opentracing's and it should only
  22. # be a matter of few regexes to move over to opentracing's access patterns proper.
  23. """
  24. ============================
  25. Using OpenTracing in Synapse
  26. ============================
  27. Python-specific tracing concepts are at https://opentracing.io/guides/python/.
  28. Note that Synapse wraps OpenTracing in a small module (this one) in order to make the
  29. OpenTracing dependency optional. That means that the access patterns are
  30. different to those demonstrated in the OpenTracing guides. However, it is
  31. still useful to know, especially if OpenTracing is included as a full dependency
  32. in the future or if you are modifying this module.
  33. OpenTracing is encapsulated so that
  34. no span objects from OpenTracing are exposed in Synapse's code. This allows
  35. OpenTracing to be easily disabled in Synapse and thereby have OpenTracing as
  36. an optional dependency. This does however limit the number of modifiable spans
  37. at any point in the code to one. From here out references to `opentracing`
  38. in the code snippets refer to the Synapses module.
  39. Most methods provided in the module have a direct correlation to those provided
  40. by opentracing. Refer to docs there for a more in-depth documentation on some of
  41. the args and methods.
  42. Tracing
  43. -------
  44. In Synapse it is not possible to start a non-active span. Spans can be started
  45. using the ``start_active_span`` method. This returns a scope (see
  46. OpenTracing docs) which is a context manager that needs to be entered and
  47. exited. This is usually done by using ``with``.
  48. .. code-block:: python
  49. from synapse.logging.opentracing import start_active_span
  50. with start_active_span("operation name"):
  51. # Do something we want to tracer
  52. Forgetting to enter or exit a scope will result in some mysterious and grievous log
  53. context errors.
  54. At anytime where there is an active span ``opentracing.set_tag`` can be used to
  55. set a tag on the current active span.
  56. Tracing functions
  57. -----------------
  58. Functions can be easily traced using decorators. The name of
  59. the function becomes the operation name for the span.
  60. .. code-block:: python
  61. from synapse.logging.opentracing import trace
  62. # Start a span using 'interesting_function' as the operation name
  63. @trace
  64. def interesting_function(*args, **kwargs):
  65. # Does all kinds of cool and expected things
  66. return something_usual_and_useful
  67. Operation names can be explicitly set for a function by using ``trace_with_opname``:
  68. .. code-block:: python
  69. from synapse.logging.opentracing import trace_with_opname
  70. @trace_with_opname("a_better_operation_name")
  71. def interesting_badly_named_function(*args, **kwargs):
  72. # Does all kinds of cool and expected things
  73. return something_usual_and_useful
  74. Setting Tags
  75. ------------
  76. To set a tag on the active span do
  77. .. code-block:: python
  78. from synapse.logging.opentracing import set_tag
  79. set_tag(tag_name, tag_value)
  80. There's a convenient decorator to tag all the args of the method. It uses
  81. inspection in order to use the formal parameter names prefixed with 'ARG_' as
  82. tag names. It uses kwarg names as tag names without the prefix.
  83. .. code-block:: python
  84. from synapse.logging.opentracing import tag_args
  85. @tag_args
  86. def set_fates(clotho, lachesis, atropos, father="Zues", mother="Themis"):
  87. pass
  88. set_fates("the story", "the end", "the act")
  89. # This will have the following tags
  90. # - ARG_clotho: "the story"
  91. # - ARG_lachesis: "the end"
  92. # - ARG_atropos: "the act"
  93. # - father: "Zues"
  94. # - mother: "Themis"
  95. Contexts and carriers
  96. ---------------------
  97. There are a selection of wrappers for injecting and extracting contexts from
  98. carriers provided. Unfortunately OpenTracing's three context injection
  99. techniques are not adequate for our inject of OpenTracing span-contexts into
  100. Twisted's http headers, EDU contents and our database tables. Also note that
  101. the binary encoding format mandated by OpenTracing is not actually implemented
  102. by jaeger_client v4.0.0 - it will silently noop.
  103. Please refer to the end of ``logging/opentracing.py`` for the available
  104. injection and extraction methods.
  105. Homeserver whitelisting
  106. -----------------------
  107. Most of the whitelist checks are encapsulated in the modules's injection
  108. and extraction method but be aware that using custom carriers or crossing
  109. unchartered waters will require the enforcement of the whitelist.
  110. ``logging/opentracing.py`` has a ``whitelisted_homeserver`` method which takes
  111. in a destination and compares it to the whitelist.
  112. Most injection methods take a 'destination' arg. The context will only be injected
  113. if the destination matches the whitelist or the destination is None.
  114. =======
  115. Gotchas
  116. =======
  117. - Checking whitelists on span propagation
  118. - Inserting pii
  119. - Forgetting to enter or exit a scope
  120. - Span source: make sure that the span you expect to be active across a
  121. function call really will be that one. Does the current function have more
  122. than one caller? Will all of those calling functions have be in a context
  123. with an active span?
  124. """
  125. import contextlib
  126. import enum
  127. import inspect
  128. import logging
  129. import re
  130. from functools import wraps
  131. from typing import (
  132. TYPE_CHECKING,
  133. Any,
  134. Callable,
  135. Collection,
  136. ContextManager,
  137. Dict,
  138. Generator,
  139. Iterable,
  140. List,
  141. Optional,
  142. Pattern,
  143. Type,
  144. TypeVar,
  145. Union,
  146. cast,
  147. overload,
  148. )
  149. import attr
  150. from typing_extensions import ParamSpec
  151. from twisted.internet import defer
  152. from twisted.web.http import Request
  153. from twisted.web.http_headers import Headers
  154. from synapse.config import ConfigError
  155. from synapse.util import json_decoder, json_encoder
  156. if TYPE_CHECKING:
  157. from synapse.http.site import SynapseRequest
  158. from synapse.server import HomeServer
  159. # Helper class
  160. # Matches the number suffix in an instance name like "matrix.org client_reader-8"
  161. STRIP_INSTANCE_NUMBER_SUFFIX_REGEX = re.compile(r"[_-]?\d+$")
  162. class _DummyTagNames:
  163. """wrapper of opentracings tags. We need to have them if we
  164. want to reference them without opentracing around. Clearly they
  165. should never actually show up in a trace. `set_tags` overwrites
  166. these with the correct ones."""
  167. INVALID_TAG = "invalid-tag"
  168. COMPONENT = INVALID_TAG
  169. DATABASE_INSTANCE = INVALID_TAG
  170. DATABASE_STATEMENT = INVALID_TAG
  171. DATABASE_TYPE = INVALID_TAG
  172. DATABASE_USER = INVALID_TAG
  173. ERROR = INVALID_TAG
  174. HTTP_METHOD = INVALID_TAG
  175. HTTP_STATUS_CODE = INVALID_TAG
  176. HTTP_URL = INVALID_TAG
  177. MESSAGE_BUS_DESTINATION = INVALID_TAG
  178. PEER_ADDRESS = INVALID_TAG
  179. PEER_HOSTNAME = INVALID_TAG
  180. PEER_HOST_IPV4 = INVALID_TAG
  181. PEER_HOST_IPV6 = INVALID_TAG
  182. PEER_PORT = INVALID_TAG
  183. PEER_SERVICE = INVALID_TAG
  184. SAMPLING_PRIORITY = INVALID_TAG
  185. SERVICE = INVALID_TAG
  186. SPAN_KIND = INVALID_TAG
  187. SPAN_KIND_CONSUMER = INVALID_TAG
  188. SPAN_KIND_PRODUCER = INVALID_TAG
  189. SPAN_KIND_RPC_CLIENT = INVALID_TAG
  190. SPAN_KIND_RPC_SERVER = INVALID_TAG
  191. try:
  192. import opentracing
  193. import opentracing.tags
  194. tags = opentracing.tags
  195. except ImportError:
  196. opentracing = None # type: ignore[assignment]
  197. tags = _DummyTagNames # type: ignore[assignment]
  198. try:
  199. from jaeger_client import Config as JaegerConfig
  200. from synapse.logging.scopecontextmanager import LogContextScopeManager
  201. except ImportError:
  202. JaegerConfig = None # type: ignore
  203. LogContextScopeManager = None # type: ignore
  204. try:
  205. from rust_python_jaeger_reporter import Reporter
  206. # jaeger-client 4.7.0 requires that reporters inherit from BaseReporter, which
  207. # didn't exist before that version.
  208. try:
  209. from jaeger_client.reporter import BaseReporter
  210. except ImportError:
  211. class BaseReporter: # type: ignore[no-redef]
  212. pass
  213. @attr.s(slots=True, frozen=True, auto_attribs=True)
  214. class _WrappedRustReporter(BaseReporter):
  215. """Wrap the reporter to ensure `report_span` never throws."""
  216. _reporter: Reporter = attr.Factory(Reporter)
  217. def set_process(self, *args: Any, **kwargs: Any) -> None:
  218. return self._reporter.set_process(*args, **kwargs)
  219. def report_span(self, span: "opentracing.Span") -> None:
  220. try:
  221. return self._reporter.report_span(span)
  222. except Exception:
  223. logger.exception("Failed to report span")
  224. RustReporter: Optional[Type[_WrappedRustReporter]] = _WrappedRustReporter
  225. except ImportError:
  226. RustReporter = None
  227. logger = logging.getLogger(__name__)
  228. class SynapseTags:
  229. # The message ID of any to_device EDU processed
  230. TO_DEVICE_EDU_ID = "to_device.edu_id"
  231. # Details about to-device messages
  232. TO_DEVICE_TYPE = "to_device.type"
  233. TO_DEVICE_SENDER = "to_device.sender"
  234. TO_DEVICE_RECIPIENT = "to_device.recipient"
  235. TO_DEVICE_RECIPIENT_DEVICE = "to_device.recipient_device"
  236. TO_DEVICE_MSGID = "to_device.msgid" # client-generated ID
  237. # Whether the sync response has new data to be returned to the client.
  238. SYNC_RESULT = "sync.new_data"
  239. INSTANCE_NAME = "instance_name"
  240. # incoming HTTP request ID (as written in the logs)
  241. REQUEST_ID = "request_id"
  242. # HTTP request tag (used to distinguish full vs incremental syncs, etc)
  243. REQUEST_TAG = "request_tag"
  244. # Text description of a database transaction
  245. DB_TXN_DESC = "db.txn_desc"
  246. # Uniqueish ID of a database transaction
  247. DB_TXN_ID = "db.txn_id"
  248. # The name of the external cache
  249. CACHE_NAME = "cache.name"
  250. # Used to tag function arguments
  251. #
  252. # Tag a named arg. The name of the argument should be appended to this prefix.
  253. FUNC_ARG_PREFIX = "ARG."
  254. # Tag extra variadic number of positional arguments (`def foo(first, second, *extras)`)
  255. FUNC_ARGS = "args"
  256. # Tag keyword args
  257. FUNC_KWARGS = "kwargs"
  258. # Some intermediate result that's interesting to the function. The label for
  259. # the result should be appended to this prefix.
  260. RESULT_PREFIX = "RESULT."
  261. class SynapseBaggage:
  262. FORCE_TRACING = "synapse-force-tracing"
  263. # Block everything by default
  264. # A regex which matches the server_names to expose traces for.
  265. # None means 'block everything'.
  266. _homeserver_whitelist: Optional[Pattern[str]] = None
  267. # Util methods
  268. class _Sentinel(enum.Enum):
  269. # defining a sentinel in this way allows mypy to correctly handle the
  270. # type of a dictionary lookup.
  271. sentinel = object()
  272. P = ParamSpec("P")
  273. R = TypeVar("R")
  274. T = TypeVar("T")
  275. def only_if_tracing(func: Callable[P, R]) -> Callable[P, Optional[R]]:
  276. """Executes the function only if we're tracing. Otherwise returns None."""
  277. @wraps(func)
  278. def _only_if_tracing_inner(*args: P.args, **kwargs: P.kwargs) -> Optional[R]:
  279. if opentracing:
  280. return func(*args, **kwargs)
  281. else:
  282. return None
  283. return _only_if_tracing_inner
  284. @overload
  285. def ensure_active_span(
  286. message: str,
  287. ) -> Callable[[Callable[P, R]], Callable[P, Optional[R]]]:
  288. ...
  289. @overload
  290. def ensure_active_span(
  291. message: str, ret: T
  292. ) -> Callable[[Callable[P, R]], Callable[P, Union[T, R]]]:
  293. ...
  294. def ensure_active_span(
  295. message: str, ret: Optional[T] = None
  296. ) -> Callable[[Callable[P, R]], Callable[P, Union[Optional[T], R]]]:
  297. """Executes the operation only if opentracing is enabled and there is an active span.
  298. If there is no active span it logs message at the error level.
  299. Args:
  300. message: Message which fills in "There was no active span when trying to %s"
  301. in the error log if there is no active span and opentracing is enabled.
  302. ret: return value if opentracing is None or there is no active span.
  303. Returns:
  304. The result of the func, falling back to ret if opentracing is disabled or there
  305. was no active span.
  306. """
  307. def ensure_active_span_inner_1(
  308. func: Callable[P, R]
  309. ) -> Callable[P, Union[Optional[T], R]]:
  310. @wraps(func)
  311. def ensure_active_span_inner_2(
  312. *args: P.args, **kwargs: P.kwargs
  313. ) -> Union[Optional[T], R]:
  314. if not opentracing:
  315. return ret
  316. if not opentracing.tracer.active_span:
  317. logger.error(
  318. "There was no active span when trying to %s."
  319. " Did you forget to start one or did a context slip?",
  320. message,
  321. stack_info=True,
  322. )
  323. return ret
  324. return func(*args, **kwargs)
  325. return ensure_active_span_inner_2
  326. return ensure_active_span_inner_1
  327. # Setup
  328. def init_tracer(hs: "HomeServer") -> None:
  329. """Set the whitelists and initialise the JaegerClient tracer"""
  330. global opentracing
  331. if not hs.config.tracing.opentracer_enabled:
  332. # We don't have a tracer
  333. opentracing = None # type: ignore[assignment]
  334. return
  335. if not opentracing or not JaegerConfig:
  336. raise ConfigError(
  337. "The server has been configured to use opentracing but opentracing is not "
  338. "installed."
  339. )
  340. # Pull out the jaeger config if it was given. Otherwise set it to something sensible.
  341. # See https://github.com/jaegertracing/jaeger-client-python/blob/master/jaeger_client/config.py
  342. set_homeserver_whitelist(hs.config.tracing.opentracer_whitelist)
  343. from jaeger_client.metrics.prometheus import PrometheusMetricsFactory
  344. # Instance names are opaque strings but by stripping off the number suffix,
  345. # we can get something that looks like a "worker type", e.g.
  346. # "client_reader-1" -> "client_reader" so we don't spread the traces across
  347. # so many services.
  348. instance_name_by_type = re.sub(
  349. STRIP_INSTANCE_NUMBER_SUFFIX_REGEX, "", hs.get_instance_name()
  350. )
  351. config = JaegerConfig(
  352. config=hs.config.tracing.jaeger_config,
  353. service_name=f"{hs.config.server.server_name} {instance_name_by_type}",
  354. scope_manager=LogContextScopeManager(),
  355. metrics_factory=PrometheusMetricsFactory(),
  356. )
  357. # If we have the rust jaeger reporter available let's use that.
  358. if RustReporter:
  359. logger.info("Using rust_python_jaeger_reporter library")
  360. assert config.sampler is not None
  361. tracer = config.create_tracer(RustReporter(), config.sampler)
  362. opentracing.set_global_tracer(tracer)
  363. else:
  364. config.initialize_tracer()
  365. # Whitelisting
  366. @only_if_tracing
  367. def set_homeserver_whitelist(homeserver_whitelist: Iterable[str]) -> None:
  368. """Sets the homeserver whitelist
  369. Args:
  370. homeserver_whitelist: regexes specifying whitelisted homeservers
  371. """
  372. global _homeserver_whitelist
  373. if homeserver_whitelist:
  374. # Makes a single regex which accepts all passed in regexes in the list
  375. _homeserver_whitelist = re.compile(
  376. "({})".format(")|(".join(homeserver_whitelist))
  377. )
  378. @only_if_tracing
  379. def whitelisted_homeserver(destination: str) -> bool:
  380. """Checks if a destination matches the whitelist
  381. Args:
  382. destination
  383. """
  384. if _homeserver_whitelist:
  385. return _homeserver_whitelist.match(destination) is not None
  386. return False
  387. # Start spans and scopes
  388. # Could use kwargs but I want these to be explicit
  389. def start_active_span(
  390. operation_name: str,
  391. child_of: Optional[Union["opentracing.Span", "opentracing.SpanContext"]] = None,
  392. references: Optional[List["opentracing.Reference"]] = None,
  393. tags: Optional[Dict[str, str]] = None,
  394. start_time: Optional[float] = None,
  395. ignore_active_span: bool = False,
  396. finish_on_close: bool = True,
  397. *,
  398. tracer: Optional["opentracing.Tracer"] = None,
  399. ) -> "opentracing.Scope":
  400. """Starts an active opentracing span.
  401. Records the start time for the span, and sets it as the "active span" in the
  402. scope manager.
  403. Args:
  404. See opentracing.tracer
  405. Returns:
  406. scope (Scope) or contextlib.nullcontext
  407. """
  408. if opentracing is None:
  409. return contextlib.nullcontext() # type: ignore[unreachable]
  410. if tracer is None:
  411. # use the global tracer by default
  412. tracer = opentracing.tracer
  413. return tracer.start_active_span(
  414. operation_name,
  415. child_of=child_of,
  416. references=references,
  417. tags=tags,
  418. start_time=start_time,
  419. ignore_active_span=ignore_active_span,
  420. finish_on_close=finish_on_close,
  421. )
  422. def start_active_span_follows_from(
  423. operation_name: str,
  424. contexts: Collection,
  425. child_of: Optional[Union["opentracing.Span", "opentracing.SpanContext"]] = None,
  426. start_time: Optional[float] = None,
  427. *,
  428. inherit_force_tracing: bool = False,
  429. tracer: Optional["opentracing.Tracer"] = None,
  430. ) -> "opentracing.Scope":
  431. """Starts an active opentracing span, with additional references to previous spans
  432. Args:
  433. operation_name: name of the operation represented by the new span
  434. contexts: the previous spans to inherit from
  435. child_of: optionally override the parent span. If unset, the currently active
  436. span will be the parent. (If there is no currently active span, the first
  437. span in `contexts` will be the parent.)
  438. start_time: optional override for the start time of the created span. Seconds
  439. since the epoch.
  440. inherit_force_tracing: if set, and any of the previous contexts have had tracing
  441. forced, the new span will also have tracing forced.
  442. tracer: override the opentracing tracer. By default the global tracer is used.
  443. """
  444. if opentracing is None:
  445. return contextlib.nullcontext() # type: ignore[unreachable]
  446. references = [opentracing.follows_from(context) for context in contexts]
  447. scope = start_active_span(
  448. operation_name,
  449. child_of=child_of,
  450. references=references,
  451. start_time=start_time,
  452. tracer=tracer,
  453. )
  454. if inherit_force_tracing and any(
  455. is_context_forced_tracing(ctx) for ctx in contexts
  456. ):
  457. force_tracing(scope.span)
  458. return scope
  459. def start_active_span_from_edu(
  460. edu_content: Dict[str, Any],
  461. operation_name: str,
  462. references: Optional[List["opentracing.Reference"]] = None,
  463. tags: Optional[Dict[str, str]] = None,
  464. start_time: Optional[float] = None,
  465. ignore_active_span: bool = False,
  466. finish_on_close: bool = True,
  467. ) -> "opentracing.Scope":
  468. """
  469. Extracts a span context from an edu and uses it to start a new active span
  470. Args:
  471. edu_content: an edu_content with a `context` field whose value is
  472. canonical json for a dict which contains opentracing information.
  473. For the other args see opentracing.tracer
  474. """
  475. references = references or []
  476. if opentracing is None:
  477. return contextlib.nullcontext() # type: ignore[unreachable]
  478. carrier = json_decoder.decode(edu_content.get("context", "{}")).get(
  479. "opentracing", {}
  480. )
  481. context = opentracing.tracer.extract(opentracing.Format.TEXT_MAP, carrier)
  482. _references = [
  483. opentracing.child_of(span_context_from_string(x))
  484. for x in carrier.get("references", [])
  485. ]
  486. # For some reason jaeger decided not to support the visualization of multiple parent
  487. # spans or explicitly show references. I include the span context as a tag here as
  488. # an aid to people debugging but it's really not an ideal solution.
  489. references += _references
  490. scope = opentracing.tracer.start_active_span(
  491. operation_name,
  492. child_of=context,
  493. references=references,
  494. tags=tags,
  495. start_time=start_time,
  496. ignore_active_span=ignore_active_span,
  497. finish_on_close=finish_on_close,
  498. )
  499. scope.span.set_tag("references", carrier.get("references", []))
  500. return scope
  501. # Opentracing setters for tags, logs, etc
  502. @only_if_tracing
  503. def active_span() -> Optional["opentracing.Span"]:
  504. """Get the currently active span, if any"""
  505. return opentracing.tracer.active_span
  506. @ensure_active_span("set a tag")
  507. def set_tag(key: str, value: Union[str, bool, int, float]) -> None:
  508. """Sets a tag on the active span"""
  509. assert opentracing.tracer.active_span is not None
  510. opentracing.tracer.active_span.set_tag(key, value)
  511. @ensure_active_span("log")
  512. def log_kv(key_values: Dict[str, Any], timestamp: Optional[float] = None) -> None:
  513. """Log to the active span"""
  514. assert opentracing.tracer.active_span is not None
  515. opentracing.tracer.active_span.log_kv(key_values, timestamp)
  516. @ensure_active_span("set the traces operation name")
  517. def set_operation_name(operation_name: str) -> None:
  518. """Sets the operation name of the active span"""
  519. assert opentracing.tracer.active_span is not None
  520. opentracing.tracer.active_span.set_operation_name(operation_name)
  521. @only_if_tracing
  522. def force_tracing(
  523. span: Union["opentracing.Span", _Sentinel] = _Sentinel.sentinel
  524. ) -> None:
  525. """Force sampling for the active/given span and its children.
  526. Args:
  527. span: span to force tracing for. By default, the active span.
  528. """
  529. if isinstance(span, _Sentinel):
  530. span_to_trace = opentracing.tracer.active_span
  531. else:
  532. span_to_trace = span
  533. if span_to_trace is None:
  534. logger.error("No active span in force_tracing")
  535. return
  536. span_to_trace.set_tag(opentracing.tags.SAMPLING_PRIORITY, 1)
  537. # also set a bit of baggage, so that we have a way of figuring out if
  538. # it is enabled later
  539. span_to_trace.set_baggage_item(SynapseBaggage.FORCE_TRACING, "1")
  540. def is_context_forced_tracing(
  541. span_context: Optional["opentracing.SpanContext"],
  542. ) -> bool:
  543. """Check if sampling has been force for the given span context."""
  544. if span_context is None:
  545. return False
  546. return span_context.baggage.get(SynapseBaggage.FORCE_TRACING) is not None
  547. # Injection and extraction
  548. @ensure_active_span("inject the span into a header dict")
  549. def inject_header_dict(
  550. headers: Dict[bytes, List[bytes]],
  551. destination: Optional[str] = None,
  552. check_destination: bool = True,
  553. ) -> None:
  554. """
  555. Injects a span context into a dict of HTTP headers
  556. Args:
  557. headers: the dict to inject headers into
  558. destination: address of entity receiving the span context. Must be given unless
  559. check_destination is False. The context will only be injected if the
  560. destination matches the opentracing whitelist
  561. check_destination: If false, destination will be ignored and the context
  562. will always be injected.
  563. Note:
  564. The headers set by the tracer are custom to the tracer implementation which
  565. should be unique enough that they don't interfere with any headers set by
  566. synapse or twisted. If we're still using jaeger these headers would be those
  567. here:
  568. https://github.com/jaegertracing/jaeger-client-python/blob/master/jaeger_client/constants.py
  569. """
  570. if check_destination:
  571. if destination is None:
  572. raise ValueError(
  573. "destination must be given unless check_destination is False"
  574. )
  575. if not whitelisted_homeserver(destination):
  576. return
  577. span = opentracing.tracer.active_span
  578. carrier: Dict[str, str] = {}
  579. assert span is not None
  580. opentracing.tracer.inject(span.context, opentracing.Format.HTTP_HEADERS, carrier)
  581. for key, value in carrier.items():
  582. headers[key.encode()] = [value.encode()]
  583. def inject_response_headers(response_headers: Headers) -> None:
  584. """Inject the current trace id into the HTTP response headers"""
  585. if not opentracing:
  586. return
  587. span = opentracing.tracer.active_span
  588. if not span:
  589. return
  590. # This is a bit implementation-specific.
  591. #
  592. # Jaeger's Spans have a trace_id property; other implementations (including the
  593. # dummy opentracing.span.Span which we use if init_tracer is not called) do not
  594. # expose it
  595. trace_id = getattr(span, "trace_id", None)
  596. if trace_id is not None:
  597. response_headers.addRawHeader("Synapse-Trace-Id", f"{trace_id:x}")
  598. @ensure_active_span(
  599. "get the active span context as a dict", ret=cast(Dict[str, str], {})
  600. )
  601. def get_active_span_text_map(destination: Optional[str] = None) -> Dict[str, str]:
  602. """
  603. Gets a span context as a dict. This can be used instead of manually
  604. injecting a span into an empty carrier.
  605. Args:
  606. destination: the name of the remote server.
  607. Returns:
  608. the active span's context if opentracing is enabled, otherwise empty.
  609. """
  610. if destination and not whitelisted_homeserver(destination):
  611. return {}
  612. carrier: Dict[str, str] = {}
  613. assert opentracing.tracer.active_span is not None
  614. opentracing.tracer.inject(
  615. opentracing.tracer.active_span.context, opentracing.Format.TEXT_MAP, carrier
  616. )
  617. return carrier
  618. @ensure_active_span("get the span context as a string.", ret={})
  619. def active_span_context_as_string() -> str:
  620. """
  621. Returns:
  622. The active span context encoded as a string.
  623. """
  624. carrier: Dict[str, str] = {}
  625. if opentracing:
  626. assert opentracing.tracer.active_span is not None
  627. opentracing.tracer.inject(
  628. opentracing.tracer.active_span.context, opentracing.Format.TEXT_MAP, carrier
  629. )
  630. return json_encoder.encode(carrier)
  631. def span_context_from_request(request: Request) -> "Optional[opentracing.SpanContext]":
  632. """Extract an opentracing context from the headers on an HTTP request
  633. This is useful when we have received an HTTP request from another part of our
  634. system, and want to link our spans to those of the remote system.
  635. """
  636. if not opentracing:
  637. return None
  638. header_dict = {
  639. k.decode(): v[0].decode() for k, v in request.requestHeaders.getAllRawHeaders()
  640. }
  641. return opentracing.tracer.extract(opentracing.Format.HTTP_HEADERS, header_dict)
  642. @only_if_tracing
  643. def span_context_from_string(carrier: str) -> Optional["opentracing.SpanContext"]:
  644. """
  645. Returns:
  646. The active span context decoded from a string.
  647. """
  648. payload: Dict[str, str] = json_decoder.decode(carrier)
  649. return opentracing.tracer.extract(opentracing.Format.TEXT_MAP, payload)
  650. @only_if_tracing
  651. def extract_text_map(carrier: Dict[str, str]) -> Optional["opentracing.SpanContext"]:
  652. """
  653. Wrapper method for opentracing's tracer.extract for TEXT_MAP.
  654. Args:
  655. carrier: a dict possibly containing a span context.
  656. Returns:
  657. The active span context extracted from carrier.
  658. """
  659. return opentracing.tracer.extract(opentracing.Format.TEXT_MAP, carrier)
  660. # Tracing decorators
  661. def _custom_sync_async_decorator(
  662. func: Callable[P, R],
  663. wrapping_logic: Callable[[Callable[P, R], Any, Any], ContextManager[None]],
  664. ) -> Callable[P, R]:
  665. """
  666. Decorates a function that is sync or async (coroutines), or that returns a Twisted
  667. `Deferred`. The custom business logic of the decorator goes in `wrapping_logic`.
  668. Example usage:
  669. ```py
  670. # Decorator to time the function and log it out
  671. def duration(func: Callable[P, R]) -> Callable[P, R]:
  672. @contextlib.contextmanager
  673. def _wrapping_logic(func: Callable[P, R], *args: P.args, **kwargs: P.kwargs) -> Generator[None, None, None]:
  674. start_ts = time.time()
  675. try:
  676. yield
  677. finally:
  678. end_ts = time.time()
  679. duration = end_ts - start_ts
  680. logger.info("%s took %s seconds", func.__name__, duration)
  681. return _custom_sync_async_decorator(func, _wrapping_logic)
  682. ```
  683. Args:
  684. func: The function to be decorated
  685. wrapping_logic: The business logic of your custom decorator.
  686. This should be a ContextManager so you are able to run your logic
  687. before/after the function as desired.
  688. """
  689. if inspect.iscoroutinefunction(func):
  690. @wraps(func)
  691. async def _wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
  692. with wrapping_logic(func, *args, **kwargs):
  693. return await func(*args, **kwargs) # type: ignore[misc]
  694. else:
  695. # The other case here handles both sync functions and those
  696. # decorated with inlineDeferred.
  697. @wraps(func)
  698. def _wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
  699. scope = wrapping_logic(func, *args, **kwargs)
  700. scope.__enter__()
  701. try:
  702. result = func(*args, **kwargs)
  703. if isinstance(result, defer.Deferred):
  704. def call_back(result: R) -> R:
  705. scope.__exit__(None, None, None)
  706. return result
  707. def err_back(result: R) -> R:
  708. scope.__exit__(None, None, None)
  709. return result
  710. result.addCallbacks(call_back, err_back)
  711. else:
  712. if inspect.isawaitable(result):
  713. logger.error(
  714. "@trace may not have wrapped %s correctly! "
  715. "The function is not async but returned a %s.",
  716. func.__qualname__,
  717. type(result).__name__,
  718. )
  719. scope.__exit__(None, None, None)
  720. return result
  721. except Exception as e:
  722. scope.__exit__(type(e), None, e.__traceback__)
  723. raise
  724. return _wrapper # type: ignore[return-value]
  725. def trace_with_opname(
  726. opname: str,
  727. *,
  728. tracer: Optional["opentracing.Tracer"] = None,
  729. ) -> Callable[[Callable[P, R]], Callable[P, R]]:
  730. """
  731. Decorator to trace a function with a custom opname.
  732. See the module's doc string for usage examples.
  733. """
  734. # type-ignore: mypy bug, see https://github.com/python/mypy/issues/12909
  735. @contextlib.contextmanager # type: ignore[arg-type]
  736. def _wrapping_logic(
  737. func: Callable[P, R], *args: P.args, **kwargs: P.kwargs
  738. ) -> Generator[None, None, None]:
  739. with start_active_span(opname, tracer=tracer):
  740. yield
  741. def _decorator(func: Callable[P, R]) -> Callable[P, R]:
  742. if not opentracing:
  743. return func
  744. return _custom_sync_async_decorator(func, _wrapping_logic)
  745. return _decorator
  746. def trace(func: Callable[P, R]) -> Callable[P, R]:
  747. """
  748. Decorator to trace a function.
  749. Sets the operation name to that of the function's name.
  750. See the module's doc string for usage examples.
  751. """
  752. return trace_with_opname(func.__name__)(func)
  753. def tag_args(func: Callable[P, R]) -> Callable[P, R]:
  754. """
  755. Decorator to tag all of the args to the active span.
  756. Args:
  757. func: `func` is assumed to be a method taking a `self` parameter, or a
  758. `classmethod` taking a `cls` parameter. In either case, a tag is not
  759. created for this parameter.
  760. """
  761. if not opentracing:
  762. return func
  763. # type-ignore: mypy bug, see https://github.com/python/mypy/issues/12909
  764. @contextlib.contextmanager # type: ignore[arg-type]
  765. def _wrapping_logic(
  766. func: Callable[P, R], *args: P.args, **kwargs: P.kwargs
  767. ) -> Generator[None, None, None]:
  768. argspec = inspect.getfullargspec(func)
  769. # We use `[1:]` to skip the `self` object reference and `start=1` to
  770. # make the index line up with `argspec.args`.
  771. #
  772. # FIXME: We could update this to handle any type of function by ignoring the
  773. # first argument only if it's named `self` or `cls`. This isn't fool-proof
  774. # but handles the idiomatic cases.
  775. for i, arg in enumerate(args[1:], start=1):
  776. set_tag(SynapseTags.FUNC_ARG_PREFIX + argspec.args[i], str(arg))
  777. set_tag(SynapseTags.FUNC_ARGS, str(args[len(argspec.args) :]))
  778. set_tag(SynapseTags.FUNC_KWARGS, str(kwargs))
  779. yield
  780. return _custom_sync_async_decorator(func, _wrapping_logic)
  781. @contextlib.contextmanager
  782. def trace_servlet(
  783. request: "SynapseRequest", extract_context: bool = False
  784. ) -> Generator[None, None, None]:
  785. """Returns a context manager which traces a request. It starts a span
  786. with some servlet specific tags such as the request metrics name and
  787. request information.
  788. Args:
  789. request
  790. extract_context: Whether to attempt to extract the opentracing
  791. context from the request the servlet is handling.
  792. """
  793. if opentracing is None:
  794. yield # type: ignore[unreachable]
  795. return
  796. request_tags = {
  797. SynapseTags.REQUEST_ID: request.get_request_id(),
  798. tags.SPAN_KIND: tags.SPAN_KIND_RPC_SERVER,
  799. tags.HTTP_METHOD: request.get_method(),
  800. tags.HTTP_URL: request.get_redacted_uri(),
  801. tags.PEER_HOST_IPV6: request.getClientAddress().host,
  802. }
  803. request_name = request.request_metrics.name
  804. context = span_context_from_request(request) if extract_context else None
  805. # we configure the scope not to finish the span immediately on exit, and instead
  806. # pass the span into the SynapseRequest, which will finish it once we've finished
  807. # sending the response to the client.
  808. scope = start_active_span(request_name, child_of=context, finish_on_close=False)
  809. request.set_opentracing_span(scope.span)
  810. with scope:
  811. inject_response_headers(request.responseHeaders)
  812. try:
  813. yield
  814. finally:
  815. # We set the operation name again in case its changed (which happens
  816. # with JsonResource).
  817. scope.span.set_operation_name(request.request_metrics.name)
  818. request_tags[
  819. SynapseTags.REQUEST_TAG
  820. ] = request.request_metrics.start_context.tag
  821. # set the tags *after* the servlet completes, in case it decided to
  822. # prioritise the span (tags will get dropped on unprioritised spans)
  823. for k, v in request_tags.items():
  824. scope.span.set_tag(k, v)