#!/bin/bash # isolated.sh -- run an experiment in a throw-away test site, cleaned up however it ends. # # Everything the command starts (headless Chromium, sglang, the laya server, the webgym server, browser-harness daemons) # lives in one transient systemd --user scope, so stopping the scope kills all of it -- nohup / setsid cannot escape a # cgroup. State goes to a fresh temp dir (INFRA_DIR: Chromium profile with the real sites' cookies, logs, pid files) # that is deleted afterwards. The scope is also stopped on Ctrl+C / kill / normal exit. set -u RUN=laya-exp-$(date +%m%d-%H%M%S)-$$ export INFRA_DIR=$(mktemp -d /tmp/$RUN.XXXX) LOG_KEEP=${LOG_KEEP:-/home/ckl/projects/S/laya/finetune/out/logs} export GYM_PIDFILE=$INFRA_DIR/webgym.pid GYM_LOG=$INFRA_DIR/webgym.log cleanup() { trap - EXIT INT TERM HUP systemctl --user stop "$RUN.scope" 2>/dev/null # wait until nothing that uses the temp dir is alive (Chromium flushes its profile while shutting down) for i in $(seq 1 20); do pgrep -f -- "$INFRA_DIR" >/dev/null || break; sleep 0.5; done # keep the logs (the rest -- browser profile, pid files -- goes) mkdir -p "$LOG_KEEP/$RUN" && cp "$INFRA_DIR"/*.log "$LOG_KEEP/$RUN/" 2>/dev/null sleep 1; rm -rf "$INFRA_DIR" echo "[isolated] $RUN cleaned up (scope stopped, $INFRA_DIR removed, logs in $LOG_KEEP/$RUN)" >&2 } trap cleanup EXIT INT TERM HUP echo "[isolated] $RUN INFRA_DIR=$INFRA_DIR" >&2 # run in the background and wait: a trapped signal interrupts `wait` at once (it would wait for a foreground child) systemd-run --user --scope --quiet --unit="$RUN" --collect -- "$@" & wait $!