context.py 32 KB

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