Debian Codegraph @

prometheus_client/openmetrics/parser.py

raw symbols SCIP
1 #!/usr/bin/env python
2
3
4 import io as StringIO
5 import math
6 import re
7
8 from ..metrics_core import Metric, METRIC_LABEL_NAME_RE
9 from ..samples import Exemplar, Sample, Timestamp
10 from ..utils import floatToGoString
11
12
13 def text_string_to_metric_families(text):
14 """Parse Openmetrics text format from a unicode string.
15
16 See text_fd_to_metric_families.
17 """
18 yield from text_fd_to_metric_families(StringIO.StringIO(text))
19
20
21 _CANONICAL_NUMBERS = {float("inf")}
22
23
24 def _isUncanonicalNumber(s):
25 f = float(s)
26 if f not in _CANONICAL_NUMBERS:
27 return False # Only the canonical numbers are required to be canonical.
28 return s != floatToGoString(f)
29
30
31 ESCAPE_SEQUENCES = {
32 '\\\\': '\\',
33 '\\n': '\n',
34 '\\"': '"',
35 }
36
37
38 def _replace_escape_sequence(match):
39 return ESCAPE_SEQUENCES[match.group(0)]
40
41
42 ESCAPING_RE = re.compile(r'\\[\\n"]')
43
44
45 def _replace_escaping(s):
46 return ESCAPING_RE.sub(_replace_escape_sequence, s)
47
48
49 def _unescape_help(text):
50 result = []
51 slash = False
52
53 for char in text:
54 if slash:
55 if char == '\\':
56 result.append('\\')
57 elif char == '"':
58 result.append('"')
59 elif char == 'n':
60 result.append('\n')
61 else:
62 result.append('\\' + char)
63 slash = False
64 else:
65 if char == '\\':
66 slash = True
67 else:
68 result.append(char)
69
70 if slash:
71 result.append('\\')
72
73 return ''.join(result)
74
75
76 def _parse_value(value):
77 value = ''.join(value)
78 if value != value.strip() or '_' in value:
79 raise ValueError(f"Invalid value: {value!r}")
80 try:
81 return int(value)
82 except ValueError:
83 return float(value)
84
85
86 def _parse_timestamp(timestamp):
87 timestamp = ''.join(timestamp)
88 if not timestamp:
89 return None
90 if timestamp != timestamp.strip() or '_' in timestamp:
91 raise ValueError(f"Invalid timestamp: {timestamp!r}")
92 try:
93 # Simple int.
94 return Timestamp(int(timestamp), 0)
95 except ValueError:
96 try:
97 # aaaa.bbbb. Nanosecond resolution supported.
98 parts = timestamp.split('.', 1)
99 return Timestamp(int(parts[0]), int(parts[1][:9].ljust(9, "0")))
100 except ValueError:
101 # Float.
102 ts = float(timestamp)
103 if math.isnan(ts) or math.isinf(ts):
104 raise ValueError(f"Invalid timestamp: {timestamp!r}")
105 return ts
106
107
108 def _is_character_escaped(s, charpos):
109 num_bslashes = 0
110 while (charpos > num_bslashes
111 and s[charpos - 1 - num_bslashes] == '\\'):
112 num_bslashes += 1
113 return num_bslashes % 2 == 1
114
115
116 def _parse_labels_with_state_machine(text):
117 # The { has already been parsed.
118 state = 'startoflabelname'
119 labelname = []
120 labelvalue = []
121 labels = {}
122 labels_len = 0
123
124 for char in text:
125 if state == 'startoflabelname':
126 if char == '}':
127 state = 'endoflabels'
128 else:
129 state = 'labelname'
130 labelname.append(char)
131 elif state == 'labelname':
132 if char == '=':
133 state = 'labelvaluequote'
134 else:
135 labelname.append(char)
136 elif state == 'labelvaluequote':
137 if char == '"':
138 state = 'labelvalue'
139 else:
140 raise ValueError("Invalid line: " + text)
141 elif state == 'labelvalue':
142 if char == '\\':
143 state = 'labelvalueslash'
144 elif char == '"':
145 ln = ''.join(labelname)
146 if not METRIC_LABEL_NAME_RE.match(ln):
147 raise ValueError("Invalid line, bad label name: " + text)
148 if ln in labels:
149 raise ValueError("Invalid line, duplicate label name: " + text)
150 labels[ln] = ''.join(labelvalue)
151 labelname = []
152 labelvalue = []
153 state = 'endoflabelvalue'
154 else:
155 labelvalue.append(char)
156 elif state == 'endoflabelvalue':
157 if char == ',':
158 state = 'labelname'
159 elif char == '}':
160 state = 'endoflabels'
161 else:
162 raise ValueError("Invalid line: " + text)
163 elif state == 'labelvalueslash':
164 state = 'labelvalue'
165 if char == '\\':
166 labelvalue.append('\\')
167 elif char == 'n':
168 labelvalue.append('\n')
169 elif char == '"':
170 labelvalue.append('"')
171 else:
172 labelvalue.append('\\' + char)
173 elif state == 'endoflabels':
174 if char == ' ':
175 break
176 else:
177 raise ValueError("Invalid line: " + text)
178 labels_len += 1
179 return labels, labels_len
180
181
182 def _parse_labels(text):
183 labels = {}
184
185 # Raise error if we don't have valid labels
186 if text and "=" not in text:
187 raise ValueError
188
189 # Copy original labels
190 sub_labels = text
191 try:
192 # Process one label at a time
193 while sub_labels:
194 # The label name is before the equal
195 value_start = sub_labels.index("=")
196 label_name = sub_labels[:value_start]
197 sub_labels = sub_labels[value_start + 1:]
198
199 # Check for missing quotes
200 if not sub_labels or sub_labels[0] != '"':
201 raise ValueError
202
203 # The first quote is guaranteed to be after the equal
204 value_substr = sub_labels[1:]
205
206 # Check for extra commas
207 if not label_name or label_name[0] == ',':
208 raise ValueError
209 if not value_substr or value_substr[-1] == ',':
210 raise ValueError
211
212 # Find the last unescaped quote
213 i = 0
214 while i < len(value_substr):
215 i = value_substr.index('"', i)
216 if not _is_character_escaped(value_substr[:i], i):
217 break
218 i += 1
219
220 # The label value is between the first and last quote
221 quote_end = i + 1
222 label_value = sub_labels[1:quote_end]
223 # Replace escaping if needed
224 if "\\" in label_value:
225 label_value = _replace_escaping(label_value)
226 if not METRIC_LABEL_NAME_RE.match(label_name):
227 raise ValueError("invalid line, bad label name: " + text)
228 if label_name in labels:
229 raise ValueError("invalid line, duplicate label name: " + text)
230 labels[label_name] = label_value
231
232 # Remove the processed label from the sub-slice for next iteration
233 sub_labels = sub_labels[quote_end + 1:]
234 if sub_labels.startswith(","):
235 next_comma = 1
236 else:
237 next_comma = 0
238 sub_labels = sub_labels[next_comma:]
239
240 # Check for missing commas
241 if sub_labels and next_comma == 0:
242 raise ValueError
243
244 return labels
245
246 except ValueError:
247 raise ValueError("Invalid labels: " + text)
248
249
250 def _parse_sample(text):
251 separator = " # "
252 # Detect the labels in the text
253 label_start = text.find("{")
254 if label_start == -1 or separator in text[:label_start]:
255 # We don't have labels, but there could be an exemplar.
256 name_end = text.index(" ")
257 name = text[:name_end]
258 # Parse the remaining text after the name
259 remaining_text = text[name_end + 1:]
260 value, timestamp, exemplar = _parse_remaining_text(remaining_text)
261 return Sample(name, {}, value, timestamp, exemplar)
262 # The name is before the labels
263 name = text[:label_start]
264 if separator not in text:
265 # Line doesn't contain an exemplar
266 # We can use `rindex` to find `label_end`
267 label_end = text.rindex("}")
268 label = text[label_start + 1:label_end]
269 labels = _parse_labels(label)
270 else:
271 # Line potentially contains an exemplar
272 # Fallback to parsing labels with a state machine
273 labels, labels_len = _parse_labels_with_state_machine(text[label_start + 1:])
274 label_end = labels_len + len(name)
275 # Parsing labels succeeded, continue parsing the remaining text
276 remaining_text = text[label_end + 2:]
277 value, timestamp, exemplar = _parse_remaining_text(remaining_text)
278 return Sample(name, labels, value, timestamp, exemplar)
279
280
281 def _parse_remaining_text(text):
282 split_text = text.split(" ", 1)
283 val = _parse_value(split_text[0])
284 if len(split_text) == 1:
285 # We don't have timestamp or exemplar
286 return val, None, None
287
288 timestamp = []
289 exemplar_value = []
290 exemplar_timestamp = []
291 exemplar_labels = None
292
293 state = 'timestamp'
294 text = split_text[1]
295
296 it = iter(text)
297 for char in it:
298 if state == 'timestamp':
299 if char == '#' and not timestamp:
300 state = 'exemplarspace'
301 elif char == ' ':
302 state = 'exemplarhash'
303 else:
304 timestamp.append(char)
305 elif state == 'exemplarhash':
306 if char == '#':
307 state = 'exemplarspace'
308 else:
309 raise ValueError("Invalid line: " + text)
310 elif state == 'exemplarspace':
311 if char == ' ':
312 state = 'exemplarstartoflabels'
313 else:
314 raise ValueError("Invalid line: " + text)
315 elif state == 'exemplarstartoflabels':
316 if char == '{':
317 label_start, label_end = text.index("{"), text.rindex("}")
318 exemplar_labels = _parse_labels(text[label_start + 1:label_end])
319 state = 'exemplarparsedlabels'
320 else:
321 raise ValueError("Invalid line: " + text)
322 elif state == 'exemplarparsedlabels':
323 if char == '}':
324 state = 'exemplarvaluespace'
325 elif state == 'exemplarvaluespace':
326 if char == ' ':
327 state = 'exemplarvalue'
328 else:
329 raise ValueError("Invalid line: " + text)
330 elif state == 'exemplarvalue':
331 if char == ' ' and not exemplar_value:
332 raise ValueError("Invalid line: " + text)
333 elif char == ' ':
334 state = 'exemplartimestamp'
335 else:
336 exemplar_value.append(char)
337 elif state == 'exemplartimestamp':
338 exemplar_timestamp.append(char)
339
340 # Trailing space after value.
341 if state == 'timestamp' and not timestamp:
342 raise ValueError("Invalid line: " + text)
343
344 # Trailing space after value.
345 if state == 'exemplartimestamp' and not exemplar_timestamp:
346 raise ValueError("Invalid line: " + text)
347
348 # Incomplete exemplar.
349 if state in ['exemplarhash', 'exemplarspace', 'exemplarstartoflabels', 'exemplarparsedlabels']:
350 raise ValueError("Invalid line: " + text)
351
352 ts = _parse_timestamp(timestamp)
353 exemplar = None
354 if exemplar_labels is not None:
355 exemplar_length = sum(len(k) + len(v) for k, v in exemplar_labels.items())
356 if exemplar_length > 128:
357 raise ValueError("Exemplar labels are too long: " + text)
358 exemplar = Exemplar(
359 exemplar_labels,
360 _parse_value(exemplar_value),
361 _parse_timestamp(exemplar_timestamp),
362 )
363
364 return val, ts, exemplar
365
366
367 def _group_for_sample(sample, name, typ):
368 if typ == 'info':
369 # We can't distinguish between groups for info metrics.
370 return {}
371 if typ == 'summary' and sample.name == name:
372 d = sample.labels.copy()
373 del d['quantile']
374 return d
375 if typ == 'stateset':
376 d = sample.labels.copy()
377 del d[name]
378 return d
379 if typ in ['histogram', 'gaugehistogram'] and sample.name == name + '_bucket':
380 d = sample.labels.copy()
381 del d['le']
382 return d
383 return sample.labels
384
385
386 def _check_histogram(samples, name):
387 group = None
388 timestamp = None
389
390 def do_checks():
391 if bucket != float('+Inf'):
392 raise ValueError("+Inf bucket missing: " + name)
393 if count is not None and value != count:
394 raise ValueError("Count does not match +Inf value: " + name)
395 if has_sum and count is None:
396 raise ValueError("_count must be present if _sum is present: " + name)
397 if has_gsum and count is None:
398 raise ValueError("_gcount must be present if _gsum is present: " + name)
399 if not (has_sum or has_gsum) and count is not None:
400 raise ValueError("_sum/_gsum must be present if _count is present: " + name)
401 if has_negative_buckets and has_sum:
402 raise ValueError("Cannot have _sum with negative buckets: " + name)
403 if not has_negative_buckets and has_negative_gsum:
404 raise ValueError("Cannot have negative _gsum with non-negative buckets: " + name)
405
406 for s in samples:
407 suffix = s.name[len(name):]
408 g = _group_for_sample(s, name, 'histogram')
409 if g != group or s.timestamp != timestamp:
410 if group is not None:
411 do_checks()
412 count = None
413 bucket = None
414 has_negative_buckets = False
415 has_sum = False
416 has_gsum = False
417 has_negative_gsum = False
418 value = 0
419 group = g
420 timestamp = s.timestamp
421
422 if suffix == '_bucket':
423 b = float(s.labels['le'])
424 if b < 0:
425 has_negative_buckets = True
426 if bucket is not None and b <= bucket:
427 raise ValueError("Buckets out of order: " + name)
428 if s.value < value:
429 raise ValueError("Bucket values out of order: " + name)
430 bucket = b
431 value = s.value
432 elif suffix in ['_count', '_gcount']:
433 count = s.value
434 elif suffix in ['_sum']:
435 has_sum = True
436 elif suffix in ['_gsum']:
437 has_gsum = True
438 if s.value < 0:
439 has_negative_gsum = True
440
441 if group is not None:
442 do_checks()
443
444
445 def text_fd_to_metric_families(fd):
446 """Parse Prometheus text format from a file descriptor.
447
448 This is a laxer parser than the main Go parser,
449 so successful parsing does not imply that the parsed
450 text meets the specification.
451
452 Yields Metric's.
453 """
454 name = None
455 allowed_names = []
456 eof = False
457
458 seen_names = set()
459 type_suffixes = {
460 'counter': ['_total', '_created'],
461 'summary': ['', '_count', '_sum', '_created'],
462 'histogram': ['_count', '_sum', '_bucket', '_created'],
463 'gaugehistogram': ['_gcount', '_gsum', '_bucket'],
464 'info': ['_info'],
465 }
466
467 def build_metric(name, documentation, typ, unit, samples):
468 if typ is None:
469 typ = 'unknown'
470 for suffix in set(type_suffixes.get(typ, []) + [""]):
471 if name + suffix in seen_names:
472 raise ValueError("Clashing name: " + name + suffix)
473 seen_names.add(name + suffix)
474 if documentation is None:
475 documentation = ''
476 if unit is None:
477 unit = ''
478 if unit and not name.endswith("_" + unit):
479 raise ValueError("Unit does not match metric name: " + name)
480 if unit and typ in ['info', 'stateset']:
481 raise ValueError("Units not allowed for this metric type: " + name)
482 if typ in ['histogram', 'gaugehistogram']:
483 _check_histogram(samples, name)
484 metric = Metric(name, documentation, typ, unit)
485 # TODO: check labelvalues are valid utf8
486 metric.samples = samples
487 return metric
488
489 for line in fd:
490 if line[-1] == '\n':
491 line = line[:-1]
492
493 if eof:
494 raise ValueError("Received line after # EOF: " + line)
495
496 if not line:
497 raise ValueError("Received blank line")
498
499 if line == '# EOF':
500 eof = True
501 elif line.startswith('#'):
502 parts = line.split(' ', 3)
503 if len(parts) < 4:
504 raise ValueError("Invalid line: " + line)
505 if parts[2] == name and samples:
506 raise ValueError("Received metadata after samples: " + line)
507 if parts[2] != name:
508 if name is not None:
509 yield build_metric(name, documentation, typ, unit, samples)
510 # New metric
511 name = parts[2]
512 unit = None
513 typ = None
514 documentation = None
515 group = None
516 seen_groups = set()
517 group_timestamp = None
518 group_timestamp_samples = set()
519 samples = []
520 allowed_names = [parts[2]]
521
522 if parts[1] == 'HELP':
523 if documentation is not None:
524 raise ValueError("More than one HELP for metric: " + line)
525 documentation = _unescape_help(parts[3])
526 elif parts[1] == 'TYPE':
527 if typ is not None:
528 raise ValueError("More than one TYPE for metric: " + line)
529 typ = parts[3]
530 if typ == 'untyped':
531 raise ValueError("Invalid TYPE for metric: " + line)
532 allowed_names = [name + n for n in type_suffixes.get(typ, [''])]
533 elif parts[1] == 'UNIT':
534 if unit is not None:
535 raise ValueError("More than one UNIT for metric: " + line)
536 unit = parts[3]
537 else:
538 raise ValueError("Invalid line: " + line)
539 else:
540 sample = _parse_sample(line)
541 if sample.name not in allowed_names:
542 if name is not None:
543 yield build_metric(name, documentation, typ, unit, samples)
544 # Start an unknown metric.
545 name = sample.name
546 documentation = None
547 unit = None
548 typ = 'unknown'
549 samples = []
550 group = None
551 group_timestamp = None
552 group_timestamp_samples = set()
553 seen_groups = set()
554 allowed_names = [sample.name]
555
556 if typ == 'stateset' and name not in sample.labels:
557 raise ValueError("Stateset missing label: " + line)
558 if (name + '_bucket' == sample.name
559 and (sample.labels.get('le', "NaN") == "NaN"
560 or _isUncanonicalNumber(sample.labels['le']))):
561 raise ValueError("Invalid le label: " + line)
562 if (name + '_bucket' == sample.name
563 and (not isinstance(sample.value, int) and not sample.value.is_integer())):
564 raise ValueError("Bucket value must be an integer: " + line)
565 if ((name + '_count' == sample.name or name + '_gcount' == sample.name)
566 and (not isinstance(sample.value, int) and not sample.value.is_integer())):
567 raise ValueError("Count value must be an integer: " + line)
568 if (typ == 'summary' and name == sample.name
569 and (not (0 <= float(sample.labels.get('quantile', -1)) <= 1)
570 or _isUncanonicalNumber(sample.labels['quantile']))):
571 raise ValueError("Invalid quantile label: " + line)
572
573 g = tuple(sorted(_group_for_sample(sample, name, typ).items()))
574 if group is not None and g != group and g in seen_groups:
575 raise ValueError("Invalid metric grouping: " + line)
576 if group is not None and g == group:
577 if (sample.timestamp is None) != (group_timestamp is None):
578 raise ValueError("Mix of timestamp presence within a group: " + line)
579 if group_timestamp is not None and group_timestamp > sample.timestamp and typ != 'info':
580 raise ValueError("Timestamps went backwards within a group: " + line)
581 else:
582 group_timestamp_samples = set()
583
584 series_id = (sample.name, tuple(sorted(sample.labels.items())))
585 if sample.timestamp != group_timestamp or series_id not in group_timestamp_samples:
586 # Not a duplicate due to timestamp truncation.
587 samples.append(sample)
588 group_timestamp_samples.add(series_id)
589
590 group = g
591 group_timestamp = sample.timestamp
592 seen_groups.add(g)
593
594 if typ == 'stateset' and sample.value not in [0, 1]:
595 raise ValueError("Stateset samples can only have values zero and one: " + line)
596 if typ == 'info' and sample.value != 1:
597 raise ValueError("Info samples can only have value one: " + line)
598 if typ == 'summary' and name == sample.name and sample.value < 0:
599 raise ValueError("Quantile values cannot be negative: " + line)
600 if sample.name[len(name):] in ['_total', '_sum', '_count', '_bucket', '_gcount', '_gsum'] and math.isnan(
601 sample.value):
602 raise ValueError("Counter-like samples cannot be NaN: " + line)
603 if sample.name[len(name):] in ['_total', '_sum', '_count', '_bucket', '_gcount'] and sample.value < 0:
604 raise ValueError("Counter-like samples cannot be negative: " + line)
605 if sample.exemplar and not (
606 (typ in ['histogram', 'gaugehistogram'] and sample.name.endswith('_bucket'))
607 or (typ in ['counter'] and sample.name.endswith('_total'))):
608 raise ValueError("Invalid line only histogram/gaugehistogram buckets and counters can have exemplars: " + line)
609
610 if name is not None:
611 yield build_metric(name, documentation, typ, unit, samples)
612
613 if not eof:
614 raise ValueError("Missing # EOF at end")