Debian Codegraph @

ansible_collections/community/docker/plugins/module_utils/_logfmt.py

raw
1 # Copyright (c) 2024, Felix Fontein <[email protected]>
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 """
9 Parse go logfmt messages.
10
11 See https://pkg.go.dev/github.com/kr/logfmt?utm_source=godoc for information on the format.
12 """
13
14 from __future__ import annotations
15
16 import typing as t
17 from enum import Enum
18
19 # The format is defined in https://pkg.go.dev/github.com/kr/logfmt?utm_source=godoc
20 # (look for "EBNFish")
21
22
23 class InvalidLogFmt(Exception):
24 pass
25
26
27 class _Mode(Enum):
28 GARBAGE = 0
29 KEY = 1
30 EQUAL = 2
31 IDENT_VALUE = 3
32 QUOTED_VALUE = 4
33
34
35 _ESCAPE_DICT = {
36 '"': '"',
37 "\\": "\\",
38 "'": "'",
39 "/": "/",
40 "b": "\b",
41 "f": "\f",
42 "n": "\n",
43 "r": "\r",
44 "t": "\t",
45 }
46
47 _HEX_DICT = {
48 "0": 0,
49 "1": 1,
50 "2": 2,
51 "3": 3,
52 "4": 4,
53 "5": 5,
54 "6": 6,
55 "7": 7,
56 "8": 8,
57 "9": 9,
58 "a": 0xA,
59 "b": 0xB,
60 "c": 0xC,
61 "d": 0xD,
62 "e": 0xE,
63 "f": 0xF,
64 "A": 0xA,
65 "B": 0xB,
66 "C": 0xC,
67 "D": 0xD,
68 "E": 0xE,
69 "F": 0xF,
70 }
71
72
73 def _is_ident(cur: str) -> bool:
74 return cur > " " and cur not in ('"', "=")
75
76
77 class _Parser:
78 def __init__(self, line: str) -> None:
79 self.line = line
80 self.index = 0
81 self.length = len(line)
82
83 def done(self) -> bool:
84 return self.index >= self.length
85
86 def cur(self) -> str:
87 return self.line[self.index]
88
89 def next(self) -> None:
90 self.index += 1
91
92 def prev(self) -> None:
93 self.index -= 1
94
95 def parse_unicode_sequence(self) -> str:
96 if self.index + 6 > self.length:
97 raise InvalidLogFmt("Not enough space for unicode escape")
98 if self.line[self.index : self.index + 2] != "\\u":
99 raise InvalidLogFmt("Invalid unicode escape start")
100 v = 0
101 for dummy_index in range(self.index + 2, self.index + 6):
102 v <<= 4
103 try:
104 v += _HEX_DICT[self.line[self.index]]
105 except KeyError:
106 raise InvalidLogFmt(
107 f"Invalid unicode escape digit {self.line[self.index]!r}"
108 ) from None
109 self.index += 6
110 return chr(v)
111
112
113 def parse_line(line: str, logrus_mode: bool = False) -> dict[str, t.Any]:
114 result: dict[str, t.Any] = {}
115 parser = _Parser(line)
116 key: list[str] = []
117 value: list[str] = []
118 mode = _Mode.GARBAGE
119
120 def handle_kv(has_no_value: bool = False) -> None:
121 k = "".join(key)
122 v = None if has_no_value else "".join(value)
123 result[k] = v
124 del key[:]
125 del value[:]
126
127 def parse_garbage(cur: str) -> _Mode:
128 if _is_ident(cur):
129 return _Mode.KEY
130 parser.next()
131 return _Mode.GARBAGE
132
133 def parse_key(cur: str) -> _Mode:
134 if _is_ident(cur):
135 key.append(cur)
136 parser.next()
137 return _Mode.KEY
138 if cur == "=":
139 parser.next()
140 return _Mode.EQUAL
141 if logrus_mode:
142 raise InvalidLogFmt('Key must always be followed by "=" in logrus mode')
143 handle_kv(has_no_value=True)
144 parser.next()
145 return _Mode.GARBAGE
146
147 def parse_equal(cur: str) -> _Mode:
148 if _is_ident(cur):
149 value.append(cur)
150 parser.next()
151 return _Mode.IDENT_VALUE
152 if cur == '"':
153 parser.next()
154 return _Mode.QUOTED_VALUE
155 handle_kv()
156 parser.next()
157 return _Mode.GARBAGE
158
159 def parse_ident_value(cur: str) -> _Mode:
160 if _is_ident(cur):
161 value.append(cur)
162 parser.next()
163 return _Mode.IDENT_VALUE
164 handle_kv()
165 parser.next()
166 return _Mode.GARBAGE
167
168 def parse_quoted_value(cur: str) -> _Mode:
169 if cur == "\\":
170 parser.next()
171 if parser.done():
172 raise InvalidLogFmt("Unterminated escape sequence in quoted string")
173 cur = parser.cur()
174 if cur in _ESCAPE_DICT:
175 value.append(_ESCAPE_DICT[cur])
176 elif cur != "u":
177 es = f"\\{cur}"
178 raise InvalidLogFmt(f"Unknown escape sequence {es!r}")
179 else:
180 parser.prev()
181 value.append(parser.parse_unicode_sequence())
182 parser.next()
183 return _Mode.QUOTED_VALUE
184 if cur == '"':
185 handle_kv()
186 parser.next()
187 return _Mode.GARBAGE
188 if cur < " ":
189 raise InvalidLogFmt("Control characters in quoted string are not allowed")
190 value.append(cur)
191 parser.next()
192 return _Mode.QUOTED_VALUE
193
194 parsers = {
195 _Mode.GARBAGE: parse_garbage,
196 _Mode.KEY: parse_key,
197 _Mode.EQUAL: parse_equal,
198 _Mode.IDENT_VALUE: parse_ident_value,
199 _Mode.QUOTED_VALUE: parse_quoted_value,
200 }
201 while not parser.done():
202 mode = parsers[mode](parser.cur())
203 if mode == _Mode.KEY and logrus_mode:
204 raise InvalidLogFmt('Key must always be followed by "=" in logrus mode')
205 if mode in (_Mode.KEY, _Mode.EQUAL):
206 handle_kv(has_no_value=True)
207 elif mode == _Mode.IDENT_VALUE:
208 handle_kv()
209 elif mode == _Mode.QUOTED_VALUE:
210 raise InvalidLogFmt("Unterminated quoted string")
211 return result