#!/usr/bin/env python3 """Prow CI release testing workflow for MicroShift. Manages the lifecycle of release testing PRs: create PR, trigger CI jobs, check status, download artifacts. Supports 4.21+ only. Usage: prow_testing.py [options] """ import argparse import json import logging import os import re import shutil import subprocess import sys import tarfile import requests from lib import brew, git_ops, prow logging.basicConfig( level=logging.INFO, format="%(levelname)s: %(message)s", stream=sys.stderr, ) logger = logging.getLogger(__name__) def _require_pr(version_info): """Find the release testing PR or exit with an error.""" pr = prow.find_release_testing_pr(version_info["pr_title"]) if pr is None: print(json.dumps({ "action": "error", "message": ( f"No release testing PR found for {version_info['version']}. " f"Run 'create-pr' to create one first." ), })) sys.exit(1) if isinstance(pr, list): print(json.dumps({ "action": "error", "message": "Multiple matching PRs found.", "prs": pr, })) sys.exit(1) return pr def _format_status_table(version_info, pr, statuses): """Format job statuses as a human-readable table.""" lines = [ f"Release Testing CI Status for {version_info['version']}", f"PR: #{pr['number']} ({pr['url']})", "", ] col_job = max(len(s["short_name"]) for s in statuses) col_job = max(col_job, len("Job")) status_icons = { "SUCCESS": "✅", "FAILURE": "❌", "ABORTED": "❌", "PENDING": "\U0001f7e0", } col_status = 9 header = f"{'Job':<{col_job}} | {'Status':<{col_status}} | Prow URL" sep = f"{'-' * col_job}-|-{'-' * col_status}-|{'-' * 50}" lines.append(header) lines.append(sep) for s in statuses: url_display = s["url"] if s["url"] else "(not started)" icon = status_icons.get(s["status"], "") display = f"{icon} {s['status']}" if icon else s["status"] lines.append(f"{s['short_name']:<{col_job}} | {display:<{col_status}} | {url_display}") lines.append("") counts = {} for s in statuses: counts[s["status"]] = counts.get(s["status"], 0) + 1 summary_parts = [ f"{v} {status_icons.get(k, '')} {k}".strip() for k, v in counts.items() ] lines.append(f"Summary: {', '.join(summary_parts)}") if counts.get("SUCCESS", 0) == len(statuses): lines.append("") lines.append( "All CI jobs passed. Run 'download' to download artifacts." ) return "\n".join(lines) _BUILD_CACHE_ARCHES = ["x86_64", "aarch64"] def _check_s3_rpms(v): """Check if RPMs exist in the S3 build cache for the target version.""" if not shutil.which("aws"): return { "check": "s3_rpms", "status": "FAIL", "reason": "aws CLI not found. Install and configure AWS CLI.", } minor = v["minor"] version = v["version"] failures = [] details = [] tar_path_for_version_check = None for arch in _BUILD_CACHE_ARCHES: base = f"{prow.S3_BUILD_CACHE}/release-{minor}/{arch}" last_result = subprocess.run( ["aws", "s3", "cp", f"{base}/last", "-"], capture_output=True, text=True, ) if last_result.returncode != 0 or not last_result.stdout.strip(): failures.append(f"{arch}: 'last' marker not found at {base}/last") continue date = last_result.stdout.strip() tar_path = f"{base}/{date}/brew-rpms.tar" ls_result = subprocess.run( ["aws", "s3", "ls", tar_path], capture_output=True, text=True, ) if ls_result.returncode != 0 or not ls_result.stdout.strip(): failures.append(f"{arch}: brew-rpms.tar not found at {tar_path}") continue details.append(f"{arch}: brew-rpms.tar found (date={date})") if tar_path_for_version_check is None: tar_path_for_version_check = tar_path if failures: return { "check": "s3_rpms", "status": "FAIL", "reason": f"Build cache check failed for {len(failures)} arch(es)", "details": failures + details, } if tar_path_for_version_check: brew_version = version.replace("-", "~") try: proc = subprocess.Popen( f"aws s3 cp '{tar_path_for_version_check}' - 2>/dev/null" f" | tar tf - 2>/dev/null | grep -m1 '{brew_version}'", shell=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, ) stdout, _ = proc.communicate(timeout=300) match = stdout.decode().strip() except subprocess.TimeoutExpired: if proc.poll() is None: proc.kill() match = None except OSError: match = None if match: details.append(f"Version match: found {brew_version} RPMs in tar") elif match is None: details.append( f"Version check timed out (tar is large) — " f"could not confirm {brew_version} RPMs" ) else: return { "check": "s3_rpms", "status": "FAIL", "reason": ( f"brew-rpms.tar does not contain RPMs for {version} " f"(searched for '{brew_version}')" ), "details": details, } return { "check": "s3_rpms", "status": "PASS", "reason": "brew-rpms.tar found in build cache for both arches", "details": details, } def _check_gh_auth(): """Check that the gh CLI is installed and authenticated.""" if not shutil.which("gh"): return { "check": "gh_auth", "status": "FAIL", "reason": "gh CLI not found. Install and authenticate the gh CLI.", } try: result = subprocess.run( ["gh", "auth", "status"], capture_output=True, text=True, timeout=30, ) except subprocess.TimeoutExpired: return { "check": "gh_auth", "status": "FAIL", "reason": "gh authentication check timed out after 30 seconds.", } if result.returncode != 0: return { "check": "gh_auth", "status": "FAIL", "reason": "gh authentication check failed. Run 'gh auth login'.", } return { "check": "gh_auth", "status": "PASS", "reason": "gh CLI is authenticated", } def _check_aws_auth(): """Validate credentials using the AWS CLI's normal provider chain.""" if not shutil.which("aws"): return { "check": "aws_auth", "status": "FAIL", "reason": "aws CLI not found. Install the AWS CLI.", } try: result = subprocess.run( ["aws", "sts", "get-caller-identity"], capture_output=True, text=True, timeout=30, ) except subprocess.TimeoutExpired: return { "check": "aws_auth", "status": "FAIL", "reason": "AWS authentication check timed out after 30 seconds.", } if result.returncode != 0: return { "check": "aws_auth", "status": "FAIL", "reason": ( "AWS authentication check failed. Check the AWS CLI credential " "configuration, selected profile and network access; run " "'aws sts get-caller-identity' to diagnose." ), } return { "check": "aws_auth", "status": "PASS", "reason": "AWS credentials valid", } def _check_gsutil_auth(): """Check that gsutil can read the public GCS bucket. Only needed later, by `download` — reported as WARN (not FAIL) so it doesn't block PR creation/triggering, but surfaces early enough that it can be fixed in parallel with the ~1-3h CI run instead of being discovered only after jobs finish. gcloud/gsutil reauth status lives entirely in the local credential store, not an env var, so this needs an actual call rather than a presence check. """ if not shutil.which("gsutil"): return { "check": "gsutil_auth", "status": "WARN", "reason": "gsutil not found. Needed later for the 'download' step.", } # Hardcoded rather than derived from lib.prow's bucket constants: this # check must work regardless of which bucket those point at, since its # whole purpose is verifying anonymous-capable access to the known-public # bucket specifically. try: result = subprocess.run( ["gsutil", "ls", "gs://test-platform-results-public/"], capture_output=True, text=True, timeout=30, ) except subprocess.TimeoutExpired: return { "check": "gsutil_auth", "status": "WARN", "reason": ( "gsutil authentication check timed out after 30 seconds. " "Needed later for the 'download' step." ), } if result.returncode != 0: return { "check": "gsutil_auth", "status": "WARN", "reason": ( "gsutil authentication check failed. Run 'gcloud auth login' " "interactively before the 'download' step." ), } return { "check": "gsutil_auth", "status": "PASS", "reason": "gsutil can access the public GCS bucket", } _GCSWEB_BASE = "https://gcsweb-ci.apps.ci.l2s4.p1.openshiftapps.com/gcs/test-platform-results-public" _SCENARIO_ROW_RE = re.compile( r'' ) _SCENARIO_NAME_RE = re.compile( r']*>([^<]+)' ) _VERSION_BADGE_RE = re.compile( r'([^<]+)' ) def _parse_scenarios(html): """Parse custom-link-tools.html and extract scenario results.""" scenarios = [] rows = html.split(" 0 for j in job_results) has_wrong_release = any( j.get("release_under_test") not in ("-", brew_version) for j in job_results ) if has_version_mismatch or has_failed or has_wrong_release: overall = "fail" else: overall = "pass" output = { "action": "scenarios", "status": overall, "version": v["version"], "jobs": job_results, } total_jobs = len(job_results) total_scenarios = sum(j.get("total", 0) for j in job_results) total_passed = sum(j.get("passed", 0) for j in job_results) total_failed = sum(j.get("failed", 0) for j in job_results) total_skipped = sum(j.get("skipped", 0) for j in job_results) parts = [f"{total_jobs} jobs, {total_scenarios} scenarios"] parts.append(f"{total_passed} passed") if total_failed: parts.append(f"{total_failed} failed") if total_skipped: parts.append(f"{total_skipped} skipped") errors = [] if has_wrong_release: wrong = [ f"{j['job']}={j['release_under_test']}" for j in job_results if j.get("release_under_test") not in ("-", brew_version) ] errors.append(f"release mismatch ({', '.join(wrong)})") if has_version_mismatch: errors.append("scenario version mismatch") summary = ", ".join(parts) if errors: summary += " — " + "; ".join(errors) output["message"] = summary print(json.dumps(output)) if overall == "fail": sys.exit(1) def cmd_preflight(args): """Run pre-flight checks before creating the release testing PR.""" v = prow.parse_version(args.version) checks = [] logger.info("Checking gh CLI authentication...") checks.append(_check_gh_auth()) logger.info("Checking AWS credentials...") aws_auth = _check_aws_auth() checks.append(aws_auth) logger.info("Verifying RPMs exist in build cache...") if aws_auth["status"] == "PASS": checks.append(_check_s3_rpms(v)) else: checks.append({ "check": "s3_rpms", "status": "SKIP", "reason": "Build cache check skipped because AWS authentication failed.", }) logger.info("Checking gsutil/gcloud authentication...") checks.append(_check_gsutil_auth()) has_fail = any(c["status"] == "FAIL" for c in checks) has_warn = any(c["status"] == "WARN" for c in checks) if has_fail: overall = "fail" elif has_warn: overall = "warn" else: overall = "pass" output = { "action": "preflight", "status": overall, "version": v["version"], "checks": checks, } if has_fail: output["message"] = "Pre-flight checks failed. Fix issues before creating PR." elif has_warn: output["message"] = "Pre-flight checks passed with warnings. Review before proceeding." else: output["message"] = "All pre-flight checks passed. Ready to create PR." print(json.dumps(output)) if has_fail: sys.exit(1) def _completion_comment_body(version): """The durable completion marker comment for a release version.""" return (f"Automated release testing for {version} completed. " "Artifacts uploaded to S3.") def _completed_release_pr(pr_title, version, trusted_login=None): """Durable completion record: a closed PR with our completion comment. A stateless run that rediscovers the Jira ticket must not recreate the PR and resubmit tests for an already-completed release. Every matching closed PR is inspected; the marker comment counts only when authored by a trusted release-automation identity (the current user, or a GitHub App bot) — a human's comment must not mark a release completed. Returns: ("completed", pr) — a completion record exists ("none", None) — the search succeeded, no record exists ("error", reason) — the check itself failed (unresolved) """ closed = prow.find_release_testing_pr(pr_title, state="closed") if not closed: return "none", None candidates = closed if isinstance(closed, list) else [closed] marker = f"Automated release testing for {version} completed" for pr in candidates: view = subprocess.run( ["gh", "pr", "view", str(pr["number"]), "--repo", prow.GH_REPO, "--json", "comments"], capture_output=True, text=True, ) if view.returncode != 0: return "error", (f"gh pr view failed for PR #{pr['number']}: " f"{view.stderr.strip()}") try: comments = json.loads(view.stdout).get("comments", []) except ValueError: return "error", f"non-JSON comment data for PR #{pr['number']}" for comment in comments: author = (comment.get("author") or {}).get("login", "") trusted = author.endswith("[bot]") or ( trusted_login and author == trusted_login) if marker in (comment.get("body") or "") and trusted: return "completed", pr return "none", None def _reusable_remote_branch(repo_dir, branch, version): """Reuse a branch pushed by a prior failed attempt, if it is ours. A prior attempt may have pushed the branch but failed to create the PR; not reusing it would wedge create-pr (pushing a recreated branch is a non-fast-forward). The branch is reused only after verifying its tip commit is this version's empty commit. The lookup follows the confirmed identity — a user's fork for users, the upstream repository for bots — and an unknown identity is an error, mirroring the identity guard in push_branch(). Returns the gh --head argument, or None. """ identity, detail = git_ops.gh_identity() if identity == "user": candidates = [(f"https://github.com/{detail}/microshift.git", detail)] elif identity == "bot": candidates = [("origin", None)] else: raise RuntimeError( f"Cannot determine the GitHub identity ({detail}); refusing " "branch reuse") # A ref private to this version: the shared clone's FETCH_HEAD can # be overwritten by a concurrent worker's fetch between this # worker's fetch and its log check. check_ref = f"refs/zstream-reuse/{version}" for remote_url, owner in candidates: ls = subprocess.run( ["git", "ls-remote", remote_url, f"refs/heads/{branch}"], cwd=repo_dir, capture_output=True, text=True, ) if ls.returncode != 0 or not ls.stdout.strip(): continue subprocess.run( ["git", "fetch", "--quiet", remote_url, f"refs/heads/{branch}:{check_ref}"], cwd=repo_dir, capture_output=True, text=True, check=True, ) subj = subprocess.run( ["git", "log", "-1", "--format=%s", check_ref], cwd=repo_dir, capture_output=True, text=True, ) # The tip must be this version's empty commit: same subject and # an identical tree to its parent (no smuggled changes). empty = subprocess.run( ["git", "diff", "--quiet", f"{check_ref}^", check_ref], cwd=repo_dir, capture_output=True, text=True, ) if (subj.returncode == 0 and subj.stdout.strip() == f"Release testing for {version}" and empty.returncode == 0): if owner: return f"{owner}:{branch}" return branch return None def cmd_create_pr(args): """Create a draft PR with an empty commit for release testing.""" v = prow.parse_version(args.version) existing = prow.find_release_testing_pr(v["pr_title"]) if existing and not isinstance(existing, list): print(json.dumps({ "action": "create-pr", "status": "exists", "pr": existing, "message": ( f"Release testing PR already exists: " f"PR #{existing['number']}: {existing['title']} — {existing['url']}" ), })) return if isinstance(existing, list): print(json.dumps({ "action": "create-pr", "status": "error", "message": "Multiple matching PRs found.", "prs": existing, })) sys.exit(1) head_branch = f"release-testing-{v['version']}" identity, detail = git_ops.gh_identity() gh_username = detail if identity == "user" else None record_status, record = _completed_release_pr( v["pr_title"], v["version"], trusted_login=gh_username) if record_status == "completed": print(json.dumps({ "action": "create-pr", "status": "completed", "pr": record, "message": (f"Release testing for {v['version']} already " f"completed (PR #{record['number']})."), })) return if record_status == "error": # Unresolved completion check: block creation rather than risk # resubmitting tests for a completed release. print(json.dumps({ "action": "create-pr", "status": "error", "message": (f"Could not verify whether release testing for " f"{v['version']} already completed: {record}"), })) sys.exit(1) if not args.execute: print(json.dumps({ "action": "create-pr", "status": "plan", "version": v["version"], "repo": prow.GH_REPO, "base_branch": v["branch"], "head_branch": head_branch, "fork": (f"{gh_username}/microshift" if gh_username else f"{prow.GH_REPO} (bot: same-repo branch)"), "pr_title": v["pr_title"], "mode": "draft", })) return logger.info("Ensuring MicroShift repo clone exists...") repo_dir = git_ops.ensure_microshift_repo() git_ops.fetch_branch(v["branch"]) # One lock across checkout/commit/push: concurrent workers share the # clone, and interleaved checkouts would push the wrong version's # branch. with git_ops.clone_mutation_lock(): head_arg = _reusable_remote_branch(repo_dir, head_branch, v["version"]) if head_arg: logger.info("Reusing existing remote branch %s", head_arg) else: logger.info("Creating branch %s from origin/%s...", head_branch, v["branch"]) subprocess.run( ["git", "checkout", "-B", head_branch, f"origin/{v['branch']}"], cwd=repo_dir, capture_output=True, text=True, check=True, ) logger.info("Creating empty commit...") subprocess.run( ["git", "commit", "--allow-empty", "-m", f"Release testing for {v['version']}"], cwd=repo_dir, capture_output=True, text=True, check=True, ) logger.info("Pushing %s...", head_branch) try: head_arg = git_ops.push_branch(head_branch) except RuntimeError as exc: print(json.dumps({ "action": "create-pr", "status": "error", "message": str(exc), })) sys.exit(1) logger.info("Creating draft PR...") body = ( f"Release testing PR for MicroShift {v['version']}. Do not merge.\n\n" "Created by /microshift-release:run-ci-testing" ) pr_result = subprocess.run( [ "gh", "pr", "create", "--repo", prow.GH_REPO, "--base", v["branch"], "--head", head_arg, "--title", v["pr_title"], "--body", body, "--draft", ], capture_output=True, text=True, ) if pr_result.returncode != 0: print(json.dumps({ "action": "create-pr", "status": "error", "message": f"gh pr create failed: {pr_result.stderr.strip()}", })) sys.exit(1) pr_url = pr_result.stdout.strip() print(json.dumps({ "action": "create-pr", "status": "created", "url": pr_url, "message": f"Draft PR created: {pr_url}", })) _CACHE_JOBS = ["e2e-aws-tests-cache", "e2e-aws-tests-cache-arm"] _MARKER_READ_ERROR = "marker-read-error" # sentinel: the read itself failed def _cache_last_marker(cache_base): """Read a build-cache 'last' marker. Returns the marker value, None when the marker is confirmed absent (key not found), or _MARKER_READ_ERROR when the read itself failed (e.g. access denied) — the caller must not treat that as an absent marker. """ result = subprocess.run( ["aws", "s3", "cp", f"{cache_base}/last", "-"], capture_output=True, text=True, ) if result.returncode != 0: err = (result.stderr or "").lower() if ("404" in err or "nosuchkey" in err or "not found" in err or "keydoesnotexist" in err): return None return _MARKER_READ_ERROR return result.stdout.strip() or None def cmd_refresh_cache(args): """Clear the stale build-cache entry and retrigger the cache jobs. Follows the manual procedure: run ``manage_build_cache.sh dellast`` from the MicroShift repo — it deletes the data the 'last' marker points at and repoints 'last' to the current version's Brew build — then post the /test cache-job comments on the release-testing PR so the cache is rebuilt from current tags. Idempotent per architecture: an arch whose 'last' already points at this build (a previous attempt, or the cache job itself) is skipped, so a retry resumes the unfinished arch without repeating — and re-deleting — a successful deletion. A failed deletion fails the command, naming the affected architecture, before any /test comments are posted. """ v = prow.parse_version(args.version) pr = _require_pr(v) if not shutil.which("aws"): print(json.dumps({ "action": "refresh-cache", "status": "error", "message": "aws CLI not found. Install and configure AWS CLI.", })) sys.exit(1) logger.info("Looking up the Brew build ID for %s...", v["version"]) build_id = brew.get_build_id(v["version"], v["release_type"]) if not build_id: print(json.dumps({ "action": "refresh-cache", "status": "error", "message": (f"Could not determine the Brew build ID for " f"{v['version']} — is the build complete?"), })) sys.exit(1) repo_dir = git_ops.ensure_microshift_repo() script = os.path.join(repo_dir, "test", "bin", "manage_build_cache.sh") if not os.path.isfile(script): print(json.dumps({ "action": "refresh-cache", "status": "error", "message": f"manage_build_cache.sh not found at {script}", })) sys.exit(1) env = dict(os.environ, AWS_BUCKET_NAME=prow.S3_BUILD_CACHE.removeprefix("s3://")) cache_log = [] failed_archs = [] for arch in _BUILD_CACHE_ARCHES: base = f"{prow.S3_BUILD_CACHE}/release-{v['minor']}/{arch}" current = _cache_last_marker(base) if current is _MARKER_READ_ERROR: # The read failed (e.g. access denied): skipping deletion # here would report a refresh that never happened. failed_archs.append(arch) cache_log.append(f"{arch}: could not read the 'last' marker " "(aws error); refresh aborted for this arch") continue if current == build_id: # Already deleted and repointed by a previous attempt (or # the cache job already set it): repeating dellast would # delete the current, correct data. cache_log.append(f"{arch}: 'last' already points at " f"{build_id}; nothing to delete") continue if current is None: # No marker at all: nothing to delete, and the retriggered # cache job creates it. cache_log.append(f"{arch}: no 'last' marker; the cache job " "will create it") continue cmd = ["bash", script, "dellast", "-b", v["branch"], "-t", build_id, "-a", arch] if not args.execute: cache_log.append(f"{arch}: would run '{' '.join(cmd)}'") continue result = subprocess.run(cmd, capture_output=True, text=True, cwd=repo_dir, env=env) if result.returncode == 0: cache_log.append(f"{arch}: stale entry deleted (was " f"{current}), last -> {build_id}") else: failed_archs.append(arch) cache_log.append(f"{arch}: dellast failed: " f"{result.stderr.strip()[-200:]}") if failed_archs: # The cache for these architectures was not repaired: do not # post /test comments or report a refresh. print(json.dumps({ "action": "refresh-cache", "status": "error", "message": ("build-cache deletion failed for: " + ", ".join(failed_archs)), "build_id": build_id, "cache": cache_log, })) sys.exit(1) comment_body = "\n".join(f"/test {job}" for job in _CACHE_JOBS) if not args.execute: print(json.dumps({ "action": "refresh-cache", "status": "plan", "pr_number": pr["number"], "pr_url": pr["url"], "build_id": build_id, "comment": comment_body, "cache": cache_log, })) return result = subprocess.run( ["gh", "pr", "comment", str(pr["number"]), "--repo", prow.GH_REPO, "--body", comment_body], capture_output=True, text=True, ) if result.returncode != 0: print(json.dumps({ "action": "refresh-cache", "status": "error", "message": f"gh pr comment failed: {result.stderr.strip()}", "build_id": build_id, "cache": cache_log, })) sys.exit(1) print(json.dumps({ "action": "refresh-cache", "status": "triggered", "pr_number": pr["number"], "pr_url": pr["url"], "build_id": build_id, "jobs": _CACHE_JOBS, "cache": cache_log, "message": f"Cache cleared (last -> {build_id}) and cache jobs " f"retriggered on PR #{pr['number']}.", })) def cmd_trigger(args): """Post /test comments to trigger failed CI jobs only.""" v = prow.parse_version(args.version) pr = _require_pr(v) logger.info("Fetching job statuses for PR #%s...", pr["number"]) gcs_jobs = prow.list_pr_jobs(pr["number"]) matched = prow.match_ci_jobs(gcs_jobs, v["minor"]) statuses = prow.fetch_all_job_statuses(pr["number"], matched, v["minor"]) failed_statuses = {"FAILURE", "ABORTED", "ERROR"} not_started = [s for s in statuses if s["status"] == "--"] failed = [s for s in statuses if s["status"] in failed_statuses] jobs_to_trigger = not_started + failed if not jobs_to_trigger: print(json.dumps({ "action": "trigger", "status": "skip", "pr_number": pr["number"], "pr_url": pr["url"], "message": "No failed jobs to retrigger. All jobs are successful or in progress.", "jobs": [{"job": s["short_name"], "status": s["status"]} for s in statuses], })) return trigger_names = [s["short_name"] for s in jobs_to_trigger] comment_body = "\n".join(f"/test {job}" for job in trigger_names) if not args.execute: print(json.dumps({ "action": "trigger", "status": "plan", "pr_number": pr["number"], "pr_url": pr["url"], "comment": comment_body, "jobs": trigger_names, "skipped": [ {"job": s["short_name"], "status": s["status"]} for s in statuses if s not in jobs_to_trigger ], })) return logger.info("Posting /test comment on PR #%s...", pr["number"]) result = subprocess.run( [ "gh", "pr", "comment", str(pr["number"]), "--repo", prow.GH_REPO, "--body", comment_body, ], capture_output=True, text=True, ) if result.returncode != 0: print(json.dumps({ "action": "trigger", "status": "error", "message": f"gh pr comment failed: {result.stderr.strip()}", })) sys.exit(1) print(json.dumps({ "action": "trigger", "status": "triggered", "pr_number": pr["number"], "jobs": trigger_names, "message": f"{len(trigger_names)} failed job(s) retriggered on PR #{pr['number']}.", })) def cmd_status(args): """Check and display CI job statuses.""" v = prow.parse_version(args.version) pr = _require_pr(v) logger.info("Fetching job list from GCS for PR #%s...", pr["number"]) gcs_jobs = prow.list_pr_jobs(pr["number"]) matched = prow.match_ci_jobs(gcs_jobs, v["minor"]) logger.info("Fetching build statuses...") statuses = prow.fetch_all_job_statuses(pr["number"], matched, v["minor"]) if args.json_output: print(json.dumps({ "action": "status", "pr": pr, "jobs": statuses, })) else: print(_format_status_table(v, pr, statuses)) def cmd_complete(args): """Post completion comment, close PR, and delete branch (idempotent). Retries after a partially-successful completion are tolerated: a PR that is already closed is reported as completed, and a close that raced with another attempt is re-checked before failing. """ v = prow.parse_version(args.version) pr = prow.find_release_testing_pr(v["pr_title"]) if pr is None: # A retry whose close already succeeded: the PR is no longer # open. Reconcile the durable completion record (the marker # comment) before reporting success — a closed PR without it # would be recreated by a stateless create-pr. closed = prow.find_release_testing_pr(v["pr_title"], state="closed") if closed and not isinstance(closed, list): marker = (f"Automated release testing for {v['version']} " "completed") view = subprocess.run( ["gh", "pr", "view", str(closed["number"]), "--repo", prow.GH_REPO, "--json", "comments"], capture_output=True, text=True, ) has_record = False if view.returncode == 0: try: has_record = any( marker in (c.get("body") or "") for c in json.loads(view.stdout).get("comments", [])) except ValueError: pass if not has_record: comment_result = subprocess.run( ["gh", "pr", "comment", str(closed["number"]), "--repo", prow.GH_REPO, "--body", _completion_comment_body(v["version"])], capture_output=True, text=True, ) if comment_result.returncode != 0: print(json.dumps({ "action": "complete", "status": "error", "message": ("PR is closed without a completion " "record and posting it failed: " f"{comment_result.stderr.strip()}"), })) sys.exit(1) print(json.dumps({ "action": "complete", "status": "completed", "pr_number": closed["number"], "url": closed["url"], "message": (f"PR #{closed['number']} is already closed — " "completion already done."), })) return print(json.dumps({ "action": "error", "message": (f"No release testing PR found for {v['version']} " "(open or closed). Run 'create-pr' to create one " "first."), })) sys.exit(1) if isinstance(pr, list): print(json.dumps({ "action": "error", "message": "Multiple matching PRs found.", "prs": pr, })) sys.exit(1) head_branch = f"release-testing-{v['version']}" if not args.execute: print(json.dumps({ "action": "complete", "status": "plan", "pr_number": pr["number"], "pr_url": pr["url"], "actions": [ f"Post completion comment on PR #{pr['number']}", f"Close PR #{pr['number']}", f"Delete remote branch {head_branch}", ], })) return logger.info("Posting completion comment on PR #%s...", pr["number"]) comment_result = subprocess.run( [ "gh", "pr", "comment", str(pr["number"]), "--repo", prow.GH_REPO, "--body", _completion_comment_body(v["version"]), ], capture_output=True, text=True, ) if comment_result.returncode != 0: print(json.dumps({ "action": "complete", "status": "error", "message": f"gh pr comment failed: {comment_result.stderr.strip()}", })) sys.exit(1) def _pr_state(): state_result = subprocess.run( ["gh", "pr", "view", str(pr["number"]), "--repo", prow.GH_REPO, "--json", "state", "-q", ".state"], capture_output=True, text=True, ) if state_result.returncode == 0: return state_result.stdout.strip() return "" def _head_ref_absent(): """True only when the API confirms the head branch is gone. False when it is present (after a deletion attempt). None when the verification itself failed — a connection error is a retryable unknown, not a confirmed absence, so the release must not be marked complete on it. """ info = subprocess.run( ["gh", "pr", "view", str(pr["number"]), "--repo", prow.GH_REPO, "--json", "headRepositoryOwner,headRepository,headRefName", "-q", '.headRepositoryOwner.login + " " ' '+ .headRepository.name + " " + .headRefName'], capture_output=True, text=True, ) if info.returncode != 0: return None parts = info.stdout.split() if len(parts) != 3 or "null" in parts: return None owner, repo_name, ref_name = parts # The documented singular ref route; the slash in "heads/…" # is percent-encoded in the path. ref = f"repos/{owner}/{repo_name}/git/ref/heads%2F{ref_name}" def _absent(check): err = (check.stderr or "") return "404" in err or "Not Found" in err check = subprocess.run(["gh", "api", ref], capture_output=True, text=True) if check.returncode == 0: # Branch present: delete it, then confirm. subprocess.run(["gh", "api", "-X", "DELETE", ref], capture_output=True, text=True) recheck = subprocess.run(["gh", "api", ref], capture_output=True, text=True) if recheck.returncode == 0: return False # still present return True if _absent(recheck) else None return True if _absent(check) else None if _pr_state() == "CLOSED": # A previous attempt (or a human) already closed it. logger.info("PR #%s is already closed; skipping close", pr["number"]) else: logger.info("Closing PR #%s and deleting branch %s...", pr["number"], head_branch) close_result = subprocess.run( [ "gh", "pr", "close", str(pr["number"]), "--repo", prow.GH_REPO, "--delete-branch", ], capture_output=True, text=True, ) if close_result.returncode != 0 and _pr_state() != "CLOSED": # Tolerate a close that raced with another attempt: if the # PR is now closed, the outcome is what we wanted. print(json.dumps({ "action": "complete", "status": "error", "message": f"gh pr close failed: {close_result.stderr.strip()}", })) sys.exit(1) absent = _head_ref_absent() if absent is not True: detail = ("could not be deleted" if absent is False else "could not be verified (API error)") print(json.dumps({ "action": "complete", "status": "error", "message": (f"PR #{pr['number']} is closed but branch " f"{head_branch} {detail}."), })) sys.exit(1) print(json.dumps({ "action": "complete", "status": "completed", "pr_number": pr["number"], "url": pr["url"], "message": ( f"PR #{pr['number']} commented, closed, " f"and branch {head_branch} deleted." ), })) def cmd_download(args): """Download job artifacts from GCS.""" v = prow.parse_version(args.version) pr = _require_pr(v) if not shutil.which("gsutil"): print(json.dumps({ "action": "download", "status": "error", "message": "gsutil not found. Install Google Cloud SDK.", })) sys.exit(1) logger.info("Checking job statuses for PR #%s...", pr["number"]) gcs_jobs = prow.list_pr_jobs(pr["number"]) matched = prow.match_ci_jobs(gcs_jobs, v["minor"]) statuses = prow.fetch_all_job_statuses(pr["number"], matched, v["minor"]) completed = [ s for s in statuses if s["status"] in ("SUCCESS", "FAILURE") and s["job"] ] if not completed: print(json.dumps({ "action": "download", "status": "error", "message": "No completed jobs to download.", "jobs": statuses, })) sys.exit(1) download_dir = os.path.join( git_ops._get_edge_tooling_root(), "_output", f"release-testing-{v['version']}", ) if not args.execute: print(json.dumps({ "action": "download", "status": "plan", "pr_number": pr["number"], "pr_url": pr["url"], "download_dir": download_dir, "jobs": [s["short_name"] for s in completed], })) return # Each attempt starts clean: leftovers from a previous, possibly # partial attempt must not leak into this attempt's upload archive. if os.path.isdir(download_dir): shutil.rmtree(download_dir) os.makedirs(download_dir, exist_ok=True) results = [] for s in completed: gcs_path = ( f"gs://test-platform-results-public/{prow.GCS_PR_PREFIX}/" f"{pr['number']}/{s['job']}/{s['build_id']}/" ) job_dir = os.path.join(download_dir, s["short_name"]) os.makedirs(job_dir, exist_ok=True) logger.info("Downloading %s → %s", s["short_name"], job_dir) dl_result = subprocess.run( ["gsutil", "-q", "-m", "cp", "-r", gcs_path, job_dir], capture_output=True, text=True, ) results.append({ "job": s["short_name"], "status": s["status"], "path": job_dir, "success": dl_result.returncode == 0, "error": dl_result.stderr.strip() if dl_result.returncode != 0 else None, }) all_ok = all(r["success"] for r in results) output = { "action": "download", "status": "completed" if all_ok else "partial", "download_dir": download_dir, "jobs": results, } if args.json_output: print(json.dumps(output)) else: print(f"Artifacts downloaded to: {download_dir}/") print() for r in results: marker = "OK" if r["success"] else "FAIL" print(f" [{marker}] {r['job']} → {r['path']}") if r["error"]: print(f" Error: {r['error']}") print() print(f"Run 'upload {v['version']}' to compress and upload to S3.") def cmd_upload(args): """Compress artifacts into tar.gz and upload to S3.""" v = prow.parse_version(args.version) if not shutil.which("aws"): print(json.dumps({ "action": "upload", "status": "error", "message": "aws CLI not found. Install and configure AWS CLI.", })) sys.exit(1) download_dir = os.path.join( git_ops._get_edge_tooling_root(), "_output", f"release-testing-{v['version']}", ) if not os.path.isdir(download_dir) or not os.listdir(download_dir): print(json.dumps({ "action": "upload", "status": "error", "message": ( f"No artifacts found at {download_dir}. " "Run 'download' first." ), })) sys.exit(1) tar_name = f"{v['version']}_prow_ci_release_testing_logs.tar.gz" tar_path = os.path.join( git_ops._get_edge_tooling_root(), "_output", tar_name, ) s3_dest = f"{prow.S3_BUCKET}/{v['version']}/{tar_name}" if not args.execute: print(json.dumps({ "action": "upload", "status": "plan", "source_dir": download_dir, "tar_path": tar_path, "s3_destination": s3_dest, "actions": [ f"Compress {download_dir}/ → {tar_name}", f"Upload {tar_name} → {s3_dest}", ], })) return logger.info("Compressing %s → %s...", download_dir, tar_path) with tarfile.open(tar_path, "w:gz") as tar: tar.add(download_dir, arcname=f"release-testing-{v['version']}") tar_size_mb = os.path.getsize(tar_path) / (1024 * 1024) logger.info("Created %s (%.1f MB)", tar_name, tar_size_mb) logger.info("Uploading to %s...", s3_dest) upload_result = subprocess.run( ["aws", "s3", "cp", tar_path, s3_dest], capture_output=True, text=True, ) if upload_result.returncode != 0: print(json.dumps({ "action": "upload", "status": "error", "message": f"aws s3 cp failed: {upload_result.stderr.strip()}", })) sys.exit(1) public_url = s3_dest.replace( "s3://release-testing-results", "https://release-testing-results.s3.us-west-2.amazonaws.com", ) print(json.dumps({ "action": "upload", "status": "uploaded", "tar_path": tar_path, "s3_destination": s3_dest, "public_url": public_url, "size_mb": round(tar_size_mb, 1), "message": f"Uploaded {tar_name} ({tar_size_mb:.1f} MB) to {public_url}", })) def main(): parser = argparse.ArgumentParser( description="MicroShift Prow CI release testing", ) subparsers = parser.add_subparsers(dest="action", required=True) for name, handler, mutating, help_text in [ ("preflight", cmd_preflight, False, "Run pre-flight checks"), ("create-pr", cmd_create_pr, True, "Create draft PR with empty commit"), ("refresh-cache", cmd_refresh_cache, True, "Clear stale build-cache markers and retrigger cache jobs"), ("trigger", cmd_trigger, True, "Trigger CI jobs via /test comment"), ("status", cmd_status, False, "Check CI job statuses"), ("scenarios", cmd_scenarios, False, "Validate scenarios and versions in completed jobs"), ("download", cmd_download, True, "Download artifacts from GCS"), ("upload", cmd_upload, True, "Compress and upload artifacts to S3"), ("complete", cmd_complete, True, "Post comment, close PR, delete branch"), ]: sp = subparsers.add_parser(name, help=help_text) sp.add_argument("version", help="MicroShift version (X.Y.Z, X.Y.Z-rc.N, X.Y.Z-ec.N)") sp.add_argument("--json", action="store_true", dest="json_output", help="JSON output") if mutating: sp.add_argument("--execute", action="store_true", help="Execute (default: dry-run)") sp.set_defaults(func=handler) args = parser.parse_args() try: args.func(args) except (ValueError, RuntimeError) as e: print(json.dumps({"action": "error", "message": str(e)})) sys.exit(1) except Exception as e: print(json.dumps({"action": "error", "message": str(e)})) sys.exit(1) if __name__ == "__main__": main()