background_process_metrics.py 9.6 KB

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