You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

201 lines
6.6 KiB

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