Cotton code
188 lines · 7.4 KB · ShellRaw
#!/usr/bin/env bash# Make sure this machine's sccache server is listening before cargo runs, and# say so when it was not — a dead server is never silent again.## Without --run this is the standalone startup helper. With --run it probes# responsiveness and supervises cargo while the caller holds the lock. When# RUSTC_WRAPPER is sccache: the server `setup-sccache.sh` saw at the start of# the job can die while the job waits behind other lanes, and cargo would then# compile every crate uncached with one warning per crate buried in the log# (run 5645, one Mac: 19m33s). A server started here is started in a session of# its own (`scripts/lib/sccache-alone.sh`), with fd 9 — the cargo lock's —# closed by the caller, so it neither dies with this job nor holds the lock.## Startup exits 0 when listening, 1 if startup failed. --run returns the# command's final status, including after an uncached retry.set -uo pipefail# --run owns the cache health check and the command's watchdog. The caller# keeps its cargo/build locks throughout both attempts and closes lock fd 9.if [ "${1:-}" = --run ]; then  shift  python3 - "$(cd "$(dirname "${BASH_SOURCE[0]}")/../lib" && pwd)" "$@" 8<&0 <<'PYTHON'import os, re, signal, subprocess, sys, tempfile, timepolicy_dir, command = sys.argv[1], sys.argv[2:]env = os.environ.copy()def warn():    print("sccache not answering; building without it", file=sys.stderr, flush=True)child = Noneprobe = Nonedef interrupted(sig, frame):    if probe is not None and probe.poll() is None:        probe.kill()        probe.wait()    if child is not None and child.poll() is None:        stop(child)    sys.exit(128 + sig)signal.signal(signal.SIGTERM, interrupted)signal.signal(signal.SIGINT, interrupted)# A pipe could stay open in a daemon started by the client. A temporary file# keeps the deadline independent of inherited descriptors. Signal only the# client we started; the machine's shared cache server is never signalled.with tempfile.TemporaryFile() as stats:    try:        probe = subprocess.Popen([env.get("SCCACHE_BIN", "sccache"), "--show-stats"],                                 stdout=stats, stderr=stats, start_new_session=True)        try:            healthy = probe.wait(timeout=5) == 0        except subprocess.TimeoutExpired:            probe.kill()            probe.wait()            healthy = False        stats.seek(0)        answer = stats.read().decode(errors="replace")        healthy = healthy and bool(answer.strip()) and not re.search(            r"not accepting|not running|shutting down|server.*disabled", answer, re.I)    except OSError:        healthy = Falseif not healthy:    warn()    env["RUSTC_WRAPPER"] = ""# Read in-process (scripts/lib/mac_disk_policy.py), never through `ps`: a# lane's seatbelt refuses the setuid `ps` on a Mac, and this watchdog then died# with the build it was guarding. Follow PPIDs from the command root, never# from a machine-wide list of names. Cumulative CPU time detects progress even# when a lifetime CPU percentage rounds to zero.sys.path.insert(0, policy_dir)from mac_disk_policy import process_args, process_table, proc_info, proc_uintif sys.platform == "darwin":    import ctypes    class Timebase(ctypes.Structure):        _fields_ = [("numer", ctypes.c_uint32), ("denom", ctypes.c_uint32)]    timebase = Timebase()    ctypes.CDLL(None).mach_timebase_info(ctypes.byref(timebase))def cpu_used(pid):    """Cumulative user+system CPU of pid in hundredths of a second — the    resolution `ps time=` gave, so the forks of a waiting shell are not progress    — or None once it is gone."""    try:        if sys.platform == "darwin":            info = proc_info(pid, 4, 96)  # PROC_PIDTASKINFO: pti_total_user, pti_total_system, in mach ticks            ticks = proc_uint(info, 16, 8) + proc_uint(info, 24, 8)            return ticks * timebase.numer // timebase.denom // 10_000_000        fields = open(f"/proc/{pid}/stat").read().rsplit(")", 1)[1].split()        return (int(fields[11]) + int(fields[12])) * 100 // os.sysconf("SC_CLK_TCK")  # utime, stime    except (OSError, ValueError, IndexError):        return Nonedef descendants(root):    children = {}    for pid, parent, _ in process_table():        children.setdefault(parent, []).append(pid)    owned = {}    frontier = [root]    while frontier:        for pid in children.get(frontier.pop(), []):            if pid not in owned:                used, args = cpu_used(pid), process_args(pid)                if used is None or args is None:                    continue                owned[pid] = (used, " ".join(args))                frontier.append(pid)    return owneddef stop(child):    # Freeze the root and then its descendants before killing leaves. Parents    # cannot exit and orphan an unresponsive child between these signals.    if child.poll() is not None:        return    os.kill(child.pid, signal.SIGSTOP)    frozen = set()    while True:        tree = descendants(child.pid)        fresh = set(tree) - frozen        if not fresh:            break        for pid in tree:            if pid in fresh and pid in descendants(child.pid):                try:                    os.kill(pid, signal.SIGSTOP)                except ProcessLookupError:                    pass        frozen.update(fresh)    for pid in reversed(list(tree)):        if pid in descendants(child.pid):            try:                os.kill(pid, signal.SIGKILL)            except ProcessLookupError:                pass    child.kill()    child.wait()idle_limit = float(env.get("COTTON_SCCACHE_IDLE_S", "120"))poll = float(env.get("COTTON_SCCACHE_POLL_S", "5"))for attempt in range(2):    child = subprocess.Popen(command, env=env, stdin=8)    idle_since = None    previous = {}    retry = False    while child.poll() is None:        if healthy and attempt == 0:            tree = descendants(child.pid)            wrappers = {pid: row for pid, row in tree.items()                        if re.search(r"(?:^|/|\s)sccache[^\s]*\s+.*(?:^|/|\s)rustc(?:\s|$)", row[1])}            idle = bool(wrappers) and all(previous.get(pid) == row[0] for pid, row in wrappers.items())            now = time.monotonic()            idle_since = (idle_since if idle_since is not None else now) if idle else None            previous = {pid: row[0] for pid, row in wrappers.items()}            if idle_since is not None and now - idle_since >= idle_limit:                stop(child)                warn()                env["RUSTC_WRAPPER"] = ""                retry = True                break        try:            child.wait(timeout=poll if healthy and attempt == 0 else 0.1)        except subprocess.TimeoutExpired:            pass    if not retry:        status = child.wait()        sys.exit(status if status >= 0 else 128 - status)PYTHON  exit $?fi# shellcheck source=../lib/sccache-alone.sh. "$(cd "$(dirname "${BASH_SOURCE[0]}")/../lib" && pwd)/sccache-alone.sh"sccache_heal_tmpif sccache_listening; then  exit 0fiSCCACHE="${SCCACHE_BIN:-sccache}"echo "::warning::sccache: no server was listening when this cargo section began — starting one in a session of its own" >&2sccache_alone "$SCCACHE" --start-server || trueif sccache_listening; then  echo "sccache: server up again (cache at ${SCCACHE_DIR:-the default directory})" >&2  exit 0fiecho "::warning::sccache: the server did not come up — this cargo section compiles without the cache" >&2exit 1