request_metrics.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2018 New Vector Ltd
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import logging
  17. from prometheus_client.core import Counter, Histogram
  18. from synapse.metrics import LaterGauge
  19. from synapse.util.logcontext import LoggingContext
  20. logger = logging.getLogger(__name__)
  21. # total number of responses served, split by method/servlet/tag
  22. response_count = Counter("synapse_http_server_response_count", "", ["method", "servlet", "tag"])
  23. requests_counter = Counter("synapse_http_server_requests_received", "", ["method", "servlet"])
  24. outgoing_responses_counter = Counter("synapse_http_server_responses", "", ["method", "code"])
  25. response_timer = Histogram("synapse_http_server_response_time_seconds", "", ["method", "servlet", "tag"])
  26. response_ru_utime = Counter("synapse_http_server_response_ru_utime_seconds", "", ["method", "servlet", "tag"])
  27. response_ru_stime = Counter("synapse_http_server_response_ru_stime_seconds", "", ["method", "servlet", "tag"])
  28. response_db_txn_count = Counter("synapse_http_server_response_db_txn_count", "", ["method", "servlet", "tag"])
  29. # seconds spent waiting for db txns, excluding scheduling time, when processing
  30. # this request
  31. response_db_txn_duration = Counter("synapse_http_server_response_db_txn_duration_seconds", "", ["method", "servlet", "tag"])
  32. # seconds spent waiting for a db connection, when processing this request
  33. response_db_sched_duration = Counter("synapse_http_request_response_db_sched_duration_seconds", "", ["method", "servlet", "tag"]
  34. )
  35. # size in bytes of the response written
  36. response_size = Counter("synapse_http_request_response_size", "", ["method", "servlet", "tag"]
  37. )
  38. # In flight metrics are incremented while the requests are in flight, rather
  39. # than when the response was written.
  40. in_flight_requests_ru_utime = Counter("synapse_http_request_in_flight_requests_ru_utime_seconds", "", ["method", "servlet"])
  41. in_flight_requests_ru_stime = Counter("synapse_http_request_in_flight_requests_ru_stime_seconds", "", ["method", "servlet"])
  42. in_flight_requests_db_txn_count = Counter("synapse_http_request_in_flight_requests_db_txn_count", "", ["method", "servlet"])
  43. # seconds spent waiting for db txns, excluding scheduling time, when processing
  44. # this request
  45. in_flight_requests_db_txn_duration = Counter("synapse_http_request_in_flight_requests_db_txn_duration_seconds", "", ["method", "servlet"])
  46. # seconds spent waiting for a db connection, when processing this request
  47. in_flight_requests_db_sched_duration = Counter("synapse_http_request_in_flight_requests_db_sched_duration_seconds", "", ["method", "servlet"])
  48. # The set of all in flight requests, set[RequestMetrics]
  49. _in_flight_requests = set()
  50. def _get_in_flight_counts():
  51. """Returns a count of all in flight requests by (method, server_name)
  52. Returns:
  53. dict[tuple[str, str], int]
  54. """
  55. for rm in _in_flight_requests:
  56. rm.update_metrics()
  57. # Map from (method, name) -> int, the number of in flight requests of that
  58. # type
  59. counts = {}
  60. for rm in _in_flight_requests:
  61. key = (rm.method, rm.name,)
  62. counts[key] = counts.get(key, 0) + 1
  63. return counts
  64. LaterGauge(
  65. "synapse_http_request_metrics_in_flight_requests_count", "",
  66. ["method", "servlet"],
  67. _get_in_flight_counts
  68. )
  69. class RequestMetrics(object):
  70. def start(self, time_msec, name, method):
  71. self.start = time_msec
  72. self.start_context = LoggingContext.current_context()
  73. self.name = name
  74. self.method = method
  75. self._request_stats = _RequestStats.from_context(self.start_context)
  76. _in_flight_requests.add(self)
  77. def stop(self, time_msec, request):
  78. _in_flight_requests.discard(self)
  79. context = LoggingContext.current_context()
  80. tag = ""
  81. if context:
  82. tag = context.tag
  83. if context != self.start_context:
  84. logger.warn(
  85. "Context have unexpectedly changed %r, %r",
  86. context, self.start_context
  87. )
  88. return
  89. outgoing_responses_counter.labels(request.method, str(request.code)).inc()
  90. response_count.labels(request.method, self.name, tag).inc()
  91. response_timer.labels(request.method, self.name, tag).observe(time_msec - self.start)
  92. ru_utime, ru_stime = context.get_resource_usage()
  93. response_ru_utime.labels(request.method, self.name, tag).inc(ru_utime)
  94. response_ru_stime.labels(request.method, self.name, tag).inc(ru_stime)
  95. response_db_txn_count.labels(request.method, self.name, tag).inc(context.db_txn_count)
  96. response_db_txn_duration.labels(request.method, self.name, tag).inc(context.db_txn_duration_ms / 1000.)
  97. response_db_sched_duration.labels(request.method, self.name, tag).inc(
  98. context.db_sched_duration_ms / 1000.)
  99. response_size.labels(request.method, self.name, tag).inc(request.sentLength)
  100. # We always call this at the end to ensure that we update the metrics
  101. # regardless of whether a call to /metrics while the request was in
  102. # flight.
  103. self.update_metrics()
  104. def update_metrics(self):
  105. """Updates the in flight metrics with values from this request.
  106. """
  107. diff = self._request_stats.update(self.start_context)
  108. in_flight_requests_ru_utime.labels(self.method, self.name).inc(diff.ru_utime)
  109. in_flight_requests_ru_stime.labels(self.method, self.name).inc(diff.ru_stime)
  110. in_flight_requests_db_txn_count.labels(self.method, self.name).inc(diff.db_txn_count)
  111. in_flight_requests_db_txn_duration.labels(self.method, self.name).inc(diff.db_txn_duration_ms / 1000.)
  112. in_flight_requests_db_sched_duration.labels(self.method, self.name).inc(diff.db_sched_duration_ms / 1000.)
  113. class _RequestStats(object):
  114. """Keeps tracks of various metrics for an in flight request.
  115. """
  116. __slots__ = [
  117. "ru_utime", "ru_stime",
  118. "db_txn_count", "db_txn_duration_ms", "db_sched_duration_ms",
  119. ]
  120. def __init__(self, ru_utime, ru_stime, db_txn_count,
  121. db_txn_duration_ms, db_sched_duration_ms):
  122. self.ru_utime = ru_utime
  123. self.ru_stime = ru_stime
  124. self.db_txn_count = db_txn_count
  125. self.db_txn_duration_ms = db_txn_duration_ms
  126. self.db_sched_duration_ms = db_sched_duration_ms
  127. @staticmethod
  128. def from_context(context):
  129. ru_utime, ru_stime = context.get_resource_usage()
  130. return _RequestStats(
  131. ru_utime, ru_stime,
  132. context.db_txn_count,
  133. context.db_txn_duration_ms,
  134. context.db_sched_duration_ms,
  135. )
  136. def update(self, context):
  137. """Updates the current values and returns the difference between the
  138. old and new values.
  139. Returns:
  140. _RequestStats: The difference between the old and new values
  141. """
  142. new = _RequestStats.from_context(context)
  143. diff = _RequestStats(
  144. new.ru_utime - self.ru_utime,
  145. new.ru_stime - self.ru_stime,
  146. new.db_txn_count - self.db_txn_count,
  147. new.db_txn_duration_ms - self.db_txn_duration_ms,
  148. new.db_sched_duration_ms - self.db_sched_duration_ms,
  149. )
  150. self.ru_utime = new.ru_utime
  151. self.ru_stime = new.ru_stime
  152. self.db_txn_count = new.db_txn_count
  153. self.db_txn_duration_ms = new.db_txn_duration_ms
  154. self.db_sched_duration_ms = new.db_sched_duration_ms
  155. return diff