From ffc62c792c9a5196cb4ce7a353287dfe20db6524 Mon Sep 17 00:00:00 2001 From: Christoph Berg Date: Fri, 9 Oct 2026 14:12:35 +0200 Subject: New upstream version 3.3.0~beta1+dfsg --- .github/scripts/armhf-ci-image-config.sh | 13 +- .github/scripts/armhf-static-ldd.sh | 6 +- .github/scripts/armhf-toolchain-config.sh | 17 + .../scripts/audit-staged-dll-imports-windows.sh | 18 +- .github/scripts/beta-scheduler.py | 798 ++++++++++++ .github/scripts/build-fftw-macos.sh | 2 +- .github/scripts/build-linux-armhf-cross.sh | 15 +- .github/scripts/generate-quick-downloads.py | 13 +- .github/scripts/is-linux-ci-image-input.sh | 2 + .github/scripts/linux-artifact-validation.sh | 10 +- .github/scripts/linux-ci-image-inputs.sh | 2 + .github/scripts/linuxdeploy-excludelist.txt | 55 + .github/scripts/package-cli-tools.sh | 499 +++++++ .github/scripts/package-linux-armhf.sh | 45 +- .github/scripts/release-linux-images.py | 202 +++ .github/scripts/release-policy.py | 463 ++++++- .github/scripts/select-linux-packaging.sh | 102 +- .github/scripts/smoke-release-tarballs.sh | 123 ++ .github/scripts/summarize-native-caches.py | 67 + .../tests/test_armhf_cross_configuration.py | 59 +- .../scripts/tests/test_armhf_sysroot_symlinks.py | 2 +- .github/scripts/tests/test_beta_scheduler.py | 1368 ++++++++++++++++++++ .github/scripts/tests/test_check_candidate_tag.py | 2 + .github/scripts/tests/test_ghcr_retention.py | 11 + .github/scripts/tests/test_linux_ccache_policy.py | 189 ++- .../tests/test_linux_image_publication_policy.py | 252 +++- .github/scripts/tests/test_native_cache_policy.py | 86 ++ .github/scripts/tests/test_package_cli_tools.py | 745 +++++++++++ .github/scripts/tests/test_release_linux_images.py | 158 +++ .github/scripts/tests/test_release_policy.py | 1156 ++++++++++++++++- .../scripts/tests/test_release_workflow_policy.py | 186 +++ .github/scripts/third-party-libraries.tsv | 27 + .github/scripts/validate-ci-inputs.sh | 29 +- .github/scripts/validate-linux-armhf-runtime.sh | 4 +- .github/scripts/validate-workflow-timeouts.py | 14 + .github/scripts/verify-armhf-ci-image.sh | 1 + .github/scripts/verify-macos-artifacts.sh | 14 +- 37 files changed, 6532 insertions(+), 223 deletions(-) create mode 100755 .github/scripts/armhf-toolchain-config.sh create mode 100644 .github/scripts/beta-scheduler.py create mode 100644 .github/scripts/linuxdeploy-excludelist.txt create mode 100755 .github/scripts/package-cli-tools.sh create mode 100644 .github/scripts/release-linux-images.py create mode 100755 .github/scripts/smoke-release-tarballs.sh create mode 100644 .github/scripts/summarize-native-caches.py create mode 100644 .github/scripts/tests/test_beta_scheduler.py create mode 100644 .github/scripts/tests/test_native_cache_policy.py create mode 100644 .github/scripts/tests/test_package_cli_tools.py create mode 100644 .github/scripts/tests/test_release_linux_images.py create mode 100644 .github/scripts/tests/test_release_workflow_policy.py create mode 100644 .github/scripts/third-party-libraries.tsv (limited to '.github/scripts') diff --git a/.github/scripts/armhf-ci-image-config.sh b/.github/scripts/armhf-ci-image-config.sh index 6e97c2f0..85b95523 100755 --- a/.github/scripts/armhf-ci-image-config.sh +++ b/.github/scripts/armhf-ci-image-config.sh @@ -6,23 +6,14 @@ _armhf_config_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)" # shellcheck source=.github/scripts/linux-ci-image-config.sh . "$_armhf_config_dir/linux-ci-image-config.sh" +# shellcheck source=.github/scripts/armhf-toolchain-config.sh +. "$_armhf_config_dir/armhf-toolchain-config.sh" unset _armhf_config_dir ARMHF_CI_IMAGE_SCHEMA=1 -ARMHF_CROSSTOOL_NG_VERSION=1.28.0 -ARMHF_CROSSTOOL_NG_SHA256=5750e29a2bda5cd8d67900592576b1670a1987a4dcd5e4f6beae09138a1f5699 -ARMHF_CROSSTOOL_NG_URL="https://github.com/crosstool-ng/crosstool-ng/releases/download/crosstool-ng-${ARMHF_CROSSTOOL_NG_VERSION}/crosstool-ng-${ARMHF_CROSSTOOL_NG_VERSION}.tar.xz" - -ARMHF_TARGET_TRIPLET=arm-linux-gnueabihf -ARMHF_TOOLCHAIN_PREFIX=/opt/wsjtx/armhf-toolchain ARMHF_SYSROOT=/opt/wsjtx/armhf-sysroot ARMHF_RUNTIME_PREFIX=/opt/wsjtx/armhf-runtime ARMHF_QEMU_EXECUTABLE=/usr/local/bin/qemu-arm-static -ARMHF_GCC_VERSION=13.4.0 -ARMHF_GLIBC_VERSION=2.36 -ARMHF_BINUTILS_VERSION=2.40 -ARMHF_LINUX_HEADERS_VERSION=6.1.147 -ARMHF_MIN_KERNEL_VERSION=3.2.0 ARMHF_SYSROOT_PACKAGES=( libc6-dev libstdc++6 libgfortran5 libgomp1 libatomic1 diff --git a/.github/scripts/armhf-static-ldd.sh b/.github/scripts/armhf-static-ldd.sh index bb85e6f3..50cecc61 100755 --- a/.github/scripts/armhf-static-ldd.sh +++ b/.github/scripts/armhf-static-ldd.sh @@ -1,9 +1,9 @@ #!/usr/bin/env bash set -euo pipefail -# linuxdeploy's ldd probe crashes when an ARM loader is nested under user-mode -# QEMU. Resolve DT_NEEDED entries from the clean ARMHF runtime without executing -# the target; packaged runtime behavior is still proved by the QEMU smoke test. +# Resolve DT_NEEDED entries from the clean ARMHF runtime without executing the +# target, so linuxdeploy sees the runtime prefix first and a libquadmath +# dependency fails; the AppImage startup smoke test proves runtime behavior. if [ "$#" -ne 1 ]; then echo "Usage: armhf-static-ldd.sh ELF" >&2 diff --git a/.github/scripts/armhf-toolchain-config.sh b/.github/scripts/armhf-toolchain-config.sh new file mode 100755 index 00000000..bcd44613 --- /dev/null +++ b/.github/scripts/armhf-toolchain-config.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash + +# Pinned inputs for the native ARMHF cross-toolchain. +# shellcheck disable=SC2034 + +ARMHF_TOOLCHAIN_REBUILD_REVISION=1 +ARMHF_CROSSTOOL_NG_VERSION=1.28.0 +ARMHF_CROSSTOOL_NG_SHA256=5750e29a2bda5cd8d67900592576b1670a1987a4dcd5e4f6beae09138a1f5699 +ARMHF_CROSSTOOL_NG_URL="https://github.com/crosstool-ng/crosstool-ng/releases/download/crosstool-ng-${ARMHF_CROSSTOOL_NG_VERSION}/crosstool-ng-${ARMHF_CROSSTOOL_NG_VERSION}.tar.xz" + +ARMHF_TARGET_TRIPLET=arm-linux-gnueabihf +ARMHF_TOOLCHAIN_PREFIX=/opt/wsjtx/armhf-toolchain +ARMHF_GCC_VERSION=13.4.0 +ARMHF_GLIBC_VERSION=2.36 +ARMHF_BINUTILS_VERSION=2.40 +ARMHF_LINUX_HEADERS_VERSION=6.1.147 +ARMHF_MIN_KERNEL_VERSION=3.2.0 diff --git a/.github/scripts/audit-staged-dll-imports-windows.sh b/.github/scripts/audit-staged-dll-imports-windows.sh index ca8b75f2..464faf7e 100644 --- a/.github/scripts/audit-staged-dll-imports-windows.sh +++ b/.github/scripts/audit-staged-dll-imports-windows.sh @@ -38,8 +38,14 @@ for exe in "$@"; do fi echo "::group::DLL imports for $exe" + if ! import_metadata=$(objdump -p "$exe"); then + echo "::error::Could not inspect DLL imports for $exe" + echo "::endgroup::" + fail=1 + continue + fi imports=$( - objdump -p "$exe" | + printf '%s\n' "$import_metadata" | awk '/DLL Name:/ {print $3}' | sort -u ) @@ -50,8 +56,16 @@ for exe in "$@"; do echo "(none)" fi + if [ "$(basename "$exe" | tr '[:upper:]' '[:lower:]')" = jt9.exe ]; then + qt_imports=$(printf '%s\n' "$imports" | awk 'tolower($0) ~ /^qt.*\.dll$/') + if [ -n "$qt_imports" ]; then + echo "::error::$exe must not depend on Qt: $qt_imports" + fail=1 + fi + fi + win7_blocked_imports=$( - objdump -p "$exe" | + printf '%s\n' "$import_metadata" | awk ' /DLL Name:/ { dll=tolower($3) } /api-ms-win-core-synch-l1-2-0\.dll/ { print "api-ms-win-core-synch-l1-2-0.dll" } diff --git a/.github/scripts/beta-scheduler.py b/.github/scripts/beta-scheduler.py new file mode 100644 index 00000000..925703ee --- /dev/null +++ b/.github/scripts/beta-scheduler.py @@ -0,0 +1,798 @@ +#!/usr/bin/env python3 +"""Advance the scheduled beta line by one state-machine step per workflow run.""" + +from __future__ import annotations + +import argparse +import base64 +import importlib.util +import io +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys +import tempfile +import textwrap +import traceback +from typing import Callable, NamedTuple +import urllib.error +import urllib.parse +import urllib.request +import zipfile + + +def load_script(name: str, filename: str): + spec = importlib.util.spec_from_file_location(name, Path(__file__).with_name(filename)) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +policy = load_script("release_policy", "release-policy.py") +images = load_script("release_linux_images", "release-linux-images.py") +image_tags = load_script("resolve_linux_ci_image_tag", "resolve-linux-ci-image-tag.py") + +PUBLIC_REPOSITORY = "WSJTX/wsjtx" +ALERT_TITLE = "Scheduled beta alerts" +ALERT_CREATOR = "github-actions[bot]" +STATE_FILE = "release-state.txt" +LOCK_FILE = "release-linux-images.json" +METADATA_FILES = frozenset((STATE_FILE, LOCK_FILE)) +PREPARED_ARTIFACT = "prepared-release-dependencies" +IMAGE_PACKAGES = ( + image_tags.NORMAL_PACKAGE, + image_tags.ARM64_PACKAGE, + image_tags.ARMHF_CROSS_PACKAGE, + image_tags.ARMHF_PACKAGE, +) +CI = "ci.yml" +CANDIDATE = "release-tag-helper.yml" +PROMOTION = "promote-release.yml" +PREPARATION = "prepare-release-dependencies.yml" +WARMER = "warm-dependency-caches.yml" +PUBLISHER = "publish-linux-ci-images.yml" +PUBLICATION = "public-release.yml" +BETA_CUT = "beta-cut.yml" +IMAGE_REFRESH_JOB = "refresh-linux-images" +NORMAL_IMAGES_JOB = "build-normal" +CANDIDATE_TITLE = re.compile(r"Prepare Release Candidate build/v(?P\S+) \((?Pvalidate|create)\)") +PREPARATION_TITLE = re.compile(r"Prepare Release Dependencies (?P\S+) (?P\S+)") +GENERATION_TAG = re.compile(r"validated-build-\d{8}-(?P\d+)-(?P\d+)") + + +class Skip(Exception): + """Nothing to do now; a later run tries again. Reported in the job summary only.""" + + +class Stop(Exception): + """A person must act. Reported in the job summary and on the tracking issue.""" + + def __init__(self, stage: str, reason: str, link: str | None = None) -> None: + super().__init__(reason) + self.stage = stage + self.link = link + + +class Spent(Exception): + """The candidate failed after its build tag was pushed; build tags never move, so the number is used up.""" + + def __init__(self, reason: str, link: str | None = None) -> None: + super().__init__(reason) + self.link = link + + +class Line(NamedTuple): + branch: str + tip: str + version: str + number: int + + def prerelease(self, number: int | None = None) -> str: + return f"{self.version}-beta{self.number if number is None else number}" + + +class Commit(NamedTuple): + sha: str + author_email: str + files: tuple[str, ...] + + +def candidate_tag(version: str) -> str: + return f"build/v{version}" + + +def in_flight(run: dict) -> bool: + return run.get("status") != "completed" + + +def run_order(run: dict) -> tuple[str, int]: + return run.get("created_at") or "", run.get("id") or 0 + + +def newest(runs: list[dict]) -> dict | None: + return max(runs, key=run_order, default=None) + + +def candidate_of(run: dict) -> tuple[str, str] | None: + match = CANDIDATE_TITLE.fullmatch(run.get("display_title") or "") + return (match["version"], match["operation"]) if match else None + + +def preparation_of(run: dict) -> tuple[str, str] | None: + match = PREPARATION_TITLE.fullmatch(run.get("display_title") or "") + return (match["source"], match["generation"]) if match else None + + +def render_state(version: str, number: int) -> str: + return f"version={version}\nchannel=BETA\nprerelease={number}\nrevision=$Format:%H$\nwindows_signing=unsigned\n" + + +def git_identity(name: str, email: str) -> dict[str, str]: + return {"GIT_AUTHOR_NAME": name, "GIT_AUTHOR_EMAIL": email, + "GIT_COMMITTER_NAME": name, "GIT_COMMITTER_EMAIL": email} + + +def lock_recipes(lock: bytes | None) -> dict[str, str] | None: + try: + selected = json.loads(lock)["images"] + return {key: selected[key]["recipe_sha256"] for key in images.IMAGES} + except (TypeError, ValueError, KeyError): + return None + + +def lock_generation(lock: bytes) -> str | None: + try: + return json.loads(lock).get("generation") + except (ValueError, AttributeError): + return None + + +class Scheduler: + def __init__(self, repository, internal, public=None, packages=None, *, bot_login: str, + bot_email: str | None = None, notes: list[str] | None = None) -> None: + self.repository = repository + self.internal = internal + self.public = public + self.packages = packages + self.bot_login = bot_login + self.bot_email = bot_email + self.notes = [] if notes is None else notes + self.recipe_cache: dict[str, dict[str, str] | None] = {} + + def beta_line(self) -> Line: + lines = [] + for branch, tip in sorted(self.repository.release_heads().items()): + if not policy.RELEASE_BRANCH_RE.fullmatch(branch): + continue + raw = self.repository.read(tip, STATE_FILE) + try: + state = policy.parse_state(raw.decode("utf-8")) + except (AttributeError, UnicodeDecodeError, ValueError) as error: + if raw is not None and b"channel=BETA" in raw.splitlines(): + raise Stop("line", f"{branch}'s {STATE_FILE} says channel=BETA but does not validate: " + f"{error}") from error + continue + if state["channel"] != "BETA": + continue + if policy.classify(state["version"])["release_branch"] != branch: + raise Stop("line", f"{branch} is in BETA state for version {state['version']}, " + "which belongs to another release line.") + lines.append(Line(branch, tip, state["version"], int(state["prerelease"]))) + if not lines: + raise Skip("No release/X.Y branch is in BETA state, as between a freeze and the next line's start; " + "nothing to do.") + if len(lines) > 1: + found = ", ".join(line.branch for line in lines) + raise Stop("line", f"Exactly one release/X.Y branch may be in BETA state; found {found}.") + line = lines[0] + self.notes.append(f"Beta line: {line.branch} at {line.tip}, state BETA {line.number}.") + return line + + def cut(self) -> str: + self.repository.sync() + line = self.beta_line() + tag_sha = self.repository.tag(candidate_tag(line.prerelease())) + if tag_sha is None: + return self.retry(line) + public_tag = f"v{line.prerelease()}" + if self.public.release_published(public_tag): + self.notes.append(f"`{public_tag}` is published, so the next cut is BETA {line.number + 1}.") + return self.advance(line) + outcome = self.unpublished(line, tag_sha) + if not isinstance(outcome, Spent): + raise outcome + self.notes.append(str(outcome)) + return self.advance(line, spent=outcome) + + def retry(self, line: Line) -> str: + version = line.prerelease() + self.notes.append(f"`{candidate_tag(version)}` does not exist, so {version} is retried under the same number.") + self.check_fixes_on_develop(line) + runs = self.internal.runs(CI, head_sha=line.tip) + if any(in_flight(run) for run in runs): + raise self.wait("ci", runs, f"CI for {line.branch} at {line.tip} is still running; {version} waits for it.") + ci = newest(runs) + if ci is None: + raise Stop("ci", f"{line.branch} at {line.tip} has no CI run, so {version} cannot be cut.") + if ci.get("conclusion") != "success": + return self.recut(line, ci) + candidates = self.candidate_runs(line) + if any(in_flight(run) for run in candidates): + raise self.wait("candidate", candidates, f"A candidate run for {version} is still running.") + return self.dispatch_candidate(line) + + def wait(self, stage: str, runs: list[dict], reason: str) -> Exception: + running = [run for run in runs if in_flight(run)] + # The continuation follows only runs the App started, and the weekly cut would otherwise wait a week. + if any((run.get("actor") or {}).get("login") == self.bot_login for run in running): + return Skip(reason) + return Stop(stage, f"{reason} Nothing resumes the cut when that run finishes, so dispatch Scheduled Beta Cut " + "after it does.", running[0].get("html_url")) + + def recut(self, line: Line, ci: dict) -> str: + version = line.prerelease() + failed = f"CI for {line.branch} at {line.tip} concluded {ci.get('conclusion')}" + target = self.newest_green_develop() + if target is None or self.repository.is_ancestor(target, line.tip): + raise Stop("ci", f"{failed}, and develop has no newer green commit to cut {version} from. Re-run the CI " + "if the failure is transient.", ci.get("html_url")) + self.notes.append(f"{failed}, so {version} is cut again from develop {target}.") + lock, lock_note = self.lock_for(line, target) + commit = self.commit_cut(line, line.number, target, lock, lock_note) + return f"Pushed {commit} to {line.branch}: develop {target} as {version} again." + + def candidate_runs(self, line: Line) -> list[dict]: + return [run for run in self.internal.runs(CANDIDATE, branch=line.branch, event="workflow_dispatch") + if candidate_of(run) == (line.prerelease(), "create")] + + def dispatch_candidate(self, line: Line) -> str: + version = line.prerelease() + self.internal.dispatch(CANDIDATE, line.branch, + {"version": version, "expected_sha": line.tip, "operation": "create"}) + return f"Dispatched Prepare Release Candidate for `{candidate_tag(version)}` at {line.tip}." + + def unpublished(self, line: Line, tag_sha: str) -> Exception: + version = line.prerelease() + public_tag = f"v{version}" + stages = { + "CI": self.internal.runs(CI, head_sha=tag_sha), + "candidate": [run for run in self.candidate_runs(line) if run.get("head_sha") == tag_sha], + "promotion": self.internal.runs(PROMOTION, branch=line.branch, event="workflow_dispatch", head_sha=tag_sha), + "public release": self.public.runs(PUBLICATION, branch=public_tag, event="push"), + } + for stage, runs in stages.items(): + if any(in_flight(run) for run in runs): + reason = f"`{public_tag}` is not published yet; its {stage} run is still in progress." + # The public release completes on its own; nothing is due from the cut until it has. + return Skip(reason) if stage == "public release" else self.wait(stage.lower(), runs, reason) + failed = newest(stages["candidate"]) + if failed is None: + return Stop("candidate", f"`{candidate_tag(version)}` exists, but no candidate run for it was found.") + candidate = newest([run for run in stages["candidate"] if run.get("conclusion") == "success"]) + # A run reports only its latest attempt, so a later failed re-run can hide a promoted candidate. + promoted = newest([run for run in stages["promotion"] if run.get("conclusion") == "success"]) + if candidate is None and promoted is None: + return Spent(f"The candidate run for `{candidate_tag(version)}` concluded {failed.get('conclusion')} after " + f"the tag was pushed. Build tags never move, so {version} is spent and the next cut is " + f"BETA {line.number + 1}.", failed.get("html_url")) + promotion = promoted or newest(stages["promotion"]) + if promotion is None: + return Stop("promotion", f"The candidate for {version} succeeded, but Promote Release Source was not " + f"dispatched. Dispatch it with operation=promote and candidate run " + f"{candidate.get('id')}.", candidate.get("html_url")) + if promotion.get("conclusion") != "success": + return Stop("promotion", f"Promote Release Source for {version} concluded {promotion.get('conclusion')}.", + promotion.get("html_url")) + publication = newest(stages["public release"]) + if publication is None: + return Stop("publication", f"`{public_tag}` was promoted, but no public release run started for it.", + promotion.get("html_url")) + if publication.get("conclusion") != "success": + return Stop("publication", f"The public release run for `{public_tag}` concluded " + f"{publication.get('conclusion')}.", publication.get("html_url")) + return Stop("publication", f"The public release run for `{public_tag}` succeeded, but the release is not " + "published.", publication.get("html_url")) + + def advance(self, line: Line, spent: Spent | None = None) -> str: + number = line.number + 1 + target = self.newest_green_develop() + if target is None: + raise Stop("develop", "No commit on develop has a successful push CI run.") + if self.repository.is_ancestor(target, line.tip): + if spent is not None: + raise Stop("candidate", f"{spent} develop has no newer green commit to cut " + f"{line.prerelease(number)} from; land the fix on develop.", spent.link) + raise Skip(f"develop has not moved: its newest green commit {target} is already in {line.branch}.") + self.check_fixes_on_develop(line) + lock, lock_note = self.lock_for(line, target) + commit = self.commit_cut(line, number, target, lock, lock_note) + return f"Pushed {commit} to {line.branch}: develop {target} as {line.prerelease(number)}." + + def newest_green_develop(self) -> str | None: + develop = self.repository.develop() + runs = self.internal.runs(CI, branch="develop", event="push", status="success") + for run in sorted(runs, key=run_order, reverse=True): + sha = run.get("head_sha", "") + if self.repository.contains(sha) and self.repository.is_ancestor(sha, develop): + self.notes.append(f"Newest green develop commit: {sha}.") + return sha + return None + + def check_fixes_on_develop(self, line: Line) -> None: + fixes = [ + commit.sha for commit in self.repository.commits_missing_from_develop(line.tip) + if commit.author_email != self.bot_email and not METADATA_FILES.issuperset(commit.files) + ] + if fixes: + raise Stop("fixes", f"{line.branch} holds commits that are not on develop: {', '.join(fixes)}. " + "Fixes land on develop first.") + + def recipes(self, commit: str) -> dict[str, str] | None: + if commit not in self.recipe_cache: + self.recipe_cache[commit] = self.repository.fingerprints(commit) + return self.recipe_cache[commit] + + def lock_for(self, line: Line, target: str) -> tuple[bytes, str]: + wanted = self.recipes(target) + if wanted is None: + raise RuntimeError(f"develop commit {target} is missing from the checkout") + current = self.repository.read(line.tip, LOCK_FILE) + if current is not None and lock_recipes(current) == wanted: + self.notes.append(f"Linux image lock: kept; develop's recipe fingerprints match {line.branch}'s lock.") + return current, "" + generation = self.generation_for(wanted) + lock, run = self.prepared_lock(generation, wanted) + self.notes.append(f"Linux image lock: replaced with {generation} from {run.get('html_url')}.") + return lock, f"The Linux image lock moves to {generation}, prepared by {run.get('html_url')}." + + def published_generations(self) -> dict[int, str]: + shared: set[str] | None = None + for package in IMAGE_PACKAGES: + tags = {tag for version in self.packages.list_versions(image_tags.OWNER, package) + for tag in version.tags if GENERATION_TAG.fullmatch(tag)} + shared = tags if shared is None else shared & tags + generations: dict[int, str] = {} + for tag in sorted(shared or (), key=lambda item: int(GENERATION_TAG.fullmatch(item)["attempt"])): + generations[int(GENERATION_TAG.fullmatch(tag)["run"])] = tag + return generations + + def generation_for(self, wanted: dict[str, str]) -> str: + published = self.published_generations() + refreshing = None + runs = (self.internal.runs(WARMER, branch="develop") + + self.internal.runs(PUBLISHER, branch="develop", event="workflow_dispatch")) + for run in sorted(runs, key=run_order, reverse=True): + matches = self.recipes(run.get("head_sha", "")) == wanted + # A generation is tagged only by the run's promote job, so it can be used before the run ends. + if matches and run.get("id") in published: + return published[run["id"]] + if refreshing is None and in_flight(run) and matches and self.refreshes_images(run): + refreshing = run + if refreshing is not None: + raise Stop("lock", "The Linux images for develop's recipe fingerprints are still being refreshed. Nothing " + "resumes the cut when that run finishes, so dispatch Scheduled Beta Cut after it does.", + refreshing.get("html_url")) + raise Stop("lock", "No validated Linux image generation matches develop's recipe fingerprints. " + "Refresh the images with Refresh Build Caches (targets: linux-images) on develop.") + + def refreshes_images(self, run: dict) -> bool: + for job in self.internal.jobs(run["id"]): + name = job.get("name") or "" + if name in (NORMAL_IMAGES_JOB, f"{IMAGE_REFRESH_JOB} / {NORMAL_IMAGES_JOB}"): + return job.get("conclusion") != "skipped" + if name == IMAGE_REFRESH_JOB: + return job.get("status") != "completed" + # The run has not yet decided whether it builds the four normal images. + return True + + def prepared_lock(self, generation: str, wanted: dict[str, str]) -> tuple[bytes, dict]: + runs = [run for run in self.internal.runs(PREPARATION, branch="develop", event="workflow_dispatch") + if preparation_of(run) == ("develop", generation)] + if any(in_flight(run) for run in runs): + raise self.wait("lock", runs, f"Prepare Release Dependencies for {generation} is still running; the cut " + "waits for its lock.") + for run in sorted(runs, key=run_order, reverse=True): + if run.get("conclusion") != "success": + continue + lock = self.internal.artifact_file(run["id"], PREPARED_ARTIFACT, LOCK_FILE) + if lock is not None and lock_generation(lock) == generation and lock_recipes(lock) == wanted: + return lock, run + latest = newest(runs) + if latest is not None and latest.get("conclusion") != "success": + raise Stop("lock", f"Prepare Release Dependencies for {generation} concluded {latest.get('conclusion')}. " + "Re-run it to resume the cut.", latest.get("html_url")) + tip = self.repository.develop() + if self.recipes(tip) != wanted: + # The preparation verifies the images against develop's tip, not against the commit being cut. + raise Stop("lock", f"develop's tip {tip} has other Linux image recipes than its newest green commit, so " + f"a preparation of {generation} would fail. Dispatch Scheduled Beta Cut once the tip's " + "CI has passed.") + self.internal.dispatch(PREPARATION, "develop", {"source_branch": "develop", "generation": generation}) + raise Skip(f"Dispatched Prepare Release Dependencies for {generation}; a later run commits its lock " + "in the cut.") + + def commit_cut(self, line: Line, number: int, target: str, lock: bytes, lock_note: str) -> str: + version = line.prerelease(number) + worktree, conflicts = self.repository.start_merge(line.tip, target, self.bot_login, self.bot_email) + try: + unexpected = sorted(set(conflicts) - METADATA_FILES) + if unexpected: + raise Stop("merge", f"Merging develop {target} into {line.branch} conflicts in " + f"{', '.join(unexpected)}.") + self.repository.write(worktree, {STATE_FILE: render_state(line.version, number).encode(), LOCK_FILE: lock}) + try: + self.repository.validate_lock(worktree) + except RuntimeError as error: + raise Stop("lock", f"The Linux image lock for {version} does not validate: {error}") from error + body = textwrap.fill( + f"Merge develop at {target} into {line.branch} with release state BETA {number}. {lock_note}".strip(), + 72, break_long_words=False, break_on_hyphens=False) + commit = self.repository.commit(worktree, self.bot_login, self.bot_email, + f"Cut {version} from develop\n\n{body}\n") + try: + self.repository.push(commit, line.branch) + except RuntimeError as error: + raise Stop("merge", f"Pushing the {version} cut to {line.branch} failed: {error}") from error + return commit + finally: + self.repository.discard(worktree) + + def continue_after(self, run: dict) -> str: + actor = (run.get("actor") or {}).get("login") + if actor != self.bot_login: + raise Skip(f"{run.get('html_url')} was started by {actor}, not {self.bot_login}; nothing to do.") + workflow = (run.get("path"), run.get("event")) + conclusion = run.get("conclusion") + if workflow == (f".github/workflows/{PREPARATION}", "workflow_dispatch"): + return self.after_preparation(run) + self.repository.sync(shallow=True) + line = self.beta_line() + if (run.get("head_branch"), run.get("head_sha")) != (line.branch, line.tip): + raise Skip(f"{run.get('html_url')} ran on {run.get('head_branch')} at {run.get('head_sha')}, not at the " + f"tip of {line.branch}; nothing to do.") + version = line.prerelease() + tag = candidate_tag(version) + if workflow == (f".github/workflows/{CI}", "push"): + if conclusion != "success": + raise Stop("ci", f"CI for the {version} cut concluded {conclusion}. Re-run it if the failure is " + "transient.", run.get("html_url")) + if self.repository.tag(tag) is not None: + raise Skip(f"`{tag}` already exists; nothing to do.") + if any(in_flight(candidate) for candidate in self.candidate_runs(line)): + raise Skip(f"A candidate run for {version} is already running; nothing to do.") + return self.dispatch_candidate(line) + candidate_run = workflow == (f".github/workflows/{CANDIDATE}", "workflow_dispatch") + if candidate_run and candidate_of(run) == (version, "create"): + if conclusion != "success": + if self.repository.tag(tag) is None: + after = f"the next scheduled cut retries {version}" + else: + after = f"the next scheduled cut moves on to BETA {line.number + 1}, because build tags never move" + raise Stop("candidate", f"The candidate run for `{tag}` concluded {conclusion}. Re-run it if the " + f"failure is transient; otherwise {after}.", run.get("html_url")) + tag_sha = self.repository.tag(tag) + if tag_sha != line.tip: + raise Stop("candidate", f"The candidate run succeeded, but `{tag}` resolves to {tag_sha or 'nothing'} " + f"instead of {line.tip}.", run.get("html_url")) + self.internal.dispatch(PROMOTION, line.branch, + {"version": version, "candidate_run_id": str(run["id"]), "operation": "promote"}) + return f"Dispatched Promote Release Source for `v{version}` from candidate run {run['id']}." + if workflow == (f".github/workflows/{PROMOTION}", "workflow_dispatch"): + if conclusion != "success": + raise Stop("promotion", f"Promote Release Source for {version} concluded {conclusion}. Re-running it " + f"resumes {version}.", run.get("html_url")) + raise Skip(f"`v{version}` is promoted; the public repository's release run publishes it.") + raise Skip(f"{run.get('html_url')} is not a CI, candidate or promotion run of the {version} cut; " + "nothing to do.") + + def after_preparation(self, run: dict) -> str: + prepared = preparation_of(run) + if run.get("head_branch") != "develop" or prepared is None or prepared[0] != "develop": + raise Skip(f"{run.get('html_url')} is not a preparation from develop; nothing to do.") + if run.get("conclusion") != "success": + raise Stop("lock", f"Prepare Release Dependencies for {prepared[1]} concluded {run.get('conclusion')}. " + "Re-run it to resume the cut.", run.get("html_url")) + self.internal.dispatch(BETA_CUT, "develop", {}) + return f"Dispatched the beta cut on develop: the lock for {prepared[1]} is prepared." + + +class Repository: + """Git operations on the workflow checkout; remote access authenticates with the release-bot token.""" + + def __init__(self, root: Path, remote: str, token: str | None = None, server: str = "https://github.com") -> None: + self.root = root + self.remote = remote + self.auth: tuple[str, ...] = () + if token: + credential = base64.b64encode(f"x-access-token:{token}".encode()).decode() + self.auth = ("-c", f"http.{server}/.extraheader=AUTHORIZATION: basic {credential}") + + def git(self, *arguments: str, cwd: Path | None = None, check: bool = True, + env: dict[str, str] | None = None) -> subprocess.CompletedProcess: + result = subprocess.run(["git", *self.auth, *arguments], cwd=cwd or self.root, capture_output=True, + env={**os.environ, "GIT_TERMINAL_PROMPT": "0", **(env or {})}) + if check and result.returncode: + detail = (result.stderr or result.stdout).decode(errors="replace").strip() + raise RuntimeError(f"git {' '.join(arguments[:2])} failed: {detail}") + return result + + def output(self, *arguments: str, cwd: Path | None = None) -> str: + return self.git(*arguments, cwd=cwd).stdout.decode().strip() + + def sync(self, *, shallow: bool = False) -> None: + releases = "+refs/heads/release/*:refs/remotes/origin/release/*" + if shallow: + self.git("fetch", "--prune", "--no-tags", "--depth=1", self.remote, releases) + else: + self.git("fetch", "--prune", "--no-tags", self.remote, + "+refs/heads/develop:refs/remotes/origin/develop", releases) + + def release_heads(self) -> dict[str, str]: + listing = self.output("for-each-ref", "--format=%(refname:strip=3) %(objectname)", + "refs/remotes/origin/release/") + return dict(line.split(" ", 1) for line in listing.splitlines()) + + def develop(self) -> str: + return self.output("rev-parse", "--verify", "refs/remotes/origin/develop^{commit}") + + def tag(self, name: str) -> str | None: + listing = self.output("ls-remote", self.remote, f"refs/tags/{name}", f"refs/tags/{name}^{{}}") + refs = {ref: sha for sha, ref in (line.split("\t") for line in listing.splitlines())} + return refs.get(f"refs/tags/{name}^{{}}") or refs.get(f"refs/tags/{name}") + + def contains(self, commit: str) -> bool: + return bool(commit) and self.git("cat-file", "-e", f"{commit}^{{commit}}", check=False).returncode == 0 + + def read(self, commit: str, path: str) -> bytes | None: + self.git("cat-file", "-e", f"{commit}^{{commit}}") + if self.git("cat-file", "-e", f"{commit}:{path}", check=False).returncode: + return None + return self.git("cat-file", "blob", f"{commit}:{path}").stdout + + def is_ancestor(self, ancestor: str, descendant: str) -> bool: + result = self.git("merge-base", "--is-ancestor", ancestor, descendant, check=False) + if result.returncode not in (0, 1): + raise RuntimeError(f"git merge-base failed: {result.stderr.decode(errors='replace').strip()}") + return result.returncode == 0 + + def commits_missing_from_develop(self, tip: str) -> list[Commit]: + commits = [] + for sha in self.output("rev-list", f"refs/remotes/origin/develop..{tip}").split(): + email, _, parents = self.output("show", "-s", "--format=%ae%n%P", sha).partition("\n") + if parents: + files = self.output("diff", "--no-renames", "--name-only", parents.split()[0], sha) + else: + files = self.output("ls-tree", "-r", "--name-only", sha) + commits.append(Commit(sha, email, tuple(files.splitlines()))) + return commits + + def fingerprints(self, commit: str) -> dict[str, str] | None: + if not self.contains(commit): + return None + archive = self.git("archive", "--format=tar", commit, ".github").stdout + with tempfile.TemporaryDirectory() as directory: + subprocess.run(["tar", "-x", "-f", "-", "-C", directory], input=archive, check=True, capture_output=True) + return { + key: subprocess.run(["bash", ".github/scripts/linux-ci-image-fingerprint.sh", profile], cwd=directory, + check=True, capture_output=True, text=True).stdout.strip() + for key, (_package, profile, *_rest) in images.IMAGES.items() + } + + def start_merge(self, tip: str, commit: str, name: str, email: str) -> tuple[Path, list[str]]: + worktree = Path(tempfile.mkdtemp(prefix="beta-cut-")) / "tree" + self.git("worktree", "add", "--detach", str(worktree), tip) + merged = self.git("merge", "--no-ff", "--no-commit", commit, cwd=worktree, check=False, + env=git_identity(name, email)) + conflicts = self.output("diff", "--name-only", "--diff-filter=U", cwd=worktree).splitlines() + if merged.returncode and not conflicts: + detail = (merged.stderr or merged.stdout).decode(errors="replace").strip() + self.discard(worktree) + raise RuntimeError(f"git merge failed: {detail}") + return worktree, conflicts + + def write(self, worktree: Path, files: dict[str, bytes]) -> None: + for path, content in files.items(): + (worktree / path).write_bytes(content) + self.git("add", "--", *files, cwd=worktree) + + def validate_lock(self, worktree: Path) -> None: + result = subprocess.run([sys.executable, ".github/scripts/release-linux-images.py", "validate", LOCK_FILE, + "--check-remote"], cwd=worktree, capture_output=True, text=True) + if result.returncode: + raise RuntimeError((result.stderr or result.stdout).strip()) + + def commit(self, worktree: Path, name: str, email: str, message: str) -> str: + self.git("commit", "--no-verify", "--quiet", "--message", message, cwd=worktree, + env=git_identity(name, email)) + return self.output("rev-parse", "HEAD", cwd=worktree) + + def push(self, commit: str, branch: str) -> None: + self.git("push", self.remote, f"{commit}:refs/heads/{branch}") + + def discard(self, worktree: Path) -> None: + self.git("worktree", "remove", "--force", str(worktree), check=False) + shutil.rmtree(worktree.parent, ignore_errors=True) + + +class KeepRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *arguments, **keywords): + return None + + +class GitHub: + def __init__(self, token: str, repository: str, api_url: str = "https://api.github.com") -> None: + self.token = token + self.repository = repository + self.api_url = api_url.rstrip("/") + + def request(self, method: str, path: str, *, params: dict | None = None, + body: object = None) -> urllib.request.Request: + url = self.api_url + path + ("?" + urllib.parse.urlencode(params) if params else "") + data = None if body is None else json.dumps(body).encode() + headers = { + "Accept": "application/vnd.github+json", + "Authorization": f"Bearer {self.token}", + "X-GitHub-Api-Version": "2022-11-28", + "User-Agent": "wsjtx-beta-scheduler", + } + if data is not None: + headers["Content-Type"] = "application/json" + return urllib.request.Request(url, data=data, method=method, headers=headers) + + def call(self, method: str, path: str, *, params: dict | None = None, body: object = None, + missing_ok: bool = False): + try: + with urllib.request.urlopen(self.request(method, path, params=params, body=body), timeout=60) as response: + payload = response.read() + except urllib.error.HTTPError as error: + if missing_ok and error.code == 404: + return None + raise RuntimeError(f"{method} {path} failed with HTTP {error.code}") from error + return json.loads(payload) if payload else None + + def runs(self, workflow: str, **filters: str) -> list[dict]: + return self.call("GET", f"/repos/{self.repository}/actions/workflows/{workflow}/runs", + params={"per_page": 100, **filters})["workflow_runs"] + + def jobs(self, run_id: int) -> list[dict]: + return self.call("GET", f"/repos/{self.repository}/actions/runs/{run_id}/jobs", + params={"per_page": 100})["jobs"] + + def dispatch(self, workflow: str, ref: str, inputs: dict[str, str]) -> None: + self.call("POST", f"/repos/{self.repository}/actions/workflows/{workflow}/dispatches", + body={"ref": ref, "inputs": inputs}) + + def release_published(self, tag: str) -> bool: + path = f"/repos/{self.repository}/releases/tags/{urllib.parse.quote(tag, safe='')}" + return self.call("GET", path, missing_ok=True) is not None + + def user_id(self, login: str) -> int: + return self.call("GET", f"/users/{urllib.parse.quote(login, safe='')}")["id"] + + def artifact_file(self, run_id: int, name: str, member: str) -> bytes | None: + listing = self.call("GET", f"/repos/{self.repository}/actions/runs/{run_id}/artifacts", + params={"name": name, "per_page": 100}) + live = [item for item in listing["artifacts"] if item.get("name") == name and not item.get("expired")] + if not live: + return None + archive = self.download(f"/repos/{self.repository}/actions/artifacts/{live[0]['id']}/zip") + with zipfile.ZipFile(io.BytesIO(archive)) as bundle: + return bundle.read(member) if member in bundle.namelist() else None + + def download(self, path: str) -> bytes: + try: + with urllib.request.build_opener(KeepRedirect).open(self.request("GET", path), timeout=60) as response: + return response.read() + except urllib.error.HTTPError as redirect: + location = redirect.headers.get("Location") + if redirect.code not in (301, 302, 303, 307, 308) or not location: + raise RuntimeError(f"GET {path} failed with HTTP {redirect.code}") from redirect + # The signed storage URL must not receive the API token. + with urllib.request.urlopen(location, timeout=120) as response: + return response.read() + + +class Alerts: + def __init__(self, github, run_url: str) -> None: + self.github = github + self.run_url = run_url + + def post(self, stage: str, reason: str, link: str | None = None) -> None: + lines = [f"**Stage:** {stage}", f"**Reason:** {reason}", f"**Run:** {link or self.run_url}"] + if link and link != self.run_url: + lines.append(f"**Reported by:** {self.run_url}") + body = "\n\n".join(lines) + issues_path = f"/repos/{self.github.repository}/issues" + issues = self.github.call("GET", issues_path, + params={"state": "open", "creator": ALERT_CREATOR, "per_page": 100}) + tracking = sorted( + issue["number"] for issue in issues + if issue.get("title") == ALERT_TITLE and "pull_request" not in issue + and (issue.get("user") or {}).get("login") == ALERT_CREATOR + ) + if tracking: + self.github.call("POST", f"{issues_path}/{tracking[0]}/comments", body={"body": body}) + else: + self.github.call("POST", issues_path, body={"title": ALERT_TITLE, "body": body}) + + +def run_step(command: str, action: Callable[[], str], + notes: list[str]) -> tuple[int, str, tuple[str, str, str | None] | None]: + alert = None + try: + result, status = action(), 0 + except Skip as skip: + result, status = str(skip), 0 + except Stop as stop: + result, status, alert = f"Stopped at {stop.stage}: {stop}", 1, (stop.stage, str(stop), stop.link) + except Exception as error: # Every unexpected failure also reaches the tracking issue. + traceback.print_exc() + result, status, alert = f"Failed: {error}", 1, (command, f"Unexpected error: {error}", None) + summary = "\n".join([f"## Scheduled beta: {command}", "", *(f"- {note}" for note in notes), "", result, ""]) + return status, summary, alert + + +def build_scheduler(command: str, env, notes: list[str]) -> Scheduler: + repository = env["GITHUB_REPOSITORY"] + server = env.get("GITHUB_SERVER_URL", "https://github.com") + api_url = env.get("GITHUB_API_URL", "https://api.github.com") + token = env["RELEASE_BOT_TOKEN"] + bot_login = f"{env['RELEASE_BOT_SLUG']}[bot]" + internal = GitHub(token, repository, api_url) + git = Repository(Path.cwd(), f"{server}/{repository}.git", token, server) + if command == "continue": + return Scheduler(git, internal, bot_login=bot_login, notes=notes) + return Scheduler( + git, internal, + GitHub(env["PUBLIC_READ_TOKEN"], PUBLIC_REPOSITORY, api_url), + image_tags.GitHubPackagesClient(env["GITHUB_TOKEN"], api_url), + bot_login=bot_login, + bot_email=f"{internal.user_id(bot_login)}+{bot_login}@users.noreply.github.com", + notes=notes, + ) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + commands.add_parser("cut", help="apply one step of the beta state machine") + commands.add_parser("continue", help="continue after the workflow run in GITHUB_EVENT_PATH") + alert_parser = commands.add_parser("alert", help="record a failure on the tracking issue") + alert_parser.add_argument("--stage", required=True) + alert_parser.add_argument("--reason", required=True) + args = parser.parse_args(argv) + env = os.environ + repository = env["GITHUB_REPOSITORY"] + run_url = f"{env.get('GITHUB_SERVER_URL', 'https://github.com')}/{repository}/actions/runs/{env['GITHUB_RUN_ID']}" + alerts = Alerts(GitHub(env["GITHUB_TOKEN"], repository, env.get("GITHUB_API_URL", "https://api.github.com")), + run_url) + if args.command == "alert": + alerts.post(args.stage, args.reason) + return 0 + notes: list[str] = [] + + def step() -> str: + scheduler = build_scheduler(args.command, env, notes) + if args.command == "cut": + return scheduler.cut() + event = json.loads(Path(env["GITHUB_EVENT_PATH"]).read_text(encoding="utf-8")) + return scheduler.continue_after(event["workflow_run"]) + + status, summary, alert = run_step(args.command, step, notes) + print(summary) + if env.get("GITHUB_STEP_SUMMARY"): + with open(env["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as stream: + stream.write(summary) + if alert: + alerts.post(*alert) + if env.get("GITHUB_OUTPUT"): + with open(env["GITHUB_OUTPUT"], "a", encoding="utf-8") as stream: + stream.write("alerted=true\n") + return status + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.github/scripts/build-fftw-macos.sh b/.github/scripts/build-fftw-macos.sh index 6ae1505d..cbaf0291 100755 --- a/.github/scripts/build-fftw-macos.sh +++ b/.github/scripts/build-fftw-macos.sh @@ -19,7 +19,7 @@ cd "fftw-${version}" --enable-single \ --enable-threads \ --enable-shared --disable-static \ - CFLAGS="-mmacosx-version-min=${deployment_target}" \ + CFLAGS="-O3 -mmacosx-version-min=${deployment_target}" \ LDFLAGS="-mmacosx-version-min=${deployment_target}" make -j"$(sysctl -n hw.ncpu)" make install diff --git a/.github/scripts/build-linux-armhf-cross.sh b/.github/scripts/build-linux-armhf-cross.sh index cfbb2f03..f8c80dd8 100755 --- a/.github/scripts/build-linux-armhf-cross.sh +++ b/.github/scripts/build-linux-armhf-cross.sh @@ -4,8 +4,13 @@ set -euo pipefail VERSION="${VERSION:?missing}" ARCH="${ARCH:?missing}" HAMLIB_BRANCH="${HAMLIB_BRANCH:?missing}" -WSJT_RELEASE_CHANNEL="${WSJT_RELEASE_CHANNEL:-DEVEL}" -WSJT_RC_NUMBER="${WSJT_RC_NUMBER:-}" +WSJT_RELEASE_CHANNEL="${WSJT_RELEASE_CHANNEL:-}" +WSJT_PRERELEASE_NUMBER="${WSJT_PRERELEASE_NUMBER:-}" +ARMHF_BUILD_ONLY="${ARMHF_BUILD_ONLY:-false}" +case "$ARMHF_BUILD_ONLY" in + true|false) ;; + *) echo "ARMHF_BUILD_ONLY must be true or false" >&2; exit 2 ;; +esac if [ "$ARCH" != armhf ]; then echo "build-linux-armhf-cross.sh supports only arch=armhf" >&2 exit 2 @@ -42,7 +47,7 @@ cmake -S . -B wsjtx-build \ -DWSJT_ENABLE_TESTS=ON \ -DWSJT_FORTRAN_LIBRARY_VARIANTS=OPENMP_ONLY \ -DWSJT_RELEASE_CHANNEL="$WSJT_RELEASE_CHANNEL" \ - -DWSJT_RC_NUMBER="$WSJT_RC_NUMBER" \ + -DWSJT_PRERELEASE_NUMBER="$WSJT_PRERELEASE_NUMBER" \ -Wno-dev cmake --build wsjtx-build --parallel "$(nproc)" ended="$(date +%s)" @@ -55,6 +60,10 @@ ccache --show-stats validate_linux_build_executables wsjtx-build "$ARCH" .github/scripts/audit-armhf-cross-build.sh wsjtx-build +if [ "$ARMHF_BUILD_ONLY" = true ]; then + echo "ARMHF build-only compilation and binary audits complete for version=$VERSION" + exit 0 +fi echo "::group::Prepare ARMHF AppDir" cmake --install wsjtx-build --prefix /work/AppDir/usr validate_linux_application_tree AppDir appdir "$ARCH" diff --git a/.github/scripts/generate-quick-downloads.py b/.github/scripts/generate-quick-downloads.py index 6706292d..0ba21c36 100755 --- a/.github/scripts/generate-quick-downloads.py +++ b/.github/scripts/generate-quick-downloads.py @@ -3,7 +3,7 @@ The release workflow attaches every build artifact to the Release, which makes the assets list long and hard for an end user to navigate (installers sit among -standalone command-line utilities, raw binaries, and source). This emits a +the command-line program tarballs, checksums, the manifest, and source). This emits a short, curated per-platform installer picker to prepend to the auto-generated release notes. @@ -19,9 +19,8 @@ Usage: generate-quick-downloads.py ... Only installer-grade assets are listed (.pkg / win64.exe / .deb / .rpm / -.AppImage) plus the source tarball. Per-mode utility tarballs and raw -command-line binaries are intentionally omitted; they remain in the full -assets list below the notes. +.AppImage) plus the source tarball. The command-line program tarballs are +intentionally omitted; they remain in the full assets list below the notes. """ import os import re @@ -66,8 +65,8 @@ def main(argv): appimage[m.group(1)] = n elif (m := re.search(r"\.([A-Za-z0-9_]+)\.rpm$", n)): rpm[m.group(1)] = n - # Anything else (utility tarballs, raw binaries) is intentionally - # excluded; it stays in the full assets list. + # Anything else (program tarballs, checksums, the manifest) is + # intentionally excluded; it stays in the full assets list. def arches(d): known = [a for a in ARCH_ORDER if a in d] @@ -83,7 +82,7 @@ def main(argv): "## Quick Downloads", "", "Choose the installer for your platform. The full assets list below also", - "includes standalone command-line utilities and source code for developers.", + "includes the command-line program tarballs and source code for developers.", ] if macos: diff --git a/.github/scripts/is-linux-ci-image-input.sh b/.github/scripts/is-linux-ci-image-input.sh index 23a76e1b..07437151 100755 --- a/.github/scripts/is-linux-ci-image-input.sh +++ b/.github/scripts/is-linux-ci-image-input.sh @@ -82,6 +82,8 @@ if [ "${1:-}" = "--self-test" ]; then expect_non_input normal-noble ".github/images/linux-ci/install-armhf-runtime-packages.sh" expect_input armhf-cross-bookworm ".github/images/linux-ci/armhf-cross-toolchain.config" expect_non_input armhf-runtime-bookworm ".github/images/linux-ci/armhf-cross-toolchain.config" + expect_input armhf-cross-bookworm ".github/scripts/armhf-toolchain-config.sh" + expect_input armhf-runtime-bookworm ".github/scripts/armhf-toolchain-config.sh" expect_input normal-noble ".github/scripts/build-hamlib-linux.sh" expect_non_input tsan-noble ".github/scripts/build-hamlib-linux.sh" expect_input tsan-noble ".github/scripts/build-qt-tsan-linux.sh" diff --git a/.github/scripts/linux-artifact-validation.sh b/.github/scripts/linux-artifact-validation.sh index 01a607f6..2a7db636 100644 --- a/.github/scripts/linux-artifact-validation.sh +++ b/.github/scripts/linux-artifact-validation.sh @@ -70,6 +70,7 @@ validate_elf_executable() { local file_output local header_output local program_output + local dynamic_output if [ ! -x "$path" ]; then linux_validation_error "Required executable is missing: $path" @@ -80,7 +81,14 @@ validate_elf_executable() { header_output=$(readelf -hW -- "$path") || return program_output=$(readelf -lW -- "$path") || return echo "$file_output" - validate_elf_metadata "$arch" "$path" "$file_output" "$header_output" "$program_output" + validate_elf_metadata "$arch" "$path" "$file_output" "$header_output" "$program_output" || return + if [ "${path##*/}" = jt9 ]; then + dynamic_output=$(readelf -dW -- "$path") || return + if printf '%s\n' "$dynamic_output" | awk '/\(NEEDED\)/ && /\[libQt/ { found=1 } END { exit found ? 0 : 1 }'; then + linux_validation_error "$path must not depend on Qt" + return 1 + fi + fi } validate_linux_build_executables() { diff --git a/.github/scripts/linux-ci-image-inputs.sh b/.github/scripts/linux-ci-image-inputs.sh index bc3e43af..938ad2d7 100644 --- a/.github/scripts/linux-ci-image-inputs.sh +++ b/.github/scripts/linux-ci-image-inputs.sh @@ -33,6 +33,7 @@ linux_ci_image_inputs() { printf '%s\n' \ .github/images/linux-ci/Dockerfile.armhf-cross \ .github/images/linux-ci/armhf-cross-toolchain.config \ + .github/scripts/armhf-toolchain-config.sh \ .github/scripts/armhf-ci-image-config.sh \ .github/scripts/build-armhf-toolchain-smoke.sh \ .github/scripts/build-hamlib-armhf-cross.sh \ @@ -49,6 +50,7 @@ linux_ci_image_inputs() { printf '%s\n' \ .github/images/linux-ci/Dockerfile.armhf-runtime \ .github/images/linux-ci/install-armhf-runtime-packages.sh \ + .github/scripts/armhf-toolchain-config.sh \ .github/scripts/armhf-ci-image-config.sh \ .github/scripts/linux-ci-image-config.sh \ .github/scripts/linux-ci-image-fingerprint.sh \ diff --git a/.github/scripts/linuxdeploy-excludelist.txt b/.github/scripts/linuxdeploy-excludelist.txt new file mode 100644 index 00000000..ee55ae4d --- /dev/null +++ b/.github/scripts/linuxdeploy-excludelist.txt @@ -0,0 +1,55 @@ +# The excludelist compiled into linuxdeploy 1-alpha-20251107-1, identical in +# its x86_64, aarch64 and armhf builds. linuxdeploy leaves these libraries, +# ld-linux* and linux-vdso to the host; update this file with the pin. +ld-linux-x86-64.so.2 +ld-linux.so.2 +libBrokenLocale.so.1 +libEGL.so.1 +libGL.so.1 +libGLX.so.0 +libGLdispatch.so.0 +libICE.so.6 +libOpenGL.so.0 +libSM.so.6 +libX11-xcb.so.1 +libX11.so.6 +libanl.so.1 +libasound.so.2 +libc.so.6 +libcidn.so.1 +libcom_err.so.2 +libdl.so.2 +libdrm.so.2 +libexpat.so.1 +libfontconfig.so.1 +libfreetype.so.6 +libfribidi.so.0 +libgbm.so.1 +libgcc_s.so.1 +libglapi.so.0 +libgmp.so.10 +libgpg-error.so.0 +libharfbuzz.so.0 +libjack.so.0 +libm.so.6 +libmvec.so.1 +libnss_compat.so.2 +libnss_dns.so.2 +libnss_files.so.2 +libnss_hesiod.so.2 +libnss_nis.so.2 +libnss_nisplus.so.2 +libpipewire-0.3.so.0 +libpthread.so.0 +libresolv.so.2 +librt.so.1 +libstdc++.so.6 +libthread_db.so.1 +libusb-1.0.so.0 +libutil.so.1 +libuuid.so.1 +libwayland-client.so.0 +libxcb-dri2.so.0 +libxcb-dri3.so.0 +libxcb.so.1 +libz.so.1 diff --git a/.github/scripts/package-cli-tools.sh b/.github/scripts/package-cli-tools.sh new file mode 100755 index 00000000..e9b7d03d --- /dev/null +++ b/.github/scripts/package-cli-tools.sh @@ -0,0 +1,499 @@ +#!/usr/bin/env bash +# Package the command-line programs into the release tarballs published beside +# the installers: one tarball per line of CMake/release-tarballs.txt. +# +# package-cli-tools.sh --platform macos|linux|windows --version V --arch A \ +# --groups FILE --source DIR --out DIR \ +# [--dll-dir DIR --system-dir DIR] [--linuxdeploy COMMAND] +# +# wsjtx-V--.tar.gz holds one directory of the same name: the +# tarball's programs, every library they load beyond the operating system's, +# README.txt, COPYING and THIRD-PARTY.txt. A missing program, an unresolved +# library or a library third-party-libraries.tsv does not name fails the run, +# and then no tarball is written. +# +# macos: --source is the CLI assets directory: the signed programs and the +# deployed lib/ of dylibs they reference as @rpath/. Each +# tarball gets its programs at the top and, in lib/, the dylibs they +# reach through their LC_RPATH entries. A reference outside /usr/lib +# and /System/Library that does not resolve there, or an absolute +# LC_RPATH, fails the run. +# linux: --source is the CMake build directory. --linuxdeploy is a command +# that runs the pinned linuxdeploy AppImage. It deploys each tarball's +# programs to bin/ and the libraries they load to lib/, except those +# on its excludelist (linuxdeploy-excludelist.txt), with RUNPATH +# $ORIGIN/../lib and $ORIGIN, and the libraries' Debian copyright +# files to share/doc/. A library that resolves neither inside the +# tarball nor to the excludelist, or a RUNPATH entry not relative to +# $ORIGIN, fails the run. +# windows: --source is the CMake build directory, --dll-dir the staged bin/ +# after DLL fixup and --system-dir the Windows system directory. Each +# tarball gets its .exe files and the transitive closure of the DLLs +# they import from --dll-dir; an import found in neither directory +# fails the run. +set -euo pipefail + +PLATFORM=""; VERSION=""; ARCH=""; GROUPS_FILE=""; SOURCE=""; OUT=""; DLL_DIR=""; SYSTEM_DIR=""; LINUXDEPLOY="" +while [ "$#" -gt 0 ]; do + case "$1" in + --platform) PLATFORM="$2"; shift 2 ;; + --version) VERSION="$2"; shift 2 ;; + --arch) ARCH="$2"; shift 2 ;; + --groups) GROUPS_FILE="$2"; shift 2 ;; + --source) SOURCE="$2"; shift 2 ;; + --out) OUT="$2"; shift 2 ;; + --dll-dir) DLL_DIR="$2"; shift 2 ;; + --system-dir) SYSTEM_DIR="$2"; shift 2 ;; + --linuxdeploy) LINUXDEPLOY="$2"; shift 2 ;; + *) echo "unknown argument: $1" >&2; exit 2 ;; + esac +done +for option in PLATFORM VERSION ARCH GROUPS_FILE SOURCE OUT; do + if [ -z "${!option}" ]; then echo "missing --$(echo "${option%_FILE}" | tr '[:upper:]' '[:lower:]')" >&2; exit 2; fi +done + +SCRIPTS="$(cd "$(dirname "$0")" && pwd)" +COPYING="${SCRIPTS}/../../COPYING" +NOTICES_TABLE="${SCRIPTS}/third-party-libraries.tsv" +EXCLUDELIST="${SCRIPTS}/linuxdeploy-excludelist.txt" +LICENSE_PAGE="${SCRIPTS}/../../doc/common/license.adoc" + +fail() { echo "::error::$*" >&2; exit 1; } + +case "$PLATFORM" in + macos) TARGET="${ARCH}-macOS"; EXT="" ;; + linux) TARGET="linux-${ARCH}"; EXT="" + [ -n "$LINUXDEPLOY" ] || { echo "::error::--linuxdeploy is required for linux" >&2; exit 2; } ;; + windows) TARGET="windows-${ARCH}"; EXT=".exe" + [ -n "$DLL_DIR" ] && [ -d "$DLL_DIR" ] || { echo "::error::--dll-dir is required for windows" >&2; exit 2; } + [ -n "$SYSTEM_DIR" ] && [ -d "$SYSTEM_DIR" ] || { echo "::error::--system-dir is required for windows" >&2; exit 2; } + ;; + *) echo "unknown platform: $PLATFORM" >&2; exit 2 ;; +esac +[ -d "$SOURCE" ] || fail "source directory not found: $SOURCE" +[ -s "$GROUPS_FILE" ] || fail "release tarball list not found or empty: $GROUPS_FILE" +[ -f "$COPYING" ] || fail "COPYING not found: $COPYING" +[ -f "$NOTICES_TABLE" ] || fail "third-party library table not found: $NOTICES_TABLE" +[ -f "$LICENSE_PAGE" ] || fail "license page not found: $LICENSE_PAGE" +[ "$PLATFORM" != linux ] || [ -f "$EXCLUDELIST" ] || fail "linuxdeploy excludelist not found: $EXCLUDELIST" + +# Plain indexed arrays and lookup files keep this runnable on bash 3.2. +GROUP_NAMES=(); GROUP_PROGRAMS=() +while IFS= read -r line || [ -n "$line" ]; do + line="${line%$'\r'}" # a Windows checkout may have CRLF endings + read -r -a fields <<< "$line" || true + [ "${#fields[@]}" -gt 0 ] || continue + case "${fields[0]}" in '#'*) continue ;; esac + [ "${#fields[@]}" -ge 2 ] || fail "release tarball ${fields[0]} names no programs in ${GROUPS_FILE}" + for name in ${GROUP_NAMES[@]+"${GROUP_NAMES[@]}"}; do + [ "$name" != "${fields[0]}" ] || fail "release tarball ${name} is named twice in ${GROUPS_FILE}" + done + GROUP_NAMES+=("${fields[0]}") + GROUP_PROGRAMS+=("${fields[*]:1}") +done < "$GROUPS_FILE" +[ "${#GROUP_NAMES[@]}" -gt 0 ] || fail "no release tarballs named in ${GROUPS_FILE}" + +missing=() +for programs in "${GROUP_PROGRAMS[@]}"; do + for program in $programs; do + [ -f "${SOURCE}/${program}${EXT}" ] || missing+=("${program}${EXT}") + done +done +[ "${#missing[@]}" -eq 0 ] || fail "programs listed in ${GROUPS_FILE} are missing under ${SOURCE}: ${missing[*]}" + +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT +mkdir -p "${WORK}/tarballs" + +# --- macOS ----------------------------------------------------------------- + +macho_rpaths() { + otool -l "$1" | awk '$1 == "cmd" && $2 == "LC_RPATH" { getline; getline; print $2 }' +} + +# Copies into $DEST/lib every dylib program $1 reaches. dyld resolves the +# @rpath references of the program, and of each dylib it loads, through that +# file's own LC_RPATH entries and then the program's; @executable_path is the +# program's directory, the top of $SOURCE. +macos_closure() { + local program="$1" rpath entry file id ref candidate directory found + local program_rpaths=() rpaths=() queue=("$1") unresolved=() i=0 visited=$'\n'"$1"$'\n' + while IFS= read -r rpath; do + case "$rpath" in + @loader_path|@executable_path) entry="" ;; + @loader_path/*) entry="${rpath#@loader_path/}" ;; + @executable_path/*) entry="${rpath#@executable_path/}" ;; + /*) fail "${program} has an absolute LC_RPATH: ${rpath}" ;; + *) fail "${program} has an LC_RPATH dyld cannot resolve: ${rpath}" ;; + esac + case "/${entry}/" in */../*) fail "${program} has an LC_RPATH outside its directory: ${rpath}" ;; esac + program_rpaths+=("$entry") + done < <(macho_rpaths "${SOURCE}/${program}") + while [ "$i" -lt "${#queue[@]}" ]; do + file="${queue[$i]}"; i=$((i + 1)) + directory=$(dirname "$file") + [ "$directory" != . ] || directory="" + rpaths=() + if [ "$file" != "$program" ]; then + while IFS= read -r rpath; do + case "$rpath" in + @loader_path) entry="$directory" ;; + @loader_path/*) entry="${directory:+${directory}/}${rpath#@loader_path/}" ;; + @executable_path) entry="" ;; + @executable_path/*) entry="${rpath#@executable_path/}" ;; + /*) fail "${file} has an absolute LC_RPATH: ${rpath}" ;; + *) fail "${file} has an LC_RPATH dyld cannot resolve: ${rpath}" ;; + esac + # QtCore searches ../Frameworks, outside the tarball; nothing may load from there. + case "/${entry}/" in */../*) continue ;; esac + rpaths+=("$entry") + done < <(macho_rpaths "${SOURCE}/${file}") + fi + rpaths+=(${program_rpaths[@]+"${program_rpaths[@]}"}) + id=$(otool -D "${SOURCE}/${file}" | awk 'NR == 2 { print; exit }') + while IFS= read -r ref; do + [ "$ref" != "$id" ] || continue + found="" + case "$ref" in + /usr/lib/*|/System/Library/*) continue ;; + @rpath/*) + for entry in ${rpaths[@]+"${rpaths[@]}"}; do + candidate="${entry:+${entry}/}${ref#@rpath/}" + if [ -f "${SOURCE}/${candidate}" ]; then found="$candidate"; break; fi + done + ;; + @loader_path/*) + candidate="${directory:+${directory}/}${ref#@loader_path/}" + if [ -f "${SOURCE}/${candidate}" ]; then found="$candidate"; fi + ;; + @executable_path/*) + candidate="${ref#@executable_path/}" + if [ -f "${SOURCE}/${candidate}" ]; then found="$candidate"; fi + ;; + esac + case "/${found}/" in */../*) found="" ;; esac + case "$found" in lib/*) ;; *) found="" ;; esac + if [ -z "$found" ]; then + unresolved+=("${ref}(${file})") + continue + fi + case "$visited" in *$'\n'"$found"$'\n'*) continue ;; esac + visited="${visited}${found}"$'\n' + queue+=("$found") + if [ ! -e "${DEST}/${found}" ]; then + mkdir -p "$(dirname "${DEST}/${found}")" + cp -p "${SOURCE}/${found}" "${DEST}/${found}" + fi + done < <(otool -L "${SOURCE}/${file}" | awk 'NR > 1 { print $1 }') + done + [ "${#unresolved[@]}" -eq 0 ] || fail "references that resolve neither to lib/ under ${SOURCE} nor to the system: ${unresolved[*]}" +} + +macos_minimum() { + local file + find "$DEST" -type f ! -name '*.txt' ! -name COPYING | while IFS= read -r file; do + otool -l "$file" | awk ' + $1 == "Load" && $2 == "command" { command = "" } + $1 == "cmd" { command = $2 } + command == "LC_BUILD_VERSION" && $1 == "minos" { print $2 } + command == "LC_VERSION_MIN_MACOSX" && $1 == "version" { print $2 } + ' + done | sort -t . -k 1,1n -k 2,2n -k 3,3n | tail -n 1 +} + +# --- Windows --------------------------------------------------------------- + +windows_setup() { + have="${WORK}/have.tsv" + : > "$have" + for dll in "$DLL_DIR"/*.dll "$DLL_DIR"/*.DLL; do + [ -e "$dll" ] || continue + printf '%s\t%s\n' "$(basename "$dll" | tr '[:upper:]' '[:lower:]')" "$dll" >> "$have" + done + system="${WORK}/system.txt" + for file in "$SYSTEM_DIR"/*; do + printf '%s\n' "${file##*/}" + done | tr '[:upper:]' '[:lower:]' > "$system" +} + +windows_closure() { + local queue=("${DEST}"/*.exe) unresolved=() i=0 bin imports dep lower src target + while [ "$i" -lt "${#queue[@]}" ]; do + bin="${queue[$i]}"; i=$((i + 1)) + imports=$(objdump -p "$bin") || fail "objdump failed on ${bin##*/}" + while read -r dep; do + lower=$(printf '%s' "$dep" | tr '[:upper:]' '[:lower:]') + src=$(awk -F '\t' -v k="$lower" '$1 == k { print $2; exit }' "$have") + if [ -z "$src" ]; then + grep -qxF "$lower" "$system" || unresolved+=("${dep}(${bin##*/})") + continue + fi + target="${DEST}/$(basename "$src")" + [ ! -e "$target" ] || continue + cp "$src" "$target" + queue+=("$target") + done < <(awk '/DLL Name:/ { print $3 }' <<< "$imports") + done + [ "${#unresolved[@]}" -eq 0 ] || fail "DLL imports found in neither ${DLL_DIR} nor ${SYSTEM_DIR}: ${unresolved[*]}" +} + +# --- Linux ----------------------------------------------------------------- + +in_excludelist() { + local library="$1" pattern + case "$library" in ld-linux*|linux-vdso*) return 0 ;; esac + while IFS= read -r pattern; do + pattern="${pattern%%#*}" + pattern="${pattern//[[:space:]]/}" + [ -n "$pattern" ] || continue + # shellcheck disable=SC2254 # entries are glob patterns + case "$library" in $pattern) return 0 ;; esac + done < "$EXCLUDELIST" + return 1 +} + +linux_deploy() { + local appdir="${WORK}/appdir-$1" program arguments=() + shift + for program in "$@"; do + arguments+=(--executable "${SOURCE}/${program}") + done + env -u GITHUB_TOKEN APPIMAGE_EXTRACT_AND_RUN=1 \ + "$LINUXDEPLOY" --appimage-extract-and-run --appdir "$appdir" "${arguments[@]}" || + fail "linuxdeploy failed for ${NAME}" + mkdir -p "${DEST}/bin" "${DEST}/lib" + for program in "$@"; do + [ -f "${appdir}/usr/bin/${program}" ] || fail "linuxdeploy did not deploy ${program}" + cp -p "${appdir}/usr/bin/${program}" "${DEST}/bin/" + done + if [ -d "${appdir}/usr/lib" ]; then + find "${appdir}/usr/lib" -maxdepth 1 -type f -exec cp -p {} "${DEST}/lib/" \; + fi + if [ -d "${appdir}/usr/share/doc" ]; then + mkdir -p "${DEST}/share" + cp -R "${appdir}/usr/share/doc" "${DEST}/share/doc" + fi +} + +# Every library a file needs must resolve inside the tarball through that +# file's own RUNPATH (it is not inherited) or be on the excludelist. Records +# what the host must provide. +linux_check() { + local file relative directory dynamic line entry library found unresolved=() searched + # shellcheck disable=SC2016 # the loader's literal ORIGIN token + local origin='$ORIGIN' braced='${ORIGIN}' + : > "${WORK}/host-libraries.txt" + : > "${WORK}/host-versions.txt" + while IFS= read -r file; do + relative="${file#"${DEST}"/}" + dynamic=$(readelf -dW "$file") || fail "readelf failed on ${relative}" + directory=$(dirname "$file") + searched=() + while IFS= read -r line; do + [[ "$line" =~ \((RUNPATH|RPATH)\).*Library[[:space:]](runpath|rpath):[[:space:]]\[([^]]+)\] ]] || continue + # The loader reads an empty entry as the current directory. + case "${BASH_REMATCH[3]}" in + :*|*:|*::*) fail "${relative} has an empty RUNPATH entry: ${BASH_REMATCH[3]}" ;; + esac + IFS=: read -r -a entries <<< "${BASH_REMATCH[3]}" + for entry in "${entries[@]}"; do + case "$entry" in + "$origin"|"$braced") searched+=("$directory") ;; + "$origin"/*) searched+=("${directory}/${entry#"$origin"/}") ;; + "$braced"/*) searched+=("${directory}/${entry#"$braced"/}") ;; + *) fail "${relative} has a RUNPATH entry not relative to ${origin}: ${entry}" ;; + esac + done + done <<< "$dynamic" + while IFS= read -r line; do + [[ "$line" =~ \(NEEDED\).*Shared[[:space:]]library:[[:space:]]\[([^]]+)\] ]] || continue + library="${BASH_REMATCH[1]}" + if in_excludelist "$library"; then + printf '%s\n' "$library" >> "${WORK}/host-libraries.txt" + continue + fi + found="" + for entry in ${searched[@]+"${searched[@]}"}; do + if [ -f "${entry}/${library}" ]; then found=1; break; fi + done + [ -n "$found" ] || unresolved+=("${library}(${relative})") + done <<< "$dynamic" + readelf -VW "$file" | awk ' + /^Version needs section/ { needs = 1; next } + /^Version (definition|symbols) section/ { needs = 0 } + needs && match($0, /Name: (GLIBC|GLIBCXX)_[0-9.]+/) { print substr($0, RSTART + 6, RLENGTH - 6) } + ' >> "${WORK}/host-versions.txt" || fail "readelf failed on ${relative}" + done < <(find "${DEST}/bin" "${DEST}/lib" -type f) + [ "${#unresolved[@]}" -eq 0 ] || fail "libraries that resolve neither inside ${NAME} nor to linuxdeploy's excludelist: ${unresolved[*]}" +} + +highest_version() { + awk -v prefix="$1_" 'index($0, prefix) == 1 { print substr($0, length(prefix) + 1) }' "${WORK}/host-versions.txt" | + sort -t . -k 1,1n -k 2,2n -k 3,3n | tail -n 1 +} + +# --- Notices and README ---------------------------------------------------- + +bundled_libraries() { + case "$PLATFORM" in + macos) if [ -d "${DEST}/lib" ]; then find "${DEST}/lib" -type f; fi ;; + linux) find "${DEST}/lib" -type f ;; + windows) find "$DEST" -maxdepth 1 -type f -iname '*.dll' ;; + esac +} + +write_notices() { + local file name pattern component license url matched unknown=() + : > "${WORK}/notices.tsv" + shopt -s nocasematch # Windows DLL names vary in case + while IFS= read -r file; do + name="${file##*/}" + matched="" + while IFS=$'\t' read -r pattern component license url; do + case "$pattern" in ''|'#'*) continue ;; esac + # shellcheck disable=SC2254 # table entries are glob patterns + case "$name" in + $pattern) printf '%s\t%s\t%s\t%s\n' "$component" "$license" "$url" "$name" >> "${WORK}/notices.tsv"; matched=1; break ;; + esac + done < "$NOTICES_TABLE" + [ -n "$matched" ] || unknown+=("$name") + done < <(bundled_libraries) + shopt -u nocasematch + while IFS=$'\t' read -r pattern component license url; do + [ "$pattern" != "@${PLATFORM}" ] || printf '%s\t%s\t%s\t(static)\n' "$component" "$license" "$url" >> "${WORK}/notices.tsv" + done < "$NOTICES_TABLE" + [ "${#unknown[@]}" -eq 0 ] || fail "bundled libraries missing from ${NOTICES_TABLE##*/}: ${unknown[*]}" + { + echo "Third-party libraries in ${NAME}" + echo + if [ -s "${WORK}/notices.tsv" ]; then + echo "These libraries are not part of WSJT-X. Each is distributed under its own license, published at the address given." + echo + LC_ALL=C sort -t $'\t' -k 1,1 -k 4,4 "${WORK}/notices.tsv" | awk -F '\t' ' + function flush() { + if (files != "") print " Files:" files + if (static) print " Linked statically into the programs" + } + $1 != last { if (last != "") { flush(); print "" } printf "%s\n License: %s\n %s\n", $1, $2, $3; last = $1; files = ""; static = 0 } + $4 == "(static)" { static = 1; next } + { files = files " " $4 } + END { if (last != "") flush() } + ' + else + echo "This tarball bundles no third-party libraries." + fi + if [ -d "${DEST}/share/doc" ]; then + echo + echo "share/doc/ holds the copyright files of the Debian packages that bundled libraries come from; a library built outside a Debian package has none there." + fi + } > "${DEST}/THIRD-PARTY.txt" +} + +describe() { + local writes="writes working files to its data directory (-a) and its temporary directory (-t), both the current directory by default; run it where it can write, or point -a and -t at writable directories." + case "$1" in + jt9) + echo "jt9 is the decoder the WSJT-X application drives through shared memory (-s). It also decodes WAV files, and framed PCM audio on standard input (--stream). jt9stream, in its own tarball, is the same decoder without Qt or shared memory." + echo "jt9 ${writes}" + ;; + jt9stream) + echo "jt9stream is the decoder of jt9 without Qt or shared memory: it decodes WAV files, and framed PCM audio on standard input (--stream). Its usage text names jt9 and lists -s, which jt9stream does not support." + echo "jt9stream ${writes}" + ;; + wsprd) + echo "wsprd decodes WSPR from WAV files, and from framed PCM audio on standard input (-0)." + echo "wsprd writes working files to its data directory (-a, default the current directory) and stops if it cannot write there." + ;; + utilities) + echo "Utilities for testing decoders: wsprcode and encode77 encode messages; ft4sim, jt4sim, jt65sim, cwsim and sfoxsim write simulated signals to WAV files in the current directory, so run them where they can write." + ;; + *) fail "no README description for release tarball $1" ;; + esac +} + +# The notice doc/common/license.adoc asks anyone using WSJT-X under the GPL to display. +copyright_notice() { + tr -d '\r' < "$LICENSE_PAGE" | + awk '/^\*The algorithms/ { on = 1 } on { printf "%s ", $0 } on && /Development Group\.\*$/ { exit }' | + sed -e 's/_{prog}_/WSJT-X/g' -e 's/^\*//' -e 's/\* *$//' -e 's/ */ /g' -e 's/ *$//' +} + +write_readme() { + local group="$1" programs="$2" floor glibc glibcxx host notice + notice=$(copyright_notice) + [ -n "$notice" ] || fail "no copyright notice found in ${LICENSE_PAGE}" + { + echo "WSJT-X ${VERSION}: ${group} for ${TARGET}" + echo + echo "Programs: ${programs}" + describe "$group" + echo + case "$PLATFORM" in + macos) + floor=$(macos_minimum) + [ -n "$floor" ] || fail "no minimum macOS version recorded in ${NAME}" + echo "Layout: the programs are at the top of this directory and the libraries they load are in lib/. Keep lib/ beside the programs. They require macOS ${floor} or later." + echo + echo "The programs and libraries carry ad-hoc signatures and are not notarized. macOS blocks quarantined programs that are not notarized, so remove the quarantine attribute from the tarball before extracting it (xattr -d com.apple.quarantine ), or from an extracted directory (xattr -dr com.apple.quarantine ). Changing one of these files, for example with install_name_tool, invalidates its signature; sign it again with codesign --force --sign - ." + ;; + linux) + glibc=$(highest_version GLIBC) + glibcxx=$(highest_version GLIBCXX) + host=$(LC_ALL=C sort -u "${WORK}/host-libraries.txt" | paste -sd ' ' -) + echo "Layout: the programs are in bin/ and the libraries they load are in lib/. Keep both directories together." + echo + echo "The system must provide glibc ${glibc:-of any version}${glibc:+ or later}${glibcxx:+, libstdc++ with GLIBCXX_${glibcxx} or later}, and these libraries: ${host}." + echo "LD_LIBRARY_PATH takes precedence over the bundled lib/, so start the programs without it." + ;; + windows) + echo "Layout: the programs and the DLLs they load are in this directory. Keep them together." + echo + echo "The programs and DLLs carry no Authenticode signature." + ;; + esac + echo + echo "WSJT-X is free software under the GNU General Public License version 3 (COPYING). Its source code is wsjtx-${VERSION}-src.tar.gz on the same release page. THIRD-PARTY.txt lists the bundled libraries and their licenses." + echo + echo "$notice" + } > "${DEST}/README.txt" +} + +# --- Package --------------------------------------------------------------- + +[ "$PLATFORM" != windows ] || windows_setup +packaged=() +for index in "${!GROUP_NAMES[@]}"; do + group="${GROUP_NAMES[$index]}" + programs="${GROUP_PROGRAMS[$index]}" + NAME="wsjtx-${VERSION}-${TARGET}-${group}" + DEST="${WORK}/${NAME}" + mkdir -p "$DEST" + # shellcheck disable=SC2086 # program names are single words + case "$PLATFORM" in + macos) + for program in $programs; do + cp -p "${SOURCE}/${program}" "${DEST}/" + macos_closure "$program" + done + ;; + linux) + linux_deploy "$group" $programs + linux_check + ;; + windows) + for program in $programs; do cp "${SOURCE}/${program}.exe" "${DEST}/"; done + windows_closure + ;; + esac + cp "$COPYING" "${DEST}/COPYING" + write_notices + write_readme "$group" "$programs" + COPYFILE_DISABLE=1 tar -czf "${WORK}/tarballs/${NAME}.tar.gz" -C "$WORK" "$NAME" + packaged+=("${NAME}.tar.gz") +done + +mkdir -p "$OUT" +for tarball in "${packaged[@]}"; do + mv "${WORK}/tarballs/${tarball}" "${OUT}/${tarball}" + echo "packaged ${OUT}/${tarball}" +done diff --git a/.github/scripts/package-linux-armhf.sh b/.github/scripts/package-linux-armhf.sh index abef3284..552fea56 100755 --- a/.github/scripts/package-linux-armhf.sh +++ b/.github/scripts/package-linux-armhf.sh @@ -16,8 +16,6 @@ source .github/scripts/armhf-ci-image-config.sh # shellcheck source=.github/scripts/linux-artifact-validation.sh source .github/scripts/linux-artifact-validation.sh export LD_LIBRARY_PATH="$ARMHF_RUNTIME_PREFIX" -export ARMHF_QEMU_EXECUTABLE -export LINUX_APPIMAGE_RUNNER="$ARMHF_QEMU_EXECUTABLE" echo "::group::Package .deb" ( @@ -89,20 +87,14 @@ QT_PLUGIN_ASSET_ID="$( )" curl "${curl_flags[@]}" -o linuxdeploy.AppImage \ "https://github.com/linuxdeploy/linuxdeploy/releases/download/${LINUXDEPLOY_TAG}/linuxdeploy-armhf.AppImage" -mkdir -p wsjtx-build/appimage-tools -github_api_curl -H "Accept: application/octet-stream" \ - -o wsjtx-build/appimage-tools/qt-plugin.AppImage \ +github_api_curl -H "Accept: application/octet-stream" -o linuxdeploy-plugin-qt.AppImage \ "https://api.github.com/repos/linuxdeploy/linuxdeploy-plugin-qt/releases/assets/${QT_PLUGIN_ASSET_ID}" echo "$LINUXDEPLOY_SHA256 linuxdeploy.AppImage" | sha256sum -c - -chmod +x linuxdeploy.AppImage wsjtx-build/appimage-tools/qt-plugin.AppImage -# shellcheck disable=SC2016 # variables expand when the generated wrapper runs -printf '%s\n' \ - '#!/bin/sh' \ - 'exec "${ARMHF_QEMU_EXECUTABLE:?}" /work/wsjtx-build/appimage-tools/qt-plugin.AppImage "$@"' \ - > linuxdeploy-plugin-qt.AppImage -chmod +x linuxdeploy-plugin-qt.AppImage -# Supply linuxdeploy with the non-executing ARMHF resolver; native ldd cannot -# safely enter the target loader from this already-emulated container. +chmod +x linuxdeploy.AppImage linuxdeploy-plugin-qt.AppImage +# linuxdeploy resolves dependencies with the non-executing ARMHF resolver, +# which reads the clean runtime prefix first and refuses a libquadmath +# dependency the ARMHF runtime cannot satisfy. +mkdir -p wsjtx-build/appimage-tools ln -sfn /work/.github/scripts/armhf-static-ldd.sh wsjtx-build/appimage-tools/ldd for target in AppDir/usr/bin/wsjtx AppDir/usr/bin/jt9 AppDir/usr/bin/qmap \ @@ -113,7 +105,6 @@ done export APPIMAGE_EXTRACT_AND_RUN=1 export OUTPUT="wsjtx-${VERSION}-linux-${ARCH}.AppImage" env -u GITHUB_TOKEN PATH="/work/wsjtx-build/appimage-tools:$PATH" \ - "$ARMHF_QEMU_EXECUTABLE" \ ./linuxdeploy.AppImage --appimage-extract-and-run \ --appdir AppDir \ --plugin qt \ @@ -124,7 +115,7 @@ file "$OUTPUT" echo "::endgroup::" echo "::group::Validate AppImage payload" -"$ARMHF_QEMU_EXECUTABLE" ./"$OUTPUT" --appimage-extract >/dev/null +./"$OUTPUT" --appimage-extract >/dev/null validate_linux_application_tree squashfs-root appimage "$ARCH" rm -rf /work/squashfs-root echo "::endgroup::" @@ -134,4 +125,26 @@ run_packaged_appimage_startup_smoke \ "./$OUTPUT" wsjtx-build/appimage-startup-smoke.log echo "::endgroup::" +echo "::group::Package release tarballs" +PATH="/work/wsjtx-build/appimage-tools:$PATH" .github/scripts/package-cli-tools.sh \ + --platform linux \ + --version "$VERSION" \ + --arch "$ARCH" \ + --groups CMake/release-tarballs.txt \ + --source wsjtx-build \ + --linuxdeploy /work/linuxdeploy.AppImage \ + --out release-tarballs +echo "::endgroup::" + +# LD_LIBRARY_PATH, exported above, would hide a GCC runtime library missing +# from a tarball; the smoke test unsets it for every program it runs. +echo "::group::Smoke-test release tarballs" +.github/scripts/smoke-release-tarballs.sh \ + --platform linux \ + --version "$VERSION" \ + --target "linux-$ARCH" \ + --groups CMake/release-tarballs.txt \ + --dir release-tarballs +echo "::endgroup::" + echo "ARMHF package phase complete for version=$VERSION" diff --git a/.github/scripts/release-linux-images.py b/.github/scripts/release-linux-images.py new file mode 100644 index 00000000..260617ed --- /dev/null +++ b/.github/scripts/release-linux-images.py @@ -0,0 +1,202 @@ +#!/usr/bin/env python3 +"""Prepare and validate the Linux dependency selection committed with a release.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess +import sys +from urllib.parse import urlencode +from urllib.request import Request, urlopen + +PUBLIC = "ghcr.io/wsjtx/wsjtx" +PRIVATE = "ghcr.io/wsjtx/wsjtx-internal" +IMAGES = { + "x86_64": ("linux-noble", "normal-noble", "linux/amd64", "normal", "x86_64"), + "aarch64": ("linux-arm64-bookworm", "normal-bookworm", "linux/arm64", "normal", "aarch64"), + "armhf_cross": ("linux-armhf-cross-bookworm", "armhf-cross-bookworm", "linux/amd64", "cross-builder", "armhf"), + "armhf_runtime": ("linux-armv7-bookworm", "armhf-runtime-bookworm", "linux/arm/v7", "runtime", "armhf"), +} +DIGEST = re.compile(r"sha256:[0-9a-f]{64}\Z") +GENERATION = re.compile(r"validated-build-[0-9]{8}-[0-9]+-[0-9]+\Z") + + +def run(args, **kwargs): + return subprocess.run(args, check=True, text=True, capture_output=True, **kwargs).stdout.strip() + + +def fingerprint(profile): + return run(["bash", ".github/scripts/linux-ci-image-fingerprint.sh", profile]) + + +def inspect(reference, anonymous=False, missing_ok=False): + command = ["skopeo", "inspect"] + if anonymous: + command += ["--no-creds"] + command += ["--raw", "docker://" + reference] + try: + manifest = subprocess.run(command, check=True, capture_output=True).stdout + except subprocess.CalledProcessError as error: + # Authentication, transport and server errors must not authorize an overwrite. + if missing_ok and b"manifest unknown" in error.stderr.lower(): + return None + raise + return "sha256:" + hashlib.sha256(manifest).hexdigest() + + +def anonymous_digest(reference): + repository, digest = reference.removeprefix("ghcr.io/").split("@", 1) + query = urlencode({"service": "ghcr.io", "scope": f"repository:{repository}:pull"}) + with urlopen("https://ghcr.io/token?" + query, timeout=30) as response: + token = json.load(response)["token"] + request = Request(f"https://ghcr.io/v2/{repository}/manifests/{digest}", headers={ + "Authorization": f"Bearer {token}", + "Accept": ", ".join(("application/vnd.oci.image.manifest.v1+json", + "application/vnd.oci.image.index.v1+json", + "application/vnd.docker.distribution.manifest.v2+json", + "application/vnd.docker.distribution.manifest.list.v2+json")), + }) + with urlopen(request, timeout=30) as response: + return "sha256:" + hashlib.sha256(response.read()).hexdigest() + + +def validate(lock, check_remote=False): + if not isinstance(lock, dict) or lock.get("schema") != 1: + raise ValueError("Unsupported Linux image selection schema") + if not isinstance(lock.get("generation"), str) or not GENERATION.fullmatch(lock["generation"]): + raise ValueError("Select an explicit validated-build generation") + if not isinstance(lock.get("images"), dict) or set(lock["images"]) != set(IMAGES): + raise ValueError("Linux image selection must contain all four release images") + for key, (package, profile, *_rest) in IMAGES.items(): + image = lock["images"][key] + if not isinstance(image, dict): + raise ValueError(f"Malformed image selection: {key}") + reference = image.get("reference", "") + prefix = f"{PUBLIC}/{package}@" + if not isinstance(reference, str) or not reference.startswith(prefix) or not DIGEST.fullmatch(reference[len(prefix):]): + raise ValueError(f"Expected public digest-pinned image: {key}") + if image.get("recipe_sha256") != fingerprint(profile): + raise ValueError(f"Stale recipe for {key}; refresh and prepare the dependency images") + if check_remote and anonymous_digest(reference) != reference.split("@", 1)[1]: + raise ValueError(f"Public image digest mismatch: {key}") + return lock + + +def provenance(lock_path): + lock = validate(json.loads(Path(lock_path).read_text())) + return { + "lock_sha256": hashlib.sha256(Path(lock_path).read_bytes()).hexdigest(), + "builders": {key: image["reference"].split("@", 1)[1] for key, image in lock["images"].items()}, + } + + +def image_manifest(reference, spec, recipe, generation): + _package, _profile, platform, role, arch = spec + root = str(Path.cwd()) + helper = "verify-linux-ci-image.sh" if role == "normal" else "verify-armhf-ci-image.sh" + hamlib = run(["bash", "-c", '. .github/scripts/linux-ci-image-config.sh; printf "%s" "$LINUX_HAMLIB_REF"']) + command = ["docker", "run", "--rm", "--platform", platform, "--network", "none", + "--mount", f"type=bind,source={root},target=/source,readonly", "--workdir", "/source", + "-e", f"IMAGE_RECIPE_SHA256={recipe}", reference] + run(command + ["bash", f".github/scripts/{helper}", role, arch, hamlib]) + raw = run(command + ["cat", "/opt/wsjtx-ci/image.env"]) + manifest = dict(line.split("=", 1) for line in raw.splitlines() if "=" in line) + if manifest.get("generation") != generation.removeprefix("validated-"): + raise ValueError(f"Image generation mismatch: {reference}") + return manifest + + +def prepare(generation): + if not GENERATION.fullmatch(generation): + raise ValueError("Select an explicit validated-build generation") + lock = {"schema": 1, "generation": generation, "images": {}} + sources = {} + manifests = {} + # Freeze the entire cohort before downloading or copying any image. + for key, spec in IMAGES.items(): + package, profile, *_rest = spec + source = f"{PRIVATE}/{package}" + digest = inspect(f"{source}:{generation}") + sources[key] = f"{source}@{digest}" + lock["images"][key] = {"reference": f"{PUBLIC}/{package}@{digest}", "recipe_sha256": fingerprint(profile)} + for key, spec in IMAGES.items(): + manifests[key] = image_manifest(sources[key], spec, lock["images"][key]["recipe_sha256"], generation) + cross, runtime = manifests["armhf_cross"], manifests["armhf_runtime"] + for field in ("generation", "recipe_sha256", "toolchain_id"): + if not cross.get(field) or runtime.get("cross_" + field) != cross[field]: + raise ValueError(f"ARMHF image pair mismatch: {field}") + if not cross.get("runtime_sha256") or runtime.get("runtime_sha256") != cross["runtime_sha256"]: + raise ValueError("ARMHF image pair mismatch: runtime_sha256") + for key, spec in IMAGES.items(): + destination = f"{PUBLIC}/{spec[0]}:release-deps-{generation}" + digest = sources[key].split("@", 1)[1] + existing = inspect(destination, missing_ok=True) + if existing is not None and existing != digest: + raise ValueError(f"Conflicting retained image tag: {destination}") + if existing is None: + run(["skopeo", "copy", "--all", "--preserve-digests", "docker://" + sources[key], "docker://" + destination]) + if inspect(destination, anonymous=True) != digest: + raise ValueError(f"Public image digest mismatch: {destination}") + validate(lock, check_remote=True) + return lock, manifests + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + check = commands.add_parser("validate") + check.add_argument("lock") + check.add_argument("--check-remote", action="store_true") + check.add_argument("--github-output") + binding = commands.add_parser("provenance") + binding.add_argument("lock") + verify = commands.add_parser("verify-provenance") + verify.add_argument("lock") + verify.add_argument("provenance") + preparation = commands.add_parser("prepare") + preparation.add_argument("generation") + preparation.add_argument("--output-directory", required=True) + args = parser.parse_args() + if args.command == "prepare": + output = Path(args.output_directory) + if output.exists(): + raise ValueError("Preparation output directory must not already exist") + lock, manifests = prepare(args.generation) + output.mkdir(parents=True) + (output / "release-linux-images.json").write_text(json.dumps(lock, indent=2) + "\n") + record = {"source_sha": run(["git", "rev-parse", "HEAD"]), "run_url": os.environ.get("PREPARATION_RUN_URL"), "manifests": manifests} + (output / "preparation-record.json").write_text(json.dumps(record, indent=2) + "\n") + elif args.command == "provenance": + print(json.dumps(provenance(args.lock))) + elif args.command == "verify-provenance": + if json.loads(Path(args.provenance).read_text()).get("linux_images") != provenance(args.lock): + raise ValueError("Candidate Linux image provenance does not match the committed selection") + else: + lock = validate(json.loads(Path(args.lock).read_text()), args.check_remote) + bound = provenance(args.lock) + outputs = {"image_tag": lock["generation"], "lock_sha256": bound["lock_sha256"]} + for key, digest in bound["builders"].items(): + outputs[("armhf" if key == "armhf_runtime" else key) + "_digest"] = digest + if args.github_output: + with open(args.github_output, "a") as target: + target.write("".join(f"{key}={value}\n" for key, value in outputs.items())) + if os.environ.get("GITHUB_STEP_SUMMARY"): + with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as summary: + summary.write("## Linux release dependencies\n\n") + summary.write(f"Generation: `{lock['generation']}`. All recipe fingerprints match.\n\n") + for key, image in lock["images"].items(): + summary.write(f"- {key}: `{image['reference']}`\n") + print(json.dumps(bound)) + + +if __name__ == "__main__": + try: + main() + except (ValueError, OSError, subprocess.CalledProcessError) as error: + detail = error.stderr if isinstance(error, subprocess.CalledProcessError) else str(error) + if isinstance(detail, bytes): + detail = detail.decode("utf-8", errors="replace") + print(f"Linux release dependencies: {detail}", file=sys.stderr) + sys.exit(1) diff --git a/.github/scripts/release-policy.py b/.github/scripts/release-policy.py index ec7abe09..b2e160ce 100644 --- a/.github/scripts/release-policy.py +++ b/.github/scripts/release-policy.py @@ -7,33 +7,381 @@ import argparse import hashlib import json import re +import subprocess import sys import tarfile import zipfile +from collections.abc import Callable from pathlib import Path -VERSION_RE = re.compile(r"^(?P\d+\.\d+\.\d+)(?:-rc(?P[1-9]\d*))?$") +VERSION_RE = re.compile(r"^(?P\d+\.\d+\.\d+)(?:-(?P