Skip to content

Commit

Permalink
Made restricted registries call collect() only on relevant collections.
Browse files Browse the repository at this point in the history
  • Loading branch information
pavel-lexyr committed Jul 1, 2021
1 parent e92fa05 commit ea2b225
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
18 changes: 14 additions & 4 deletions prometheus_client/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
13 changes: 13 additions & 0 deletions tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from concurrent.futures import ThreadPoolExecutor
import time
from unittest.mock import MagicMock

import pytest

Expand Down Expand Up @@ -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()

0 comments on commit ea2b225

Please sign in to comment.