| 1 | """Compare published Vinix files to the exact package versions in release-closure's TSV.""" |
| 2 | |
| 3 | import argparse |
| 4 | import base64 |
| 5 | import csv |
| 6 | import gzip |
| 7 | import hashlib |
| 8 | import os |
| 9 | import posixpath |
| 10 | import subprocess |
| 11 | import tarfile |
| 12 | from collections import Counter, defaultdict |
| 13 | from pathlib import Path |
| 14 | |
| 15 | |
| 16 | def path_name(name): |
| 17 | path = posixpath.normpath(name) |
| 18 | if path.startswith("/") or path == ".." or path.startswith("../"): |
| 19 | raise ValueError(f"path outside archive: {name}") |
| 20 | return path |
| 21 | |
| 22 | |
| 23 | def hashes(stream): |
| 24 | sha256, sha1 = hashlib.sha256(), hashlib.sha1() |
| 25 | while block := stream.read(1024 * 1024): |
| 26 | sha256.update(block) |
| 27 | sha1.update(block) |
| 28 | return sha256.hexdigest(), sha1.hexdigest() |
| 29 | |
| 30 | |
| 31 | def archive_members(path, *, apk=False): |
| 32 | entries = {} |
| 33 | links = {} |
| 34 | # APK v2 has concatenated gzip signature, control, and data members. |
| 35 | with gzip.open(path, "rb") as stream, tarfile.open(fileobj=stream, mode="r|", ignore_zeros=apk) as archive: |
| 36 | for member in archive: |
| 37 | name = path_name(member.name) |
| 38 | if apk and name.startswith(".") and "/" not in name: |
| 39 | continue |
| 40 | if member.isfile(): |
| 41 | entries[name] = ("file", *hashes(archive.extractfile(member))) |
| 42 | elif member.issym(): |
| 43 | target = member.linkname |
| 44 | entries[name] = ("symlink", target, hashlib.sha1(os.fsencode(target)).hexdigest()) |
| 45 | elif member.islnk(): |
| 46 | links[name] = path_name(member.linkname) |
| 47 | for name, target in links.items(): |
| 48 | visited = {name} |
| 49 | while target in links: |
| 50 | if target in visited: |
| 51 | raise ValueError(f"cyclic hard link in {path}: {name}") |
| 52 | visited.add(target) |
| 53 | target = links[target] |
| 54 | entries[name] = entries[target] |
| 55 | return entries |
| 56 | |
| 57 | |
| 58 | def miniroot_members(installed): |
| 59 | packages = {} |
| 60 | for record in installed.read_text().strip().split("\n\n"): |
| 61 | files = {} |
| 62 | fields = {} |
| 63 | for line in record.splitlines(): |
| 64 | key, value = line.split(":", 1) |
| 65 | if key == "F": |
| 66 | directory = value |
| 67 | elif key == "R": |
| 68 | path = path_name(posixpath.join(directory, value)) |
| 69 | files[path] = None |
| 70 | elif key == "Z" and value.startswith("Q1"): |
| 71 | files[path] = base64.b64decode(value[2:], validate=True).hex() |
| 72 | elif key in {"P", "V"}: |
| 73 | fields[key] = value |
| 74 | packages[fields["P"], fields["V"]] = files |
| 75 | return packages |
| 76 | |
| 77 | |
| 78 | def cached_apk(row, cache): |
| 79 | repo = row["repository"] |
| 80 | branch = repo if repo.startswith("v3.") else "v3.21/" + repo |
| 81 | relative = f'{branch}/{row["arch"]}/{row["binary"]}-{row["version"]}.apk' |
| 82 | path = cache / relative |
| 83 | if not path.is_file(): |
| 84 | path.parent.mkdir(parents=True, exist_ok=True) |
| 85 | partial = path.with_suffix(".partial") |
| 86 | url = "https://dl-cdn.alpinelinux.org/alpine/" + relative |
| 87 | subprocess.run(["curl", "-fsSL", "--retry", "2", "--connect-timeout", "15", |
| 88 | "--max-time", "180", "-o", partial, url], check=True) |
| 89 | partial.replace(path) |
| 90 | return path |
| 91 | |
| 92 | |
| 93 | def resolved_member(files, name): |
| 94 | seen = set() |
| 95 | while name in files: |
| 96 | if name in seen: |
| 97 | return None |
| 98 | seen.add(name) |
| 99 | entry = files[name] |
| 100 | if entry[0] != "symlink": |
| 101 | return entry |
| 102 | link = entry[1] |
| 103 | name = posixpath.normpath(posixpath.join("/", posixpath.dirname(name), link)).lstrip("/") |
| 104 | return None |
| 105 | |
| 106 | |
| 107 | def compare(args): |
| 108 | args.output.mkdir(parents=True, exist_ok=True) |
| 109 | published = {part: archive_members(archive) for part, archive in |
| 110 | [("image", args.initramfs), ("sidecar", args.sidecar)]} |
| 111 | relocated = defaultdict(list) |
| 112 | for part, entries in published.items(): |
| 113 | for name, (kind, content, _) in entries.items(): |
| 114 | if kind == "file" and ".so" in posixpath.basename(name): |
| 115 | relocated[posixpath.basename(name), content].append((part, name)) |
| 116 | base = miniroot_members(args.installed) |
| 117 | with args.inventory.open() as inventory: |
| 118 | rows = list(csv.DictReader(inventory, delimiter="\t")) |
| 119 | errors = 0 |
| 120 | with (args.output / "package-files.tsv").open("x") as detail, (args.output / "packages.tsv").open("x") as summary: |
| 121 | matches = csv.writer(detail, delimiter="\t", lineterminator="\n") |
| 122 | totals = csv.writer(summary, delimiter="\t", lineterminator="\n") |
| 123 | matches.writerow(["binary", "version", "repository", "layer", "candidate_path", "published_path", "comparison"]) |
| 124 | totals.writerow(["binary", "version", "origin", "repository", "profiles", "input_sha256", |
| 125 | "input_files", "exact", "materialized_link", "relocated_library", "different", "unavailable"]) |
| 126 | for row in rows: |
| 127 | name, version, repo = (row[key] for key in ("binary", "version", "repository")) |
| 128 | counts = Counter() |
| 129 | source = args.installed |
| 130 | files = {} |
| 131 | digest = "" |
| 132 | try: |
| 133 | if repo == "minirootfs": |
| 134 | files = base[name, version] |
| 135 | else: |
| 136 | source = cached_apk(row, args.cache) |
| 137 | files = archive_members(source, apk=True) |
| 138 | with source.open("rb") as stream: |
| 139 | digest = hashlib.file_digest(stream, "sha256").hexdigest() |
| 140 | except (OSError, subprocess.CalledProcessError, tarfile.TarError, EOFError, KeyError) as exc: |
| 141 | print(f"{name} {version}: {exc}", flush=True) |
| 142 | counts["unavailable"] = 1 |
| 143 | errors += 1 |
| 144 | for path, candidate in files.items(): |
| 145 | for part, members in published.items(): |
| 146 | if path not in members: |
| 147 | continue |
| 148 | member = members[path] |
| 149 | exact = candidate == member[2] if repo == "minirootfs" else candidate == member |
| 150 | status = "exact" if exact else "different" |
| 151 | if not exact and repo != "minirootfs" and candidate[0] == "symlink" and member[0] == "file": |
| 152 | if resolved_member(files, path) == member: |
| 153 | status = "materialized_link" |
| 154 | matches.writerow([name, version, repo, part, path, path, status]) |
| 155 | counts[status] += 1 |
| 156 | if repo != "minirootfs" and candidate[0] == "file": |
| 157 | for part, shipped in relocated.get((posixpath.basename(path), candidate[1]), []): |
| 158 | if path != shipped: |
| 159 | matches.writerow([name, version, repo, part, path, shipped, "relocated_library"]) |
| 160 | counts["relocated_library"] += 1 |
| 161 | totals.writerow([name, version, row["source"], repo, row["profiles"], digest, len(files), |
| 162 | *[counts[k] for k in ("exact", "materialized_link", "relocated_library", "different", "unavailable")]]) |
| 163 | summary.flush() |
| 164 | detail.flush() |
| 165 | return int(errors != 0) |
| 166 | |
| 167 | |
| 168 | if __name__ == "__main__": |
| 169 | parser = argparse.ArgumentParser(description=__doc__) |
| 170 | for argument in ("inventory", "installed", "initramfs", "sidecar", "cache", "output"): |
| 171 | parser.add_argument(argument, type=Path) |
| 172 | raise SystemExit(compare(parser.parse_args())) |
| 173 | |