_legacy_exposition.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. # Copyright 2015-2019 Prometheus Python Client Developers
  2. # Copyright 2019 Matrix.org Foundation C.I.C.
  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. """
  16. This code is based off `prometheus_client/exposition.py` from version 0.7.1.
  17. Due to the renaming of metrics in prometheus_client 0.4.0, this customised
  18. vendoring of the code will emit both the old versions that Synapse dashboards
  19. expect, and the newer "best practice" version of the up-to-date official client.
  20. """
  21. import logging
  22. import math
  23. import threading
  24. from http.server import BaseHTTPRequestHandler, HTTPServer
  25. from socketserver import ThreadingMixIn
  26. from typing import Any, Dict, List, Type, Union
  27. from urllib.parse import parse_qs, urlparse
  28. from prometheus_client import REGISTRY, CollectorRegistry
  29. from prometheus_client.core import Sample
  30. from twisted.web.resource import Resource
  31. from twisted.web.server import Request
  32. logger = logging.getLogger(__name__)
  33. CONTENT_TYPE_LATEST = "text/plain; version=0.0.4; charset=utf-8"
  34. def floatToGoString(d: Union[int, float]) -> str:
  35. d = float(d)
  36. if d == math.inf:
  37. return "+Inf"
  38. elif d == -math.inf:
  39. return "-Inf"
  40. elif math.isnan(d):
  41. return "NaN"
  42. else:
  43. s = repr(d)
  44. dot = s.find(".")
  45. # Go switches to exponents sooner than Python.
  46. # We only need to care about positive values for le/quantile.
  47. if d > 0 and dot > 6:
  48. mantissa = f"{s[0]}.{s[1:dot]}{s[dot + 1 :]}".rstrip("0.")
  49. return f"{mantissa}e+0{dot - 1}"
  50. return s
  51. def sample_line(line: Sample, name: str) -> str:
  52. if line.labels:
  53. labelstr = "{{{0}}}".format(
  54. ",".join(
  55. [
  56. '{}="{}"'.format(
  57. k,
  58. v.replace("\\", r"\\").replace("\n", r"\n").replace('"', r"\""),
  59. )
  60. for k, v in sorted(line.labels.items())
  61. ]
  62. )
  63. )
  64. else:
  65. labelstr = ""
  66. timestamp = ""
  67. if line.timestamp is not None:
  68. # Convert to milliseconds.
  69. timestamp = f" {int(float(line.timestamp) * 1000):d}"
  70. return "{}{} {}{}\n".format(name, labelstr, floatToGoString(line.value), timestamp)
  71. # Mapping from new metric names to legacy metric names.
  72. # We translate these back to their old names when exposing them through our
  73. # legacy vendored exporter.
  74. # Only this legacy exposition module applies these name changes.
  75. LEGACY_METRIC_NAMES = {
  76. "synapse_util_caches_cache_hits": "synapse_util_caches_cache:hits",
  77. "synapse_util_caches_cache_size": "synapse_util_caches_cache:size",
  78. "synapse_util_caches_cache_evicted_size": "synapse_util_caches_cache:evicted_size",
  79. "synapse_util_caches_cache": "synapse_util_caches_cache:total",
  80. "synapse_util_caches_response_cache_size": "synapse_util_caches_response_cache:size",
  81. "synapse_util_caches_response_cache_hits": "synapse_util_caches_response_cache:hits",
  82. "synapse_util_caches_response_cache_evicted_size": "synapse_util_caches_response_cache:evicted_size",
  83. "synapse_util_caches_response_cache": "synapse_util_caches_response_cache:total",
  84. "synapse_federation_client_sent_pdu_destinations": "synapse_federation_client_sent_pdu_destinations:total",
  85. "synapse_federation_client_sent_pdu_destinations_count": "synapse_federation_client_sent_pdu_destinations:count",
  86. "synapse_admin_mau_current": "synapse_admin_mau:current",
  87. "synapse_admin_mau_max": "synapse_admin_mau:max",
  88. "synapse_admin_mau_registered_reserved_users": "synapse_admin_mau:registered_reserved_users",
  89. }
  90. def generate_latest(registry: CollectorRegistry, emit_help: bool = False) -> bytes:
  91. """
  92. Generate metrics in legacy format. Modern metrics are generated directly
  93. by prometheus-client.
  94. """
  95. output = []
  96. for metric in registry.collect():
  97. if not metric.samples:
  98. # No samples, don't bother.
  99. continue
  100. # Translate to legacy metric name if it has one.
  101. mname = LEGACY_METRIC_NAMES.get(metric.name, metric.name)
  102. mnewname = metric.name
  103. mtype = metric.type
  104. # OpenMetrics -> Prometheus
  105. if mtype == "counter":
  106. mnewname = mnewname + "_total"
  107. elif mtype == "info":
  108. mtype = "gauge"
  109. mnewname = mnewname + "_info"
  110. elif mtype == "stateset":
  111. mtype = "gauge"
  112. elif mtype == "gaugehistogram":
  113. mtype = "histogram"
  114. elif mtype == "unknown":
  115. mtype = "untyped"
  116. # Output in the old format for compatibility.
  117. if emit_help:
  118. output.append(
  119. "# HELP {} {}\n".format(
  120. mname,
  121. metric.documentation.replace("\\", r"\\").replace("\n", r"\n"),
  122. )
  123. )
  124. output.append(f"# TYPE {mname} {mtype}\n")
  125. om_samples: Dict[str, List[str]] = {}
  126. for s in metric.samples:
  127. for suffix in ["_created", "_gsum", "_gcount"]:
  128. if s.name == mname + suffix:
  129. # OpenMetrics specific sample, put in a gauge at the end.
  130. # (these come from gaugehistograms which don't get renamed,
  131. # so no need to faff with mnewname)
  132. om_samples.setdefault(suffix, []).append(sample_line(s, s.name))
  133. break
  134. else:
  135. newname = s.name.replace(mnewname, mname)
  136. if ":" in newname and newname.endswith("_total"):
  137. newname = newname[: -len("_total")]
  138. output.append(sample_line(s, newname))
  139. for suffix, lines in sorted(om_samples.items()):
  140. if emit_help:
  141. output.append(
  142. "# HELP {}{} {}\n".format(
  143. mname,
  144. suffix,
  145. metric.documentation.replace("\\", r"\\").replace("\n", r"\n"),
  146. )
  147. )
  148. output.append(f"# TYPE {mname}{suffix} gauge\n")
  149. output.extend(lines)
  150. # Get rid of the weird colon things while we're at it
  151. if mtype == "counter":
  152. mnewname = mnewname.replace(":total", "")
  153. mnewname = mnewname.replace(":", "_")
  154. if mname == mnewname:
  155. continue
  156. # Also output in the new format, if it's different.
  157. if emit_help:
  158. output.append(
  159. "# HELP {} {}\n".format(
  160. mnewname,
  161. metric.documentation.replace("\\", r"\\").replace("\n", r"\n"),
  162. )
  163. )
  164. output.append(f"# TYPE {mnewname} {mtype}\n")
  165. for s in metric.samples:
  166. # Get rid of the OpenMetrics specific samples (we should already have
  167. # dealt with them above anyway.)
  168. for suffix in ["_created", "_gsum", "_gcount"]:
  169. if s.name == mname + suffix:
  170. break
  171. else:
  172. sample_name = LEGACY_METRIC_NAMES.get(s.name, s.name)
  173. output.append(
  174. sample_line(s, sample_name.replace(":total", "").replace(":", "_"))
  175. )
  176. return "".join(output).encode("utf-8")
  177. class MetricsHandler(BaseHTTPRequestHandler):
  178. """HTTP handler that gives metrics from ``REGISTRY``."""
  179. registry = REGISTRY
  180. def do_GET(self) -> None:
  181. registry = self.registry
  182. params = parse_qs(urlparse(self.path).query)
  183. if "help" in params:
  184. emit_help = True
  185. else:
  186. emit_help = False
  187. try:
  188. output = generate_latest(registry, emit_help=emit_help)
  189. except Exception:
  190. self.send_error(500, "error generating metric output")
  191. raise
  192. try:
  193. self.send_response(200)
  194. self.send_header("Content-Type", CONTENT_TYPE_LATEST)
  195. self.send_header("Content-Length", str(len(output)))
  196. self.end_headers()
  197. self.wfile.write(output)
  198. except BrokenPipeError as e:
  199. logger.warning(
  200. "BrokenPipeError when serving metrics (%s). Did Prometheus restart?", e
  201. )
  202. def log_message(self, format: str, *args: Any) -> None:
  203. """Log nothing."""
  204. @classmethod
  205. def factory(cls, registry: CollectorRegistry) -> Type:
  206. """Returns a dynamic MetricsHandler class tied
  207. to the passed registry.
  208. """
  209. # This implementation relies on MetricsHandler.registry
  210. # (defined above and defaulted to REGISTRY).
  211. # As we have unicode_literals, we need to create a str()
  212. # object for type().
  213. cls_name = str(cls.__name__)
  214. MyMetricsHandler = type(cls_name, (cls, object), {"registry": registry})
  215. return MyMetricsHandler
  216. class _ThreadingSimpleServer(ThreadingMixIn, HTTPServer):
  217. """Thread per request HTTP server."""
  218. # Make worker threads "fire and forget". Beginning with Python 3.7 this
  219. # prevents a memory leak because ``ThreadingMixIn`` starts to gather all
  220. # non-daemon threads in a list in order to join on them at server close.
  221. # Enabling daemon threads virtually makes ``_ThreadingSimpleServer`` the
  222. # same as Python 3.7's ``ThreadingHTTPServer``.
  223. daemon_threads = True
  224. def start_http_server(
  225. port: int, addr: str = "", registry: CollectorRegistry = REGISTRY
  226. ) -> None:
  227. """Starts an HTTP server for prometheus metrics as a daemon thread"""
  228. CustomMetricsHandler = MetricsHandler.factory(registry)
  229. httpd = _ThreadingSimpleServer((addr, port), CustomMetricsHandler)
  230. t = threading.Thread(target=httpd.serve_forever)
  231. t.daemon = True
  232. t.start()
  233. class MetricsResource(Resource):
  234. """
  235. Twisted ``Resource`` that serves prometheus metrics.
  236. """
  237. isLeaf = True
  238. def __init__(self, registry: CollectorRegistry = REGISTRY):
  239. self.registry = registry
  240. def render_GET(self, request: Request) -> bytes:
  241. request.setHeader(b"Content-Type", CONTENT_TYPE_LATEST.encode("ascii"))
  242. response = generate_latest(self.registry)
  243. request.setHeader(b"Content-Length", str(len(response)))
  244. return response