Created
September 24, 2026 21:50
-
-
Save dingman/9c8dffd71b3195e8fb1639aff1e47d76 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env bash | |
| # Prevent host-wide OOM stalls that drop Emdash SSH sessions. | |
| # 1. Cap total memory for user 1000's systemd manager (agents, tmux tasks, timers) | |
| # so SSH login sessions always keep headroom. | |
| # 2. Install + enable systemd-oomd to kill runaway cgroups before the kernel stalls. | |
| # 3. Lower vm.swappiness to reduce thrashing. | |
| # Per-task caps (tmux-spawn-*.scope, breezy.slice) live in ~/.config/systemd/user/ and | |
| # are applied separately without root. | |
| # | |
| # Usage: sudo ~/bin/harden-memory.sh apply | |
| # sudo ~/bin/harden-memory.sh --revert undo everything this script changed | |
| set -euo pipefail | |
| TARGET_UID=1000 | |
| MEMORY_HIGH=22G | |
| MEMORY_MAX=24G | |
| SWAPPINESS=10 | |
| USER_DROPIN_DIR="/etc/systemd/system/user@${TARGET_UID}.service.d" | |
| USER_DROPIN="${USER_DROPIN_DIR}/memory.conf" | |
| SYSCTL_FILE=/etc/sysctl.d/99-swappiness.conf | |
| if [[ $EUID -ne 0 ]]; then | |
| echo "Run with sudo: sudo $0 ${*}" >&2 | |
| exit 1 | |
| fi | |
| revert() { | |
| rm -f "$USER_DROPIN" "$SYSCTL_FILE" | |
| rmdir --ignore-fail-on-non-empty "$USER_DROPIN_DIR" 2>/dev/null || true | |
| systemctl daemon-reload | |
| sysctl -q --system | |
| systemctl disable --now systemd-oomd 2>/dev/null || true | |
| echo "Reverted. (systemd-oomd package left installed; remove with: apt remove systemd-oomd)" | |
| } | |
| apply() { | |
| echo "==> Capping user@${TARGET_UID}.service at MemoryHigh=${MEMORY_HIGH} MemoryMax=${MEMORY_MAX}" | |
| mkdir -p "$USER_DROPIN_DIR" | |
| printf '[Service]\nMemoryHigh=%s\nMemoryMax=%s\n' "$MEMORY_HIGH" "$MEMORY_MAX" > "$USER_DROPIN" | |
| systemctl daemon-reload | |
| echo "==> Installing and enabling systemd-oomd" | |
| if ! dpkg -s systemd-oomd >/dev/null 2>&1; then | |
| apt-get update -qq | |
| apt-get install -y systemd-oomd | |
| fi | |
| systemctl enable --now systemd-oomd | |
| echo "==> Setting vm.swappiness=${SWAPPINESS}" | |
| echo "vm.swappiness=${SWAPPINESS}" > "$SYSCTL_FILE" | |
| sysctl -q --system | |
| echo | |
| echo "==> Verification" | |
| systemctl show "user@${TARGET_UID}.service" -p MemoryHigh -p MemoryMax | |
| echo "systemd-oomd: $(systemctl is-active systemd-oomd)" | |
| echo "vm.swappiness=$(sysctl -n vm.swappiness)" | |
| } | |
| case "${1:-}" in | |
| --revert) revert ;; | |
| "") apply ;; | |
| *) echo "Usage: sudo $0 [--revert]" >&2; exit 2 ;; | |
| esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment