Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ jobs:
test:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python: ["3.10", "3.13"]
steps:
Expand Down
49 changes: 32 additions & 17 deletions board/board-ctl.sh
Original file line number Diff line number Diff line change
Expand Up @@ -41,22 +41,28 @@ alive() {
}

# --- lock: the same text in scripts/gh-runners-ctl.sh, scripts/runner-ctl.sh and board/board-ctl.sh ---
# Serialises start/stop/restart (Termux:Boot and an SSH session at the same moment). mkdir is atomic, so
# whoever creates $LOCK holds it. The holder then writes "<pid> <start>" to $LOCK/pid, <start> being field
# 22 of /proc/<pid>/stat (when that process started, in clock ticks since boot). The lock is stale only
# when that process is gone: the pid is dead, or now belongs to a process with another start time (pids
# are reused, after a reboot above all, and the lock directory survives one). A restart holds it for as
# long as it takes.
# Serialises start/stop/restart (Termux:Boot and an SSH session at the same moment). The lock is the
# directory $LOCK with the file $LOCK/pid in it, "<pid> <start>" of the holder, <start> being field 22 of
# /proc/<pid>/stat (when that process started, in clock ticks since boot). A call holds the lock when it
# creates $LOCK and then creates $LOCK/pid itself under noclobber (set -C: the shell opens the file with
# O_EXCL, so of several calls exactly one creates it). The exit status of mkdir alone does not decide:
# uutils mkdir, the default mkdir on Ubuntu 26.04, also reports success to a call whose directory another
# call created a moment before. A call that loses leaves the directory alone: it is the winner's.
# The lock is stale only when its holder is gone: the pid is dead, or now belongs to a process with another
# start time (pids are reused, after a reboot above all, and the lock directory survives one). A restart
# holds it for as long as it takes.
# With no readable pid (the holder died between mkdir and writing it, or an older version of these
# scripts, which wrote none, holds it), the lock is stale once find -mmin +LOCK_ORPHAN_MIN matches it
# (GNU find counts whole minutes: from 11 minutes old; the old one-minute rule fired at 2). Those
# older versions held it for a whole restart: up to 30 s per runner to stop it, plus a check-repo.sh call
# per runner, which has no timeout of its own. Ten minutes covers a restart of several runners over a
# slow link; eleven is the longest such a leftover can block the scripts.
# A stale lock is removed only under a second lock, $LOCK.reclaim, after checking again inside it: two
# callers that both saw it stale would otherwise both remove it, the second one removing the lock the
# first had just taken. $LOCK.reclaim is held for milliseconds; one that find -mmin +1 matches was left by
# a call killed while reclaiming, and is removed.
# A stale lock is removed only under a second lock, $LOCK.reclaim, taken the same way, after checking again
# inside it: two callers that both saw it stale would otherwise both remove it, the second one removing the
# lock the first had just taken. $LOCK.reclaim is held for milliseconds; one that find -mmin +1 matches was
# left by a call killed while reclaiming (empty when an older version left it), and is removed.
# Both are released file first, then directory, never recursively: a call that created its pid file in a
# directory being released keeps it, and the rmdir fails.
# Residual risks: two callers removing such a leftover $LOCK.reclaim in the same instant can both
# reclaim. After a reboot, a process that gets the old holder's pid and started in the same clock tick
# since boot passes for the holder; calls then fail with "another call holds" until $LOCK is removed.
Expand All @@ -83,32 +89,41 @@ lock_stale() {
[ -n "$lock_start" ] && [ "$(proc_start "$lock_pid")" != "$lock_start" ]
}

# take directory $1: create it, then $1/pid under noclobber; true only for the call that created $1/pid
lock_make() {
mkdir "$1" 2>/dev/null && (set -C; echo "$LOCK_ME" >"$1/pid") 2>/dev/null
}

# release directory $1: its pid file, then the directory itself, and only if it is still empty
lock_free() {
rm -f "$1/pid" && rmdir "$1" 2>/dev/null
}

take_lock() {
LOCK_ME="$$ $(proc_start $$)"
i=0
until mkdir "$LOCK" 2>/dev/null; do
until lock_make "$LOCK"; do
if lock_stale; then
if mkdir "$LOCK.reclaim" 2>/dev/null; then
if lock_make "$LOCK.reclaim"; then
# nobody else removes $LOCK while $LOCK.reclaim is ours, so this second look is final
if lock_stale; then rm -rf "$LOCK"; fi
rmdir "$LOCK.reclaim"
lock_free "$LOCK.reclaim"
[ -d "$LOCK" ] || continue
elif [ -n "$(find "$LOCK.reclaim" -maxdepth 0 -mmin +1 2>/dev/null)" ]; then
rmdir "$LOCK.reclaim" 2>/dev/null && continue
lock_free "$LOCK.reclaim" && continue
fi
fi
i=$((i + 1))
if [ "$i" -ge 30 ]; then echo "$CTL: another call holds $LOCK" >&2; exit 1; fi
sleep 1
done
LOCK_ME="$$ $(proc_start $$)"
echo "$LOCK_ME" >"$LOCK/pid"
trap drop_lock EXIT
trap 'exit 1' INT TERM HUP
}

# release $LOCK, only while it is still ours
drop_lock() {
[ "$(cat "$LOCK/pid" 2>/dev/null)" = "$LOCK_ME" ] && rm -f "$LOCK/pid" && rmdir "$LOCK" 2>/dev/null
[ "$(cat "$LOCK/pid" 2>/dev/null)" = "$LOCK_ME" ] && lock_free "$LOCK"
}
# --- end lock ---

Expand Down
72 changes: 65 additions & 7 deletions board/tests/test_ctl.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

