Skip to content
Open
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
10 changes: 6 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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
Expand Down
141 changes: 141 additions & 0 deletions board/tests/test_clean_workdirs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
"""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())

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()
3 changes: 2 additions & 1 deletion docs/hosts.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

Expand Down
200 changes: 200 additions & 0 deletions scripts/clean-workdirs.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
#!/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

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
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 [ ! -f "$marker_file" ]; then
echo "clean_workdirs: nothing older than $DAYS days"
else
rm -f "$marker_file"
fi
exit 0