Debian Codegraph @

debian/tests/check-log

raw
1 #!/usr/bin/python3
2
3 # pylint: disable=invalid-name
4 # pylint: enable=invalid-name
5
6 """Run given checks on the log output."""
7
8 import argparse
9 import json
10 import pathlib
11 import re
12 import shlex
13 import sys
14 import typing
15
16
17 class Check:
18 """The Check class contains all the checks that the caller can run."""
19
20 def __init__(self, log: str) -> None:
21 self.errors = 0
22 self.command_outputs = self._extract_command_outputs_from_log(log)
23
24 def _error(self, msg: str) -> None:
25 print("ERROR: " + msg)
26 self.errors += 1
27
28 @staticmethod
29 def _extract_command_outputs_from_log(log: str) -> dict[str, str]:
30 """Extract command outputs from the given log output.
31
32 The output must be framed by a header and a footer line. The header
33 line contains the key surrounded by 10 # characters. The footer
34 line consist of 40 # characters. Returns a mapping from the output
35 key to the command output.
36 """
37 marker = "#" * 10
38 footer = "#" * 40
39 matches = re.findall(
40 f"^{marker} ([^#]+) {marker}\n(.*?\n){footer}$",
41 log,
42 flags=re.DOTALL | re.MULTILINE,
43 )
44 return {m[0]: m[1] for m in matches}
45
46 def get_commands_from_ps_output(self) -> list[str]:
47 """Get list of command from `ps -ww aux` output."""
48 ps_output = self.command_outputs["ps -ww aux"]
49 lines = ps_output.strip().split("\n")[1:]
50 commands = []
51 for line in lines:
52 columns = re.split(r"\s+", line, maxsplit=10)
53 commands.append(columns[10])
54 return commands
55
56 def get_ip_addr(self) -> list[typing.Any]:
57 """Get IP address information from `ip addr` JSON output."""
58 ip_addr = json.loads(self.command_outputs["ip -json addr"])
59 assert isinstance(ip_addr, list)
60 return ip_addr
61
62 def get_ip_route(self) -> list[typing.Any]:
63 """Get IP route information from `ip route` JSON output."""
64 ip_route = json.loads(self.command_outputs["ip -json route"])
65 assert isinstance(ip_route, list)
66 return ip_route
67
68 def run_checks(self, args: list[str]) -> int:
69 """Run the checks and return the number of errors found.
70
71 The methods of this class can be u
72 """
73 if not args:
74 return self.errors
75
76 try:
77 check = getattr(self, args[0])
78 except AttributeError:
79 self._error(f"Check '{args[0]}' not found.")
80 return self.errors
81 check_args = []
82
83 for arg in args[1:]:
84 if not hasattr(self, arg):
85 check_args.append(arg)
86 continue
87
88 check(*check_args)
89 check = getattr(self, arg)
90 check_args = []
91
92 check(*check_args)
93 return self.errors
94
95 def _check_is_subset(self, actual: set[str], expected: set[str]) -> None:
96 """Check that the first dictionary is a subset of the second one.
97
98 Log errors if the sets are different.
99 """
100 unexpected = actual - expected
101 if unexpected:
102 self._error(f"Not expected entries: {unexpected}")
103
104 def _check_is_subdict(
105 self,
106 expected_dict: dict[str, str],
107 actual_dict: dict[str, str],
108 log_prefix: str,
109 ) -> None:
110 """Check that the first dictionary is a subset of the second one.
111
112 Log errors if differences are found.
113 """
114 missing_keys = set(expected_dict.keys()) - set(actual_dict.keys())
115 if missing_keys:
116 self._error(f"{log_prefix}Missing keys: {missing_keys}")
117 for key, expected_value in sorted(expected_dict.items()):
118 actual_value = actual_dict.get(key, "")
119 if expected_value != actual_value:
120 self._error(
121 f"{log_prefix}Value for key '{key}' differs:"
122 f" '{expected_value}' expected, but got '{actual_value}'"
123 )
124
125 # Below are all checks that the user might call.
126
127 def has_hostname(self, hostname_pattern: str) -> None:
128 """Check that the hostname matches the given regular expression."""
129 hostname = self.command_outputs["hostname"].strip()
130 if re.fullmatch(hostname_pattern, hostname):
131 print(f"hostname '{hostname}' matches pattern '{hostname_pattern}'")
132 return
133 self._error(
134 f"hostname '{hostname}' does not match"
135 f" expected pattern '{hostname_pattern}'"
136 )
137
138 def has_interface_mtu(self, device_pattern: str, expected_mtu: str) -> None:
139 """Check that a matching network device has the expected MTU set."""
140 for device in self.get_ip_addr():
141 if not re.fullmatch(device_pattern, device["ifname"]):
142 continue
143 if str(device["mtu"]) == expected_mtu:
144 print(f"device {device['ifname']} has MTU {device['mtu']}")
145 return
146 self._error(
147 f"device {device['ifname']} has MTU {device['mtu']}"
148 f" but expected {expected_mtu}"
149 )
150 return
151 self._error(f"no link found that matches '{device_pattern}'")
152
153 def has_ip_addr(self, family: str, addr_pattern: str, device_pattern: str) -> None:
154 """Check that a matching network device has a matching IP address."""
155 for device in self.get_ip_addr():
156 if not re.fullmatch(device_pattern, device["ifname"]):
157 continue
158 for addr in device["addr_info"]:
159 if addr["family"] != family or addr["scope"] != "global":
160 continue
161 address = f"{addr['local']}/{addr['prefixlen']}"
162 if re.fullmatch(addr_pattern, address):
163 print(f"found addr {address} for {device['ifname']}: {addr}")
164 return
165 self._error(
166 f"addr {address} for {device['ifname']}"
167 f" does not match {addr_pattern}: {addr}"
168 )
169 return
170 name = {"inet": "IPv4", "inet6": "IPv6"}[family]
171 self._error(
172 f"no link found that matches '{device_pattern}' and has an {name} address"
173 )
174
175 def has_ipv4_addr(self, addr_pattern: str, device_pattern: str) -> None:
176 """Check that a matching network device has a matching IPv4 address."""
177 self.has_ip_addr("inet", addr_pattern, device_pattern)
178
179 def has_ipv6_addr(self, addr_pattern: str, device_pattern: str) -> None:
180 """Check that a matching network device has a matching IPv6 address."""
181 self.has_ip_addr("inet6", addr_pattern, device_pattern)
182
183 def has_ipv4_default_route(self, gateway_pattern: str, device_pattern: str) -> None:
184 """Check that the IPv4 default route is via a matching gateway and device."""
185 for route in self.get_ip_route():
186 if route["dst"] != "default":
187 continue
188 if not re.fullmatch(gateway_pattern, route["gateway"]) or not re.fullmatch(
189 device_pattern, route["dev"]
190 ):
191 self._error(
192 f"Default IPv4 route does not match expected gateway pattern"
193 f" '{gateway_pattern}' or dev pattern '{device_pattern}': {route}"
194 )
195 continue
196 print(
197 f"found IPv4 default route via {route['gateway']}"
198 f" for {route['dev']}: {route}"
199 )
200 return
201 self._error("no IPv4 default route found")
202
203 def has_net_conf(self, min_expected_files: str, *expected_net_confs: str) -> None:
204 """Compare the /run/net*.conf files.
205
206 There must be at least `min_expected_files` /run/net*.conf files
207 in the log output and no unexpected one. The format for
208 `expected_net_confs` is `<file name>=<expected content>`.
209 """
210
211 expected = dict(nc.split("=", maxsplit=1) for nc in expected_net_confs)
212 prog = re.compile(r"/run/net[^#]+\.conf")
213 got = {
214 key: value for key, value in self.command_outputs.items() if prog.match(key)
215 }
216
217 if len(got) < int(min_expected_files):
218 self._error(
219 f"Expected at least {min_expected_files} /run/net*.conf files,"
220 f" but got only {len(got)}: {set(got.keys())}"
221 )
222 self._check_is_subset(set(got.keys()), set(expected.keys()))
223
224 for net_dev in sorted(got.keys()):
225 log_prefix = f"{net_dev}: "
226 expected_net_conf = parse_net_conf(expected.get(net_dev, ""))
227 actual_net_conf = parse_net_conf(got.get(net_dev, ""))
228 self._check_is_subdict(expected_net_conf, actual_net_conf, log_prefix)
229 print(f"compared {len(expected_net_conf)} items from {net_dev}")
230
231 def has_no_hostname(self) -> None:
232 """Check that the hostname is not set."""
233 hostname = self.command_outputs["hostname"].strip()
234 if hostname in ("", "(none)"):
235 print("hostname is not set")
236 return
237 self._error(f"hostname '{hostname}' is set")
238
239 def has_no_running_processes(self) -> None:
240 """Check that there are no remaining running processes from the initrd."""
241 processes = drop_kernel_processes(self.get_commands_from_ps_output())
242 if len(processes) == 2:
243 print(f"found only expected init and ps process: {processes}")
244 return
245 self._error(
246 f"Expected only init and ps process, but got {len(processes)}: {processes}"
247 )
248
249
250 def drop_kernel_processes(processes: list[str]) -> list[str]:
251 """Return a list of processes with the kernel processes dropped."""
252 return [p for p in processes if not p.startswith("[") or not p.endswith("]")]
253
254
255 def parse_net_conf(net_conf: str) -> dict[str, str]:
256 """Parse /run/net*.conf file and return a key to value mapping."""
257 items = shlex.split(net_conf)
258 return dict(item.split("=", maxsplit=1) for item in items)
259
260
261 def main(arguments: list[str]) -> int:
262 """Run given checks on the log output. Return number of errors."""
263 parser = argparse.ArgumentParser()
264 parser.add_argument("log_file", metavar="log-file")
265 parser.add_argument("checks", metavar="check", nargs="+")
266 args = parser.parse_args(arguments)
267
268 log = pathlib.Path(args.log_file).read_text(encoding="ascii")
269 check = Check(log)
270 return check.run_checks(args.checks)
271
272
273 if __name__ == "__main__":
274 sys.exit(main(sys.argv[1:]))