#!/usr/bin/env bash ## ols-htaccess-watcher.sh — graceful-restart the shared OLS when any tenant's ## .htaccess changes. OLS reads .htaccess (RewriteFile) at (re)start, NOT per ## request, so without this a WordPress permalink/LiteSpeed-Cache change would ## silently not take effect. Required by spec 5.3. ## ## Watches all docroots for .htaccess writes, COALESCES bursts (a WP plugin save ## touches the file several times) within a debounce window, and RATE-LIMITS to ## a floor (one restart per FLOOR seconds) so many tenants saving at once can't ## trigger a restart storm. Debounce/floor are env-tunable (panel discloses the ## resulting "~60s" window to customers). ## ## Failure of THIS process is the silent-ticket failure mode (spec 7): if it ## dies, tenants' rewrite changes stop applying with no error. The entrypoint ## runs it and the panel monitors it (check-ols-htaccess-watcher.php). set -uo pipefail ## WATCH_ROOT is deliberately left as the host-wide /mnt/users, not narrowed to ## the shared-OLS tenant set, even though that set IS derivable in-container ## (render-shared-ols-config.sh's $SITES_ROOT/*/site.meta VHROOT= is exactly ## that list). Narrowing it would mean handing inotifywait a fixed argv list of ## VHROOT dirs at process start — and inotifywait cannot be told to watch a NEW ## directory once running. The panel provisions sites onto this container live, ## between renders; a site added after the watcher started would then sit ## outside every watch until the next container restart, i.e. exactly the ## silent-failure mode (spec 7) this script exists to prevent, now for brand ## new tenants instead of none. Doing this safely needs a reload path (SIGHUP ## re-exec off the current site.meta list, coordinated with ## render-shared-ols-config.sh) that does not exist yet and is its own change. ## So: WATCH_ROOT stays broad, and correctness comes entirely from the path ## match below, which is sufficient on its own. WATCH_ROOT="${OLS_WATCH_ROOT:-/mnt/users}" DEBOUNCE="${OLS_HTACCESS_DEBOUNCE:-15}" # coalesce window (s) FLOOR="${OLS_HTACCESS_FLOOR:-60}" # min seconds between restarts LSWSCTRL="${LSWSCTRL:-/usr/local/lsws/bin/lswsctrl}" ## Rendered config + per-site files (defaults match entrypoint-shared-ols.sh / ## render-shared-ols-config.sh; overridable so tests can run without OLS). LSWS_CONF="${OLS_LSWS_CONF:-/usr/local/lsws/conf}" SITES_ROOT="${OLS_SITES_ROOT:-${SITES_ROOT:-$LSWS_CONF/shared-sites}}" ## Set of vhost docRoot directories (absolute, no trailing slash), keyed by ## path. Rebuilt from $SITES_ROOT/*/vhconf.conf only when the rendered ## httpd_config.conf changes (the panel re-renders it atomically on every site ## change), and only when a candidate .htaccess event arrives. declare -A DOCROOTS=() docroots_sig="unset" config_sig() { stat -c '%i:%Y:%s' "$LSWS_CONF/httpd_config.conf" 2>/dev/null || echo missing } refresh_docroots() { local sig; sig=$(config_sig) [ "$sig" = "$docroots_sig" ] && return docroots_sig="$sig" DOCROOTS=() local files=() d shopt -s nullglob files=("$SITES_ROOT"/*/vhconf.conf) shopt -u nullglob [ "${#files[@]}" -gt 0 ] || return 0 ## Panel data is only ever READ as text (awk), never sourced. Only absolute ## docRoot values without variables/'..'/whitespace are accepted. Process ## substitution (not a pipeline) so an early reader exit cannot SIGPIPE. while read -r d; do d="${d%/}" case "$d" in /*/..|/*/../*|*'$'*|*' '*|"") continue ;; /*) DOCROOTS["$d"]=1 ;; esac done < <(awk '$1=="docRoot" && NF==2 && substr($2,1,1)=="/" {print $2}' "${files[@]}" 2>/dev/null) log "docroot set refreshed: ${#DOCROOTS[@]} vhost docroot(s)" } ## 0 if $1 (full path of a changed file) is a .htaccess directly inside a vhost ## docRoot. If the docRoot set is empty/unreadable, fall back to the legacy ## */public_html/.htaccess match so a parse failure is never LESS sensitive. is_docroot_htaccess() { case "$1" in */.htaccess) ;; *) return 1 ;; esac refresh_docroots if [ "${#DOCROOTS[@]}" -gt 0 ]; then [ -n "${DOCROOTS[${1%/.htaccess}]:-}" ] else case "$1" in */public_html/.htaccess) return 0 ;; esac return 1 fi } log() { echo "ols-htaccess-watcher: $*" >&2; } ## Time comes from bash's $SECONDS (monotonic w.r.t. wall-clock steps, no fork ## per check). A backward clock jump therefore cannot stretch the floor wait, and ## the drain loops below stay cheap even when unrelated churn under $WATCH_ROOT ## makes `read` return instantly on every event. last_restart="" # $SECONDS of the last restart ATTEMPT; empty = none yet do_restart() { path="$1" local wait_until if [ -n "$last_restart" ] && [ $((SECONDS - last_restart)) -lt "$FLOOR" ]; then ## COALESCE, don't drop: an edit inside the floor window used to be ## discarded, so it never applied until some later edit happened. Instead ## wait out the remainder of the window (hard-bounded by FLOOR), draining ## the event stream meanwhile so the pipe cannot back up, then restart ONCE ## for everything that arrived. A burst of N edits still costs one restart. wait_until=$((last_restart + FLOOR)) log "within ${FLOOR}s floor — deferring restart to end of window ($path)" while [ "$SECONDS" -lt "$wait_until" ]; do read -r -t 1 _ || true done fi ## Stamp the ATTEMPT (not only success) so a failing lswsctrl is also limited ## to one try per FLOOR instead of retrying on every event. last_restart=$SECONDS if "$LSWSCTRL" restart >/dev/null 2>&1; then log "graceful restart issued — $path changed" else log "WARNING: lswsctrl restart failed ($path)" fi } if ! command -v inotifywait >/dev/null 2>&1; then log "FATAL: inotifywait not installed (inotify-tools)"; exit 1 fi mkdir -p "$WATCH_ROOT" log "watching $WATCH_ROOT for vhost-docroot .htaccess changes (debounce=${DEBOUNCE}s floor=${FLOOR}s)" ## -m monitor, -r recursive. We filter in the read loop rather than --include ## so this works on older inotify-tools too. modify/create/delete/move all ## matter (delete of .htaccess also changes rewrite behavior). ## ## --format '%w%f' (full path), NOT '%f' (basename only). OLS reads .htaccess ## (RewriteFile) only from a vhost's DOCROOT — /mnt/users/// ## public_html, or public_html/ when the site has a document-root folder ## (taken from the rendered $SITES_ROOT/*/vhconf.conf docRoot lines) — never ## anything below it. A basename-only match fires ## for ANY .htaccess anywhere under a tenant, at any depth, and WordPress ## plugins write plenty of those that OLS never opens: measured on whp01 over ## 24h, this watcher fired 63 restarts, of which the docroot .htaccess actually ## changed in 0. All 28 distinct files behind those 63 were plugin guard files ## — Wordfence self-healing waf/views/vendor/tmp/models/lib/.htaccess, W3 Total ## Cache writing one per cached URL under wp-content/cache/page_enhanced/, plus ## WPForms/Gravity Forms/UpdraftPlus/Groundhogg/WP Staging upload guards — and ## most of those tenants are on the shared Apache tier (cac-fpm), not this OLS ## tier at all, so their cache churn was restarting the OLS serving 15 unrelated ## tenants for no reason. Matching the full path against the set of real docRoot ## directories is what ties a change to something OLS will reread. (Legacy ## */public_html/.htaccess match is kept only when that set is empty.) inotifywait -m -r -e modify,create,delete,move "$WATCH_ROOT" --format '%w%f' 2>/dev/null | while IFS= read -r path; do is_docroot_htaccess "$path" || continue ## A tenant DOCROOT .htaccess changed. Coalesce the save-burst, then restart ONCE. ## ## The coalesce is HARD-BOUNDED to DEBOUNCE seconds: a previous version blocked ## on `read -t DEBOUNCE` which, on a busy multi-tenant server, never timed out ## (unrelated file writes under $WATCH_ROOT kept resetting it) — so the restart ## was starved and rewrite changes silently never applied. Here we read further ## events only until the deadline OR ~2s of total quiet, whichever comes first, ## so continuous activity can delay us by at most DEBOUNCE. do_restart's FLOOR ## then rate-limits across consecutive bursts. deadline=$((SECONDS + DEBOUNCE)) while [ "$SECONDS" -lt "$deadline" ]; do if read -r -t 2 _; then continue # more activity — keep coalescing toward the deadline else break # ~2s of total quiet — the burst has settled fi done do_restart "$path" done