REPO = Path(__file__).resolve().parent.parent.parent
FAKE = """#!/bin/sh
echo "$$ ppid=$PPID $0 $*" >> "$MINIRUNNER_RUN/copies"
sh -c 'trap "" TERM; sleep 300' &
echo $! >> "$MINIRUNNER_RUN/children"
wait
Expand Down Expand Up @@ -60,6 +61,16 @@ def procs_with(marker, tag):
return out


def proc_line(pid):
"""pid, ppid, process group, state and command line of a process, for a failure dump."""
try:
f = Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()
cmd = Path(f"/proc/{pid}/cmdline").read_bytes().replace(b"\0", b" ").decode(errors="replace")
except OSError:
return f"{pid}: gone"
return f"{pid}: ppid={f[1]} pgid={f[2]} state={f[0]} start={f[19]} cmd={cmd.strip()!r}"


def copies_running(marker, tag):
"""the copies among procs_with(): a match whose parent is itself a match is that copy's own fork that has
not exec'd yet (it still shows the parent's command line), not a second copy."""
Expand Down Expand Up @@ -212,6 +223,14 @@ def test_concurrent_starts_over_a_stale_lock_run_one_copy(self):
self.make_lock(f"{dead.pid} 1")
self.test_concurrent_starts_run_one_copy()

def test_concurrent_starts_with_a_mkdir_that_cannot_lose_run_one_copy(self):
# uutils mkdir (Ubuntu 26.04) reports success to a call whose directory a concurrent call created a
# moment before; this one always does: the pid file, created with noclobber, has to decide alone
mkdir = self.tmp / "bin" / "mkdir"
mkdir.write_text(f'#!/bin/sh\n{shutil.which("mkdir")} "$@" 2>/dev/null\nexit 0\n')
mkdir.chmod(0o755)
self.test_concurrent_starts_run_one_copy()

def test_start_during_an_exec_runs_one_copy(self):
# the second start comes while the first copy's command line reads empty: still running, not stale
nohup = self.tmp / "bin" / "nohup"
Expand All @@ -233,14 +252,53 @@ def test_start_twice_runs_one_copy(self):
self.assertEqual(len(copies_running(self.marker, str(self.tmp))), self.copies)

def test_concurrent_starts_run_one_copy(self):
ps = [subprocess.Popen(["sh", str(REPO / self.script), "start"], env=self.env,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) for _ in range(3)]
for p in ps:
p.wait(60)
self.assertTrue(self.wait_for(lambda: len(self.children()) >= self.copies))
# Each call runs under sh -x with its output kept, so a failure shows what every call did: whether two
# held the lock at once, one took the lock and judged the running copy dead, or one never took it.
env = {**self.env, "PS4": "+ "}
t0 = time.monotonic()
calls = []
for i in range(3):
trace = (self.tmp / f"trace-{i}").open("w")
self.addCleanup(trace.close)
p = subprocess.Popen(["sh", "-x", str(REPO / self.script), "start"], env=env, stdout=trace,
stderr=subprocess.STDOUT)
calls.append({"p": p, "spawned": time.monotonic() - t0, "ended": None})
while any(c["ended"] is None for c in calls) and time.monotonic() - t0 < 60:
for c in calls:
if c["ended"] is None and c["p"].poll() is not None:
c["ended"] = time.monotonic() - t0
time.sleep(0.005)
if not self.wait_for(lambda: len(self.children()) >= self.copies):
self.fail(f"{len(self.children())} copies started, {self.copies} expected\n" + self.dump(calls))
time.sleep(0.3)
self.assertEqual(len(self.children()), self.copies)
self.assertEqual(len(copies_running(self.marker, str(self.tmp))), self.copies)
if len(self.children()) != self.copies or len(copies_running(self.marker, str(self.tmp))) != self.copies:
self.fail(f"{len(self.children())} copies started, {self.copies} expected\n" + self.dump(calls))

def dump(self, calls):
"""what the concurrent calls did and left behind, printed only when the test fails."""
out = ["--- concurrent start evidence ---"]
for i, c in enumerate(calls):
out.append(f"== call {i}: pid={c['p'].pid} rc={c['p'].poll()} spawned={c['spawned']:.3f}s "
f"ended={c['ended'] if c['ended'] is None else round(c['ended'], 3)}s")
out.append((self.tmp / f"trace-{i}").read_text(errors="replace").rstrip())
for f in sorted(self.run_dir.glob("*.pid")):
pid = f.read_text().strip()
out.append(f"== pidfile {f.name}: {pid!r} -> {proc_line(pid) if pid.isdigit() else '-'}")
out.append(f"== lock {self.lock.name}: " + (
f"present, entries={sorted(x.name for x in self.lock.iterdir())}" if self.lock.is_dir() else "absent"))
if (self.lock / "pid").exists():
out.append(f"== lock pid file: {(self.lock / 'pid').read_text()!r}")
for name in ("children", "copies"):
f = self.run_dir / name
out.append(f"== {name}:\n" + (f.read_text().rstrip() if f.exists() else "(none)"))
for f in sorted(self.run_dir.glob("*.out")) + sorted(self.run_dir.glob("*.log")):
out.append(f"== output of the copy, {f.name}:\n" + f.read_text(errors="replace").rstrip())
status = subprocess.run(["sh", "-x", str(REPO / self.script), "status"], env={**self.env, "PS4": "+ "},
capture_output=True, text=True, timeout=60)
out.append(f"== status now: rc={status.returncode}\n" + (status.stdout + status.stderr).rstrip())
out.append("== processes of this test:")
out += [proc_line(pid) for pid in sorted(procs_with(str(self.tmp), str(self.tmp)) + self.children())]
return "\n".join(out)

def test_stop_kills_the_process_group(self):
self.ctl("start")
Expand Down
49 changes: 32 additions & 17 deletions scripts/gh-runners-ctl.sh
Original file line number Diff line number Diff line change
Expand Up @@ -45,22 +45,28 @@ alive() {
}

# --- lock: the same text in scripts/gh-runners-ctl.sh, scripts/runner-ctl.sh and board/board-ctl.sh ---
# Serialises start/stop/restart (Termux:Boot and an SSH session at the same moment). mkdir is atomic, so
# whoever creates $LOCK holds it. The holder then writes "<pid> <start>" to $LOCK/pid, <start> being field
# 22 of /proc/<pid>/stat (when that process started, in clock ticks since boot). The lock is stale only
# when that process is gone: the pid is dead, or now belongs to a process with another start time (pids
# are reused, after a reboot above all, and the lock directory survives one). A restart holds it for as
# long as it takes.
# Serialises start/stop/restart (Termux:Boot and an SSH session at the same moment). The lock is the
# directory $LOCK with the file $LOCK/pid in it, "<pid> <start>" of the holder, <start> being field 22 of
# /proc/<pid>/stat (when that process started, in clock ticks since boot). A call holds the lock when it
# creates $LOCK and then creates $LOCK/pid itself under noclobber (set -C: the shell opens the file with
# O_EXCL, so of several calls exactly one creates it). The exit status of mkdir alone does not decide:
# uutils mkdir, the default mkdir on Ubuntu 26.04, also reports success to a call whose directory another
# call created a moment before. A call that loses leaves the directory alone: it is the winner's.
# The lock is stale only when its holder is gone: the pid is dead, or now belongs to a process with another
# start time (pids are reused, after a reboot above all, and the lock directory survives one). A restart
# holds it for as long as it takes.
# With no readable pid (the holder died between mkdir and writing it, or an older version of these
# scripts, which wrote none, holds it), the lock is stale once find -mmin +LOCK_ORPHAN_MIN matches it
# (GNU find counts whole minutes: from 11 minutes old; the old one-minute rule fired at 2). Those
# older versions held it for a whole restart: up to 30 s per runner to stop it, plus a check-repo.sh call
# per runner, which has no timeout of its own. Ten minutes covers a restart of several runners over a
# slow link; eleven is the longest such a leftover can block the scripts.
# A stale lock is removed only under a second lock, $LOCK.reclaim, after checking again inside it: two
# callers that both saw it stale would otherwise both remove it, the second one removing the lock the
# first had just taken. $LOCK.reclaim is held for milliseconds; one that find -mmin +1 matches was left by
# a call killed while reclaiming, and is removed.
# A stale lock is removed only under a second lock, $LOCK.reclaim, taken the same way, after checking again
# inside it: two callers that both saw it stale would otherwise both remove it, the second one removing the
# lock the first had just taken. $LOCK.reclaim is held for milliseconds; one that find -mmin +1 matches was
# left by a call killed while reclaiming (empty when an older version left it), and is removed.
# Both are released file first, then directory, never recursively: a call that created its pid file in a
# directory being released keeps it, and the rmdir fails.
# Residual risks: two callers removing such a leftover $LOCK.reclaim in the same instant can both
# reclaim. After a reboot, a process that gets the old holder's pid and started in the same clock tick
# since boot passes for the holder; calls then fail with "another call holds" until $LOCK is removed.
Expand All @@ -87,32 +93,41 @@ lock_stale() {
[ -n "$lock_start" ] && [ "$(proc_start "$lock_pid")" != "$lock_start" ]
}

# take directory $1: create it, then $1/pid under noclobber; true only for the call that created $1/pid
lock_make() {
mkdir "$1" 2>/dev/null && (set -C; echo "$LOCK_ME" >"$1/pid") 2>/dev/null
}

# release directory $1: its pid file, then the directory itself, and only if it is still empty
lock_free() {
rm -f "$1/pid" && rmdir "$1" 2>/dev/null
}

take_lock() {
LOCK_ME="$$ $(proc_start $$)"
i=0
until mkdir "$LOCK" 2>/dev/null; do
until lock_make "$LOCK"; do
if lock_stale; then
if mkdir "$LOCK.reclaim" 2>/dev/null; then
if lock_make "$LOCK.reclaim"; then
# nobody else removes $LOCK while $LOCK.reclaim is ours, so this second look is final
if lock_stale; then rm -rf "$LOCK"; fi
rmdir "$LOCK.reclaim"
lock_free "$LOCK.reclaim"
[ -d "$LOCK" ] || continue
elif [ -n "$(find "$LOCK.reclaim" -maxdepth 0 -mmin +1 2>/dev/null)" ]; then
rmdir "$LOCK.reclaim" 2>/dev/null && continue
lock_free "$LOCK.reclaim" && continue
fi
fi
i=$((i + 1))
if [ "$i" -ge 30 ]; then echo "$CTL: another call holds $LOCK" >&2; exit 1; fi
sleep 1
done
LOCK_ME="$$ $(proc_start $$)"
echo "$LOCK_ME" >"$LOCK/pid"
trap drop_lock EXIT
trap 'exit 1' INT TERM HUP
}

# release $LOCK, only while it is still ours
drop_lock() {
[ "$(cat "$LOCK/pid" 2>/dev/null)" = "$LOCK_ME" ] && rm -f "$LOCK/pid" && rmdir "$LOCK" 2>/dev/null
[ "$(cat "$LOCK/pid" 2>/dev/null)" = "$LOCK_ME" ] && lock_free "$LOCK"
}
# --- end lock ---

Expand Down
Loading