request_metrics.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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. import threading
  18. from prometheus_client.core import Counter, Histogram
  19. from synapse.metrics import LaterGauge
  20. from synapse.util.logcontext import LoggingContext
  21. logger = logging.getLogger(__name__)
  22. # total number of responses served, split by method/servlet/tag
  23. response_count = Counter(
  24. "synapse_http_server_response_count", "", ["method", "servlet", "tag"]
  25. )
  26. requests_counter = Counter(
  27. "synapse_http_server_requests_received", "", ["method", "servlet"]
  28. )
  29. outgoing_responses_counter = Counter(
  30. "synapse_http_server_responses", "", ["method", "code"]
  31. )
  32. response_timer = Histogram(
  33. "synapse_http_server_response_time_seconds", "sec",
  34. ["method", "servlet", "tag", "code"],
  35. )
  36. response_ru_utime = Counter(
  37. "synapse_http_server_response_ru_utime_seconds", "sec", ["method", "servlet", "tag"]
  38. )
  39. response_ru_stime = Counter(
  40. "synapse_http_server_response_ru_stime_seconds", "sec", ["method", "servlet", "tag"]
  41. )
  42. response_db_txn_count = Counter(
  43. "synapse_http_server_response_db_txn_count", "", ["method", "servlet", "tag"]
  44. )
  45. # seconds spent waiting for db txns, excluding scheduling time, when processing
  46. # this request
  47. response_db_txn_duration = Counter(
  48. "synapse_http_server_response_db_txn_duration_seconds",
  49. "",
  50. ["method", "servlet", "tag"],
  51. )
  52. # seconds spent waiting for a db connection, when processing this request
  53. response_db_sched_duration = Counter(
  54. "synapse_http_server_response_db_sched_duration_seconds",
  55. "",
  56. ["method", "servlet", "tag"],
  57. )
  58. # size in bytes of the response written
  59. response_size = Counter(
  60. "synapse_http_server_response_size", "", ["method", "servlet", "tag"]
  61. )
  62. # In flight metrics are incremented while the requests are in flight, rather
  63. # than when the response was written.
  64. in_flight_requests_ru_utime = Counter(
  65. "synapse_http_server_in_flight_requests_ru_utime_seconds",
  66. "",
  67. ["method", "servlet"],
  68. )
  69. in_flight_requests_ru_stime = Counter(
  70. "synapse_http_server_in_flight_requests_ru_stime_seconds",
  71. "",
  72. ["method", "servlet"],
  73. )
  74. in_flight_requests_db_txn_count = Counter(
  75. "synapse_http_server_in_flight_requests_db_txn_count", "", ["method", "servlet"]
  76. )
  77. # seconds spent waiting for db txns, excluding scheduling time, when processing
  78. # this request
  79. in_flight_requests_db_txn_duration = Counter(
  80. "synapse_http_server_in_flight_requests_db_txn_duration_seconds",
  81. "",
  82. ["method", "servlet"],
  83. )
  84. # seconds spent waiting for a db connection, when processing this request
  85. in_flight_requests_db_sched_duration = Counter(
  86. "synapse_http_server_in_flight_requests_db_sched_duration_seconds",
  87. "",
  88. ["method", "servlet"],
  89. )
  90. # The set of all in flight requests, set[RequestMetrics]
  91. _in_flight_requests = set()
  92. # Protects the _in_flight_requests set from concurrent accesss
  93. _in_flight_requests_lock = threading.Lock()
  94. def _get_in_flight_counts():
  95. """Returns a count of all in flight requests by (method, server_name)
  96. Returns:
  97. dict[tuple[str, str], int]
  98. """
  99. # Cast to a list to prevent it changing while the Prometheus
  100. # thread is collecting metrics
  101. with _in_flight_requests_lock:
  102. reqs = list(_in_flight_requests)
  103. for rm in reqs:
  104. rm.update_metrics()
  105. # Map from (method, name) -> int, the number of in flight requests of that
  106. # type
  107. counts = {}
  108. for rm in reqs:
  109. key = (rm.method, rm.name,)
  110. counts[key] = counts.get(key, 0) + 1
  111. return counts
  112. LaterGauge(
  113. "synapse_http_server_in_flight_requests_count",
  114. "",
  115. ["method", "servlet"],
  116. _get_in_flight_counts,
  117. )
  118. class RequestMetrics(object):
  119. def start(self, time_sec, name, method):
  120. self.start = time_sec
  121. self.start_context = LoggingContext.current_context()
  122. self.name = name
  123. self.method = method
  124. # _request_stats records resource usage that we have already added
  125. # to the "in flight" metrics.
  126. self._request_stats = self.start_context.get_resource_usage()
  127. with _in_flight_requests_lock:
  128. _in_flight_requests.add(self)
  129. def stop(self, time_sec, request):
  130. with _in_flight_requests_lock:
  131. _in_flight_requests.discard(self)
  132. context = LoggingContext.current_context()
  133. tag = ""
  134. if context:
  135. tag = context.tag
  136. if context != self.start_context:
  137. logger.warn(
  138. "Context have unexpectedly changed %r, %r",
  139. context, self.start_context
  140. )
  141. return
  142. response_code = str(request.code)
  143. outgoing_responses_counter.labels(request.method, response_code).inc()
  144. response_count.labels(request.method, self.name, tag).inc()
  145. response_timer.labels(request.method, self.name, tag, response_code).observe(
  146. time_sec - self.start
  147. )
  148. resource_usage = context.get_resource_usage()
  149. response_ru_utime.labels(request.method, self.name, tag).inc(
  150. resource_usage.ru_utime,
  151. )
  152. response_ru_stime.labels(request.method, self.name, tag).inc(
  153. resource_usage.ru_stime,
  154. )
  155. response_db_txn_count.labels(request.method, self.name, tag).inc(
  156. resource_usage.db_txn_count
  157. )
  158. response_db_txn_duration.labels(request.method, self.name, tag).inc(
  159. resource_usage.db_txn_duration_sec
  160. )
  161. response_db_sched_duration.labels(request.method, self.name, tag).inc(
  162. resource_usage.db_sched_duration_sec
  163. )
  164. response_size.labels(request.method, self.name, tag).inc(request.sentLength)
  165. # We always call this at the end to ensure that we update the metrics
  166. # regardless of whether a call to /metrics while the request was in
  167. # flight.
  168. self.update_metrics()
  169. def update_metrics(self):
  170. """Updates the in flight metrics with values from this request.
  171. """
  172. new_stats = self.start_context.get_resource_usage()
  173. diff = new_stats - self._request_stats
  174. self._request_stats = new_stats
  175. in_flight_requests_ru_utime.labels(self.method, self.name).inc(diff.ru_utime)
  176. in_flight_requests_ru_stime.labels(self.method, self.name).inc(diff.ru_stime)
  177. in_flight_requests_db_txn_count.labels(self.method, self.name).inc(
  178. diff.db_txn_count
  179. )
  180. in_flight_requests_db_txn_duration.labels(self.method, self.name).inc(
  181. diff.db_txn_duration_sec
  182. )
  183. in_flight_requests_db_sched_duration.labels(self.method, self.name).inc(
  184. diff.db_sched_duration_sec
  185. )