Battam's picture
Release [run release-20261109T032054Z] (#2)
cc02077
Raw History Blame
26.3 kB
"""Lay out a batch fetched with fetch.py as a task pool: one folder per domain and source, the unit files under
their paths, a README.md and a LICENSE per source, and _meta/ with manifest.jsonl, sizes.tsv and delivery.json.
fetch.py itself writes the files in its own layout (<domain>/<source>/<unit folder>/..., _meta/manifest.jsonl
and _meta/sizes.tsv) and writes each unit as recorded: a unit stored inside another file (transform steps such as
unzip:<member>) is made out of the downloaded file and checked against the unit's recorded sha256 there. So most
selections need no second step. This script does only what fetch.py does not: it unpacks units marked expand into
folders, measures the decompressed size of single-file compressed units, checks that every source has its README.md
and LICENSE, writes _meta/delivery.json and the pool layout (files at their pool paths, as the pool builder does),
and extracts units (transform) from the output of fetch.py versions that delivered them as
fetched. It needs unpack.py, archive_formats.py, archive_formats.tsv and transform.py from tools/ next to it.
Input is the --out folder of a fetch.py run over a collection tag (campaign:<name>): its _meta/fetch_manifest.jsonl
and _meta/fetch_run.json (fetch_manifest.jsonl and fetch_run.json at the top of the folder for output of fetch.py
before the layout). The rows of such a collection carry their place in the pool (pool_domain, pool_path,
unit_group, pool_fields and the others fetch.py copies into the manifest). Every row must have been
fetched (status ok); otherwise nothing is written.
Layout of <out>/<name>/:
<domain>/<source>/<path> a unit file (the path as given by the selection)
<domain>/<source>/<package folder>/... files written for a package (such as its README.md or a run
script), listed with their full text in authored_files on the
first manifest line of the package
<domain>/<source>/README.md, LICENSE one each per source
_meta/manifest.jsonl one line per unit file (a row with pool_fields): source, path, url,
sha256, bytes, spdx, licence_url, publisher, origin_kind, retrieved,
and the other fields recorded for the unit (agency for works of a
government agency, need, package, ...)
_meta/sizes.tsv one line per source, no header: leaf, source, origin, bytes of the
source folder, license, license tier
_meta/delivery.json repository, revision, fetch.py arguments and row count of the run;
local paths in the arguments are written as placeholders (<data>,
<out>, <temp-dir>, <path>), so the file is the same on any machine
A unit with transform steps (unzip:<member>, untar:<member>, bunzip2, gunzip, unxz, unxxd, uudecode, uncompress,
gzip) is extracted by fetch.py (its fetch manifest line says extracted) and is copied here, checked against the
sha256 of that line. Output of an older fetch.py holds the upstream original instead; it is extracted here with
transform.py (only the named member, at most
256,000,000 bytes out of unxz, untar, unxxd, uudecode and uncompress) and checked against the index: its sha256, or
when the last step is gzip (whose bytes depend on the zlib build) the sha256 of the bytes before that step
(content_sha256).
Its manifest line keeps transform, upstream_sha256, upstream_bytes and content_sha256, so the unit can be checked
again by downloading the upstream original and extracting it the same way. A row marked
rolling may differ from the index; the manifest then keeps the bytes, sha256 and date actually downloaded and
sets differs_from_index.
A unit that is one compressed file (.gz, .bz2, .xz, .zst around a single file; not .tar.gz and the like) is
delivered as it is; its manifest line gets compression and decompressed_bytes, measured by decompressing it as a
stream and counting the bytes, without writing the decompressed file. If that measurement fails (damaged data, a
different format, a tar inside, no zstd decoder before Python 3.14), the build stops and names the unit and the
reason.
The result counts the units by how fetch.py obtained them (obtained: reused or staged from a local file whose
sha256 matched, fetched, already_present); the pool manifest does not carry this.
A unit marked expand is also unpacked into <domain>/<source>/_expanded/<unit path>/, and its manifest line gets
expanded: "_expanded/<unit path>" and expand_rule, the rule that marked it. The rule and the unpacking live in
unpack.py, shared with the pool builder: a unit is marked when the format table (archive_formats.tsv)
classes it as a multi-member archive meant to be used as a folder (zip, tar and its compressed forms, 7z, rar);
single-file compression and zip-based containers (xlsx, npz, docx and the like) are files. The pool format's limits
apply and are counted while unpacking, which stops at the first excess: every file and every unpacked folder is at
most 20,000,000 bytes, and a source holds at most 400,000 files across all its archives. An archive that cannot be
unpacked (unsafe member path, link or special member, nested archive, a format unpack.py cannot unpack, over a
limit) is not unpacked: its manifest line gets expand_failed with the reason, the result lists it, and the archive
itself stays in the pool as a file unit.
Uses the Python standard library only (measuring a .zst unit needs Python 3.14 or later).
Example:
python tools/fetch.py --tag campaign:<name> --all --revision <commit> --out ./fetched
python tools/to_pool.py ./fetched --out ./pools --name <name>
Deletes: a unit copied from the fetch output whose sha256 differs from its fetch manifest line (place): a
byte-identical copy exists, the fetched file under the fetch folder it was copied from.
Deletes: a unit extracted with transform.py whose sha256 differs from the index (place): recomputable, by
transform.apply from the fetched upstream file under the fetch folder.
"""
from __future__ import annotations
import argparse
import bz2
import gzip
import hashlib
import importlib
import json
import lzma
import os
import posixpath
import re
import shutil
import sys
from pathlib import Path
try:
from . import public_transform as transform
except ImportError:
try:
import transform
except ImportError:
import public_transform as transform
try: # the shipped tools/ folder holds unpack.py, archive_formats.py and archive_formats.tsv next to this file
from . import unpack
from .facts import archive_formats as AF
except ImportError:
import unpack
import archive_formats as AF
MANIFEST = "fetch_manifest.jsonl"
RUN_FILE = "fetch_run.json"
META = "_meta"
NAME = re.compile(r"^[a-z0-9._-]+$")
TAG_PREFIX = "campaign:"
EXPANDED = "_expanded"
# the pool format's limits: a file or directory unit is at most 20,000,000 bytes
# (max_unit_bytes); a source holds at most 400,000 files
MAX_UNIT_BYTES = unpack.MAX_UNIT_BYTES
MAX_SOURCE_FILES = unpack.MAX_SOURCE_FILES
class PoolError(ValueError):
pass
# fetch.py records its arguments as given, so --data and --out hold paths of the machine that ran it (its home
# folder, its working folders). delivery.json travels with the pool: kept as is, it would show the paths of the
# machine that built it, and on another machine the same field would record that machine's paths. Local paths are
# therefore written as fixed placeholders; what a reader needs (revision, tags, filters, which options were given) stays as it was.
PATH_OPTIONS = {"--data": "<data>", "--out": "<out>", "--temp-dir": "<temp-dir>"}
PATH_PLACEHOLDER = "<path>"
_URL = re.compile(r"^[a-z][a-z0-9+.-]*://", re.I)
_ABS = re.compile(r"^(/|~|\\\\|[a-z]:[\\/])", re.I)
def _homes() -> list:
out = []
for h in (os.path.expanduser("~"), os.environ.get("HOME"), os.environ.get("USERPROFILE")):
if h and len(h) > 1 and h not in out:
out.append(h)
return out
def _local_path(value: str, homes: list) -> bool:
if _URL.match(value):
return False
return bool(_ABS.match(value)) or any(h in value for h in homes)
def portable_fetch_args(args) -> list | None:
"""fetch.py arguments with every local path replaced by a fixed placeholder (URLs are kept)."""
if args is None:
return None
homes, out, pending = _homes(), [], None
for a in args:
a = str(a)
if pending is not None:
out.append(a if _URL.match(a) else pending)
pending = None
continue
opt, eq, val = a.partition("=")
if opt in PATH_OPTIONS:
if eq:
out.append(f"{opt}={val if _URL.match(val) else PATH_OPTIONS[opt]}")
else:
out.append(a)
pending = PATH_OPTIONS[opt]
continue
if eq and opt.startswith("--") and _local_path(val, homes):
out.append(f"{opt}={PATH_PLACEHOLDER}")
elif _local_path(a, homes):
out.append(PATH_PLACEHOLDER)
else:
out.append(a)
return out
def sha256_file(path: Path) -> str:
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def safe_rel(rel) -> str:
"""A relative path inside the pool: no absolute path, no empty, '.' or '..' part, no backslash."""
if not isinstance(rel, str) or not rel or rel.startswith("/") or "\\" in rel:
raise PoolError(f"unsafe path: {rel!r}")
parts = rel.split("/")
if any(p in ("", ".", "..") for p in parts):
raise PoolError(f"unsafe path: {rel!r}")
return posixpath.join(*parts)
def safe_name(name, what: str) -> str:
if not isinstance(name, str) or not name or "/" in name or "\\" in name or name in (".", ".."):
raise PoolError(f"unsafe {what}: {name!r}")
return name
def read_jsonl(path: Path) -> list:
with open(path, encoding="utf-8") as f:
return [json.loads(line) for line in f if line.strip()]
def campaign_rows(lines: list, campaign: str | None) -> tuple:
"""-> (collection name, its manifest lines). Lines without a collection are ignored; more than one collection
needs campaign."""
names = sorted({x["campaign"] for x in lines if x.get("campaign")})
if campaign is not None:
if campaign.startswith(TAG_PREFIX):
campaign = campaign[len(TAG_PREFIX):]
if campaign not in names:
raise PoolError(f"no row of collection {campaign!r} in the manifest (found: {', '.join(names) or 'none'})")
elif len(names) == 1:
campaign = names[0]
elif not names:
raise PoolError("no row of the manifest belongs to a collection (fetch with --tag campaign:<name>)")
else:
raise PoolError(f"the manifest holds several collections ({', '.join(names)}); choose one with --campaign")
return campaign, [x for x in lines if x.get("campaign") == campaign]
def fetched_file(fetch_dir: Path, x: dict) -> Path:
"""The downloaded file of a manifest row, looked up under the fetch output folder only (never the current
directory): an absolute path is used when it lies inside that folder; a relative path is tried as given under
the folder and from its <source>/<collection> part on (fetch.py records the --out it was given, which may have
been relative to another directory); last, <source>/<collection>/<pool_path> under the folder."""
root = fetch_dir.resolve()
source, coll = x.get("source"), x.get("collection") or x.get("campaign")
cands = []
if x.get("layout_path"): # where fetch.py put it in its layout, relative to its --out
cands.append(root.joinpath(*safe_rel(x["layout_path"]).split("/")))
if x.get("path"):
p = Path(x["path"])
if p.is_absolute():
if p.resolve().is_relative_to(root):
cands.append(p)
else:
parts = [q for q in p.parts if q not in ("", ".")]
if parts and ".." not in parts:
cands.append(root.joinpath(*parts))
cands += [root.joinpath(*parts[i:]) for i in range(1, len(parts) - 1)
if parts[i] == source and parts[i + 1] == coll]
for c in cands:
if c.is_file():
return c
c = root.joinpath(safe_name(source, "source"), safe_name(coll, "collection"),
*safe_rel(x.get("pool_path")).split("/"))
if c.is_file():
return c
raise PoolError(f"{x.get('source')} {x.get('pool_path')}: downloaded file not found under {fetch_dir}")
def check_rows(rows: list) -> None:
bad = [x for x in rows if x.get("status") != "ok"]
if bad:
shown = "; ".join(f"{x.get('source')} {x.get('pool_path')}: {x.get('status')} {x.get('reason') or ''}".strip()
for x in bad[:10])
raise PoolError(f"{len(bad)} row(s) were not fetched, nothing written ({shown})")
for x in rows:
for k in ("pool_domain", "pool_path", "pool_source"):
if x.get(k) in (None, ""):
raise PoolError(f"{x.get('source')} {x.get('pool_path')}: field {k} missing")
seen = set()
for x in rows:
key = (x["pool_domain"], x["source"], x["pool_path"])
if key in seen:
raise PoolError(f"two rows for {'/'.join(key)}")
seen.add(key)
def place(fetch_dir: Path, x: dict, dest: Path) -> dict:
"""Copy (or extract) one fetched row to dest. -> {sha256, bytes}, plus content_sha256 for an extracted unit."""
src = fetched_file(fetch_dir, x)
dest.parent.mkdir(parents=True, exist_ok=True)
if x.get("transform") is not None and x.get("extracted"):
# fetch.py already made the unit and checked it against the index: copy it, checked against its line
shutil.copyfile(src, dest)
sha = sha256_file(dest)
if sha != x.get("sha256"):
dest.unlink(missing_ok=True)
raise PoolError(f"{x['source']} {x['pool_path']}: sha256 {sha} differs from the fetch manifest "
f"({x.get('sha256')})")
return {"sha256": sha, "bytes": dest.stat().st_size, "content_sha256": x.get("content_sha256") or sha}
if x.get("transform") is not None:
got = transform.apply(src, x["transform"], dest)
want, want_c = x.get("unit_sha256"), x.get("content_sha256")
# gzip output depends on the zlib build: the bytes before a final gzip step decide
same = got["sha256"] == want or (want_c is not None and got["content_sha256"] == want_c)
if (want or want_c) and not same:
dest.unlink(missing_ok=True)
raise PoolError(f"{x['source']} {x['pool_path']}: extracted sha256 {got['sha256']} differs from the "
f"index ({want})")
return {"sha256": got["sha256"], "bytes": got["bytes"], "content_sha256": got["content_sha256"]}
shutil.copyfile(src, dest)
return {"sha256": sha256_file(dest), "bytes": dest.stat().st_size}
def unit_line(x: dict, got: dict, date: str) -> dict:
"""The manifest line of a unit: the recorded fields in their order, with sha256, bytes, retrieved and
fetched_from from this run. An extracted unit also keeps its transform steps, the sha256 and size of the
upstream original and content_sha256 (the bytes before a final gzip step), which a later check needs to
download the original again and extract it the same way."""
m = {}
for k, v in x["pool_fields"]:
m[k] = v
m["sha256"], m["bytes"] = got["sha256"], got["bytes"]
m["retrieved"] = x.get("retrieved") or date
if x.get("url"):
m["fetched_from"] = x["url"]
else:
m.pop("fetched_from", None)
if x.get("transform") is not None:
m["transform"] = list(x["transform"])
for k in ("upstream_sha256", "upstream_bytes"):
if x.get(k) is not None:
m[k] = x[k]
m["content_sha256"] = got["content_sha256"]
if x.get("differs_from_index"):
m["differs_from_index"] = True
m["expected_bytes"] = x.get("expected_bytes")
m["expected_sha256"] = x.get("expected_sha256")
return m
# A unit that is one file stored compressed (gzip, bzip2, xz, zstd around a single file) is delivered as it is. Its
# manifest line gets compression and decompressed_bytes, measured here by decompressing it as a stream and counting
# the bytes (nothing is written), so the delivery notes can say how much space each needs once decompressed. A tar
# inside (.tar.gz and the like) is an archive of several files, not one file, and is not counted here.
# Which units are single-file compression is decided by the format table (archive_formats.tsv, class
# single_file_compression), read through archive_formats.place; the table's tar forms (.tar.gz and the like) are
# multi-member archives and are not counted here. DECODERS names the decoder per table format; a table format with
# no decoder here (lz4, Z) is not measured.
DECODERS = {"gz": "gzip", "bz2": "bzip2", "xz": "xz", "zst": "zstd"}
COMPRESSED_MAGIC = {DECODERS[f]: AF.FORMATS[f].magic for f in DECODERS}
_CHUNK = 1 << 20
class MeasureError(ValueError):
pass
def single_file_compression(name: str) -> str | None:
"""The compression format of a unit that is one compressed file, judged by its name through the format table;
None for anything else."""
pl = AF.place(str(name))
return DECODERS.get(pl.format) if pl.cls == AF.COMPRESSION else None
def _zstd_reader(f, zstd_opener=None):
try:
zstd = importlib.import_module("compression.zstd") # in the standard library from Python 3.14
except ImportError:
if zstd_opener is None:
raise MeasureError("no zstd decoder in this Python (the standard library has one from Python 3.14)") \
from None
return zstd_opener(f)
return zstd.ZstdFile(f)
def decompressed_size(path, fmt: str, zstd_opener=None) -> int:
"""Decompress the file at path as a stream and count the bytes; nothing is written. Raises MeasureError with
the reason when the file is not that format, is damaged or truncated, or holds a tar archive."""
path = Path(path)
try:
with open(path, "rb") as raw:
head = raw.read(len(COMPRESSED_MAGIC[fmt]))
if head != COMPRESSED_MAGIC[fmt]:
raise MeasureError(f"not a {fmt} file (it starts with {head.hex() or 'nothing'})")
raw.seek(0)
opener = {"gzip": gzip.GzipFile, "bzip2": bz2.BZ2File, "xz": lzma.LZMAFile}.get(fmt)
f = opener(fileobj=raw) if fmt == "gzip" else opener(raw) if opener else _zstd_reader(raw, zstd_opener)
n, first = 0, b""
with f:
while True:
b = f.read(_CHUNK)
if not b:
break
if len(first) < 512:
first += b[:512 - len(first)]
n += len(b)
except MeasureError:
raise
except Exception as e: # damaged or truncated data: zlib, lzma, bz2, zstd and EOF errors all end up here
raise MeasureError(f"cannot decompress: {type(e).__name__}: {e}") from None
if first[257:262] == b"ustar":
raise MeasureError(f"the {fmt} file holds a tar archive, not a single file")
return n
def measure_compressed(path, name: str, zstd_opener=None) -> dict | None:
"""-> {"compression", "decompressed_bytes"} for a unit that is one compressed file, None for any other unit.
zstd_opener (a function from a binary file to a readable stream) is used for .zst when this Python has no zstd
decoder of its own."""
fmt = single_file_compression(name)
if fmt is None:
return None
return {"compression": fmt, "decompressed_bytes": decompressed_size(path, fmt, zstd_opener)}
def is_unit_file(x: dict) -> bool:
"""#1633: a unit's own file, the row whose pool_fields hold its line of the pool manifest; the other rows are files
the index wrote (a package's README.md, the source's README.md and LICENSE)."""
return isinstance(x.get("pool_fields"), list)
def order_key(x: dict) -> tuple:
src = (x.get("pool_source") or {}).get("order", 0)
o = x.get("pool_order") or [src, -1]
return (src, o[1] if x.get("unit_group") else 1 << 30, not is_unit_file(x), x["pool_path"])
def build(fetch_dir, out, name: str, *, campaign: str | None = None, max_unit_bytes: int = MAX_UNIT_BYTES,
max_source_files: int = MAX_SOURCE_FILES) -> dict:
fetch_dir = Path(fetch_dir)
if not NAME.match(name or ""):
raise PoolError(f"batch folder name may only use lowercase letters, digits and . _ -: {name!r}")
run_p, man_p = fetch_dir / META / RUN_FILE, fetch_dir / META / MANIFEST
if not run_p.is_file() or not man_p.is_file():
run_p, man_p = fetch_dir / RUN_FILE, fetch_dir / MANIFEST
if not run_p.is_file() or not man_p.is_file():
raise PoolError(f"{fetch_dir} is not a fetch.py output folder ({META}/{RUN_FILE} and {META}/{MANIFEST} are "
f"needed)")
run = json.loads(run_p.read_text(encoding="utf-8"))
campaign, rows = campaign_rows(read_jsonl(man_p), campaign)
check_rows(rows)
root = Path(out) / name
if root.exists() and any(root.iterdir()):
raise PoolError(f"{root} exists and is not empty")
date = run.get("date")
rows = sorted(rows, key=order_key)
manifest, sources, expands, obtained = [], {}, [], {}
for x in rows:
domain = safe_name(x["pool_domain"], "domain")
source = safe_name(x["source"], "source")
rel = safe_rel(x["pool_path"])
dest = root.joinpath(domain, source, *rel.split("/"))
got = place(fetch_dir, x, dest)
sources.setdefault((domain, source), x["pool_source"])
if is_unit_file(x):
how = x.get("obtained") or ("already_present" if x.get("already_present") else "not_recorded")
obtained[how] = obtained.get(how, 0) + 1
line = unit_line(x, got, date)
try:
measured = measure_compressed(dest, rel)
except MeasureError as e:
raise PoolError(f"{source} {rel}: decompressed size not measured, the build stops for this unit: {e}")
if measured:
line.update(measured)
manifest.append(line)
if x.get("expand"):
expands.append((domain, source, rel, dest, manifest[-1], x.get("expand_rule")))
expand_failed, counts = [], {}
for domain, source, rel, dest, m, rule in expands:
sd = root / domain / source
if (domain, source) not in counts: # one count per source, shared by all its archives
counts[(domain, source)] = unpack.SourceFiles.of_dir(sd, max_source_files)
r = unpack.expand(dest, sd.joinpath(EXPANDED, *rel.split("/")), files=counts[(domain, source)],
max_bytes=max_unit_bytes)
m["expand_rule"] = rule or unpack.EXPAND_RULE
if r["status"] != "ok":
m["expand_failed"] = r["reason"]
expand_failed.append({"source": source, "path": rel, "reason": r["reason"]})
else:
m["expanded"] = f"{EXPANDED}/{rel}"
sizes = []
for (domain, source), ps in sorted(sources.items(), key=lambda kv: kv[1].get("order", 0)):
sd = root / domain / source
missing = [f for f in ("README.md", "LICENSE") if not (sd / f).is_file()]
if missing:
raise PoolError(f"{source}: {' and '.join(missing)} missing from the fetched rows")
total = sum(p.stat().st_size for p in sd.rglob("*") if p.is_file())
sizes.append([str(ps.get("leaf")), source, str(ps.get("origin")), str(total), str(ps.get("licence")),
str(ps.get("tier"))])
meta = root / META
meta.mkdir(parents=True, exist_ok=True)
(meta / "sizes.tsv").write_bytes("".join("\t".join(r) + "\n" for r in sizes).encode("utf-8"))
(meta / "manifest.jsonl").write_bytes("".join(json.dumps(m, ensure_ascii=False) + "\n" for m in manifest)
.encode("utf-8"))
delivery = {"repo": run.get("repo"), "revision": run.get("revision"),
"fetch_args": portable_fetch_args(run.get("fetch_args")), "rows": len(rows)}
if expands:
delivery["expanded"] = len(expands) - len(expand_failed)
delivery["expand_failed"] = expand_failed
(meta / "delivery.json").write_bytes((json.dumps(delivery, ensure_ascii=False, indent=1) + "\n").encode("utf-8"))
return {"pool": str(root), "campaign": campaign, "sources": len(sizes), "units": len(manifest), "rows": len(rows),
"differs_from_index": sum(1 for m in manifest if m.get("differs_from_index")), "obtained": obtained,
**({"expanded": len(expands) - len(expand_failed), "expand_failed": expand_failed} if expands else {})}
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description="Lay out a fetched collection (fetch.py --tag campaign:<name>) as a "
"task pool.")
ap.add_argument("fetched", help="the --out folder of the fetch.py run")
ap.add_argument("--out", required=True, help="folder that receives the batch folder")
ap.add_argument("--name", required=True, help="batch folder name (lowercase letters, digits and . _ -)")
ap.add_argument("--campaign", help="collection to lay out when the fetch covered several (name or campaign:<name>)")
args = ap.parse_args(argv)
try:
res = build(args.fetched, args.out, args.name, campaign=args.campaign)
except (PoolError, ValueError, OSError) as e:
print(f"error: {e}", file=sys.stderr)
return 1
print(json.dumps(res, sort_keys=True))
return 0
if __name__ == "__main__":
sys.exit(main())