context.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2019 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """ Thread-local-alike tracking of log contexts within synapse
  16. This module provides objects and utilities for tracking contexts through
  17. synapse code, so that log lines can include a request identifier, and so that
  18. CPU and database activity can be accounted for against the request that caused
  19. them.
  20. See doc/log_contexts.rst for details on how this works.
  21. """
  22. import inspect
  23. import logging
  24. import threading
  25. import types
  26. import warnings
  27. from typing import TYPE_CHECKING, Optional, Tuple, TypeVar, Union
  28. from typing_extensions import Literal
  29. from twisted.internet import defer, threads
  30. if TYPE_CHECKING:
  31. from synapse.logging.scopecontextmanager import _LogContextScope
  32. logger = logging.getLogger(__name__)
  33. try:
  34. import resource
  35. # Python doesn't ship with a definition of RUSAGE_THREAD but it's defined
  36. # to be 1 on linux so we hard code it.
  37. RUSAGE_THREAD = 1
  38. # If the system doesn't support RUSAGE_THREAD then this should throw an
  39. # exception.
  40. resource.getrusage(RUSAGE_THREAD)
  41. is_thread_resource_usage_supported = True
  42. def get_thread_resource_usage() -> "Optional[resource._RUsage]":
  43. return resource.getrusage(RUSAGE_THREAD)
  44. except Exception:
  45. # If the system doesn't support resource.getrusage(RUSAGE_THREAD) then we
  46. # won't track resource usage.
  47. is_thread_resource_usage_supported = False
  48. def get_thread_resource_usage() -> "Optional[resource._RUsage]":
  49. return None
  50. # a hook which can be set during testing to assert that we aren't abusing logcontexts.
  51. def logcontext_error(msg: str):
  52. logger.warning(msg)
  53. # get an id for the current thread.
  54. #
  55. # threading.get_ident doesn't actually return an OS-level tid, and annoyingly,
  56. # on Linux it actually returns the same value either side of a fork() call. However
  57. # we only fork in one place, so it's not worth the hoop-jumping to get a real tid.
  58. #
  59. get_thread_id = threading.get_ident
  60. class ContextResourceUsage:
  61. """Object for tracking the resources used by a log context
  62. Attributes:
  63. ru_utime (float): user CPU time (in seconds)
  64. ru_stime (float): system CPU time (in seconds)
  65. db_txn_count (int): number of database transactions done
  66. db_sched_duration_sec (float): amount of time spent waiting for a
  67. database connection
  68. db_txn_duration_sec (float): amount of time spent doing database
  69. transactions (excluding scheduling time)
  70. evt_db_fetch_count (int): number of events requested from the database
  71. """
  72. __slots__ = [
  73. "ru_stime",
  74. "ru_utime",
  75. "db_txn_count",
  76. "db_txn_duration_sec",
  77. "db_sched_duration_sec",
  78. "evt_db_fetch_count",
  79. ]
  80. def __init__(self, copy_from: "Optional[ContextResourceUsage]" = None) -> None:
  81. """Create a new ContextResourceUsage
  82. Args:
  83. copy_from (ContextResourceUsage|None): if not None, an object to
  84. copy stats from
  85. """
  86. if copy_from is None:
  87. self.reset()
  88. else:
  89. # FIXME: mypy can't infer the types set via reset() above, so specify explicitly for now
  90. self.ru_utime = copy_from.ru_utime # type: float
  91. self.ru_stime = copy_from.ru_stime # type: float
  92. self.db_txn_count = copy_from.db_txn_count # type: int
  93. self.db_txn_duration_sec = copy_from.db_txn_duration_sec # type: float
  94. self.db_sched_duration_sec = copy_from.db_sched_duration_sec # type: float
  95. self.evt_db_fetch_count = copy_from.evt_db_fetch_count # type: int
  96. def copy(self) -> "ContextResourceUsage":
  97. return ContextResourceUsage(copy_from=self)
  98. def reset(self) -> None:
  99. self.ru_stime = 0.0
  100. self.ru_utime = 0.0
  101. self.db_txn_count = 0
  102. self.db_txn_duration_sec = 0.0
  103. self.db_sched_duration_sec = 0.0
  104. self.evt_db_fetch_count = 0
  105. def __repr__(self) -> str:
  106. return (
  107. "<ContextResourceUsage ru_stime='%r', ru_utime='%r', "
  108. "db_txn_count='%r', db_txn_duration_sec='%r', "
  109. "db_sched_duration_sec='%r', evt_db_fetch_count='%r'>"
  110. ) % (
  111. self.ru_stime,
  112. self.ru_utime,
  113. self.db_txn_count,
  114. self.db_txn_duration_sec,
  115. self.db_sched_duration_sec,
  116. self.evt_db_fetch_count,
  117. )
  118. def __iadd__(self, other: "ContextResourceUsage") -> "ContextResourceUsage":
  119. """Add another ContextResourceUsage's stats to this one's.
  120. Args:
  121. other (ContextResourceUsage): the other resource usage object
  122. """
  123. self.ru_utime += other.ru_utime
  124. self.ru_stime += other.ru_stime
  125. self.db_txn_count += other.db_txn_count
  126. self.db_txn_duration_sec += other.db_txn_duration_sec
  127. self.db_sched_duration_sec += other.db_sched_duration_sec
  128. self.evt_db_fetch_count += other.evt_db_fetch_count
  129. return self
  130. def __isub__(self, other: "ContextResourceUsage") -> "ContextResourceUsage":
  131. self.ru_utime -= other.ru_utime
  132. self.ru_stime -= other.ru_stime
  133. self.db_txn_count -= other.db_txn_count
  134. self.db_txn_duration_sec -= other.db_txn_duration_sec
  135. self.db_sched_duration_sec -= other.db_sched_duration_sec
  136. self.evt_db_fetch_count -= other.evt_db_fetch_count
  137. return self
  138. def __add__(self, other: "ContextResourceUsage") -> "ContextResourceUsage":
  139. res = ContextResourceUsage(copy_from=self)
  140. res += other
  141. return res
  142. def __sub__(self, other: "ContextResourceUsage") -> "ContextResourceUsage":
  143. res = ContextResourceUsage(copy_from=self)
  144. res -= other
  145. return res
  146. LoggingContextOrSentinel = Union["LoggingContext", "_Sentinel"]
  147. class _Sentinel:
  148. """Sentinel to represent the root context"""
  149. __slots__ = ["previous_context", "finished", "request", "scope", "tag"]
  150. def __init__(self) -> None:
  151. # Minimal set for compatibility with LoggingContext
  152. self.previous_context = None
  153. self.finished = False
  154. self.request = None
  155. self.scope = None
  156. self.tag = None
  157. def __str__(self):
  158. return "sentinel"
  159. def copy_to(self, record):
  160. pass
  161. def copy_to_twisted_log_entry(self, record):
  162. record["request"] = None
  163. record["scope"] = None
  164. def start(self, rusage: "Optional[resource._RUsage]"):
  165. pass
  166. def stop(self, rusage: "Optional[resource._RUsage]"):
  167. pass
  168. def add_database_transaction(self, duration_sec):
  169. pass
  170. def add_database_scheduled(self, sched_sec):
  171. pass
  172. def record_event_fetch(self, event_count):
  173. pass
  174. def __bool__(self):
  175. return False
  176. SENTINEL_CONTEXT = _Sentinel()
  177. class LoggingContext:
  178. """Additional context for log formatting. Contexts are scoped within a
  179. "with" block.
  180. If a parent is given when creating a new context, then:
  181. - logging fields are copied from the parent to the new context on entry
  182. - when the new context exits, the cpu usage stats are copied from the
  183. child to the parent
  184. Args:
  185. name (str): Name for the context for debugging.
  186. parent_context (LoggingContext|None): The parent of the new context
  187. """
  188. __slots__ = [
  189. "previous_context",
  190. "name",
  191. "parent_context",
  192. "_resource_usage",
  193. "usage_start",
  194. "main_thread",
  195. "finished",
  196. "request",
  197. "tag",
  198. "scope",
  199. ]
  200. def __init__(self, name=None, parent_context=None, request=None) -> None:
  201. self.previous_context = current_context()
  202. self.name = name
  203. # track the resources used by this context so far
  204. self._resource_usage = ContextResourceUsage()
  205. # The thread resource usage when the logcontext became active. None
  206. # if the context is not currently active.
  207. self.usage_start = None # type: Optional[resource._RUsage]
  208. self.main_thread = get_thread_id()
  209. self.request = None
  210. self.tag = ""
  211. self.scope = None # type: Optional[_LogContextScope]
  212. # keep track of whether we have hit the __exit__ block for this context
  213. # (suggesting that the the thing that created the context thinks it should
  214. # be finished, and that re-activating it would suggest an error).
  215. self.finished = False
  216. self.parent_context = parent_context
  217. if self.parent_context is not None:
  218. self.parent_context.copy_to(self)
  219. if request is not None:
  220. # the request param overrides the request from the parent context
  221. self.request = request
  222. def __str__(self) -> str:
  223. if self.request:
  224. return str(self.request)
  225. return "%s@%x" % (self.name, id(self))
  226. @classmethod
  227. def current_context(cls) -> LoggingContextOrSentinel:
  228. """Get the current logging context from thread local storage
  229. This exists for backwards compatibility. ``current_context()`` should be
  230. called directly.
  231. Returns:
  232. LoggingContext: the current logging context
  233. """
  234. warnings.warn(
  235. "synapse.logging.context.LoggingContext.current_context() is deprecated "
  236. "in favor of synapse.logging.context.current_context().",
  237. DeprecationWarning,
  238. stacklevel=2,
  239. )
  240. return current_context()
  241. @classmethod
  242. def set_current_context(
  243. cls, context: LoggingContextOrSentinel
  244. ) -> LoggingContextOrSentinel:
  245. """Set the current logging context in thread local storage
  246. This exists for backwards compatibility. ``set_current_context()`` should be
  247. called directly.
  248. Args:
  249. context(LoggingContext): The context to activate.
  250. Returns:
  251. The context that was previously active
  252. """
  253. warnings.warn(
  254. "synapse.logging.context.LoggingContext.set_current_context() is deprecated "
  255. "in favor of synapse.logging.context.set_current_context().",
  256. DeprecationWarning,
  257. stacklevel=2,
  258. )
  259. return set_current_context(context)
  260. def __enter__(self) -> "LoggingContext":
  261. """Enters this logging context into thread local storage"""
  262. old_context = set_current_context(self)
  263. if self.previous_context != old_context:
  264. logcontext_error(
  265. "Expected previous context %r, found %r"
  266. % (self.previous_context, old_context,)
  267. )
  268. return self
  269. def __exit__(self, type, value, traceback) -> None:
  270. """Restore the logging context in thread local storage to the state it
  271. was before this context was entered.
  272. Returns:
  273. None to avoid suppressing any exceptions that were thrown.
  274. """
  275. current = set_current_context(self.previous_context)
  276. if current is not self:
  277. if current is SENTINEL_CONTEXT:
  278. logcontext_error("Expected logging context %s was lost" % (self,))
  279. else:
  280. logcontext_error(
  281. "Expected logging context %s but found %s" % (self, current)
  282. )
  283. # the fact that we are here suggests that the caller thinks that everything
  284. # is done and dusted for this logcontext, and further activity will not get
  285. # recorded against the correct metrics.
  286. self.finished = True
  287. def copy_to(self, record) -> None:
  288. """Copy logging fields from this context to a log record or
  289. another LoggingContext
  290. """
  291. # we track the current request
  292. record.request = self.request
  293. # we also track the current scope:
  294. record.scope = self.scope
  295. def copy_to_twisted_log_entry(self, record) -> None:
  296. """
  297. Copy logging fields from this context to a Twisted log record.
  298. """
  299. record["request"] = self.request
  300. record["scope"] = self.scope
  301. def start(self, rusage: "Optional[resource._RUsage]") -> None:
  302. """
  303. Record that this logcontext is currently running.
  304. This should not be called directly: use set_current_context
  305. Args:
  306. rusage: the resources used by the current thread, at the point of
  307. switching to this logcontext. May be None if this platform doesn't
  308. support getrusuage.
  309. """
  310. if get_thread_id() != self.main_thread:
  311. logcontext_error("Started logcontext %s on different thread" % (self,))
  312. return
  313. if self.finished:
  314. logcontext_error("Re-starting finished log context %s" % (self,))
  315. # If we haven't already started record the thread resource usage so
  316. # far
  317. if self.usage_start:
  318. logcontext_error("Re-starting already-active log context %s" % (self,))
  319. else:
  320. self.usage_start = rusage
  321. def stop(self, rusage: "Optional[resource._RUsage]") -> None:
  322. """
  323. Record that this logcontext is no longer running.
  324. This should not be called directly: use set_current_context
  325. Args:
  326. rusage: the resources used by the current thread, at the point of
  327. switching away from this logcontext. May be None if this platform
  328. doesn't support getrusuage.
  329. """
  330. try:
  331. if get_thread_id() != self.main_thread:
  332. logcontext_error("Stopped logcontext %s on different thread" % (self,))
  333. return
  334. if not rusage:
  335. return
  336. # Record the cpu used since we started
  337. if not self.usage_start:
  338. logcontext_error(
  339. "Called stop on logcontext %s without recording a start rusage"
  340. % (self,)
  341. )
  342. return
  343. utime_delta, stime_delta = self._get_cputime(rusage)
  344. self.add_cputime(utime_delta, stime_delta)
  345. finally:
  346. self.usage_start = None
  347. def get_resource_usage(self) -> ContextResourceUsage:
  348. """Get resources used by this logcontext so far.
  349. Returns:
  350. ContextResourceUsage: a *copy* of the object tracking resource
  351. usage so far
  352. """
  353. # we always return a copy, for consistency
  354. res = self._resource_usage.copy()
  355. # If we are on the correct thread and we're currently running then we
  356. # can include resource usage so far.
  357. is_main_thread = get_thread_id() == self.main_thread
  358. if self.usage_start and is_main_thread:
  359. rusage = get_thread_resource_usage()
  360. assert rusage is not None
  361. utime_delta, stime_delta = self._get_cputime(rusage)
  362. res.ru_utime += utime_delta
  363. res.ru_stime += stime_delta
  364. return res
  365. def _get_cputime(self, current: "resource._RUsage") -> Tuple[float, float]:
  366. """Get the cpu usage time between start() and the given rusage
  367. Args:
  368. rusage: the current resource usage
  369. Returns: Tuple[float, float]: seconds in user mode, seconds in system mode
  370. """
  371. assert self.usage_start is not None
  372. utime_delta = current.ru_utime - self.usage_start.ru_utime
  373. stime_delta = current.ru_stime - self.usage_start.ru_stime
  374. # sanity check
  375. if utime_delta < 0:
  376. logger.error(
  377. "utime went backwards! %f < %f",
  378. current.ru_utime,
  379. self.usage_start.ru_utime,
  380. )
  381. utime_delta = 0
  382. if stime_delta < 0:
  383. logger.error(
  384. "stime went backwards! %f < %f",
  385. current.ru_stime,
  386. self.usage_start.ru_stime,
  387. )
  388. stime_delta = 0
  389. return utime_delta, stime_delta
  390. def add_cputime(self, utime_delta: float, stime_delta: float) -> None:
  391. """Update the CPU time usage of this context (and any parents, recursively).
  392. Args:
  393. utime_delta: additional user time, in seconds, spent in this context.
  394. stime_delta: additional system time, in seconds, spent in this context.
  395. """
  396. self._resource_usage.ru_utime += utime_delta
  397. self._resource_usage.ru_stime += stime_delta
  398. if self.parent_context:
  399. self.parent_context.add_cputime(utime_delta, stime_delta)
  400. def add_database_transaction(self, duration_sec: float) -> None:
  401. """Record the use of a database transaction and the length of time it took.
  402. Args:
  403. duration_sec: The number of seconds the database transaction took.
  404. """
  405. if duration_sec < 0:
  406. raise ValueError("DB txn time can only be non-negative")
  407. self._resource_usage.db_txn_count += 1
  408. self._resource_usage.db_txn_duration_sec += duration_sec
  409. if self.parent_context:
  410. self.parent_context.add_database_transaction(duration_sec)
  411. def add_database_scheduled(self, sched_sec: float) -> None:
  412. """Record a use of the database pool
  413. Args:
  414. sched_sec: number of seconds it took us to get a connection
  415. """
  416. if sched_sec < 0:
  417. raise ValueError("DB scheduling time can only be non-negative")
  418. self._resource_usage.db_sched_duration_sec += sched_sec
  419. if self.parent_context:
  420. self.parent_context.add_database_scheduled(sched_sec)
  421. def record_event_fetch(self, event_count: int) -> None:
  422. """Record a number of events being fetched from the db
  423. Args:
  424. event_count: number of events being fetched
  425. """
  426. self._resource_usage.evt_db_fetch_count += event_count
  427. if self.parent_context:
  428. self.parent_context.record_event_fetch(event_count)
  429. class LoggingContextFilter(logging.Filter):
  430. """Logging filter that adds values from the current logging context to each
  431. record.
  432. Args:
  433. **defaults: Default values to avoid formatters complaining about
  434. missing fields
  435. """
  436. def __init__(self, **defaults) -> None:
  437. self.defaults = defaults
  438. def filter(self, record) -> Literal[True]:
  439. """Add each fields from the logging contexts to the record.
  440. Returns:
  441. True to include the record in the log output.
  442. """
  443. context = current_context()
  444. for key, value in self.defaults.items():
  445. setattr(record, key, value)
  446. # context should never be None, but if it somehow ends up being, then
  447. # we end up in a death spiral of infinite loops, so let's check, for
  448. # robustness' sake.
  449. if context is not None:
  450. context.copy_to(record)
  451. return True
  452. class PreserveLoggingContext:
  453. """Context manager which replaces the logging context
  454. The previous logging context is restored on exit."""
  455. __slots__ = ["_old_context", "_new_context"]
  456. def __init__(
  457. self, new_context: LoggingContextOrSentinel = SENTINEL_CONTEXT
  458. ) -> None:
  459. self._new_context = new_context
  460. def __enter__(self) -> None:
  461. self._old_context = set_current_context(self._new_context)
  462. def __exit__(self, type, value, traceback) -> None:
  463. context = set_current_context(self._old_context)
  464. if context != self._new_context:
  465. if not context:
  466. logcontext_error(
  467. "Expected logging context %s was lost" % (self._new_context,)
  468. )
  469. else:
  470. logcontext_error(
  471. "Expected logging context %s but found %s"
  472. % (self._new_context, context,)
  473. )
  474. _thread_local = threading.local()
  475. _thread_local.current_context = SENTINEL_CONTEXT
  476. def current_context() -> LoggingContextOrSentinel:
  477. """Get the current logging context from thread local storage"""
  478. return getattr(_thread_local, "current_context", SENTINEL_CONTEXT)
  479. def set_current_context(context: LoggingContextOrSentinel) -> LoggingContextOrSentinel:
  480. """Set the current logging context in thread local storage
  481. Args:
  482. context(LoggingContext): The context to activate.
  483. Returns:
  484. The context that was previously active
  485. """
  486. # everything blows up if we allow current_context to be set to None, so sanity-check
  487. # that now.
  488. if context is None:
  489. raise TypeError("'context' argument may not be None")
  490. current = current_context()
  491. if current is not context:
  492. rusage = get_thread_resource_usage()
  493. current.stop(rusage)
  494. _thread_local.current_context = context
  495. context.start(rusage)
  496. return current
  497. def nested_logging_context(
  498. suffix: str, parent_context: Optional[LoggingContext] = None
  499. ) -> LoggingContext:
  500. """Creates a new logging context as a child of another.
  501. The nested logging context will have a 'request' made up of the parent context's
  502. request, plus the given suffix.
  503. CPU/db usage stats will be added to the parent context's on exit.
  504. Normal usage looks like:
  505. with nested_logging_context(suffix):
  506. # ... do stuff
  507. Args:
  508. suffix (str): suffix to add to the parent context's 'request'.
  509. parent_context (LoggingContext|None): parent context. Will use the current context
  510. if None.
  511. Returns:
  512. LoggingContext: new logging context.
  513. """
  514. if parent_context is not None:
  515. context = parent_context # type: LoggingContextOrSentinel
  516. else:
  517. context = current_context()
  518. return LoggingContext(
  519. parent_context=context, request=str(context.request) + "-" + suffix
  520. )
  521. def preserve_fn(f):
  522. """Function decorator which wraps the function with run_in_background"""
  523. def g(*args, **kwargs):
  524. return run_in_background(f, *args, **kwargs)
  525. return g
  526. def run_in_background(f, *args, **kwargs):
  527. """Calls a function, ensuring that the current context is restored after
  528. return from the function, and that the sentinel context is set once the
  529. deferred returned by the function completes.
  530. Useful for wrapping functions that return a deferred or coroutine, which you don't
  531. yield or await on (for instance because you want to pass it to
  532. deferred.gatherResults()).
  533. If f returns a Coroutine object, it will be wrapped into a Deferred (which will have
  534. the side effect of executing the coroutine).
  535. Note that if you completely discard the result, you should make sure that
  536. `f` doesn't raise any deferred exceptions, otherwise a scary-looking
  537. CRITICAL error about an unhandled error will be logged without much
  538. indication about where it came from.
  539. """
  540. current = current_context()
  541. try:
  542. res = f(*args, **kwargs)
  543. except: # noqa: E722
  544. # the assumption here is that the caller doesn't want to be disturbed
  545. # by synchronous exceptions, so let's turn them into Failures.
  546. return defer.fail()
  547. if isinstance(res, types.CoroutineType):
  548. res = defer.ensureDeferred(res)
  549. if not isinstance(res, defer.Deferred):
  550. return res
  551. if res.called and not res.paused:
  552. # The function should have maintained the logcontext, so we can
  553. # optimise out the messing about
  554. return res
  555. # The function may have reset the context before returning, so
  556. # we need to restore it now.
  557. ctx = set_current_context(current)
  558. # The original context will be restored when the deferred
  559. # completes, but there is nothing waiting for it, so it will
  560. # get leaked into the reactor or some other function which
  561. # wasn't expecting it. We therefore need to reset the context
  562. # here.
  563. #
  564. # (If this feels asymmetric, consider it this way: we are
  565. # effectively forking a new thread of execution. We are
  566. # probably currently within a ``with LoggingContext()`` block,
  567. # which is supposed to have a single entry and exit point. But
  568. # by spawning off another deferred, we are effectively
  569. # adding a new exit point.)
  570. res.addBoth(_set_context_cb, ctx)
  571. return res
  572. def make_deferred_yieldable(deferred):
  573. """Given a deferred (or coroutine), make it follow the Synapse logcontext
  574. rules:
  575. If the deferred has completed (or is not actually a Deferred), essentially
  576. does nothing (just returns another completed deferred with the
  577. result/failure).
  578. If the deferred has not yet completed, resets the logcontext before
  579. returning a deferred. Then, when the deferred completes, restores the
  580. current logcontext before running callbacks/errbacks.
  581. (This is more-or-less the opposite operation to run_in_background.)
  582. """
  583. if inspect.isawaitable(deferred):
  584. # If we're given a coroutine we convert it to a deferred so that we
  585. # run it and find out if it immediately finishes, it it does then we
  586. # don't need to fiddle with log contexts at all and can return
  587. # immediately.
  588. deferred = defer.ensureDeferred(deferred)
  589. if not isinstance(deferred, defer.Deferred):
  590. return deferred
  591. if deferred.called and not deferred.paused:
  592. # it looks like this deferred is ready to run any callbacks we give it
  593. # immediately. We may as well optimise out the logcontext faffery.
  594. return deferred
  595. # ok, we can't be sure that a yield won't block, so let's reset the
  596. # logcontext, and add a callback to the deferred to restore it.
  597. prev_context = set_current_context(SENTINEL_CONTEXT)
  598. deferred.addBoth(_set_context_cb, prev_context)
  599. return deferred
  600. ResultT = TypeVar("ResultT")
  601. def _set_context_cb(result: ResultT, context: LoggingContext) -> ResultT:
  602. """A callback function which just sets the logging context"""
  603. set_current_context(context)
  604. return result
  605. def defer_to_thread(reactor, f, *args, **kwargs):
  606. """
  607. Calls the function `f` using a thread from the reactor's default threadpool and
  608. returns the result as a Deferred.
  609. Creates a new logcontext for `f`, which is created as a child of the current
  610. logcontext (so its CPU usage metrics will get attributed to the current
  611. logcontext). `f` should preserve the logcontext it is given.
  612. The result deferred follows the Synapse logcontext rules: you should `yield`
  613. on it.
  614. Args:
  615. reactor (twisted.internet.base.ReactorBase): The reactor in whose main thread
  616. the Deferred will be invoked, and whose threadpool we should use for the
  617. function.
  618. Normally this will be hs.get_reactor().
  619. f (callable): The function to call.
  620. args: positional arguments to pass to f.
  621. kwargs: keyword arguments to pass to f.
  622. Returns:
  623. Deferred: A Deferred which fires a callback with the result of `f`, or an
  624. errback if `f` throws an exception.
  625. """
  626. return defer_to_threadpool(reactor, reactor.getThreadPool(), f, *args, **kwargs)
  627. def defer_to_threadpool(reactor, threadpool, f, *args, **kwargs):
  628. """
  629. A wrapper for twisted.internet.threads.deferToThreadpool, which handles
  630. logcontexts correctly.
  631. Calls the function `f` using a thread from the given threadpool and returns
  632. the result as a Deferred.
  633. Creates a new logcontext for `f`, which is created as a child of the current
  634. logcontext (so its CPU usage metrics will get attributed to the current
  635. logcontext). `f` should preserve the logcontext it is given.
  636. The result deferred follows the Synapse logcontext rules: you should `yield`
  637. on it.
  638. Args:
  639. reactor (twisted.internet.base.ReactorBase): The reactor in whose main thread
  640. the Deferred will be invoked. Normally this will be hs.get_reactor().
  641. threadpool (twisted.python.threadpool.ThreadPool): The threadpool to use for
  642. running `f`. Normally this will be hs.get_reactor().getThreadPool().
  643. f (callable): The function to call.
  644. args: positional arguments to pass to f.
  645. kwargs: keyword arguments to pass to f.
  646. Returns:
  647. Deferred: A Deferred which fires a callback with the result of `f`, or an
  648. errback if `f` throws an exception.
  649. """
  650. logcontext = current_context()
  651. def g():
  652. with LoggingContext(parent_context=logcontext):
  653. return f(*args, **kwargs)
  654. return make_deferred_yieldable(threads.deferToThreadPool(reactor, threadpool, g))