metrics.py 5.4 KB

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