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 start(self, rusage: "Optional[resource._RUsage]"):
  162. pass
  163. def stop(self, rusage: "Optional[resource._RUsage]"):
  164. pass
  165. def add_database_transaction(self, duration_sec):
  166. pass
  167. def add_database_scheduled(self, sched_sec):
  168. pass
  169. def record_event_fetch(self, event_count):
  170. pass
  171. def __bool__(self):
  172. return False
  173. SENTINEL_CONTEXT = _Sentinel()
  174. class LoggingContext:
  175. """Additional context for log formatting. Contexts are scoped within a
  176. "with" block.
  177. If a parent is given when creating a new context, then:
  178. - logging fields are copied from the parent to the new context on entry
  179. - when the new context exits, the cpu usage stats are copied from the
  180. child to the parent
  181. Args:
  182. name (str): Name for the context for debugging.
  183. parent_context (LoggingContext|None): The parent of the new context
  184. """
  185. __slots__ = [
  186. "previous_context",
  187. "name",
  188. "parent_context",
  189. "_resource_usage",
  190. "usage_start",
  191. "main_thread",
  192. "finished",
  193. "request",
  194. "tag",
  195. "scope",
  196. ]
  197. def __init__(
  198. self,
  199. name: Optional[str] = None,
  200. parent_context: "Optional[LoggingContext]" = None,
  201. request: Optional[str] = None,
  202. ) -> None:
  203. self.previous_context = current_context()
  204. self.name = name
  205. # track the resources used by this context so far
  206. self._resource_usage = ContextResourceUsage()
  207. # The thread resource usage when the logcontext became active. None
  208. # if the context is not currently active.
  209. self.usage_start = None # type: Optional[resource._RUsage]
  210. self.main_thread = get_thread_id()
  211. self.request = None
  212. self.tag = ""
  213. self.scope = None # type: Optional[_LogContextScope]
  214. # keep track of whether we have hit the __exit__ block for this context
  215. # (suggesting that the the thing that created the context thinks it should
  216. # be finished, and that re-activating it would suggest an error).
  217. self.finished = False
  218. self.parent_context = parent_context
  219. if self.parent_context is not None:
  220. self.parent_context.copy_to(self)
  221. if request is not None:
  222. # the request param overrides the request from the parent context
  223. self.request = request
  224. def __str__(self) -> str:
  225. if self.request:
  226. return str(self.request)
  227. return "%s@%x" % (self.name, id(self))
  228. @classmethod
  229. def current_context(cls) -> LoggingContextOrSentinel:
  230. """Get the current logging context from thread local storage
  231. This exists for backwards compatibility. ``current_context()`` should be
  232. called directly.
  233. Returns:
  234. LoggingContext: the current logging context
  235. """
  236. warnings.warn(
  237. "synapse.logging.context.LoggingContext.current_context() is deprecated "
  238. "in favor of synapse.logging.context.current_context().",
  239. DeprecationWarning,
  240. stacklevel=2,
  241. )
  242. return current_context()
  243. @classmethod
  244. def set_current_context(
  245. cls, context: LoggingContextOrSentinel
  246. ) -> LoggingContextOrSentinel:
  247. """Set the current logging context in thread local storage
  248. This exists for backwards compatibility. ``set_current_context()`` should be
  249. called directly.
  250. Args:
  251. context(LoggingContext): The context to activate.
  252. Returns:
  253. The context that was previously active
  254. """
  255. warnings.warn(
  256. "synapse.logging.context.LoggingContext.set_current_context() is deprecated "
  257. "in favor of synapse.logging.context.set_current_context().",
  258. DeprecationWarning,
  259. stacklevel=2,
  260. )
  261. return set_current_context(context)
  262. def __enter__(self) -> "LoggingContext":
  263. """Enters this logging context into thread local storage"""
  264. old_context = set_current_context(self)
  265. if self.previous_context != old_context:
  266. logcontext_error(
  267. "Expected previous context %r, found %r"
  268. % (self.previous_context, old_context,)
  269. )
  270. return self
  271. def __exit__(self, type, value, traceback) -> None:
  272. """Restore the logging context in thread local storage to the state it
  273. was before this context was entered.
  274. Returns:
  275. None to avoid suppressing any exceptions that were thrown.
  276. """
  277. current = set_current_context(self.previous_context)
  278. if current is not self:
  279. if current is SENTINEL_CONTEXT:
  280. logcontext_error("Expected logging context %s was lost" % (self,))
  281. else:
  282. logcontext_error(
  283. "Expected logging context %s but found %s" % (self, current)
  284. )
  285. # the fact that we are here suggests that the caller thinks that everything
  286. # is done and dusted for this logcontext, and further activity will not get
  287. # recorded against the correct metrics.
  288. self.finished = True
  289. def copy_to(self, record) -> None:
  290. """Copy logging fields from this context to a log record or
  291. another LoggingContext
  292. """
  293. # we track the current request
  294. record.request = self.request
  295. # we also track the current scope:
  296. record.scope = self.scope
  297. def start(self, rusage: "Optional[resource._RUsage]") -> None:
  298. """
  299. Record that this logcontext is currently running.
  300. This should not be called directly: use set_current_context
  301. Args:
  302. rusage: the resources used by the current thread, at the point of
  303. switching to this logcontext. May be None if this platform doesn't
  304. support getrusuage.
  305. """
  306. if get_thread_id() != self.main_thread:
  307. logcontext_error("Started logcontext %s on different thread" % (self,))
  308. return
  309. if self.finished:
  310. logcontext_error("Re-starting finished log context %s" % (self,))
  311. # If we haven't already started record the thread resource usage so
  312. # far
  313. if self.usage_start:
  314. logcontext_error("Re-starting already-active log context %s" % (self,))
  315. else:
  316. self.usage_start = rusage
  317. def stop(self, rusage: "Optional[resource._RUsage]") -> None:
  318. """
  319. Record that this logcontext is no longer running.
  320. This should not be called directly: use set_current_context
  321. Args:
  322. rusage: the resources used by the current thread, at the point of
  323. switching away from this logcontext. May be None if this platform
  324. doesn't support getrusuage.
  325. """
  326. try:
  327. if get_thread_id() != self.main_thread:
  328. logcontext_error("Stopped logcontext %s on different thread" % (self,))
  329. return
  330. if not rusage:
  331. return
  332. # Record the cpu used since we started
  333. if not self.usage_start:
  334. logcontext_error(
  335. "Called stop on logcontext %s without recording a start rusage"
  336. % (self,)
  337. )
  338. return
  339. utime_delta, stime_delta = self._get_cputime(rusage)
  340. self.add_cputime(utime_delta, stime_delta)
  341. finally:
  342. self.usage_start = None
  343. def get_resource_usage(self) -> ContextResourceUsage:
  344. """Get resources used by this logcontext so far.
  345. Returns:
  346. ContextResourceUsage: a *copy* of the object tracking resource
  347. usage so far
  348. """
  349. # we always return a copy, for consistency
  350. res = self._resource_usage.copy()
  351. # If we are on the correct thread and we're currently running then we
  352. # can include resource usage so far.
  353. is_main_thread = get_thread_id() == self.main_thread
  354. if self.usage_start and is_main_thread:
  355. rusage = get_thread_resource_usage()
  356. assert rusage is not None
  357. utime_delta, stime_delta = self._get_cputime(rusage)
  358. res.ru_utime += utime_delta
  359. res.ru_stime += stime_delta
  360. return res
  361. def _get_cputime(self, current: "resource._RUsage") -> Tuple[float, float]:
  362. """Get the cpu usage time between start() and the given rusage
  363. Args:
  364. rusage: the current resource usage
  365. Returns: Tuple[float, float]: seconds in user mode, seconds in system mode
  366. """
  367. assert self.usage_start is not None
  368. utime_delta = current.ru_utime - self.usage_start.ru_utime
  369. stime_delta = current.ru_stime - self.usage_start.ru_stime
  370. # sanity check
  371. if utime_delta < 0:
  372. logger.error(
  373. "utime went backwards! %f < %f",
  374. current.ru_utime,
  375. self.usage_start.ru_utime,
  376. )
  377. utime_delta = 0
  378. if stime_delta < 0:
  379. logger.error(
  380. "stime went backwards! %f < %f",
  381. current.ru_stime,
  382. self.usage_start.ru_stime,
  383. )
  384. stime_delta = 0
  385. return utime_delta, stime_delta
  386. def add_cputime(self, utime_delta: float, stime_delta: float) -> None:
  387. """Update the CPU time usage of this context (and any parents, recursively).
  388. Args:
  389. utime_delta: additional user time, in seconds, spent in this context.
  390. stime_delta: additional system time, in seconds, spent in this context.
  391. """
  392. self._resource_usage.ru_utime += utime_delta
  393. self._resource_usage.ru_stime += stime_delta
  394. if self.parent_context:
  395. self.parent_context.add_cputime(utime_delta, stime_delta)
  396. def add_database_transaction(self, duration_sec: float) -> None:
  397. """Record the use of a database transaction and the length of time it took.
  398. Args:
  399. duration_sec: The number of seconds the database transaction took.
  400. """
  401. if duration_sec < 0:
  402. raise ValueError("DB txn time can only be non-negative")
  403. self._resource_usage.db_txn_count += 1
  404. self._resource_usage.db_txn_duration_sec += duration_sec
  405. if self.parent_context:
  406. self.parent_context.add_database_transaction(duration_sec)
  407. def add_database_scheduled(self, sched_sec: float) -> None:
  408. """Record a use of the database pool
  409. Args:
  410. sched_sec: number of seconds it took us to get a connection
  411. """
  412. if sched_sec < 0:
  413. raise ValueError("DB scheduling time can only be non-negative")
  414. self._resource_usage.db_sched_duration_sec += sched_sec
  415. if self.parent_context:
  416. self.parent_context.add_database_scheduled(sched_sec)
  417. def record_event_fetch(self, event_count: int) -> None:
  418. """Record a number of events being fetched from the db
  419. Args:
  420. event_count: number of events being fetched
  421. """
  422. self._resource_usage.evt_db_fetch_count += event_count
  423. if self.parent_context:
  424. self.parent_context.record_event_fetch(event_count)
  425. class LoggingContextFilter(logging.Filter):
  426. """Logging filter that adds values from the current logging context to each
  427. record.
  428. """
  429. def __init__(self, request: str = ""):
  430. self._default_request = request
  431. def filter(self, record: logging.LogRecord) -> Literal[True]:
  432. """Add each fields from the logging contexts to the record.
  433. Returns:
  434. True to include the record in the log output.
  435. """
  436. context = current_context()
  437. record.request = self._default_request # type: ignore
  438. # context should never be None, but if it somehow ends up being, then
  439. # we end up in a death spiral of infinite loops, so let's check, for
  440. # robustness' sake.
  441. if context is not None:
  442. # Logging is interested in the request.
  443. record.request = context.request # type: ignore
  444. return True
  445. class PreserveLoggingContext:
  446. """Context manager which replaces the logging context
  447. The previous logging context is restored on exit."""
  448. __slots__ = ["_old_context", "_new_context"]
  449. def __init__(
  450. self, new_context: LoggingContextOrSentinel = SENTINEL_CONTEXT
  451. ) -> None:
  452. self._new_context = new_context
  453. def __enter__(self) -> None:
  454. self._old_context = set_current_context(self._new_context)
  455. def __exit__(self, type, value, traceback) -> None:
  456. context = set_current_context(self._old_context)
  457. if context != self._new_context:
  458. if not context:
  459. logcontext_error(
  460. "Expected logging context %s was lost" % (self._new_context,)
  461. )
  462. else:
  463. logcontext_error(
  464. "Expected logging context %s but found %s"
  465. % (self._new_context, context,)
  466. )
  467. _thread_local = threading.local()
  468. _thread_local.current_context = SENTINEL_CONTEXT
  469. def current_context() -> LoggingContextOrSentinel:
  470. """Get the current logging context from thread local storage"""
  471. return getattr(_thread_local, "current_context", SENTINEL_CONTEXT)
  472. def set_current_context(context: LoggingContextOrSentinel) -> LoggingContextOrSentinel:
  473. """Set the current logging context in thread local storage
  474. Args:
  475. context(LoggingContext): The context to activate.
  476. Returns:
  477. The context that was previously active
  478. """
  479. # everything blows up if we allow current_context to be set to None, so sanity-check
  480. # that now.
  481. if context is None:
  482. raise TypeError("'context' argument may not be None")
  483. current = current_context()
  484. if current is not context:
  485. rusage = get_thread_resource_usage()
  486. current.stop(rusage)
  487. _thread_local.current_context = context
  488. context.start(rusage)
  489. return current
  490. def nested_logging_context(suffix: str) -> LoggingContext:
  491. """Creates a new logging context as a child of another.
  492. The nested logging context will have a 'request' made up of the parent context's
  493. request, plus the given suffix.
  494. CPU/db usage stats will be added to the parent context's on exit.
  495. Normal usage looks like:
  496. with nested_logging_context(suffix):
  497. # ... do stuff
  498. Args:
  499. suffix: suffix to add to the parent context's 'request'.
  500. Returns:
  501. LoggingContext: new logging context.
  502. """
  503. curr_context = current_context()
  504. if not curr_context:
  505. logger.warning(
  506. "Starting nested logging context from sentinel context: metrics will be lost"
  507. )
  508. parent_context = None
  509. prefix = ""
  510. else:
  511. assert isinstance(curr_context, LoggingContext)
  512. parent_context = curr_context
  513. prefix = str(parent_context.request)
  514. return LoggingContext(parent_context=parent_context, request=prefix + "-" + suffix)
  515. def preserve_fn(f):
  516. """Function decorator which wraps the function with run_in_background"""
  517. def g(*args, **kwargs):
  518. return run_in_background(f, *args, **kwargs)
  519. return g
  520. def run_in_background(f, *args, **kwargs):
  521. """Calls a function, ensuring that the current context is restored after
  522. return from the function, and that the sentinel context is set once the
  523. deferred returned by the function completes.
  524. Useful for wrapping functions that return a deferred or coroutine, which you don't
  525. yield or await on (for instance because you want to pass it to
  526. deferred.gatherResults()).
  527. If f returns a Coroutine object, it will be wrapped into a Deferred (which will have
  528. the side effect of executing the coroutine).
  529. Note that if you completely discard the result, you should make sure that
  530. `f` doesn't raise any deferred exceptions, otherwise a scary-looking
  531. CRITICAL error about an unhandled error will be logged without much
  532. indication about where it came from.
  533. """
  534. current = current_context()
  535. try:
  536. res = f(*args, **kwargs)
  537. except: # noqa: E722
  538. # the assumption here is that the caller doesn't want to be disturbed
  539. # by synchronous exceptions, so let's turn them into Failures.
  540. return defer.fail()
  541. if isinstance(res, types.CoroutineType):
  542. res = defer.ensureDeferred(res)
  543. if not isinstance(res, defer.Deferred):
  544. return res
  545. if res.called and not res.paused:
  546. # The function should have maintained the logcontext, so we can
  547. # optimise out the messing about
  548. return res
  549. # The function may have reset the context before returning, so
  550. # we need to restore it now.
  551. ctx = set_current_context(current)
  552. # The original context will be restored when the deferred
  553. # completes, but there is nothing waiting for it, so it will
  554. # get leaked into the reactor or some other function which
  555. # wasn't expecting it. We therefore need to reset the context
  556. # here.
  557. #
  558. # (If this feels asymmetric, consider it this way: we are
  559. # effectively forking a new thread of execution. We are
  560. # probably currently within a ``with LoggingContext()`` block,
  561. # which is supposed to have a single entry and exit point. But
  562. # by spawning off another deferred, we are effectively
  563. # adding a new exit point.)
  564. res.addBoth(_set_context_cb, ctx)
  565. return res
  566. def make_deferred_yieldable(deferred):
  567. """Given a deferred (or coroutine), make it follow the Synapse logcontext
  568. rules:
  569. If the deferred has completed (or is not actually a Deferred), essentially
  570. does nothing (just returns another completed deferred with the
  571. result/failure).
  572. If the deferred has not yet completed, resets the logcontext before
  573. returning a deferred. Then, when the deferred completes, restores the
  574. current logcontext before running callbacks/errbacks.
  575. (This is more-or-less the opposite operation to run_in_background.)
  576. """
  577. if inspect.isawaitable(deferred):
  578. # If we're given a coroutine we convert it to a deferred so that we
  579. # run it and find out if it immediately finishes, it it does then we
  580. # don't need to fiddle with log contexts at all and can return
  581. # immediately.
  582. deferred = defer.ensureDeferred(deferred)
  583. if not isinstance(deferred, defer.Deferred):
  584. return deferred
  585. if deferred.called and not deferred.paused:
  586. # it looks like this deferred is ready to run any callbacks we give it
  587. # immediately. We may as well optimise out the logcontext faffery.
  588. return deferred
  589. # ok, we can't be sure that a yield won't block, so let's reset the
  590. # logcontext, and add a callback to the deferred to restore it.
  591. prev_context = set_current_context(SENTINEL_CONTEXT)
  592. deferred.addBoth(_set_context_cb, prev_context)
  593. return deferred
  594. ResultT = TypeVar("ResultT")
  595. def _set_context_cb(result: ResultT, context: LoggingContext) -> ResultT:
  596. """A callback function which just sets the logging context"""
  597. set_current_context(context)
  598. return result
  599. def defer_to_thread(reactor, f, *args, **kwargs):
  600. """
  601. Calls the function `f` using a thread from the reactor's default threadpool and
  602. returns the result as a Deferred.
  603. Creates a new logcontext for `f`, which is created as a child of the current
  604. logcontext (so its CPU usage metrics will get attributed to the current
  605. logcontext). `f` should preserve the logcontext it is given.
  606. The result deferred follows the Synapse logcontext rules: you should `yield`
  607. on it.
  608. Args:
  609. reactor (twisted.internet.base.ReactorBase): The reactor in whose main thread
  610. the Deferred will be invoked, and whose threadpool we should use for the
  611. function.
  612. Normally this will be hs.get_reactor().
  613. f (callable): The function to call.
  614. args: positional arguments to pass to f.
  615. kwargs: keyword arguments to pass to f.
  616. Returns:
  617. Deferred: A Deferred which fires a callback with the result of `f`, or an
  618. errback if `f` throws an exception.
  619. """
  620. return defer_to_threadpool(reactor, reactor.getThreadPool(), f, *args, **kwargs)
  621. def defer_to_threadpool(reactor, threadpool, f, *args, **kwargs):
  622. """
  623. A wrapper for twisted.internet.threads.deferToThreadpool, which handles
  624. logcontexts correctly.
  625. Calls the function `f` using a thread from the given threadpool and returns
  626. the result as a Deferred.
  627. Creates a new logcontext for `f`, which is created as a child of the current
  628. logcontext (so its CPU usage metrics will get attributed to the current
  629. logcontext). `f` should preserve the logcontext it is given.
  630. The result deferred follows the Synapse logcontext rules: you should `yield`
  631. on it.
  632. Args:
  633. reactor (twisted.internet.base.ReactorBase): The reactor in whose main thread
  634. the Deferred will be invoked. Normally this will be hs.get_reactor().
  635. threadpool (twisted.python.threadpool.ThreadPool): The threadpool to use for
  636. running `f`. Normally this will be hs.get_reactor().getThreadPool().
  637. f (callable): The function to call.
  638. args: positional arguments to pass to f.
  639. kwargs: keyword arguments to pass to f.
  640. Returns:
  641. Deferred: A Deferred which fires a callback with the result of `f`, or an
  642. errback if `f` throws an exception.
  643. """
  644. curr_context = current_context()
  645. if not curr_context:
  646. logger.warning(
  647. "Calling defer_to_threadpool from sentinel context: metrics will be lost"
  648. )
  649. parent_context = None
  650. else:
  651. assert isinstance(curr_context, LoggingContext)
  652. parent_context = curr_context
  653. def g():
  654. with LoggingContext(parent_context=parent_context):
  655. return f(*args, **kwargs)
  656. return make_deferred_yieldable(threads.deferToThreadPool(reactor, threadpool, g))