Cotton code
325 lines · 14.6 KB · ShellRaw
#!/usr/bin/env bash# THIS MAC'S WALK SIMULATOR — the one simulator the launch smoke and the walk# may erase.##   scripts/ios-walk-sim.sh                     # print udid|name|runtime, creating it when missing#   scripts/ios-walk-sim.sh --cleanup           # CI: shut down and delete this job's devices#   scripts/ios-walk-sim.sh --cleanup-device ID # delete only this caller's walk device#   scripts/ios-walk-sim.sh --preflight         # refuse leftover job devices#   scripts/ios-walk-sim.sh --may-erase <udid>  # exit 0 when <udid> may be erased, 1 with the reason## `ios-launch-smoke.sh` ERASES the simulator it runs on. With no COTTON_SIM it# used to take the first iPhone listed, and on a Mac where other sessions work# that was a booted simulator someone was using (29 Sep). So every caller# with no COTTON_SIM — `ios-test.sh`, the smoke, the `ios` job and verify-main's# "which simulator" steps — asks here instead. The walk simulator is named# "<iPhone model> — walk-<host>"; the name is the mark that it was made for the# walk. When none exists this creates one from the newest iOS runtime's first# iPhone, so a fresh runner needs no setup. A COTTON_SIM already in the# environment at a local terminal is never overridden:# local callers only ask here when it is empty. CI callers always allocate# their own run/job/attempt namespace and delete it on exit.## `--may-erase` is the smoke's guard before `simctl erase`: a standing# simulator (`standing-<app>`) never may; a shut-down# simulator may be erased (nobody is using it), and so may this Mac's walk# simulator in any state; a BOOTED simulator the walk did not create may not.## COTTON_WALK_SIM_HOST overrides the host part of the name (tests).set -euo pipefailROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"# Keep the ownership helper with the entrypoint, as orphan-processes.sh does:# a pinned/copied script must not depend on a helper in the caller's checkout.simulator_owners() {  python3 - "$@" <<'PY_OWNERS'import jsonimport osfrom pathlib import Pathimport reimport subprocessimport sysROOT = Path(os.environ.get("COTTON_CACHE_ROOT", str(Path.home() / ".cache/cottondb"))) / "ci-simulators"def simctl(*args):    return subprocess.run(["xcrun", "simctl", *args], check=True, capture_output=True, text=True).stdoutdef record_path(key):    if not re.fullmatch(r"[a-f0-9]{20}", key):        raise ValueError("invalid CI simulator identity")    return ROOT / (key + ".json")def reap():    records = list(ROOT.glob("*.json"))    if not records:        return    devices = {d["udid"]: d for group in json.loads(simctl("list", "devices", "-j"))["devices"].values() for d in group}    for path in records:        try:            record_path(path.stem)            record = json.loads(path.read_text())            workspace = Path(record["workspace"])            suffix = record["suffix"]            if not workspace.is_absolute() or not suffix.endswith("-ci-" + path.stem):                raise ValueError("invalid ownership record")            # Workspace removal is the runner's end-of-job signal. Never infer            # completion from age: a live job can wait a long time for a lock.            if workspace.exists():                continue            device = devices.get(record["udid"])            if device:                if not device["name"].endswith(suffix):                    raise ValueError("simulator no longer matches its ownership record")                if workspace.exists():                    continue                if device["state"] != "Shutdown":                    simctl("shutdown", device["udid"])                simctl("delete", device["udid"])                print(f"ios-walk-sim: reclaimed canceled job simulator {device['udid']}", file=sys.stderr)            path.unlink(missing_ok=True)        except (OSError, ValueError, KeyError, TypeError, subprocess.CalledProcessError) as error:            print(f"ios-walk-sim: preserving {path.name}: {error}", file=sys.stderr)def job_alive(record):    workspace = Path(record["workspace"])    if not workspace.exists():        return False    if record.get("run") and record.get("job"):        reply = subprocess.run(["pnpm", "forge", "run", "view", record["run"], "--json", "jobs"],                               check=True, capture_output=True, text=True, timeout=30)        # pnpm writes its invocation banner ahead of the JSON result.        start = reply.stdout.find('{')        jobs = json.loads(reply.stdout[start:])["jobs"]        matches = [job for job in jobs if job["name"] == record["job"]]        if not matches:            raise ValueError("the owning job could not be found")        return any(job["status"] not in {"success", "failure", "cancelled", "skipped", "timed_out"} for job in matches)    # Legacy records have no run identity. A process holding the workspace is    # live; an empty retained workspace is not evidence of a running job.    opened = subprocess.run(["lsof", "-t", "+D", str(workspace)], capture_output=True, timeout=30)    if opened.returncode == 0:        return True    if opened.returncode == 1 and not opened.stdout and not opened.stderr:        return False    raise ValueError("could not establish the legacy job's liveness")def preflight():    records = {}    for path in ROOT.glob("*.json"):        record_path(path.stem)        record = json.loads(path.read_text())        if record["suffix"].endswith("-ci-" + path.stem):            records[record["udid"]] = (path, record)    devices = [d for group in json.loads(simctl("list", "devices", "-j"))["devices"].values() for d in group]    # Old host-named devices predate owner records. Their shell remains alive    # while a walk/test/build is waiting or running; no age heuristic is used.    processes = subprocess.run(["ps", "-axo", "args="], check=True, capture_output=True, text=True).stdout    legacy_alive = any(re.search(r"(?:^|[ /])(ios-launch-smoke|walk-board|ios-test|recopy-sim)\.sh(?:\s|$)", line)                       for line in processes.splitlines())    refused = []    for device in devices:        if not re.fullmatch(r".+ — walk-[a-z0-9-]+", device["name"]):            continue        if not device.get("udid") or device.get("state") not in {"Shutdown", "Booted", "Booting", "Shutting Down"}:            sys.exit("Simulator pre-flight refused: cannot inspect simulator identity or state: " + device["name"])        owned = records.get(device["udid"])        if owned:            path, record = owned            if not device["name"].endswith(record["suffix"]):                raise ValueError("simulator no longer matches its ownership record")            alive = job_alive(record)        else:            alive = legacy_alive        if alive:            refused.append(device["name"])            continue        if device["state"] != "Shutdown":            simctl("shutdown", device["udid"])        simctl("delete", device["udid"])        if owned:            path.unlink(missing_ok=True)        print(f"ios-walk-sim: reclaimed abandoned job simulator {device['udid']}", file=sys.stderr)    if refused:        sys.exit("Simulator pre-flight refused: owning job is alive: " + ", ".join(refused))def main():    command = sys.argv[1]    if command == "preflight":        preflight()    elif command == "reap":        try:            reap()        except (OSError, ValueError, KeyError, subprocess.CalledProcessError) as error:            print(f"ios-walk-sim: could not recover canceled job simulators: {error}", file=sys.stderr)    elif command == "forget":        record_path(sys.argv[2]).unlink(missing_ok=True)    elif command == "register":        key, suffix, udid = sys.argv[2:]        path = record_path(key)        workspace = Path(os.environ.get("GITHUB_WORKSPACE", os.getcwd())).resolve(strict=True)        if not suffix.endswith("-ci-" + key):            raise ValueError("invalid CI simulator suffix")        ROOT.mkdir(parents=True, exist_ok=True)        temporary = path.with_suffix(f".{os.getpid()}.tmp")        temporary.write_text(json.dumps({"workspace": str(workspace), "suffix": suffix, "udid": udid,                                          "run": os.environ.get("GITHUB_RUN_ID"), "job": os.environ.get("GITHUB_JOB")}))        temporary.replace(path)    else:        raise ValueError("unknown command")if __name__ == "__main__":    main()PY_OWNERS}host="${COTTON_WALK_SIM_HOST:-$(hostname -s)}"host="$(printf '%s' "$host" | tr '[:upper:]' '[:lower:]' | tr -c 'a-z0-9-' '-')"SUFFIX=" — walk-$host"# CI jobs must not share a simulator: a finished job may delete its device while# another job is waiting for the machine lock. Retries get a new namespace too.CI_KEY=""if [ -n "${GITHUB_RUN_ID:-}" ] && [ -n "${GITHUB_JOB:-}" ]; then  CI_KEY="$(python3 -c 'import hashlib,sys; print(hashlib.sha256("\0".join(sys.argv[1:]).encode()).hexdigest()[:20])' \    "$GITHUB_RUN_ID" "${GITHUB_RUN_ATTEMPT:-1}" "$GITHUB_JOB" "${GITHUB_WORKSPACE:-$PWD}")"  SUFFIX="$SUFFIX-ci-$CI_KEY"fi# Recover abandoned job devices before allocating; only a live owner refuses.if [ "${1:-}" = "--preflight" ]; then  [ "$#" -eq 1 ] || exit 2  simulator_owners preflight  exit $?fi# A device can shut itself down between the read and the shutdown (one Mac,# 8 Nov: after a 600 s diagnostics timeout, and swift-main run 8147 after a# green loom pass, "Unable to shutdown device in current state: Shutdown").# The delete is what says whether it is gone: simctl refuses to delete a# device still booted.shut_down_and_delete() {  if [ "$2" != Shutdown ]; then    xcrun simctl shutdown "$1" || echo "ios-walk-sim: $1 did not shut down from $2; the delete says whether it is gone" >&2  fi  xcrun simctl delete "$1"}# An explicit device is deleted only when its name proves this caller owns it.if [ "${1:-}" = "--cleanup-device" ]; then  [ "$#" -eq 2 ] && [ -n "$2" ] || exit 2  state="$(xcrun simctl list devices -j | SUFFIX="$SUFFIX" UDID="$2" python3 -c 'import json, os, sysfor group in json.load(sys.stdin)["devices"].values():    for d in group:        if d["udid"] == os.environ["UDID"]:            if not d["name"].endswith(os.environ["SUFFIX"]):                sys.exit("refusing cleanup of simulator owned by another caller: " + d["name"])            print(d["state"]); sys.exit(0)')"  # Already deleted (for example by a workflow post step) is harmless.  [ -n "$state" ] || exit 0  failed=0  shut_down_and_delete "$2" "$state" || failed=1  if [ "$failed" -eq 0 ] && [ -n "$CI_KEY" ]; then    simulator_owners forget "$CI_KEY"  fi  exit "$failed"fiif [ "${1:-}" = "--cleanup" ]; then  [ "$#" -eq 1 ] && [ -n "$CI_KEY" ] || { echo "ios-walk-sim: refusing cleanup without a CI run and job identity" >&2; exit 2; }  owned="$(xcrun simctl list devices -j | SUFFIX="$SUFFIX" python3 -c 'import json, os, sysfor devices in json.load(sys.stdin)["devices"].values():    for d in devices:        if d["name"].endswith(os.environ["SUFFIX"]):            print(d["udid"] + "|" + d["state"])')"  failed=0  while IFS='|' read -r udid state; do    [ -n "$udid" ] || continue    shut_down_and_delete "$udid" "$state" || { failed=1; continue; }    echo "ios-walk-sim: deleted job simulator $udid"  done <<< "$owned"  [ "$failed" -eq 0 ] || exit "$failed"  simulator_owners forget "$CI_KEY"  exit 0fiif [ "${1:-}" = "--may-erase" ]; then  [ -n "${2:-}" ] || { echo "ios-walk-sim: --may-erase needs a udid" >&2; exit 2; }  xcrun simctl list devices -j | SUFFIX="$SUFFIX" UDID="$2" python3 -c 'import json, os, syssuffix, udid = os.environ["SUFFIX"], os.environ["UDID"]for devices in json.load(sys.stdin)["devices"].values():    for d in devices:        if d["udid"] != udid:            continue        if d["name"].startswith("standing-"):            name = d["name"]            sys.exit(f"refusing to erase \"{name}\" ({udid}): it is a standing simulator, installed over and never erased by a job; pnpm sim:standing <app> --reset erases it.")        if d["name"].endswith(suffix) or d.get("state") != "Booted":            raise SystemExit(0)        name = d["name"]        sys.exit(f"refusing to erase \"{name}\" ({udid}): it is booted and it is not this Mac'"'"'s walk simulator, so another session may be using it. Leave COTTON_SIM unset to use the walk simulator, or shut this one down first.")sys.exit(f"no simulator {udid} on this Mac")'  exit $?fi[ $# -eq 0 ] || { echo "ios-walk-sim: unknown argument $1" >&2; exit 2; }if [ -n "$CI_KEY" ]; then  simulator_owners reapfi# Newest runtime first, by version number, not by string ("iOS-9" > "iOS-26").# A new walk simulator takes its model from the runtime's own list of the# iPhones it supports (Apple lists the newest first), never from another# device on this Mac: a Mac whose only simulator is a standing one (8 Nov)# has every runtime installed and no iPhone to copy.pick="$(DEVICES="$(xcrun simctl list devices available -j)" RUNTIMES="$(xcrun simctl list runtimes available -j)" SUFFIX="$SUFFIX" python3 -c 'import json, os, re, syssuffix = os.environ["SUFFIX"]found = json.loads(os.environ["DEVICES"])["devices"]def version(runtime):    return [int(n) for n in re.findall(r"\d+", runtime.rsplit(".", 1)[-1])]for r in sorted((r for r in found if "iOS" in r), key=version, reverse=True):    for d in found[r]:        if d["name"].endswith(suffix):            print("have|{}|{}|{}".format(d["udid"], d["name"], r)); raise SystemExitruntimes = [r for r in json.loads(os.environ["RUNTIMES"])["runtimes"]            if r.get("platform") == "iOS" and r.get("isAvailable", True)]for r in sorted(runtimes, key=lambda r: version(r["identifier"]), reverse=True):    for t in r.get("supportedDeviceTypes", []):        if t.get("productFamily") == "iPhone":            print("make|{}|{}|{}".format(t["identifier"], t["name"] + suffix, r["identifier"])); raise SystemExitsys.exit("no available iPhone simulator on this Mac - install an iOS runtime in Xcode")')"IFS='|' read -r verb first name runtime <<<"$pick"if [ "$verb" = make ]; then  first="$(xcrun simctl create "$name" "$first" "$runtime")"  echo "ios-walk-sim: created \"$name\" ($first) — this Mac's walk simulator" >&2  # The exit trap deletes this device; the claim is a backstop for hard kills.  bash "$ROOT/scripts/lane-claim.sh" "$HOME/Library/Developer/CoreSimulator/Devices/$first" \    --kind simulator --rule idle_hours:168 --lane walk >&2 || truefiif [ -n "$CI_KEY" ]; then  if ! simulator_owners register "$CI_KEY" "$SUFFIX" "$first"; then    # Disk-full must not strand a newly created device without an owner record.    xcrun simctl shutdown "$first" >/dev/null 2>&1 || true    xcrun simctl delete "$first" || true    exit 1  fifiecho "$first|$name|${runtime##*.}"