metrics.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. # Copyright 2016 OpenMarket 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. from functools import wraps
  16. from types import TracebackType
  17. from typing import Any, Callable, Optional, Type, TypeVar, cast
  18. from prometheus_client import Counter
  19. from typing_extensions import Protocol
  20. from synapse.logging.context import (
  21. ContextResourceUsage,
  22. LoggingContext,
  23. current_context,
  24. )
  25. from synapse.metrics import InFlightGauge
  26. from synapse.util import Clock
  27. logger = logging.getLogger(__name__)
  28. block_counter = Counter("synapse_util_metrics_block_count", "", ["block_name"])
  29. block_timer = Counter("synapse_util_metrics_block_time_seconds", "", ["block_name"])
  30. block_ru_utime = Counter(
  31. "synapse_util_metrics_block_ru_utime_seconds", "", ["block_name"]
  32. )
  33. block_ru_stime = Counter(
  34. "synapse_util_metrics_block_ru_stime_seconds", "", ["block_name"]
  35. )
  36. block_db_txn_count = Counter(
  37. "synapse_util_metrics_block_db_txn_count", "", ["block_name"]
  38. )
  39. # seconds spent waiting for db txns, excluding scheduling time, in this block
  40. block_db_txn_duration = Counter(
  41. "synapse_util_metrics_block_db_txn_duration_seconds", "", ["block_name"]
  42. )
  43. # seconds spent waiting for a db connection, in this block
  44. block_db_sched_duration = Counter(
  45. "synapse_util_metrics_block_db_sched_duration_seconds", "", ["block_name"]
  46. )
  47. # Tracks the number of blocks currently active
  48. in_flight = InFlightGauge(
  49. "synapse_util_metrics_block_in_flight",
  50. "",
  51. labels=["block_name"],
  52. sub_metrics=["real_time_max", "real_time_sum"],
  53. )
  54. # This is dynamically created in InFlightGauge.__init__.
  55. class _InFlightMetric(Protocol):
  56. real_time_max: float
  57. real_time_sum: float
  58. T = TypeVar("T", bound=Callable[..., Any])
  59. class HasClock(Protocol):
  60. clock: Clock
  61. def measure_func(name: Optional[str] = None) -> Callable[[T], T]:
  62. """
  63. Used to decorate an async function with a `Measure` context manager.
  64. Usage:
  65. @measure_func()
  66. async def foo(...):
  67. ...
  68. Which is analogous to:
  69. async def foo(...):
  70. with Measure(...):
  71. ...
  72. """
  73. def wrapper(func: T) -> T:
  74. block_name = func.__name__ if name is None else name
  75. @wraps(func)
  76. async def measured_func(self: HasClock, *args: Any, **kwargs: Any) -> Any:
  77. with Measure(self.clock, block_name):
  78. r = await func(self, *args, **kwargs)
  79. return r
  80. return cast(T, measured_func)
  81. return wrapper
  82. class Measure:
  83. __slots__ = [
  84. "clock",
  85. "name",
  86. "_logging_context",
  87. "start",
  88. ]
  89. def __init__(self, clock: Clock, name: str) -> None:
  90. """
  91. Args:
  92. clock: An object with a "time()" method, which returns the current
  93. time in seconds.
  94. name: The name of the metric to report.
  95. """
  96. self.clock = clock
  97. self.name = name
  98. curr_context = current_context()
  99. if not curr_context:
  100. logger.warning(
  101. "Starting metrics collection %r from sentinel context: metrics will be lost",
  102. name,
  103. )
  104. parent_context = None
  105. else:
  106. assert isinstance(curr_context, LoggingContext)
  107. parent_context = curr_context
  108. self._logging_context = LoggingContext(str(curr_context), parent_context)
  109. self.start: Optional[float] = None
  110. def __enter__(self) -> "Measure":
  111. if self.start is not None:
  112. raise RuntimeError("Measure() objects cannot be re-used")
  113. self.start = self.clock.time()
  114. self._logging_context.__enter__()
  115. in_flight.register((self.name,), self._update_in_flight)
  116. logger.debug("Entering block %s", self.name)
  117. return self
  118. def __exit__(
  119. self,
  120. exc_type: Optional[Type[BaseException]],
  121. exc_val: Optional[BaseException],
  122. exc_tb: Optional[TracebackType],
  123. ) -> None:
  124. if self.start is None:
  125. raise RuntimeError("Measure() block exited without being entered")
  126. logger.debug("Exiting block %s", self.name)
  127. duration = self.clock.time() - self.start
  128. usage = self.get_resource_usage()
  129. in_flight.unregister((self.name,), self._update_in_flight)
  130. self._logging_context.__exit__(exc_type, exc_val, exc_tb)
  131. try:
  132. block_counter.labels(self.name).inc()
  133. block_timer.labels(self.name).inc(duration)
  134. block_ru_utime.labels(self.name).inc(usage.ru_utime)
  135. block_ru_stime.labels(self.name).inc(usage.ru_stime)
  136. block_db_txn_count.labels(self.name).inc(usage.db_txn_count)
  137. block_db_txn_duration.labels(self.name).inc(usage.db_txn_duration_sec)
  138. block_db_sched_duration.labels(self.name).inc(usage.db_sched_duration_sec)
  139. except ValueError:
  140. logger.warning("Failed to save metrics! Usage: %s", usage)
  141. def get_resource_usage(self) -> ContextResourceUsage:
  142. """Get the resources used within this Measure block
  143. If the Measure block is still active, returns the resource usage so far.
  144. """
  145. return self._logging_context.get_resource_usage()
  146. def _update_in_flight(self, metrics: _InFlightMetric) -> None:
  147. """Gets called when processing in flight metrics"""
  148. assert self.start is not None
  149. duration = self.clock.time() - self.start
  150. metrics.real_time_max = max(metrics.real_time_max, duration)
  151. metrics.real_time_sum += duration
  152. # TODO: Add other in flight metrics.