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.
 
 
 
 
 
 

162 lines
5.3 KiB

  1. # Copyright 2022 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import logging
  15. import time
  16. from selectors import SelectSelector, _PollLikeSelector # type: ignore[attr-defined]
  17. from typing import Any, Callable, Iterable
  18. from prometheus_client import Histogram, Metric
  19. from prometheus_client.core import REGISTRY, GaugeMetricFamily
  20. from twisted.internet import reactor, selectreactor
  21. from twisted.internet.asyncioreactor import AsyncioSelectorReactor
  22. from synapse.metrics._types import Collector
  23. try:
  24. from selectors import KqueueSelector
  25. except ImportError:
  26. class KqueueSelector: # type: ignore[no-redef]
  27. pass
  28. try:
  29. from twisted.internet.epollreactor import EPollReactor
  30. except ImportError:
  31. class EPollReactor: # type: ignore[no-redef]
  32. pass
  33. try:
  34. from twisted.internet.pollreactor import PollReactor
  35. except ImportError:
  36. class PollReactor: # type: ignore[no-redef]
  37. pass
  38. logger = logging.getLogger(__name__)
  39. #
  40. # Twisted reactor metrics
  41. #
  42. tick_time = Histogram(
  43. "python_twisted_reactor_tick_time",
  44. "Tick time of the Twisted reactor (sec)",
  45. buckets=[0.001, 0.002, 0.005, 0.01, 0.025, 0.05, 0.1, 0.2, 0.5, 1, 2, 5],
  46. )
  47. class CallWrapper:
  48. """A wrapper for a callable which records the time between calls"""
  49. def __init__(self, wrapped: Callable[..., Any]):
  50. self.last_polled = time.time()
  51. self._wrapped = wrapped
  52. def __call__(self, *args, **kwargs) -> Any: # type: ignore[no-untyped-def]
  53. # record the time since this was last called. This gives a good proxy for
  54. # how long it takes to run everything in the reactor - ie, how long anything
  55. # waiting for the next tick will have to wait.
  56. tick_time.observe(time.time() - self.last_polled)
  57. ret = self._wrapped(*args, **kwargs)
  58. self.last_polled = time.time()
  59. return ret
  60. class ObjWrapper:
  61. """A wrapper for an object which wraps a specified method in CallWrapper.
  62. Other methods/attributes are passed to the original object.
  63. This is necessary when the wrapped object does not allow the attribute to be
  64. overwritten.
  65. """
  66. def __init__(self, wrapped: Any, method_name: str):
  67. self._wrapped = wrapped
  68. self._method_name = method_name
  69. self._wrapped_method = CallWrapper(getattr(wrapped, method_name))
  70. def __getattr__(self, item: str) -> Any:
  71. if item == self._method_name:
  72. return self._wrapped_method
  73. return getattr(self._wrapped, item)
  74. class ReactorLastSeenMetric(Collector):
  75. def __init__(self, call_wrapper: CallWrapper):
  76. self._call_wrapper = call_wrapper
  77. def collect(self) -> Iterable[Metric]:
  78. cm = GaugeMetricFamily(
  79. "python_twisted_reactor_last_seen",
  80. "Seconds since the Twisted reactor was last seen",
  81. )
  82. cm.add_metric([], time.time() - self._call_wrapper.last_polled)
  83. yield cm
  84. # Twisted has already select a reasonable reactor for us, so assumptions can be
  85. # made about the shape.
  86. wrapper = None
  87. try:
  88. if isinstance(reactor, (PollReactor, EPollReactor)):
  89. reactor._poller = ObjWrapper(reactor._poller, "poll") # type: ignore[attr-defined]
  90. wrapper = reactor._poller._wrapped_method # type: ignore[attr-defined]
  91. elif isinstance(reactor, selectreactor.SelectReactor):
  92. # Twisted uses a module-level _select function.
  93. wrapper = selectreactor._select = CallWrapper(selectreactor._select)
  94. elif isinstance(reactor, AsyncioSelectorReactor):
  95. # For asyncio look at the underlying asyncio event loop.
  96. asyncio_loop = reactor._asyncioEventloop # A sub-class of BaseEventLoop,
  97. # A sub-class of BaseSelector.
  98. selector = asyncio_loop._selector # type: ignore[attr-defined]
  99. if isinstance(selector, SelectSelector):
  100. wrapper = selector._select = CallWrapper(selector._select) # type: ignore[attr-defined]
  101. # poll, epoll, and /dev/poll.
  102. elif isinstance(selector, _PollLikeSelector):
  103. selector._selector = ObjWrapper(selector._selector, "poll") # type: ignore[attr-defined]
  104. wrapper = selector._selector._wrapped_method # type: ignore[attr-defined]
  105. elif isinstance(selector, KqueueSelector):
  106. selector._selector = ObjWrapper(selector._selector, "control") # type: ignore[attr-defined]
  107. wrapper = selector._selector._wrapped_method # type: ignore[attr-defined]
  108. else:
  109. # E.g. this does not support the (Windows-only) ProactorEventLoop.
  110. logger.warning(
  111. "Skipping configuring ReactorLastSeenMetric: unexpected asyncio loop selector: %r via %r",
  112. selector,
  113. asyncio_loop,
  114. )
  115. except Exception as e:
  116. logger.warning("Configuring ReactorLastSeenMetric failed: %r", e)
  117. if wrapper:
  118. REGISTRY.register(ReactorLastSeenMetric(wrapper))