diff --git a/prometheus_client/registry.py b/prometheus_client/registry.py index 0eb003bb..8a45b39a 100644 --- a/prometheus_client/registry.py +++ b/prometheus_client/registry.py @@ -135,10 +135,20 @@ def __init__(self, names, registry): self._registry = registry def collect(self): - for metric in self._registry.collect(): - m = metric._restricted_metric(self._name_set) - if m: - yield m + names = copy.copy(self._name_set) + collectors = set() + with self._registry._lock: + if 'target_info' in names and self._registry._target_info: + yield self._registry._target_info_metric() + names.remove('target_info') + for name in names: + if name in self._registry._names_to_collectors: + collectors.add(self._registry._names_to_collectors[name]) + for collector in collectors: + for metric in collector.collect(): + m = metric._restricted_metric(self._name_set) + if m: + yield m REGISTRY = CollectorRegistry(auto_describe=True) diff --git a/tests/test_core.py b/tests/test_core.py index d36aef0a..da90cfbe 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -2,6 +2,7 @@ from concurrent.futures import ThreadPoolExecutor import time +from unittest.mock import MagicMock import pytest @@ -838,6 +839,18 @@ def test_target_info_restricted_registry(self): m.samples = [Sample('target_info', {'foo': 'bar'}, 1)] self.assertEqual([m], list(registry.restricted_registry(['target_info']).collect())) + def test_restricted_registry_does_not_call_extra(self): + registry = CollectorRegistry() + mock_collector = MagicMock() + mock_collector.describe.return_value = [Metric('foo', 'help', 'summary')] + registry.register(mock_collector) + Summary('s', 'help', registry=registry).observe(7) + + m = Metric('s', 'help', 'summary') + m.samples = [Sample('s_sum', {}, 7)] + self.assertEqual([m], list(registry.restricted_registry(['s_sum']).collect())) + mock_collector.collect.assert_not_called() + if __name__ == '__main__': unittest.main()