Release: cut over Echoion 2.0 components
Modular container CI / release-build (push) Has been cancelled
Modular container CI / release-build (push) Has been cancelled
This commit is contained in:
169 files changed
+3069
-32261
No files matched your search
Executable
+282
@@ -0,0 +1,282 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Create deterministic independent Echoion component tar.zst packages."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path, PurePosixPath
|
||||
import re
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import tempfile
|
||||
from typing import Any, NoReturn
|
||||
|
||||
|
||||
CHANNELS = {"stable", "beta", "nightly"}
|
||||
SEMVER = re.compile(
|
||||
r"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)"
|
||||
r"(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$"
|
||||
)
|
||||
|
||||
|
||||
def fail(message: str) -> NoReturn:
|
||||
raise SystemExit(f"package-components: {message}")
|
||||
|
||||
|
||||
def load_object(path: Path, label: str) -> dict[str, Any]:
|
||||
try:
|
||||
document = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, UnicodeError, json.JSONDecodeError) as error:
|
||||
fail(f"cannot read {label} {path}: {error}")
|
||||
if not isinstance(document, dict):
|
||||
fail(f"{label} must be a JSON object")
|
||||
return document
|
||||
|
||||
|
||||
def canonical(document: Any) -> bytes:
|
||||
return (
|
||||
json.dumps(
|
||||
document,
|
||||
ensure_ascii=False,
|
||||
allow_nan=False,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
).encode("utf-8")
|
||||
+ b"\n"
|
||||
)
|
||||
|
||||
|
||||
def digest(path: Path) -> str:
|
||||
value = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
value.update(chunk)
|
||||
return value.hexdigest()
|
||||
|
||||
|
||||
def component_version(stable: str, channel: str, sequence: int) -> str:
|
||||
if not SEMVER.fullmatch(stable):
|
||||
fail(f"locked component version is not stable SemVer: {stable!r}")
|
||||
if channel == "stable":
|
||||
return stable
|
||||
return f"{stable}-{channel}.{sequence}"
|
||||
|
||||
|
||||
def validate_tree(root: Path) -> list[dict[str, Any]]:
|
||||
files: list[dict[str, Any]] = []
|
||||
if root.is_symlink() or not root.is_dir():
|
||||
fail(f"component staging root is not a directory: {root}")
|
||||
for path in sorted(root.rglob("*")):
|
||||
relative = path.relative_to(root)
|
||||
pure = PurePosixPath(relative.as_posix())
|
||||
if pure.is_absolute() or ".." in pure.parts:
|
||||
fail(f"unsafe package path: {relative}")
|
||||
metadata = path.lstat()
|
||||
if stat.S_ISDIR(metadata.st_mode):
|
||||
if path.is_symlink():
|
||||
fail(f"directory symlink is forbidden: {relative}")
|
||||
continue
|
||||
if stat.S_ISLNK(metadata.st_mode):
|
||||
target = os.readlink(path)
|
||||
target_path = PurePosixPath(target)
|
||||
if not target or target_path.is_absolute() or ".." in target_path.parts:
|
||||
fail(f"unsafe package symlink: {relative} -> {target}")
|
||||
try:
|
||||
path.resolve(strict=True).relative_to(root.resolve(strict=True))
|
||||
except (OSError, RuntimeError, ValueError):
|
||||
fail(f"package symlink escapes or is dangling: {relative}")
|
||||
files.append(
|
||||
{
|
||||
"path": relative.as_posix(),
|
||||
"type": "symlink",
|
||||
"target": target,
|
||||
}
|
||||
)
|
||||
continue
|
||||
if not stat.S_ISREG(metadata.st_mode):
|
||||
fail(f"non-regular package entry: {relative}")
|
||||
files.append(
|
||||
{
|
||||
"path": relative.as_posix(),
|
||||
"type": "file",
|
||||
"size": metadata.st_size,
|
||||
"sha256": digest(path),
|
||||
"mode": stat.S_IMODE(metadata.st_mode),
|
||||
}
|
||||
)
|
||||
if not files:
|
||||
fail(f"component staging tree is empty: {root}")
|
||||
return files
|
||||
|
||||
|
||||
def is_elf(path: Path) -> bool:
|
||||
if path.is_symlink() or not path.is_file():
|
||||
return False
|
||||
with path.open("rb") as stream:
|
||||
return stream.read(4) == b"\x7fELF"
|
||||
|
||||
|
||||
def private_libraries(root: Path) -> list[str]:
|
||||
return sorted(
|
||||
path.relative_to(root).as_posix()
|
||||
for path in root.rglob("*")
|
||||
if path.parent.name == "lib" and is_elf(path)
|
||||
)
|
||||
|
||||
|
||||
def create_archive(source: Path, destination: Path, epoch: int) -> None:
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = destination.with_name(f".{destination.name}.tmp")
|
||||
temporary.unlink(missing_ok=True)
|
||||
tar = subprocess.Popen(
|
||||
[
|
||||
"tar",
|
||||
"--sort=name",
|
||||
"--format=gnu",
|
||||
f"--mtime=@{epoch}",
|
||||
"--owner=0",
|
||||
"--group=0",
|
||||
"--numeric-owner",
|
||||
"-C",
|
||||
os.fspath(source),
|
||||
"-cf",
|
||||
"-",
|
||||
".",
|
||||
],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
assert tar.stdout is not None
|
||||
compressed = subprocess.run(
|
||||
["zstd", "-19", "--threads=1", "-q", "-o", os.fspath(temporary)],
|
||||
stdin=tar.stdout,
|
||||
check=False,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
tar.stdout.close()
|
||||
tar_stderr = tar.stderr.read() if tar.stderr else b""
|
||||
tar_result = tar.wait()
|
||||
if tar_result != 0 or compressed.returncode != 0:
|
||||
temporary.unlink(missing_ok=True)
|
||||
detail = (
|
||||
tar_stderr + b"\n" + compressed.stderr
|
||||
).decode("utf-8", errors="replace").strip()
|
||||
fail(f"cannot create {destination.name}: {detail}")
|
||||
os.replace(temporary, destination)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--registry", type=Path, default=Path("components.json"))
|
||||
parser.add_argument(
|
||||
"--lock", type=Path, default=Path("components.lock.json")
|
||||
)
|
||||
parser.add_argument("--staging-root", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--channel", choices=sorted(CHANNELS), default="stable")
|
||||
parser.add_argument("--sequence", type=int, required=True)
|
||||
parser.add_argument("--product-version", required=True)
|
||||
parser.add_argument(
|
||||
"--toolchain-contract",
|
||||
default="linux-x86_64-glibc-2.35-cxx26",
|
||||
)
|
||||
arguments = parser.parse_args()
|
||||
if arguments.sequence < 1:
|
||||
fail("--sequence must be positive")
|
||||
product_match = SEMVER.fullmatch(arguments.product_version)
|
||||
if product_match is None:
|
||||
fail("--product-version must be canonical SemVer")
|
||||
|
||||
registry = load_object(arguments.registry, "component registry")
|
||||
lock = load_object(arguments.lock, "component lock")
|
||||
if registry.get("schemaVersion") != 1 or lock.get("schemaVersion") != 2:
|
||||
fail("unsupported component registry or lock schema")
|
||||
definitions = registry.get("components")
|
||||
locked_components = lock.get("components")
|
||||
if (
|
||||
not isinstance(definitions, dict)
|
||||
or not isinstance(locked_components, dict)
|
||||
or set(definitions) != set(locked_components)
|
||||
):
|
||||
fail("component registry and lock do not match")
|
||||
locked_product_match = SEMVER.fullmatch(str(lock.get("productVersion", "")))
|
||||
if locked_product_match is None or "-" in str(lock["productVersion"]):
|
||||
fail("locked productVersion must be stable SemVer")
|
||||
locked_tuple = tuple(int(value) for value in locked_product_match.groups()[:3])
|
||||
product_tuple = tuple(int(value) for value in product_match.groups()[:3])
|
||||
if arguments.channel == "stable":
|
||||
if arguments.product_version != lock["productVersion"]:
|
||||
fail("stable product version does not match the lock")
|
||||
elif (
|
||||
product_tuple[:2] != locked_tuple[:2]
|
||||
or product_tuple[2] not in (locked_tuple[2], locked_tuple[2] + 1)
|
||||
):
|
||||
fail("prerelease product version is not the locked or next patch line")
|
||||
staging_root = arguments.staging_root.resolve(strict=True)
|
||||
output = arguments.output.resolve()
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
epoch_value = os.environ.get("SOURCE_DATE_EPOCH", "0")
|
||||
if not epoch_value.isdigit():
|
||||
fail("SOURCE_DATE_EPOCH must be a non-negative integer")
|
||||
epoch = int(epoch_value)
|
||||
|
||||
with tempfile.TemporaryDirectory(
|
||||
prefix=".component-packages.", dir=output
|
||||
) as temporary:
|
||||
work_root = Path(temporary)
|
||||
for component_id in sorted(definitions):
|
||||
definition = definitions[component_id]
|
||||
locked = locked_components[component_id]
|
||||
package_id = definition["packageId"]
|
||||
source = staging_root / package_id
|
||||
version = component_version(
|
||||
locked["componentVersion"],
|
||||
arguments.channel,
|
||||
arguments.sequence,
|
||||
)
|
||||
artifact_identity = (
|
||||
f"{package_id}-{version}-linux-x86_64"
|
||||
)
|
||||
if (
|
||||
arguments.channel == "stable"
|
||||
and artifact_identity != locked["artifactIdentity"]
|
||||
):
|
||||
fail(f"artifact identity mismatch for {component_id}")
|
||||
package_root = work_root / artifact_identity
|
||||
shutil.copytree(source, package_root, symlinks=True)
|
||||
files = validate_tree(package_root)
|
||||
manifest = {
|
||||
"schemaVersion": 1,
|
||||
"componentId": component_id,
|
||||
"packageId": package_id,
|
||||
"kind": definition["kind"],
|
||||
"productVersion": arguments.product_version,
|
||||
"componentVersion": version,
|
||||
"sourceSha": locked["revision"],
|
||||
"sourceTreeHash": locked["sourceTreeHash"],
|
||||
"abiHash": locked["abiHash"],
|
||||
"activation": definition["activation"],
|
||||
"dependencies": definition["dependencies"],
|
||||
"platform": "linux",
|
||||
"architecture": "x86_64",
|
||||
"toolchainContract": arguments.toolchain_contract,
|
||||
"artifactIdentity": artifact_identity,
|
||||
"privateLibraries": private_libraries(package_root),
|
||||
"files": files,
|
||||
}
|
||||
manifest_bytes = canonical(manifest)
|
||||
(package_root / "manifest.json").write_bytes(manifest_bytes)
|
||||
archive = output / f"{artifact_identity}.tar.zst"
|
||||
create_archive(package_root, archive, epoch)
|
||||
(output / f"{artifact_identity}.manifest.json").write_bytes(
|
||||
manifest_bytes
|
||||
)
|
||||
print(f"packaged {component_id}: {archive.name}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user