vinix-ports / tools / release-archives.py
128 lines · 113 sloc · 5.74 KB
Raw
1"""Match a Vinix source plan to receipted native package archives."""
2
3import argparse
4from collections import Counter, defaultdict
5import csv
6import hashlib
7from pathlib import Path
8import re
9import subprocess
10
11
12def digest(path):
13 with path.open("rb") as stream:
14 return hashlib.file_digest(stream, "sha256").hexdigest()
15
16
17def records(path):
18 with path.open() as stream:
19 return list(csv.DictReader(stream, delimiter="\t"))
20
21
22def archives(pool, arch):
23 if pool.suffix == ".tsv":
24 for row in records(pool):
25 filename = row["archive"]
26 if row["arch"] in (arch, "any") and Path(filename).name == filename:
27 yield pool.parent / arch / filename, row["sha256"]
28 return
29 for receipt in sorted(pool.glob("*.sha256")) if pool.is_dir() else [pool]:
30 for line in receipt.read_text().splitlines():
31 fields = line.split(maxsplit=1)
32 if len(fields) != 2 or not re.fullmatch("[a-f0-9]{64}", fields[0]):
33 continue
34 checksum, filename = fields
35 filename = filename.lstrip("*")
36 if filename.endswith(".pkg.tar.zst") and Path(filename).name == filename:
37 yield receipt.parent / filename, checksum
38
39
40def package_field(archive, metadata):
41 body = subprocess.check_output(["bsdtar", "-xOf", archive, metadata],
42 stderr=subprocess.DEVNULL, text=True)
43 return dict(line.split(" = ", 1) for line in body.splitlines() if " = " in line)
44
45
46def verify(archive, checksum, name, version, arch, recipe_hash):
47 if not archive.is_file():
48 return "archive-missing"
49 try:
50 if digest(archive) != checksum:
51 return "checksum-mismatch"
52 pkg = package_field(archive, ".PKGINFO")
53 if (pkg.get("pkgname") != name or pkg.get("pkgver") != version
54 or pkg.get("arch") not in (arch, "any")
55 or archive.name != f"{name}-{version}-{pkg['arch']}.pkg.tar.zst"):
56 return "package-metadata-mismatch"
57 info = package_field(archive, ".BUILDINFO")
58 except (OSError, subprocess.CalledProcessError, UnicodeError):
59 return "unreadable-archive"
60 if info.get("pkgbuild_sha256sum") != recipe_hash:
61 return "recipe-mismatch"
62 return "verified"
63
64
65def report(args):
66 packages = records(args.order)
67 variants = (args.arch, "any")
68 paths = defaultdict(set)
69 for pool in args.pools:
70 for archive, checksum in archives(pool, args.arch):
71 paths[archive.name].add((archive, checksum))
72 override = {path.parent.name: path for path in args.extra_recipe}
73 args.output.mkdir()
74 results = {}
75 with (args.output / "candidates.tsv").open("x") as stream:
76 writer = csv.writer(stream, delimiter="\t", lineterminator="\n")
77 writer.writerow(["package", "archive", "sha256", "result"])
78 for row in packages:
79 name, version = row["package"], row["version"]
80 source = row["source_recipe"]
81 recipe = override.get(source, args.recipes / source / "PKGBUILD.vile")
82 if not recipe.is_file():
83 results[name] = "missing-recipe", "", "", ""
84 continue
85 recipe_hash = digest(recipe)
86 valid = {}
87 rejected = set()
88 for machine in variants:
89 for archive, checksum in sorted(paths[f"{name}-{version}-{machine}.pkg.tar.zst"]):
90 result = verify(archive, checksum, name, version, args.arch, recipe_hash)
91 writer.writerow([name, archive, checksum, result])
92 if result == "verified":
93 valid.setdefault(checksum, archive)
94 else:
95 rejected.add(result)
96 if len(valid) == 1:
97 checksum, archive = next(iter(valid.items()))
98 results[name] = "verified", str(archive), checksum, recipe_hash
99 elif valid:
100 results[name] = "archive-conflict", "", "", recipe_hash
101 else:
102 status = ",".join(sorted(rejected)) if rejected else "missing-receipt"
103 results[name] = status, "", "", recipe_hash
104 with (args.output / "coverage.tsv").open("x") as stream:
105 writer = csv.writer(stream, delimiter="\t", lineterminator="\n")
106 writer.writerow(["stage", "package", "version", "source_recipe", "status", "archive",
107 "archive_sha256", "recipe_sha256", "prerequisites_without_verified_archive"])
108 for row in packages:
109 name = row["package"]
110 pending = [dep for dep in filter(None, row["depends_on"].split(","))
111 if results[dep][0] != "verified"]
112 writer.writerow([row["stage"], name, row["version"], row["source_recipe"],
113 *results[name], ",".join(pending)])
114 counts = Counter(result[0] for result in results.values())
115 print(args.arch, *[f"{state}={count}" for state, count in sorted(counts.items())])
116 return int(not packages or counts["verified"] != len(packages))
117
118
119if __name__ == "__main__":
120 parser = argparse.ArgumentParser(description=__doc__)
121 parser.add_argument("arch", choices=("aarch64", "x86_64"))
122 parser.add_argument("order", type=Path, help="architecture-specific order.tsv")
123 parser.add_argument("recipes", type=Path, help="recipe directory used for the plan, such as ports/ or an exact snapshot")
124 parser.add_argument("output", type=Path, help="new directory for the coverage reports")
125 parser.add_argument("pools", type=Path, nargs="+",
126 help="archive receipt directories, individual receipts, or feed packages.tsv files")
127 parser.add_argument("--extra-recipe", action="append", type=Path, default=[])
128 raise SystemExit(report(parser.parse_args()))
129