background_process_metrics.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. # Copyright 2018 New Vector Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import logging
  15. import threading
  16. from functools import wraps
  17. from typing import TYPE_CHECKING, Dict, Optional, Set, Union
  18. from prometheus_client.core import REGISTRY, Counter, Gauge
  19. from twisted.internet import defer
  20. from synapse.logging.context import LoggingContext, PreserveLoggingContext
  21. from synapse.logging.opentracing import (
  22. SynapseTags,
  23. noop_context_manager,
  24. start_active_span,
  25. )
  26. from synapse.util.async_helpers import maybe_awaitable
  27. if TYPE_CHECKING:
  28. import resource
  29. logger = logging.getLogger(__name__)
  30. _background_process_start_count = Counter(
  31. "synapse_background_process_start_count",
  32. "Number of background processes started",
  33. ["name"],
  34. )
  35. _background_process_in_flight_count = Gauge(
  36. "synapse_background_process_in_flight_count",
  37. "Number of background processes in flight",
  38. labelnames=["name"],
  39. )
  40. # we set registry=None in all of these to stop them getting registered with
  41. # the default registry. Instead we collect them all via the CustomCollector,
  42. # which ensures that we can update them before they are collected.
  43. #
  44. _background_process_ru_utime = Counter(
  45. "synapse_background_process_ru_utime_seconds",
  46. "User CPU time used by background processes, in seconds",
  47. ["name"],
  48. registry=None,
  49. )
  50. _background_process_ru_stime = Counter(
  51. "synapse_background_process_ru_stime_seconds",
  52. "System CPU time used by background processes, in seconds",
  53. ["name"],
  54. registry=None,
  55. )
  56. _background_process_db_txn_count = Counter(
  57. "synapse_background_process_db_txn_count",
  58. "Number of database transactions done by background processes",
  59. ["name"],
  60. registry=None,
  61. )
  62. _background_process_db_txn_duration = Counter(
  63. "synapse_background_process_db_txn_duration_seconds",
  64. (
  65. "Seconds spent by background processes waiting for database "
  66. "transactions, excluding scheduling time"
  67. ),
  68. ["name"],
  69. registry=None,
  70. )
  71. _background_process_db_sched_duration = Counter(
  72. "synapse_background_process_db_sched_duration_seconds",
  73. "Seconds spent by background processes waiting for database connections",
  74. ["name"],
  75. registry=None,
  76. )
  77. # map from description to a counter, so that we can name our logcontexts
  78. # incrementally. (It actually duplicates _background_process_start_count, but
  79. # it's much simpler to do so than to try to combine them.)
  80. _background_process_counts: Dict[str, int] = {}
  81. # Set of all running background processes that became active active since the
  82. # last time metrics were scraped (i.e. background processes that performed some
  83. # work since the last scrape.)
  84. #
  85. # We do it like this to handle the case where we have a large number of
  86. # background processes stacking up behind a lock or linearizer, where we then
  87. # only need to iterate over and update metrics for the process that have
  88. # actually been active and can ignore the idle ones.
  89. _background_processes_active_since_last_scrape: "Set[_BackgroundProcess]" = set()
  90. # A lock that covers the above set and dict
  91. _bg_metrics_lock = threading.Lock()
  92. class _Collector:
  93. """A custom metrics collector for the background process metrics.
  94. Ensures that all of the metrics are up-to-date with any in-flight processes
  95. before they are returned.
  96. """
  97. def collect(self):
  98. global _background_processes_active_since_last_scrape
  99. # We swap out the _background_processes set with an empty one so that
  100. # we can safely iterate over the set without holding the lock.
  101. with _bg_metrics_lock:
  102. _background_processes_copy = _background_processes_active_since_last_scrape
  103. _background_processes_active_since_last_scrape = set()
  104. for process in _background_processes_copy:
  105. process.update_metrics()
  106. # now we need to run collect() over each of the static Counters, and
  107. # yield each metric they return.
  108. for m in (
  109. _background_process_ru_utime,
  110. _background_process_ru_stime,
  111. _background_process_db_txn_count,
  112. _background_process_db_txn_duration,
  113. _background_process_db_sched_duration,
  114. ):
  115. yield from m.collect()
  116. REGISTRY.register(_Collector())
  117. class _BackgroundProcess:
  118. def __init__(self, desc, ctx):
  119. self.desc = desc
  120. self._context = ctx
  121. self._reported_stats = None
  122. def update_metrics(self):
  123. """Updates the metrics with values from this process."""
  124. new_stats = self._context.get_resource_usage()
  125. if self._reported_stats is None:
  126. diff = new_stats
  127. else:
  128. diff = new_stats - self._reported_stats
  129. self._reported_stats = new_stats
  130. _background_process_ru_utime.labels(self.desc).inc(diff.ru_utime)
  131. _background_process_ru_stime.labels(self.desc).inc(diff.ru_stime)
  132. _background_process_db_txn_count.labels(self.desc).inc(diff.db_txn_count)
  133. _background_process_db_txn_duration.labels(self.desc).inc(
  134. diff.db_txn_duration_sec
  135. )
  136. _background_process_db_sched_duration.labels(self.desc).inc(
  137. diff.db_sched_duration_sec
  138. )
  139. def run_as_background_process(desc: str, func, *args, bg_start_span=True, **kwargs):
  140. """Run the given function in its own logcontext, with resource metrics
  141. This should be used to wrap processes which are fired off to run in the
  142. background, instead of being associated with a particular request.
  143. It returns a Deferred which completes when the function completes, but it doesn't
  144. follow the synapse logcontext rules, which makes it appropriate for passing to
  145. clock.looping_call and friends (or for firing-and-forgetting in the middle of a
  146. normal synapse async function).
  147. Args:
  148. desc: a description for this background process type
  149. func: a function, which may return a Deferred or a coroutine
  150. bg_start_span: Whether to start an opentracing span. Defaults to True.
  151. Should only be disabled for processes that will not log to or tag
  152. a span.
  153. args: positional args for func
  154. kwargs: keyword args for func
  155. Returns: Deferred which returns the result of func, but note that it does not
  156. follow the synapse logcontext rules.
  157. """
  158. async def run():
  159. with _bg_metrics_lock:
  160. count = _background_process_counts.get(desc, 0)
  161. _background_process_counts[desc] = count + 1
  162. _background_process_start_count.labels(desc).inc()
  163. _background_process_in_flight_count.labels(desc).inc()
  164. with BackgroundProcessLoggingContext(desc, count) as context:
  165. try:
  166. if bg_start_span:
  167. ctx = start_active_span(
  168. f"bgproc.{desc}", tags={SynapseTags.REQUEST_ID: str(context)}
  169. )
  170. else:
  171. ctx = noop_context_manager()
  172. with ctx:
  173. return await maybe_awaitable(func(*args, **kwargs))
  174. except Exception:
  175. logger.exception(
  176. "Background process '%s' threw an exception",
  177. desc,
  178. )
  179. finally:
  180. _background_process_in_flight_count.labels(desc).dec()
  181. with PreserveLoggingContext():
  182. # Note that we return a Deferred here so that it can be used in a
  183. # looping_call and other places that expect a Deferred.
  184. return defer.ensureDeferred(run())
  185. def wrap_as_background_process(desc):
  186. """Decorator that wraps a function that gets called as a background
  187. process.
  188. Equivalent of calling the function with `run_as_background_process`
  189. """
  190. def wrap_as_background_process_inner(func):
  191. @wraps(func)
  192. def wrap_as_background_process_inner_2(*args, **kwargs):
  193. return run_as_background_process(desc, func, *args, **kwargs)
  194. return wrap_as_background_process_inner_2
  195. return wrap_as_background_process_inner
  196. class BackgroundProcessLoggingContext(LoggingContext):
  197. """A logging context that tracks in flight metrics for background
  198. processes.
  199. """
  200. __slots__ = ["_proc"]
  201. def __init__(self, name: str, instance_id: Optional[Union[int, str]] = None):
  202. """
  203. Args:
  204. name: The name of the background process. Each distinct `name` gets a
  205. separate prometheus time series.
  206. instance_id: an identifer to add to `name` to distinguish this instance of
  207. the named background process in the logs. If this is `None`, one is
  208. made up based on id(self).
  209. """
  210. if instance_id is None:
  211. instance_id = id(self)
  212. super().__init__("%s-%s" % (name, instance_id))
  213. self._proc = _BackgroundProcess(name, self)
  214. def start(self, rusage: "Optional[resource.struct_rusage]"):
  215. """Log context has started running (again)."""
  216. super().start(rusage)
  217. # We've become active again so we make sure we're in the list of active
  218. # procs. (Note that "start" here means we've become active, as opposed
  219. # to starting for the first time.)
  220. with _bg_metrics_lock:
  221. _background_processes_active_since_last_scrape.add(self._proc)
  222. def __exit__(self, type, value, traceback) -> None:
  223. """Log context has finished."""
  224. super().__exit__(type, value, traceback)
  225. # The background process has finished. We explicitly remove and manually
  226. # update the metrics here so that if nothing is scraping metrics the set
  227. # doesn't infinitely grow.
  228. with _bg_metrics_lock:
  229. _background_processes_active_since_last_scrape.discard(self._proc)
  230. self._proc.update_metrics()