From b3ab780a7193895de7869090b20205f63c7f3d4b Mon Sep 17 00:00:00 2001 From: jhshreya Date: Fri, 4 Dec 2026 23:49:27 +0530 Subject: [PATCH 1/3] Add clean_workdirs.sh script with dry-run mode and tests --- README.md | 10 +- board/tests/test_clean_workdirs.py | 130 ++++++++++++++++++++++++ docs/hosts.md | 3 +- scripts/clean_workdirs.sh | 155 +++++++++++++++++++++++++++++ 4 files changed, 293 insertions(+), 5 deletions(-) create mode 100644 board/tests/test_clean_workdirs.py create mode 100644 scripts/clean_workdirs.sh diff --git a/README.md b/README.md index ba62282..b7643f5 100644 --- a/README.md +++ b/README.md @@ -123,9 +123,10 @@ have not been done. - **Android may kill processes.** The phantom process killer (Android 12+), battery optimization and OEM task killers can stop runners at any time. A setup counts as working only after a **24 h soak** with no manual restarts. -- **Disk grows.** `actions-runner-*/_work` and the GitLab build dirs are never cleaned automatically. +- **Disk grows.** `actions-runner-*/_work` and the GitLab build dirs are not cleaned automatically on a schedule; run `scripts/clean_workdirs.sh` (dry run by default, `--apply` to delete) when no job is running. - **Not a sandbox.** proot isolates by path, not by user. On a public repo, a fork's pull request runs on the phone only after you approve it. See [Public repositories](#public-repositories). + ## How it fails (and how to see it) @@ -388,9 +389,10 @@ plan-template.md the setup as a Mission Kit plan for /start-project ## Gaps Not in this repo yet: an installer and uninstaller, a `doctor`, runner `config.toml` and `sshd_config` -templates, checksum automation, a CI job that proves `--isolated` on each install, and disk cleanup for -runner work dirs. Items marked **to be confirmed** above have not been verified on a second device. - +templates, checksum automation, a CI job that proves `--isolated` on each install, and scheduled +disk cleanup for runner work dirs (`scripts/clean_workdirs.sh` runs manually; dry run by default, +`--apply` to delete when no job is running). Items marked **to be confirmed** above have not been +verified on a second device. ## Contributing and security Before you push, run `bash scripts/hygiene-scan.sh`. To also check for your own host, account and project diff --git a/board/tests/test_clean_workdirs.py b/board/tests/test_clean_workdirs.py new file mode 100644 index 0000000..6e21c02 --- /dev/null +++ b/board/tests/test_clean_workdirs.py @@ -0,0 +1,130 @@ +"""Tests for scripts/clean_workdirs.sh against a fake rootfs.""" +import os +import shutil +import subprocess +import sys +import tempfile +import time +import unittest +from pathlib import Path + +REPO = Path(__file__).resolve().parent.parent.parent +SCRIPT = REPO / "scripts" / "clean_workdirs.sh" + + +def set_age_days(path: Path, days: float) -> None: + ts = time.time() - (days * 86400) + os.utime(path, (ts, ts)) + + +class CleanWorkdirsTest(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp(prefix="mr-clean-")) + self.addCleanup(shutil.rmtree, self.tmp, True) + + self.home = self.tmp / "home" + self.run_dir = self.home / "run" + self.rootfs = self.tmp / "rootfs" + self.home.mkdir(parents=True) + self.run_dir.mkdir(parents=True) + + self.gh_work = self.rootfs / "root" / "actions-runner-app" / "_work" + self.gl_builds = self.rootfs / "root" / "builds" + self.outside_dir = self.rootfs / "root" / "important-outside" + self.gh_work.mkdir(parents=True) + self.gl_builds.mkdir(parents=True) + self.outside_dir.mkdir(parents=True) + + self.env = { + **os.environ, + "HOME": str(self.home), + "MINIRUNNER_HOME": str(self.home), + "MINIRUNNER_RUN": str(self.run_dir), + "MINIRUNNER_ROOTFS": str(self.rootfs), + "GH_RUNNER_ROOT": "/root", + "GITLAB_RUNNER_WORKDIR": "/root", + } + + def run_clean(self, *args): + return subprocess.run( + ["sh", str(SCRIPT), *args], + env=self.env, + capture_output=True, + text=True, + timeout=30, + ) + + def make_workdir(self, parent: Path, name: str, age_days: float) -> Path: + d = parent / name + d.mkdir(parents=True, exist_ok=True) + f = d / "artifact.txt" + f.write_text("payload\n") + set_age_days(f, age_days) + set_age_days(d, age_days) + return d + + def test_nothing_old(self): + recent_gh = self.make_workdir(self.gh_work, "repo-recent", age_days=2) + recent_gl = self.make_workdir(self.gl_builds, "project-recent", age_days=1) + + dry = self.run_clean() + self.assertEqual(dry.returncode, 0, dry.stderr) + self.assertIn("nothing older than 7 days", dry.stdout) + self.assertTrue(recent_gh.exists()) + self.assertTrue(recent_gl.exists()) + + applied = self.run_clean("--apply") + self.assertEqual(applied.returncode, 0, applied.stderr) + self.assertTrue(recent_gh.exists()) + self.assertTrue(recent_gl.exists()) + + def test_some_old_dry_run_and_apply(self): + old_gh = self.make_workdir(self.gh_work, "repo-old", age_days=10) + fresh_gh = self.make_workdir(self.gh_work, "repo-fresh", age_days=2) + old_gl = self.make_workdir(self.gl_builds, "project-old", age_days=12) + + out_norm = "" + dry = self.run_clean() + self.assertEqual(dry.returncode, 0, dry.stderr) + out_norm = dry.stdout.replace("\\", "/") + self.assertIn("would remove", out_norm) + self.assertIn(old_gh.as_posix(), out_norm) + self.assertIn(old_gl.as_posix(), out_norm) + self.assertNotIn(fresh_gh.as_posix(), out_norm) + self.assertTrue(old_gh.exists()) + self.assertTrue(old_gl.exists()) + + applied = self.run_clean("--apply") + self.assertEqual(applied.returncode, 0, applied.stderr) + self.assertIn("removed", applied.stdout) + self.assertFalse(old_gh.exists()) + self.assertFalse(old_gl.exists()) + self.assertTrue(fresh_gh.exists()) + + def test_refuses_when_job_is_running(self): + old_gh = self.make_workdir(self.gh_work, "repo-old", age_days=10) + holder = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"]) + self.addCleanup(holder.wait) + self.addCleanup(holder.kill) + + lock = self.run_dir / "runner.lock" + lock.mkdir() + (lock / "pid").write_text(f"{holder.pid}\n") + + res = self.run_clean("--apply") + self.assertNotEqual(res.returncode, 0) + self.assertIn("refusing to run", res.stderr) + self.assertTrue(old_gh.exists()) + + def test_outside_paths_are_left_alone(self): + outside_old = self.make_workdir(self.outside_dir, "keep-me", age_days=30) + old_gh = self.make_workdir(self.gh_work, "repo-old", age_days=10) + + res = self.run_clean("--apply") + self.assertEqual(res.returncode, 0, res.stderr) + self.assertFalse(old_gh.exists()) + self.assertTrue(outside_old.exists()) + + +if __name__ == "__main__": + unittest.main() \ No newline at end of file diff --git a/docs/hosts.md b/docs/hosts.md index 0ed5ea2..dbf0b6d 100644 --- a/docs/hosts.md +++ b/docs/hosts.md @@ -33,7 +33,8 @@ right supervisor there. This is a guided procedure, not a tested installer. Tag `LABEL`, untagged jobs off, and `concurrent = 1` in `/etc/gitlab-runner/config.toml` unless the host has room for more. -5. **Disk.** Runner work directories grow. Add a scheduled cleanup or a job that prunes old builds. +5. **Disk.** Runner work directories grow. Run `scripts/clean_workdirs.sh` (dry run by default, `--apply` to delete) when no job is running, or add a scheduled cleanup / job that prunes old builds. + 6. **A VPS is on the internet.** Keep ssh key-only, do not open a port for the runner (it only makes outbound connections) and do not open the board's port (below). diff --git a/scripts/clean_workdirs.sh b/scripts/clean_workdirs.sh new file mode 100644 index 0000000..d81da19 --- /dev/null +++ b/scripts/clean_workdirs.sh @@ -0,0 +1,155 @@ +#!/data/data/com.termux/files/usr/bin/sh +# clean_workdirs.sh [--days N] [--apply]: prune old GitHub Actions (_work) and GitLab (builds) work directories. +# +# Dry run is the default: prints each candidate directory path and size without deleting anything unless +# --apply is given. Refuses to run if a runner process or lock is active. +set -u + +MINIRUNNER_HOME=${MINIRUNNER_HOME:-$HOME/mini-runner} +# shellcheck disable=SC1091 +[ -f "$MINIRUNNER_HOME/mini-runner.env" ] && . "$MINIRUNNER_HOME/mini-runner.env" +RUN=${MINIRUNNER_RUN:-$MINIRUNNER_HOME/run} +PROOT_DISTRO=${PROOT_DISTRO:-ubuntu} +GITLAB_RUNNER_WORKDIR=${GITLAB_RUNNER_WORKDIR:-/root} +GH_RUNNER_ROOT=${GH_RUNNER_ROOT:-/root} + +if [ -z "${MINIRUNNER_ROOTFS+x}" ]; then + if [ -n "${PREFIX:-}" ] && [ -d "$PREFIX/var/lib/proot-distro/installed-rootfs/$PROOT_DISTRO" ]; then + MINIRUNNER_ROOTFS=$PREFIX/var/lib/proot-distro/installed-rootfs/$PROOT_DISTRO + else + MINIRUNNER_ROOTFS= + fi +fi + +DAYS=${CLEAN_WORKDIRS_DAYS:-7} +APPLY=0 + +usage() { + echo "usage: $0 [--days N] [--apply]" >&2 + exit 2 +} + +while [ $# -gt 0 ]; do + case "$1" in + --apply) + APPLY=1 + shift + ;; + --days) + [ $# -ge 2 ] || usage + DAYS=$2 + shift 2 + ;; + --days=*) + DAYS=${1#*=} + shift + ;; + -h | --help) + usage + ;; + *) + usage + ;; + esac +done + +case $DAYS in + '' | *[!0-9]*) + echo "clean_workdirs: --days must be a non-negative integer" >&2 + exit 2 + ;; +esac + +pid_alive() { + pid_file=$1 + [ -f "$pid_file" ] && p=$(cat "$pid_file" 2>/dev/null) && [ -n "$p" ] || return 1 + case $p in '' | *[!0-9]*) return 1 ;; esac + if [ -r "/proc/$p/cmdline" ]; then + alive_c=$(tr '\0' ' ' <"/proc/$p/cmdline" 2>/dev/null) + case $alive_c in + *proot* | *gitlab-runner* | *Runner.Listener* | *Runner.Worker*) return 0 ;; + *[!\ ]*) return 1 ;; + esac + fi + kill -0 "$p" 2>/dev/null +} + +LOCK_ORPHAN_MIN=10 + +proc_start() { + lock_s=$(cat "/proc/$1/stat" 2>/dev/null) || return 0 + lock_s=${lock_s##*) } + # shellcheck disable=SC2086 + set -- $lock_s + [ "$1" = Z ] || [ $# -lt 20 ] || echo "${20}" +} + +lock_held() { + lock_dir=$1 + [ -d "$lock_dir" ] || return 1 + lock_pid=; lock_start= + { read -r lock_pid lock_start <"$lock_dir/pid"; } 2>/dev/null + case $lock_pid in + '' | *[!0-9]*) + [ -z "$(find "$lock_dir" -maxdepth 0 -mmin +"$LOCK_ORPHAN_MIN" 2>/dev/null)" ] + return + ;; + esac + kill -0 "$lock_pid" 2>/dev/null || [ -d "/proc/$lock_pid" ] || return 1 + if [ -n "$lock_start" ] && [ -r "/proc/$lock_pid/stat" ]; then + [ "$(proc_start "$lock_pid")" = "$lock_start" ] + return + fi + return 0 +} + +check_no_job_running() { + for pf in "$RUN/runner.pid" "$RUN"/gh-*.pid; do + if pid_alive "$pf"; then + echo "clean_workdirs: refusing to run while runner is active ($pf)" >&2 + exit 1 + fi + done + for lk in "$RUN/runner.lock" "$RUN/gh-runners.lock"; do + if lock_held "$lk"; then + echo "clean_workdirs: refusing to run while lock is held ($lk)" >&2 + exit 1 + fi + done +} + +check_no_job_running + +roots="" +for base in "$MINIRUNNER_ROOTFS$GH_RUNNER_ROOT"/actions-runner-*/_work "$MINIRUNNER_ROOTFS$GITLAB_RUNNER_WORKDIR/builds"; do + [ -d "$base" ] && roots="$roots +$base" +done + +if [ -z "$roots" ]; then + echo "clean_workdirs: no runner work directories found" + exit 0 +fi + +found=0 +IFS=' +' +for base in $roots; do + for entry in $(find "$base" -mindepth 1 -maxdepth 1 -type d -mtime +"$DAYS" 2>/dev/null | LC_ALL=C sort); do + found=1 + size=$(du -sh "$entry" 2>/dev/null | awk '{print $1}') + size=${size:-0} + if [ "$APPLY" -eq 1 ]; then + rm -rf "$entry" + echo "removed $size $entry" + else + echo "would remove $size $entry" + fi + done +done +unset IFS + +if [ "$found" -eq 0 ]; then + echo "clean_workdirs: nothing older than $DAYS days" +fi +exit 0 From aa97567553d97637075896c575669eb727c482be Mon Sep 17 00:00:00 2001 From: jhshreya Date: Sat, 5 Dec 2026 11:46:15 +0530 Subject: [PATCH 2/3] Harden clean_workdirs loop and re-check active runners/locks --- scripts/clean_workdirs.sh | 73 +++++++++++++++++++++++++++++++-------- 1 file changed, 59 insertions(+), 14 deletions(-) diff --git a/scripts/clean_workdirs.sh b/scripts/clean_workdirs.sh index d81da19..93a5543 100644 --- a/scripts/clean_workdirs.sh +++ b/scripts/clean_workdirs.sh @@ -131,25 +131,70 @@ if [ -z "$roots" ]; then exit 0 fi -found=0 +marker_file=$(mktemp 2>/dev/null || printf '%s/clean-workdirs.%s' "${TMPDIR:-/tmp}" "$$") +rm -f "$marker_file" + +export APPLY RUN +export -f pid_alive proc_start lock_held check_no_job_running 2>/dev/null || true + IFS=' ' for base in $roots; do - for entry in $(find "$base" -mindepth 1 -maxdepth 1 -type d -mtime +"$DAYS" 2>/dev/null | LC_ALL=C sort); do - found=1 - size=$(du -sh "$entry" 2>/dev/null | awk '{print $1}') - size=${size:-0} - if [ "$APPLY" -eq 1 ]; then - rm -rf "$entry" - echo "removed $size $entry" - else - echo "would remove $size $entry" - fi - done + find "$base" -mindepth 1 -maxdepth 1 -type d -mtime +"$DAYS" -exec sh -c ' + set -u + marker=$1 + shift + for entry in "$@"; do + : > "$marker" + for pf in "$RUN/runner.pid" "$RUN"/gh-*.pid; do + [ -f "$pf" ] || continue + p=$(cat "$pf" 2>/dev/null) || continue + case $p in "" | *[!0-9]*) continue ;; esac + if kill -0 "$p" 2>/dev/null; then + echo "clean_workdirs: refusing to run while runner is active ($pf)" >&2 + exit 1 + fi + done + for lk in "$RUN/runner.lock" "$RUN/gh-runners.lock"; do + if [ -d "$lk" ]; then + lock_pid= + { read -r lock_pid _ <"$lk/pid"; } 2>/dev/null || true + case $lock_pid in + "" | *[!0-9]*) + if [ -z "$(find "$lk" -maxdepth 0 -mmin +10 2>/dev/null)" ]; then + echo "clean_workdirs: refusing to run while lock is held ($lk)" >&2 + exit 1 + fi + ;; + *) + if kill -0 "$lock_pid" 2>/dev/null; then + echo "clean_workdirs: refusing to run while lock is held ($lk)" >&2 + exit 1 + fi + ;; + esac + fi + done + size=$(du -sh "$entry" 2>/dev/null | awk "{print \$1}") + size=${size:-0} + if [ "$APPLY" -eq 1 ]; then + rm -rf -- "$entry" + echo "removed $size $entry" + else + echo "would remove $size $entry" + fi + done + ' sh "$marker_file" {} + || { + rc=$? + rm -f "$marker_file" + exit "$rc" + } done unset IFS -if [ "$found" -eq 0 ]; then +if [ ! -f "$marker_file" ]; then echo "clean_workdirs: nothing older than $DAYS days" +else + rm -f "$marker_file" fi -exit 0 +exit 0 \ No newline at end of file From 67aee5fb15f0595d6bbe04db7a2a53423747a3a5 Mon Sep 17 00:00:00 2001 From: jhshreya Date: Sat, 5 Dec 2026 12:25:18 +0530 Subject: [PATCH 3/3] Rename script to clean-workdirs.sh, add glob test, and clarify docs --- README.md | 4 ++-- board/tests/test_clean_workdirs.py | 15 +++++++++++++-- docs/hosts.md | 2 +- scripts/{clean_workdirs.sh => clean-workdirs.sh} | 2 +- 4 files changed, 17 insertions(+), 6 deletions(-) rename scripts/{clean_workdirs.sh => clean-workdirs.sh} (98%) diff --git a/README.md b/README.md index b7643f5..47e966d 100644 --- a/README.md +++ b/README.md @@ -123,7 +123,7 @@ have not been done. - **Android may kill processes.** The phantom process killer (Android 12+), battery optimization and OEM task killers can stop runners at any time. A setup counts as working only after a **24 h soak** with no manual restarts. -- **Disk grows.** `actions-runner-*/_work` and the GitLab build dirs are not cleaned automatically on a schedule; run `scripts/clean_workdirs.sh` (dry run by default, `--apply` to delete) when no job is running. +- **Disk grows.** `actions-runner-*/_work` and the GitLab build dirs are not cleaned automatically on a schedule; run `scripts/clean-workdirs.sh` (dry run by default, `--apply` to delete) when no job is running. - **Not a sandbox.** proot isolates by path, not by user. On a public repo, a fork's pull request runs on the phone only after you approve it. See [Public repositories](#public-repositories). @@ -390,7 +390,7 @@ plan-template.md the setup as a Mission Kit plan for /start-project Not in this repo yet: an installer and uninstaller, a `doctor`, runner `config.toml` and `sshd_config` templates, checksum automation, a CI job that proves `--isolated` on each install, and scheduled -disk cleanup for runner work dirs (`scripts/clean_workdirs.sh` runs manually; dry run by default, +disk cleanup for runner work dirs (`scripts/clean-workdirs.sh` runs manually; dry run by default, `--apply` to delete when no job is running). Items marked **to be confirmed** above have not been verified on a second device. ## Contributing and security diff --git a/board/tests/test_clean_workdirs.py b/board/tests/test_clean_workdirs.py index 6e21c02..7054a26 100644 --- a/board/tests/test_clean_workdirs.py +++ b/board/tests/test_clean_workdirs.py @@ -1,4 +1,4 @@ -"""Tests for scripts/clean_workdirs.sh against a fake rootfs.""" +"""Tests for scripts/clean-workdirs.sh against a fake rootfs.""" import os import shutil import subprocess @@ -9,7 +9,7 @@ from pathlib import Path REPO = Path(__file__).resolve().parent.parent.parent -SCRIPT = REPO / "scripts" / "clean_workdirs.sh" +SCRIPT = REPO / "scripts" / "clean-workdirs.sh" def set_age_days(path: Path, days: float) -> None: @@ -124,7 +124,18 @@ def test_outside_paths_are_left_alone(self): self.assertEqual(res.returncode, 0, res.stderr) self.assertFalse(old_gh.exists()) self.assertTrue(outside_old.exists()) + + def test_star_dirname_does_not_remove_fresh_dir(self): + fresh_gh = self.make_workdir(self.gh_work, "repo-fresh", age_days=1) + try: + star_old = self.make_workdir(self.gh_work, "*", age_days=10) + except OSError: + self.skipTest("Filesystem does not allow '*' in directory names") + res = self.run_clean("--apply") + self.assertEqual(res.returncode, 0, res.stderr) + self.assertFalse(star_old.exists()) + self.assertTrue(fresh_gh.exists()) if __name__ == "__main__": unittest.main() \ No newline at end of file diff --git a/docs/hosts.md b/docs/hosts.md index dbf0b6d..606cba1 100644 --- a/docs/hosts.md +++ b/docs/hosts.md @@ -33,7 +33,7 @@ right supervisor there. This is a guided procedure, not a tested installer. Tag `LABEL`, untagged jobs off, and `concurrent = 1` in `/etc/gitlab-runner/config.toml` unless the host has room for more. -5. **Disk.** Runner work directories grow. Run `scripts/clean_workdirs.sh` (dry run by default, `--apply` to delete) when no job is running, or add a scheduled cleanup / job that prunes old builds. +5. **Disk.** Runner work directories grow. Run `scripts/clean-workdirs.sh` (dry run by default, `--apply` to delete) when no job is running, or add a scheduled cleanup / job that prunes old builds. 6. **A VPS is on the internet.** Keep ssh key-only, do not open a port for the runner (it only makes outbound connections) and do not open the board's port (below). diff --git a/scripts/clean_workdirs.sh b/scripts/clean-workdirs.sh similarity index 98% rename from scripts/clean_workdirs.sh rename to scripts/clean-workdirs.sh index 93a5543..32d3079 100644 --- a/scripts/clean_workdirs.sh +++ b/scripts/clean-workdirs.sh @@ -1,5 +1,5 @@ #!/data/data/com.termux/files/usr/bin/sh -# clean_workdirs.sh [--days N] [--apply]: prune old GitHub Actions (_work) and GitLab (builds) work directories. +# clean-workdirs.sh [--days N] [--apply]: prune old GitHub Actions (_work) and GitLab (builds) work directories. # # Dry run is the default: prints each candidate directory path and size without deleting anything unless # --apply is given. Refuses to run if a runner process or lock is active.