test_metrics.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. # Copyright 2018 New Vector Ltd
  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. from typing import Dict, Tuple
  16. from typing_extensions import Protocol
  17. try:
  18. from importlib import metadata
  19. except ImportError:
  20. import importlib_metadata as metadata # type: ignore[no-redef]
  21. from unittest.mock import patch
  22. from pkg_resources import parse_version
  23. from prometheus_client.core import Sample
  24. from synapse.app._base import _set_prometheus_client_use_created_metrics
  25. from synapse.metrics import REGISTRY, InFlightGauge, generate_latest
  26. from synapse.util.caches.deferred_cache import DeferredCache
  27. from tests import unittest
  28. def get_sample_labels_value(sample: Sample) -> Tuple[Dict[str, str], float]:
  29. """Extract the labels and values of a sample.
  30. prometheus_client 0.5 changed the sample type to a named tuple with more
  31. members than the plain tuple had in 0.4 and earlier. This function can
  32. extract the labels and value from the sample for both sample types.
  33. Args:
  34. sample: The sample to get the labels and value from.
  35. Returns:
  36. A tuple of (labels, value) from the sample.
  37. """
  38. # If the sample has a labels and value attribute, use those.
  39. if hasattr(sample, "labels") and hasattr(sample, "value"):
  40. return sample.labels, sample.value
  41. # Otherwise fall back to treating it as a plain 3 tuple.
  42. else:
  43. # In older versions of prometheus_client Sample was a 3-tuple.
  44. labels: Dict[str, str]
  45. value: float
  46. _, labels, value = sample # type: ignore[misc]
  47. return labels, value
  48. class TestMauLimit(unittest.TestCase):
  49. def test_basic(self) -> None:
  50. class MetricEntry(Protocol):
  51. foo: int
  52. bar: int
  53. gauge: InFlightGauge[MetricEntry] = InFlightGauge(
  54. "test1", "", labels=["test_label"], sub_metrics=["foo", "bar"]
  55. )
  56. def handle1(metrics: MetricEntry) -> None:
  57. metrics.foo += 2
  58. metrics.bar = max(metrics.bar, 5)
  59. def handle2(metrics: MetricEntry) -> None:
  60. metrics.foo += 3
  61. metrics.bar = max(metrics.bar, 7)
  62. gauge.register(("key1",), handle1)
  63. self.assert_dict(
  64. {
  65. "test1_total": {("key1",): 1},
  66. "test1_foo": {("key1",): 2},
  67. "test1_bar": {("key1",): 5},
  68. },
  69. self.get_metrics_from_gauge(gauge),
  70. )
  71. gauge.unregister(("key1",), handle1)
  72. self.assert_dict(
  73. {
  74. "test1_total": {("key1",): 0},
  75. "test1_foo": {("key1",): 0},
  76. "test1_bar": {("key1",): 0},
  77. },
  78. self.get_metrics_from_gauge(gauge),
  79. )
  80. gauge.register(("key1",), handle1)
  81. gauge.register(("key2",), handle2)
  82. self.assert_dict(
  83. {
  84. "test1_total": {("key1",): 1, ("key2",): 1},
  85. "test1_foo": {("key1",): 2, ("key2",): 3},
  86. "test1_bar": {("key1",): 5, ("key2",): 7},
  87. },
  88. self.get_metrics_from_gauge(gauge),
  89. )
  90. gauge.unregister(("key2",), handle2)
  91. gauge.register(("key1",), handle2)
  92. self.assert_dict(
  93. {
  94. "test1_total": {("key1",): 2, ("key2",): 0},
  95. "test1_foo": {("key1",): 5, ("key2",): 0},
  96. "test1_bar": {("key1",): 7, ("key2",): 0},
  97. },
  98. self.get_metrics_from_gauge(gauge),
  99. )
  100. def get_metrics_from_gauge(
  101. self, gauge: InFlightGauge
  102. ) -> Dict[str, Dict[Tuple[str, ...], float]]:
  103. results = {}
  104. for r in gauge.collect():
  105. results[r.name] = {
  106. tuple(labels[x] for x in gauge.labels): value
  107. for labels, value in map(get_sample_labels_value, r.samples)
  108. }
  109. return results
  110. class BuildInfoTests(unittest.TestCase):
  111. def test_get_build(self) -> None:
  112. """
  113. The synapse_build_info metric reports the OS version, Python version,
  114. and Synapse version.
  115. """
  116. items = list(
  117. filter(
  118. lambda x: b"synapse_build_info{" in x,
  119. generate_latest(REGISTRY).split(b"\n"),
  120. )
  121. )
  122. self.assertEqual(len(items), 1)
  123. self.assertTrue(b"osversion=" in items[0])
  124. self.assertTrue(b"pythonversion=" in items[0])
  125. self.assertTrue(b"version=" in items[0])
  126. class CacheMetricsTests(unittest.HomeserverTestCase):
  127. def test_cache_metric(self) -> None:
  128. """
  129. Caches produce metrics reflecting their state when scraped.
  130. """
  131. CACHE_NAME = "cache_metrics_test_fgjkbdfg"
  132. cache: DeferredCache[str, str] = DeferredCache(CACHE_NAME, max_entries=777)
  133. items = {
  134. x.split(b"{")[0].decode("ascii"): x.split(b" ")[1].decode("ascii")
  135. for x in filter(
  136. lambda x: b"cache_metrics_test_fgjkbdfg" in x,
  137. generate_latest(REGISTRY).split(b"\n"),
  138. )
  139. }
  140. self.assertEqual(items["synapse_util_caches_cache_size"], "0.0")
  141. self.assertEqual(items["synapse_util_caches_cache_max_size"], "777.0")
  142. cache.prefill("1", "hi")
  143. items = {
  144. x.split(b"{")[0].decode("ascii"): x.split(b" ")[1].decode("ascii")
  145. for x in filter(
  146. lambda x: b"cache_metrics_test_fgjkbdfg" in x,
  147. generate_latest(REGISTRY).split(b"\n"),
  148. )
  149. }
  150. self.assertEqual(items["synapse_util_caches_cache_size"], "1.0")
  151. self.assertEqual(items["synapse_util_caches_cache_max_size"], "777.0")
  152. class PrometheusMetricsHackTestCase(unittest.HomeserverTestCase):
  153. if parse_version(metadata.version("prometheus_client")) < parse_version("0.14.0"):
  154. skip = "prometheus-client too old"
  155. def test_created_metrics_disabled(self) -> None:
  156. """
  157. Tests that a brittle hack, to disable `_created` metrics, works.
  158. This involves poking at the internals of prometheus-client.
  159. It's not the end of the world if this doesn't work.
  160. This test gives us a way to notice if prometheus-client changes
  161. their internals.
  162. """
  163. import prometheus_client.metrics
  164. PRIVATE_FLAG_NAME = "_use_created"
  165. # By default, the pesky `_created` metrics are enabled.
  166. # Check this assumption is still valid.
  167. self.assertTrue(getattr(prometheus_client.metrics, PRIVATE_FLAG_NAME))
  168. with patch("prometheus_client.metrics") as mock:
  169. setattr(mock, PRIVATE_FLAG_NAME, True)
  170. _set_prometheus_client_use_created_metrics(False)
  171. self.assertFalse(getattr(mock, PRIVATE_FLAG_NAME, False))