File size: 7,744 Bytes
44084af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
"""Alertmanager 0.28 matcher strings, parsed the way the config loader does.

A `matchers:` entry is one string that may hold several comma-separated matchers, with or without the
surrounding braces (`'alertname="X"'`, `'alertname="X",severity="page"'`, `'{alertname="X"}'`,
`'alertname=X'`). Alertmanager 0.28 runs in its default fallback mode: both the classic parser
(`pkg/labels.ParseMatchers`) and the UTF-8 parser (`matcher/parse`) read the string; when the classic parser
accepts it, its result is the one used (it wins any disagreement); otherwise the UTF-8 parser's result is used;
the string is rejected only when both reject it. Regexes are anchored (`^(?:re)$`).

`parse(s)` returns [(name, op, value)] or raises Unsupported for strings Alertmanager itself rejects.
"""

from __future__ import annotations

import re

from .amcheck import Unsupported  # noqa: F401  (the simulators catch this one)


# ---------------------------------------------------------------------------- classic parser (pkg/labels/parse.go)

_CLASSIC = re.compile(r"^\s*([a-zA-Z_:][a-zA-Z0-9_:]*)\s*(=~|=|!=|!~)\s*(.*?)\s*$", re.S)


def _classic_tokens(s: str) -> list[str]:
    if s.startswith("{"):
        s = s[1:]
    if s.endswith("}"):
        s = s[:-1]
    tokens, tok, inside, escaped = [], [], False, False
    for ch in s:
        if ch == "," and not inside:
            tokens.append("".join(tok))
            tok = []
            continue
        if ch == '"':
            if not escaped:
                inside = not inside
            else:
                escaped = False
        elif ch == "\\":
            escaped = not escaped
        else:
            escaped = False
        tok.append(ch)
    last = "".join(tok).strip()
    if last:
        tokens.append(last)
    return tokens


def _classic_one(tok: str) -> tuple[str, str, str]:
    m = _CLASSIC.match(tok)
    if not m:
        raise Unsupported(f"bad matcher format: {tok!r}")
    raw, quoted = m.group(3), False
    if raw.startswith('"'):
        raw, quoted = raw[1:], True
    out, escaped, n = [], False, len(raw)
    for i, ch in enumerate(raw):
        if escaped:
            escaped = False
            if ch == "n":
                out.append("\n")
            elif ch in '"\\':
                out.append(ch)
            else:
                out.append("\\" + ch)   # a spurious escape keeps its backslash
            continue
        if ch == "\\":
            if i < n - 1:
                escaped = True
                continue
            out.append("\\")
        elif ch == '"':
            if not quoted or i < n - 1:
                raise Unsupported(f"unescaped double quote in {tok!r}")
            quoted = False
        else:
            out.append(ch)
    if quoted:
        raise Unsupported(f"missing trailing quote in {tok!r}")
    return m.group(1), m.group(2), "".join(out)


def parse_classic(s: str) -> list[tuple[str, str, str]]:
    return [_classic_one(t) for t in _classic_tokens(s)]


# ---------------------------------------------------------------------------- UTF-8 parser (matcher/parse)

_RESERVED = set("{}!=~,\\\"'`")
_OPS = ("=~", "!=", "!~", "=")
_ESC = {"a": "\a", "b": "\b", "f": "\f", "n": "\n", "r": "\r", "t": "\t", "v": "\v", "\\": "\\", '"': '"', "'": "'"}


