Debian Codegraph @

crt/s2n/tests/cbmc/proofs/run-cbmc-proofs.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 #
3 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 # SPDX-License-Identifier: MIT-0
5
6
7 import argparse
8 import asyncio
9 import json
10 import logging
11 import math
12 import os
13 import pathlib
14 import re
15 import subprocess
16 import sys
17 import tempfile
18 import uuid
19
20 from lib.summarize import print_proof_results
21
22
23 DESCRIPTION = "Configure and run all CBMC proofs in parallel"
24
25 # Keep the epilog hard-wrapped at 70 characters, as it gets printed
26 # verbatim in the terminal. 70 characters stops here --------------> |
27 EPILOG = """
28 This tool automates the process of running `make report` in each of
29 the CBMC proof directories. The tool calculates the dependency graph
30 of all tasks needed to build, run, and report on all the proofs, and
31 executes these tasks in parallel.
32
33 The tool is roughly equivalent to doing this:
34
35 litani init --project "my-cool-project";
36
37 find . -name cbmc-proof.txt | while read -r proof; do
38 pushd $(dirname ${proof});
39
40 # The `make _report` rule adds a single proof to litani
41 # without running it
42 make _report;
43
44 popd;
45 done
46
47 litani run-build;
48
49 except that it is much faster and provides some convenience options.
50 The CBMC CI runs this script with no arguments to build and run all
51 proofs in parallel. The value of "my-cool-project" is taken from the
52 PROJECT_NAME variable in Makefile-project-defines.
53
54 The --no-standalone argument omits the `litani init` and `litani
55 run-build`; use it when you want to add additional proof jobs, not
56 just the CBMC ones. In that case, you would run `litani init`
57 yourself; then run `run-cbmc-proofs --no-standalone`; add any
58 additional jobs that you want to execute with `litani add-job`; and
59 finally run `litani run-build`.
60
61 The litani dashboard will be written under the `output` directory; the
62 cbmc-viewer reports remain in the `$PROOF_DIR/report` directory. The
63 HTML dashboard from the latest Litani run will always be symlinked to
64 `output/latest/html/index.html`, so you can keep that page open in
65 your browser and reload the page whenever you re-run this script.
66 """
67 # 70 characters stops here ----------------------------------------> |
68
69
70 def get_project_name():
71 cmd = [
72 "make",
73 "--no-print-directory",
74 "-f", "Makefile.common",
75 "echo-project-name",
76 ]
77 logging.debug(" ".join(cmd))
78 proc = subprocess.run(cmd, universal_newlines=True, stdout=subprocess.PIPE, check=False)
79 if proc.returncode:
80 logging.critical("could not run make to determine project name")
81 sys.exit(1)
82 if not proc.stdout.strip():
83 logging.warning(
84 "project name has not been set; using generic name instead. "
85 "Set the PROJECT_NAME value in Makefile-project-defines to "
86 "remove this warning")
87 return "<PROJECT NAME HERE>"
88 return proc.stdout.strip()
89
90
91 def get_args():
92 pars = argparse.ArgumentParser(
93 description=DESCRIPTION, epilog=EPILOG,
94 formatter_class=argparse.RawDescriptionHelpFormatter)
95 for arg in [{
96 "flags": ["-j", "--parallel-jobs"],
97 "type": int,
98 "metavar": "N",
99 "help": "run at most N proof jobs in parallel",
100 }, {
101 "flags": ["--fail-on-proof-failure"],
102 "action": "store_true",
103 "help": "exit with return code `10' if any proof failed"
104 " (default: exit 0)",
105 }, {
106 "flags": ["--no-standalone"],
107 "action": "store_true",
108 "help": "only configure proofs: do not initialize nor run",
109 }, {
110 "flags": ["-p", "--proofs"],
111 "nargs": "+",
112 "metavar": "DIR",
113 "help": "only run proof in directory DIR (can pass more than one)",
114 }, {
115 "flags": ["--project-name"],
116 "metavar": "NAME",
117 "default": get_project_name(),
118 "help": "project name for report. Default: %(default)s",
119 }, {
120 "flags": ["--marker-file"],
121 "metavar": "FILE",
122 "default": "cbmc-proof.txt",
123 "help": (
124 "name of file that marks proof directories. Default: "
125 "%(default)s"),
126 }, {
127 "flags": ["--no-memory-profile"],
128 "action": "store_true",
129 "help": "disable memory profiling, even if Litani supports it"
130 }, {
131 "flags": ["--no-expensive-limit"],
132 "action": "store_true",
133 "help": "do not limit parallelism of 'EXPENSIVE' jobs",
134 }, {
135 "flags": ["--expensive-jobs-parallelism"],
136 "metavar": "N",
137 "default": 1,
138 "type": int,
139 "help": (
140 "how many proof jobs marked 'EXPENSIVE' to run in parallel. "
141 "Default: %(default)s"),
142 }, {
143 "flags": ["--verbose"],
144 "action": "store_true",
145 "help": "verbose output",
146 }, {
147 "flags": ["--debug"],
148 "action": "store_true",
149 "help": "debug output",
150 }, {
151 "flags": ["--summarize"],
152 "action": "store_true",
153 "help": "summarize proof results with two tables on stdout",
154 }, {
155 "flags": ["--version"],
156 "action": "version",
157 "version": "CBMC starter kit 2.8.8",
158 "help": "display version and exit"
159 }, {
160 "flags": ["--no-coverage"],
161 "action": "store_true",
162 "help": "do property checking without coverage checking"
163 }]:
164 flags = arg.pop("flags")
165 pars.add_argument(*flags, **arg)
166 return pars.parse_args()
167
168
169 def set_up_logging(verbose):
170 if verbose:
171 level = logging.DEBUG
172 else:
173 level = logging.WARNING
174 logging.basicConfig(
175 format="run-cbmc-proofs: %(message)s", level=level)
176
177
178 def task_pool_size():
179 ret = os.cpu_count()
180 if ret is None or ret < 3:
181 return 1
182 return ret - 2
183
184
185 def print_counter(counter):
186 # pylint: disable=consider-using-f-string
187 print("\rConfiguring CBMC proofs: "
188 "{complete:{width}} / {total:{width}}".format(**counter), end="", file=sys.stderr)
189
190
191 def get_proof_dirs(proof_root, proof_list, marker_file):
192 if proof_list is not None:
193 proofs_remaining = list(proof_list)
194 else:
195 proofs_remaining = []
196
197 for root, _, fyles in os.walk(proof_root):
198 proof_name = str(pathlib.Path(root).name)
199 if root != str(proof_root) and ".litani_cache_dir" in fyles:
200 pathlib.Path(f"{root}/.litani_cache_dir").unlink()
201 if proof_list and proof_name not in proof_list:
202 continue
203 if proof_list and proof_name in proofs_remaining:
204 proofs_remaining.remove(proof_name)
205 if marker_file in fyles:
206 yield root
207
208 if proofs_remaining:
209 logging.critical(
210 "The following proofs were not found: %s",
211 ", ".join(proofs_remaining))
212 sys.exit(1)
213
214
215 def run_build(litani, jobs, fail_on_proof_failure, summarize):
216 cmd = [str(litani), "run-build"]
217 if jobs:
218 cmd.extend(["-j", str(jobs)])
219 if fail_on_proof_failure:
220 cmd.append("--fail-on-pipeline-failure")
221 if summarize:
222 out_file = pathlib.Path(tempfile.gettempdir(), "run.json").resolve()
223 cmd.extend(["--out-file", str(out_file)])
224
225 logging.debug(" ".join(cmd))
226 proc = subprocess.run(cmd, check=False)
227
228 if proc.returncode and not fail_on_proof_failure:
229 logging.critical("Failed to run litani run-build")
230 sys.exit(1)
231
232 if summarize:
233 print_proof_results(out_file)
234 out_file.unlink()
235
236 if proc.returncode:
237 logging.error("One or more proofs failed")
238 sys.exit(10)
239
240
241 def get_litani_path(proof_root):
242 cmd = [
243 "make",
244 "--no-print-directory",
245 f"PROOF_ROOT={proof_root}",
246 "-f", "Makefile.common",
247 "litani-path",
248 ]
249 logging.debug(" ".join(cmd))
250 proc = subprocess.run(cmd, universal_newlines=True, stdout=subprocess.PIPE, check=False)
251 if proc.returncode:
252 logging.critical("Could not determine path to litani")
253 sys.exit(1)
254 return proc.stdout.strip()
255
256
257 def get_litani_capabilities(litani_path):
258 cmd = [litani_path, "print-capabilities"]
259 proc = subprocess.run(
260 cmd, text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=False)
261 if proc.returncode:
262 return []
263 try:
264 return json.loads(proc.stdout)
265 except RuntimeError:
266 logging.warning("Could not load litani capabilities: '%s'", proc.stdout)
267 return []
268
269
270 def check_uid_uniqueness(proof_dir, proof_uids):
271 with (pathlib.Path(proof_dir) / "Makefile").open() as handle:
272 for line in handle:
273 match = re.match(r"^PROOF_UID\s*=\s*(?P<uid>\w+)", line)
274 if not match:
275 continue
276 if match["uid"] not in proof_uids:
277 proof_uids[match["uid"]] = proof_dir
278 return
279
280 logging.critical(
281 "The Makefile in directory '%s' should have a different "
282 "PROOF_UID than the Makefile in directory '%s'",
283 proof_dir, proof_uids[match["uid"]])
284 sys.exit(1)
285
286 logging.critical(
287 "The Makefile in directory '%s' should contain a line like", proof_dir)
288 logging.critical("PROOF_UID = ...")
289 logging.critical("with a unique identifier for the proof.")
290 sys.exit(1)
291
292
293 def should_enable_memory_profiling(litani_caps, args):
294 if args.no_memory_profile:
295 return False
296 return "memory_profile" in litani_caps
297
298
299 def should_enable_pools(litani_caps, args):
300 if args.no_expensive_limit:
301 return False
302 return "pools" in litani_caps
303
304
305 async def configure_proof_dirs( # pylint: disable=too-many-arguments
306 queue, counter, proof_uids, enable_pools, enable_memory_profiling, report_target, debug):
307 while True:
308 print_counter(counter)
309 path = str(await queue.get())
310
311 check_uid_uniqueness(path, proof_uids)
312
313 pools = ["ENABLE_POOLS=true"] if enable_pools else []
314 profiling = [
315 "ENABLE_MEMORY_PROFILING=true"] if enable_memory_profiling else []
316
317 # Allow interactive tasks to preempt proof configuration
318 proc = await asyncio.create_subprocess_exec(
319 "nice", "-n", "15", "make", *pools,
320 *profiling, "-B", report_target, "" if debug else "--quiet", cwd=path,
321 stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
322 stdout, stderr = await proc.communicate()
323 logging.debug("returncode: %s", str(proc.returncode))
324 logging.debug("stdout:")
325 for line in stdout.decode().splitlines():
326 logging.debug(line)
327 logging.debug("stderr:")
328 for line in stderr.decode().splitlines():
329 logging.debug(line)
330
331 counter["fail" if proc.returncode else "pass"].append(path)
332 counter["complete"] += 1
333
334 print_counter(counter)
335 queue.task_done()
336
337
338 def add_tool_version_job():
339 cmd = [
340 "litani", "add-job",
341 "--command", "./lib/print_tool_versions.py .",
342 "--description", "printing out tool versions",
343 "--phony-outputs", str(uuid.uuid4()),
344 "--pipeline-name", "print_tool_versions",
345 "--ci-stage", "report",
346 "--tags", "front-page-text",
347 ]
348 proc = subprocess.run(cmd)
349 if proc.returncode:
350 logging.critical("Could not add tool version printing job")
351 sys.exit(1)
352
353
354 async def main(): # pylint: disable=too-many-locals
355 args = get_args()
356 set_up_logging(args.verbose)
357
358 proof_root = pathlib.Path(os.getcwd())
359 litani = get_litani_path(proof_root)
360
361 litani_caps = get_litani_capabilities(litani)
362 enable_pools = should_enable_pools(litani_caps, args)
363 init_pools = [
364 "--pools", f"expensive:{args.expensive_jobs_parallelism}"
365 ] if enable_pools else []
366
367 if not args.no_standalone:
368 cmd = [
369 str(litani), "init", *init_pools, "--project", args.project_name,
370 "--no-print-out-dir",
371 ]
372
373 if "output_directory_flags" in litani_caps:
374 out_prefix = proof_root / "output"
375 out_symlink = out_prefix / "latest"
376 out_index = out_symlink / "html" / "index.html"
377 cmd.extend([
378 "--output-prefix", str(out_prefix),
379 "--output-symlink", str(out_symlink),
380 ])
381 print(
382 "\nFor your convenience, the output of this run will be symbolically linked to ",
383 out_index, "\n")
384
385 logging.debug(" ".join(cmd))
386 proc = subprocess.run(cmd, check=False)
387 if proc.returncode:
388 logging.critical("Failed to run litani init")
389 sys.exit(1)
390
391 proof_dirs = list(get_proof_dirs(
392 proof_root, args.proofs, args.marker_file))
393 if not proof_dirs:
394 logging.critical("No proof directories found")
395 sys.exit(1)
396
397 proof_queue = asyncio.Queue()
398 for proof_dir in proof_dirs:
399 proof_queue.put_nowait(proof_dir)
400
401 counter = {
402 "pass": [],
403 "fail": [],
404 "complete": 0,
405 "total": len(proof_dirs),
406 "width": int(math.log10(len(proof_dirs))) + 1
407 }
408
409 proof_uids = {}
410 tasks = []
411
412 enable_memory_profiling = should_enable_memory_profiling(litani_caps, args)
413 report_target = "_report_no_coverage" if args.no_coverage else "_report"
414
415 for _ in range(task_pool_size()):
416 task = asyncio.create_task(configure_proof_dirs(
417 proof_queue, counter, proof_uids, enable_pools,
418 enable_memory_profiling, report_target, args.debug))
419 tasks.append(task)
420
421 await proof_queue.join()
422
423 add_tool_version_job()
424
425 print_counter(counter)
426 print("", file=sys.stderr)
427
428 if counter["fail"]:
429 logging.critical(
430 "Failed to configure the following proofs:\n%s", "\n".join(
431 [str(f) for f in counter["fail"]]))
432 sys.exit(1)
433
434 if not args.no_standalone:
435 run_build(litani, args.parallel_jobs, args.fail_on_proof_failure, args.summarize)
436
437
438 if __name__ == "__main__":
439 asyncio.run(main())