run-cbmc-proofs.py 13 KB

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