def _go_unquote(body: str) -> str:
    """strconv.Unquote of a double-quoted Go string body."""
    out, i = [], 0
    while i < len(body):
        c = body[i]
        if c == "\n":
            raise Unsupported("newline in quoted string")
        if c != "\\":
            out.append(c)
            i += 1
            continue
        if i + 1 >= len(body):
            raise Unsupported("trailing backslash")
        e = body[i + 1]
        if e in _ESC:
            out.append(_ESC[e])
            i += 2
        elif e in "xuU":
            k = {"x": 2, "u": 4, "U": 8}[e]
            h = body[i + 2:i + 2 + k]
            if len(h) != k or not all(x in "0123456789abcdefABCDEF" for x in h):
                raise Unsupported(f"bad \\{e} escape")
            out.append(chr(int(h, 16)))
            i += 2 + k
        elif e in "01234567":
            o = body[i + 1:i + 4]
            if len(o) != 3 or not all(x in "01234567" for x in o) or int(o, 8) > 255:
                raise Unsupported("bad octal escape")
            out.append(chr(int(o, 8)))
            i += 4
        else:
            raise Unsupported(f"unknown escape \\{e}")
    return "".join(out)


def _lex(s: str) -> list[tuple[str, str]]:
    toks, i = [], 0
    while i < len(s):
        c = s[i]
        if c.isspace():
            i += 1
        elif c in "{},":
            toks.append((c, c))
            i += 1
        elif c in "=!":
            op = next((o for o in _OPS if s.startswith(o, i)), None)
            if op is None:
                raise Unsupported(f"bad operator at {i}")
            toks.append(("op", op))
            i += len(op)
        elif c == '"':
            j, esc = i + 1, False
            while j < len(s) and (esc or s[j] != '"'):
                esc = (s[j] == "\\") and not esc
                j += 1
            if j >= len(s):
                raise Unsupported("unterminated quoted string")
            toks.append(("str", _go_unquote(s[i + 1:j])))
            i = j + 1
        elif c in _RESERVED:
            raise Unsupported(f"unexpected {c!r}")
        else:
            j = i
            while j < len(s) and not s[j].isspace() and s[j] not in _RESERVED:
                j += 1
            toks.append(("str", s[i:j]))
            i = j
    return toks


def parse_utf8(s: str) -> list[tuple[str, str, str]]:
    toks = _lex(s)
    if not toks:
        return []
    braced = toks[0][0] == "{"
    if braced:
        if toks[-1][0] != "}":
            raise Unsupported("missing closing brace")
        toks = toks[1:-1]
    elif any(t[0] in "{}" for t in toks):
        raise Unsupported("unbalanced braces")
    out, i = [], 0
    while i < len(toks):
        if len(toks) - i < 3:
            raise Unsupported("incomplete matcher")
        (k1, name), (k2, op), (k3, val) = toks[i], toks[i + 1], toks[i + 2]
        if k1 != "str" or k2 != "op" or k3 != "str" or name == "":
            raise Unsupported("expected name, operator, value")
        out.append((name, op, val))
        i += 3
        if i < len(toks):
            if toks[i][0] != ",":
                raise Unsupported("expected a comma")
            i += 1
    return out


# ---------------------------------------------------------------------------- the config loader's choice

def parse(s) -> list[tuple[str, str, str]]:
    if not isinstance(s, str):
        raise Unsupported(f"matcher {s!r} is not a string")
    try:
        out = parse_classic(s)
    except Unsupported:
        out = parse_utf8(s)
    for _, op, val in out:
        if op in ("=~", "!~"):
            compile_value(op, val)   # an invalid regex is a config error in Alertmanager too
    return out


def compile_value(op: str, value: str):
    if op in ("=~", "!~"):
        try:
            rx = re.compile(f"^(?:{value})$")
        except re.error as e:
            raise Unsupported(f"bad regex {value!r}") from e
        return (lambda v: bool(rx.match(v))) if op == "=~" else (lambda v: not rx.match(v))
    return (lambda v: v == value) if op == "=" else (lambda v: v != value)


def compile_list(ms) -> list[tuple[str, object]]:
    """A `matchers:` list (each entry may hold several matchers) as [(label, predicate)]."""
    if ms is None:
        return []
    if not isinstance(ms, list):
        raise Unsupported("matchers must be a list")
    out = []
    for m in ms:
        for name, op, val in parse(m):
            out.append((name, compile_value(op, val)))
    return out