Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,19 @@ REGISTRY.register(CustomCollector())

`SummaryMetricFamily` and `HistogramMetricFamily` work similarly.

A collector may implement a `describe` method which returns metrics in the same
format as `collect` (though you don't have to include the samples). This is
used to predetermine the names of time series a `CollectorRegistry` exposes and
thus to detect collisions and duplicate registrations.

Usually custom collectors do not have to implement `describe`. If `describe` is
not implemented and the CollectorRegistry was created with `auto_desribe=True`
(which is the case for the default registry) then `collect` will be called at
registration time instead of `describe`. If this could cause problems, either
implement a proper `describe`, or if that's not practical have `describe`
return an empty list.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the intention that in the latter case, collectors returning an empty list will never be included by a restricted_registry?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. My thinking is that for something like JMX which can be quite expensive, it's best not to call it rather than silently calling it in the background when users thing they're only fetching a few cheap counters.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While I understand the resource argument, it's opaque to the user of an /metrics endpoint which collectors describe themselves properly, and thus the behavior might appear quite puzzling. Between "accidentally using a lot of resources" and "accidentally and silently not getting expected metrics" I'd prefer the former.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This expected use case of this is high-frequency polling of a very small number of metrics. Using a lot of resources in such a case would be bad.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But I would notice – because it would defeat the purpose of restricting the metrics.

If some metrics are silently missing, I might not notice. I'm imagining the Postmortem review right now...

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You'd be specifying a small number of names by hand so you'd likely notice.

The logic here is that calling collect() at registration time is problematic, so we should also be tending not to call it when the collector has asked us not to include it in this feature.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we have reached the same point as in the thread above: Apparently, we see the use case exactly inverted, see there.

However, the point about an expensive collect() at registration time is different. The doc comment reads: "… if that's not practical have describe return an empty list." But then describe is not expensive to call, and collect won't be called at registration time because describe is implemented. No?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, after some background processing, I think I got your last point now. You assumption is essentially that collectors that have problems describing themselves will also be those that are expensive to collect().

That's true for the JMX case, I guess, but not in general.

I see the value of allowing collectors to say "I cannot describe myself but I'm also expensive to collect so please never collect me if the user has restricted the scrape in any way". But I also see the potential for bad surprises, and I guess the feeling is so strong for me because I see the "blacklist a few metrics" as a common use case. If suddenly some seemingly unrelated metrics disappear just because I blacklisted a single one, feels weird.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would hope that non-describing collectors will be rare. In direct instrumentation, they should never occur, essentially. It's mostly an exporter thing, so we should encourage clear documentation about metrics not being collected if any restriction is given as a scrape parameter.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You assumption is essentially that collectors that have problems describing themselves will also be those that are expensive to collect().

Yes, or impossible to describe(). JMX is both impossible and expensive. A one-off collect() at startup would be tolerable (ignoring that that breaks with config reloading), but at every collection would be bad.

If suddenly some seemingly unrelated metrics disappear just because I blacklisted a single one, feels weird.

The whitelist approach doesn't really have that issue. Returning an empty describe signals that you don't support this feature.

It's mostly an exporter thing, so we should encourage clear documentation about metrics not being collected if any restriction is given as a scrape parameter.

Yeah, this only comes up with custom collectors.



## Multiprocess Mode (Gunicorn)

**Experimental: This feature is new and has rough edges.**
Expand Down
81 changes: 75 additions & 6 deletions prometheus_client/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,29 +38,94 @@ class CollectorRegistry(object):
Metric objects. The returned metrics should be consistent with the Prometheus
exposition formats.
'''
def __init__(self):
self._collectors = set()
def __init__(self, auto_describe=False):
self._collector_to_names = {}
self._names_to_collectors = {}
self._auto_describe = auto_describe
self._lock = Lock()

def register(self, collector):
'''Add a collector to the registry.'''
with self._lock:
self._collectors.add(collector)
names = self._get_names(collector)
for name in names:
if name in self._names_to_collectors:
raise ValueError('Timeseries already present '
'in CollectorRegistry: ' + name)
for name in names:
self._names_to_collectors[name] = collector
self._collector_to_names[collector] = names

def unregister(self, collector):
'''Remove a collector from the registry.'''
with self._lock:
self._collectors.remove(collector)
for name in self._collector_to_names[collector]:
del self._names_to_collectors[name]
del self._collector_to_names[collector]

def _get_names(self, collector):
'''Get names of timeseries the collector produces.'''
desc_func = None
# If there's a describe function, use it.
try:
desc_func = collector.describe
except AttributeError:
pass
# Otherwise, if auto describe is enabled use the collect function.
if not desc_func and self._auto_describe:
desc_func = collector.collect

if not desc_func:
return []

result = []
type_suffixes = {
'summary': ['', '_sum', '_count'],
'histogram': ['_bucket', '_sum', '_count']
}
for metric in desc_func():
for suffix in type_suffixes.get(metric.type, ['']):
result.append(metric.name + suffix)
return result

def collect(self):
'''Yields metrics from the collectors in the registry.'''
collectors = None
with self._lock:
collectors = copy.copy(self._collectors)
collectors = copy.copy(self._collector_to_names)
for collector in collectors:
for metric in collector.collect():
yield metric

def restricted_registry(self, names):
'''Returns object that only collects some metrics.

Returns an object which upon collect() will return
only samples with the given names.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wasn't the plan to allow regexp matches for names, too? And inverted matches? (i.e. collect all metrics except those matching 'foo.*')?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is v1, so I didn't add the regexes yet.

Inverted wasn't something I'd planned.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would imagine it's a common use case: You want a scrape as "normal" as possible, just that one expensive metric with high cardinality should go.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm presuming that that'd be handled on the Prometheus side with metric relabelling.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Which would not avoid collecting the metric (which might be expensive) and sending it over the wire (which might be bandwidth limited).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think I've ever come across the case where the cost of collecting, sending, receiving and rejecting the metric was relevant (beyond a slight dip in CPU when the metric was fixed).

If someone asks us for it we can consider it then.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't understand. If this is the case, why are we doing client-side restrictions (like in this PR) at all?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The cost has never been relevant when dealing with a high-cardinality metric for normal scraping.

It has been relevant when attempting to do high-frequency scraping of a very limited set of metrics.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps we are missing each others point here. I try to rephrase:

  • I wish to do high frequency scraping.
  • I have identified a single metric that is expensive for any of the following reasons:
    • It comprises 80% of the scrape volume, and I am bandwidth limited.
    • It is expensive to collect().
  • Let's assume for the sake of your argument that it's usually the latter and not the former that matters. I could of course hand-pick and whitelist the metrics I'm interested in. But if I can do my high frequency scraping without problem by just blacklisting the one metric known to be expensive to collect()?

IIRC the mysqld_exporter has exactly that case. So what we do right now is to switch certain metrics on and off on the command line. At SC, we run separate high-frequency collectors with fewer metrics activated. It would be great if we could just tell the collector via URL params to not collect selected few expensive-to-collect metrics for high-frequency scraping rather than running separate exporter instances with different command line flags.

If I understand you correctly, you are claiming that the high-frequency scrape case will naturally result in scraping a whitelisted set of metrics. But if I understand the mysqld_exporter use case correctly, it's the opposite: One tends to blacklist known expensive metrics and wants to collect all others with high frequency. @SuperQ please correct me if I'm wrong.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I understand you correctly, you are claiming that the high-frequency scrape case will naturally result in scraping a whitelisted set of metrics.

Yes. Given the data volumes involved with such systems no other way is practical, and I've never seen any other approach taken. Usually you'd be whitelisting on the order of 10 metrics, and with a blacklisting approach the organic growth of metrics would be sufficient to take out such a system.

To be honest, if you've a system where one metric comprises 80% of data volume you've bigger problems (I came across that exact case once, and greatly decreased the metric cardinality).

But if I understand the mysqld_exporter use case correctly, it's the opposite: One tends to blacklist known expensive metrics and wants to collect all others with high frequency.

That's not my understanding. The mysqld exporter isn't covered by this anyway, it's sufficiently weird that it can't implement describe.


Intended usage is:
generate_latest(REGISTRY.restricted_registry(['a_timeseries']))

Experimental.'''
names = set(names)
collectors = set()
with self._lock:
for name in names:
if name in self._names_to_collectors:
collectors.add(self._names_to_collectors[name])
metrics = []
for collector in collectors:
for metric in collector.collect():
samples = [s for s in metric.samples if s[0] in names]
if samples:
m = Metric(metric.name, metric.documentation, metric.type)
m.samples = samples
metrics.append(m)
class RestrictedRegistry(object):
def collect(self):
return metrics
return RestrictedRegistry()

def get_sample_value(self, name, labels=None):
'''Returns the sample value, or None if not found.

Expand All @@ -75,7 +140,7 @@ def get_sample_value(self, name, labels=None):
return None


REGISTRY = CollectorRegistry()
REGISTRY = CollectorRegistry(auto_describe=True)
'''The default registry.'''

_METRIC_TYPES = ('counter', 'gauge', 'summary', 'histogram', 'untyped')
Expand Down Expand Up @@ -476,6 +541,10 @@ def init(name, documentation, labelnames=(), namespace='', subsystem='', registr
if not _METRIC_NAME_RE.match(full_name):
raise ValueError('Invalid metric name: ' + full_name)

def describe():
return [Metric(full_name, documentation, cls._type)]
collector.describe = describe

def collect():
metric = Metric(full_name, documentation, cls._type)
for suffix, labels, value in collector._samples():
Expand Down
15 changes: 12 additions & 3 deletions prometheus_client/exposition.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,14 @@
from BaseHTTPServer import HTTPServer
from urllib2 import build_opener, Request, HTTPHandler
from urllib import quote_plus
from urlparse import parse_qs, urlparse
except ImportError:
# Python 3
unicode = str
from http.server import BaseHTTPRequestHandler
from http.server import HTTPServer
from urllib.request import build_opener, Request, HTTPHandler
from urllib.parse import quote_plus
from urllib.parse import quote_plus, parse_qs, urlparse


CONTENT_TYPE_LATEST = str('text/plain; version=0.0.4; charset=utf-8')
Expand All @@ -34,7 +35,11 @@ def prometheus_app(environ, start_response):
status = str('200 OK')
headers = [(str('Content-type'), CONTENT_TYPE_LATEST)]
start_response(status, headers)
return [generate_latest(registry)]
params = parse_qs(environ['QUERY_STRING'])
r = registry
if 'name[]' in params:
r = r.restricted_registry(params['name[]'])
return [generate_latest(r)]
return prometheus_app


Expand Down Expand Up @@ -73,7 +78,11 @@ def do_GET(self):
self.send_response(200)
self.send_header('Content-Type', CONTENT_TYPE_LATEST)
self.end_headers()
self.wfile.write(generate_latest(core.REGISTRY))
registry = core.REGISTRY
params = parse_qs(urlparse(self.path).query)
if 'name[]' in params:
registry = registry.restricted_registry(params['name[]'])
self.wfile.write(generate_latest(registry))

def log_message(self, format, *args):
return
Expand Down
58 changes: 58 additions & 0 deletions tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,64 @@ def test_bad_constructors(self):
self.assertRaises(ValueError, HistogramMetricFamily, 'h', 'help', buckets={}, sum_value=1, labels=['a'])
self.assertRaises(KeyError, HistogramMetricFamily, 'h', 'help', buckets={}, sum_value=1)

class TestCollectorRegistry(unittest.TestCase):
def test_duplicate_metrics_raises(self):
registry = CollectorRegistry()
Counter('c', 'help', registry=registry)
self.assertRaises(ValueError, Counter, 'c', 'help', registry=registry)
self.assertRaises(ValueError, Gauge, 'c', 'help', registry=registry)

Gauge('g', 'help', registry=registry)
self.assertRaises(ValueError, Gauge, 'g', 'help', registry=registry)
self.assertRaises(ValueError, Counter, 'g', 'help', registry=registry)

Summary('s', 'help', registry=registry)
self.assertRaises(ValueError, Summary, 's', 'help', registry=registry)
# We don't currently expose quantiles, but let's prevent future
# clashes anyway.
self.assertRaises(ValueError, Gauge, 's', 'help', registry=registry)

Histogram('h', 'help', registry=registry)
self.assertRaises(ValueError, Histogram, 'h', 'help', registry=registry)
# Clashes aggaint various suffixes.
self.assertRaises(ValueError, Summary, 'h', 'help', registry=registry)
self.assertRaises(ValueError, Counter, 'h_count', 'help', registry=registry)
self.assertRaises(ValueError, Counter, 'h_sum', 'help', registry=registry)
self.assertRaises(ValueError, Counter, 'h_bucket', 'help', registry=registry)
# The name of the histogram itself isn't taken.
Counter('h', 'help', registry=registry)

def test_unregister_works(self):
registry = CollectorRegistry()
s = Summary('s', 'help', registry=registry)
self.assertRaises(ValueError, Counter, 's_count', 'help', registry=registry)
registry.unregister(s)
Counter('s_count', 'help', registry=registry)

def custom_collector(self, metric_family, registry):
class CustomCollector(object):
def collect(self):
return [metric_family]
registry.register(CustomCollector())

def test_autodescribe_disabled_by_default(self):
registry = CollectorRegistry()
self.custom_collector(CounterMetricFamily('c', 'help', value=1), registry)
self.custom_collector(CounterMetricFamily('c', 'help', value=1), registry)

registry = CollectorRegistry(auto_describe=True)
self.custom_collector(CounterMetricFamily('c', 'help', value=1), registry)
self.assertRaises(ValueError, self.custom_collector, CounterMetricFamily('c', 'help', value=1), registry)

def test_restricted_registry(self):
registry = CollectorRegistry()
Counter('c', 'help', registry=registry)
Summary('s', 'help', registry=registry).observe(7)

m = Metric('s', 'help', 'summary')
m.samples = [('s_sum', {}, 7)]
self.assertEquals([m], registry.restricted_registry(['s_sum']).collect())


if __name__ == '__main__':
unittest.main()