| 1 |
import io as StringIO |
| 2 |
import re |
| 3 |
from typing import Dict, Iterable, List, Match, Optional, TextIO, Tuple |
| 4 |
|
| 5 |
from .metrics_core import Metric |
| 6 |
from .samples import Sample |
| 7 |
|
| 8 |
|
| 9 |
def text_string_to_metric_families(text: str) -> Iterable[Metric]: |
| 10 |
"""Parse Prometheus text format from a unicode string. |
| 11 |
|
| 12 |
See text_fd_to_metric_families. |
| 13 |
""" |
| 14 |
yield from text_fd_to_metric_families(StringIO.StringIO(text)) |
| 15 |
|
| 16 |
|
| 17 |
ESCAPE_SEQUENCES = { |
| 18 |
'\\\\': '\\', |
| 19 |
'\\n': '\n', |
| 20 |
'\\"': '"', |
| 21 |
} |
| 22 |
|
| 23 |
|
| 24 |
def replace_escape_sequence(match: Match[str]) -> str: |
| 25 |
return ESCAPE_SEQUENCES[match.group(0)] |
| 26 |
|
| 27 |
|
| 28 |
HELP_ESCAPING_RE = re.compile(r'\\[\\n]') |
| 29 |
ESCAPING_RE = re.compile(r'\\[\\n"]') |
| 30 |
|
| 31 |
|
| 32 |
def _replace_help_escaping(s: str) -> str: |
| 33 |
return HELP_ESCAPING_RE.sub(replace_escape_sequence, s) |
| 34 |
|
| 35 |
|
| 36 |
def _replace_escaping(s: str) -> str: |
| 37 |
return ESCAPING_RE.sub(replace_escape_sequence, s) |
| 38 |
|
| 39 |
|
| 40 |
def _is_character_escaped(s: str, charpos: int) -> bool: |
| 41 |
num_bslashes = 0 |
| 42 |
while (charpos > num_bslashes |
| 43 |
and s[charpos - 1 - num_bslashes] == '\\'): |
| 44 |
num_bslashes += 1 |
| 45 |
return num_bslashes % 2 == 1 |
| 46 |
|
| 47 |
|
| 48 |
def _parse_labels(labels_string: str) -> Dict[str, str]: |
| 49 |
labels: Dict[str, str] = {} |
| 50 |
|
| 51 |
if "=" not in labels_string: |
| 52 |
return labels |
| 53 |
|
| 54 |
escaping = False |
| 55 |
if "\\" in labels_string: |
| 56 |
escaping = True |
| 57 |
|
| 58 |
|
| 59 |
sub_labels = labels_string |
| 60 |
try: |
| 61 |
|
| 62 |
while sub_labels: |
| 63 |
|
| 64 |
value_start = sub_labels.index("=") |
| 65 |
label_name = sub_labels[:value_start] |
| 66 |
sub_labels = sub_labels[value_start + 1:].lstrip() |
| 67 |
|
| 68 |
quote_start = sub_labels.index('"') + 1 |
| 69 |
value_substr = sub_labels[quote_start:] |
| 70 |
|
| 71 |
|
| 72 |
i = 0 |
| 73 |
while i < len(value_substr): |
| 74 |
i = value_substr.index('"', i) |
| 75 |
if not _is_character_escaped(value_substr, i): |
| 76 |
break |
| 77 |
i += 1 |
| 78 |
|
| 79 |
|
| 80 |
quote_end = i + 1 |
| 81 |
label_value = sub_labels[quote_start:quote_end] |
| 82 |
|
| 83 |
if escaping: |
| 84 |
label_value = _replace_escaping(label_value) |
| 85 |
labels[label_name.strip()] = label_value |
| 86 |
|
| 87 |
|
| 88 |
sub_labels = sub_labels[quote_end + 1:] |
| 89 |
next_comma = sub_labels.find(",") + 1 |
| 90 |
sub_labels = sub_labels[next_comma:].lstrip() |
| 91 |
|
| 92 |
return labels |
| 93 |
|
| 94 |
except ValueError: |
| 95 |
raise ValueError("Invalid labels: %s" % labels_string) |
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
def _parse_value_and_timestamp(s: str) -> Tuple[float, Optional[float]]: |
| 100 |
s = s.lstrip() |
| 101 |
separator = " " |
| 102 |
if separator not in s: |
| 103 |
separator = "\t" |
| 104 |
values = [value.strip() for value in s.split(separator) if value.strip()] |
| 105 |
if not values: |
| 106 |
return float(s), None |
| 107 |
value = float(values[0]) |
| 108 |
timestamp = (float(values[-1]) / 1000) if len(values) > 1 else None |
| 109 |
return value, timestamp |
| 110 |
|
| 111 |
|
| 112 |
def _parse_sample(text: str) -> Sample: |
| 113 |
|
| 114 |
try: |
| 115 |
label_start, label_end = text.index("{"), text.rindex("}") |
| 116 |
|
| 117 |
name = text[:label_start].strip() |
| 118 |
|
| 119 |
label = text[label_start + 1:label_end] |
| 120 |
|
| 121 |
value, timestamp = _parse_value_and_timestamp(text[label_end + 1:]) |
| 122 |
return Sample(name, _parse_labels(label), value, timestamp) |
| 123 |
|
| 124 |
|
| 125 |
except ValueError: |
| 126 |
|
| 127 |
separator = " " |
| 128 |
if separator not in text: |
| 129 |
separator = "\t" |
| 130 |
name_end = text.index(separator) |
| 131 |
name = text[:name_end] |
| 132 |
|
| 133 |
value, timestamp = _parse_value_and_timestamp(text[name_end:]) |
| 134 |
return Sample(name, {}, value, timestamp) |
| 135 |
|
| 136 |
|
| 137 |
def text_fd_to_metric_families(fd: TextIO) -> Iterable[Metric]: |
| 138 |
"""Parse Prometheus text format from a file descriptor. |
| 139 |
|
| 140 |
This is a laxer parser than the main Go parser, |
| 141 |
so successful parsing does not imply that the parsed |
| 142 |
text meets the specification. |
| 143 |
|
| 144 |
Yields Metric's. |
| 145 |
""" |
| 146 |
name = '' |
| 147 |
documentation = '' |
| 148 |
typ = 'untyped' |
| 149 |
samples: List[Sample] = [] |
| 150 |
allowed_names = [] |
| 151 |
|
| 152 |
def build_metric(name: str, documentation: str, typ: str, samples: List[Sample]) -> Metric: |
| 153 |
|
| 154 |
|
| 155 |
if typ == 'counter': |
| 156 |
if name.endswith('_total'): |
| 157 |
name = name[:-6] |
| 158 |
else: |
| 159 |
new_samples = [] |
| 160 |
for s in samples: |
| 161 |
new_samples.append(Sample(s[0] + '_total', *s[1:])) |
| 162 |
samples = new_samples |
| 163 |
metric = Metric(name, documentation, typ) |
| 164 |
metric.samples = samples |
| 165 |
return metric |
| 166 |
|
| 167 |
for line in fd: |
| 168 |
line = line.strip() |
| 169 |
|
| 170 |
if line.startswith('#'): |
| 171 |
parts = line.split(None, 3) |
| 172 |
if len(parts) < 2: |
| 173 |
continue |
| 174 |
if parts[1] == 'HELP': |
| 175 |
if parts[2] != name: |
| 176 |
if name != '': |
| 177 |
yield build_metric(name, documentation, typ, samples) |
| 178 |
|
| 179 |
name = parts[2] |
| 180 |
typ = 'untyped' |
| 181 |
samples = [] |
| 182 |
allowed_names = [parts[2]] |
| 183 |
if len(parts) == 4: |
| 184 |
documentation = _replace_help_escaping(parts[3]) |
| 185 |
else: |
| 186 |
documentation = '' |
| 187 |
elif parts[1] == 'TYPE': |
| 188 |
if parts[2] != name: |
| 189 |
if name != '': |
| 190 |
yield build_metric(name, documentation, typ, samples) |
| 191 |
|
| 192 |
name = parts[2] |
| 193 |
documentation = '' |
| 194 |
samples = [] |
| 195 |
typ = parts[3] |
| 196 |
allowed_names = { |
| 197 |
'counter': [''], |
| 198 |
'gauge': [''], |
| 199 |
'summary': ['_count', '_sum', ''], |
| 200 |
'histogram': ['_count', '_sum', '_bucket'], |
| 201 |
}.get(typ, ['']) |
| 202 |
allowed_names = [name + n for n in allowed_names] |
| 203 |
else: |
| 204 |
|
| 205 |
pass |
| 206 |
elif line == '': |
| 207 |
|
| 208 |
pass |
| 209 |
else: |
| 210 |
sample = _parse_sample(line) |
| 211 |
if sample.name not in allowed_names: |
| 212 |
if name != '': |
| 213 |
yield build_metric(name, documentation, typ, samples) |
| 214 |
|
| 215 |
name = '' |
| 216 |
documentation = '' |
| 217 |
typ = 'untyped' |
| 218 |
samples = [] |
| 219 |
allowed_names = [] |
| 220 |
yield build_metric(sample[0], documentation, typ, [sample]) |
| 221 |
else: |
| 222 |
samples.append(sample) |
| 223 |
|
| 224 |
if name != '': |
| 225 |
yield build_metric(name, documentation, typ, samples) |