1#!/usr/bin/env python
2
3
4from ..utils import floatToGoString
5
6CONTENT_TYPE_LATEST = 'application/openmetrics-text; version=1.0.0; charset=utf-8'
7"""Content type of the latest OpenMetrics text format"""
8
9
10def _is_valid_exemplar_metric(metric, sample):
11 if metric.type == 'counter' and sample.name.endswith('_total'):
12 return True
13 if metric.type in ('histogram', 'gaugehistogram') and sample.name.endswith('_bucket'):
14 return True
15 return False
16
17
18def generate_latest(registry):
19 '''Returns the metrics from the registry in latest text format as a string.'''
20 output = []
21 for metric in registry.collect():
22 try:
23 mname = metric.name
24 output.append('# HELP {} {}\n'.format(
25 mname, metric.documentation.replace('\\', r'\\').replace('\n', r'\n').replace('"', r'\"')))
26 output.append(f'# TYPE {mname} {metric.type}\n')
27 if metric.unit:
28 output.append(f'# UNIT {mname} {metric.unit}\n')
29 for s in metric.samples:
30 if s.labels:
31 labelstr = '{{{0}}}'.format(','.join(
32 ['{}="{}"'.format(
33 k, v.replace('\\', r'\\').replace('\n', r'\n').replace('"', r'\"'))
34 for k, v in sorted(s.labels.items())]))
35 else:
36 labelstr = ''
37 if s.exemplar:
38 if not _is_valid_exemplar_metric(metric, s):
39 raise ValueError(f"Metric {metric.name} has exemplars, but is not a histogram bucket or counter")
40 labels = '{{{0}}}'.format(','.join(
41 ['{}="{}"'.format(
42 k, v.replace('\\', r'\\').replace('\n', r'\n').replace('"', r'\"'))
43 for k, v in sorted(s.exemplar.labels.items())]))
44 if s.exemplar.timestamp is not None:
45 exemplarstr = ' # {} {} {}'.format(
46 labels,
47 floatToGoString(s.exemplar.value),
48 s.exemplar.timestamp,
49 )
50 else:
51 exemplarstr = ' # {} {}'.format(
52 labels,
53 floatToGoString(s.exemplar.value),
54 )
55 else:
56 exemplarstr = ''
57 timestamp = ''
58 if s.timestamp is not None:
59 timestamp = f' {s.timestamp}'
60 output.append('{}{} {}{}{}\n'.format(
61 s.name,
62 labelstr,
63 floatToGoString(s.value),
64 timestamp,
65 exemplarstr,
66 ))
67 except Exception as exception:
68 exception.args = (exception.args or ('',)) + (metric,)
69 raise
70
71 output.append('# EOF\n')
72 return ''.join(output).encode('utf-8')