#!/bin/bash # ============================================================================= # ram-watchdog.sh - Watchdog memoire pour le photomaton # ============================================================================= # Usage: Lancer via cron toutes les minutes : # * * * * * /home/pi/opencode/scripts/ram-watchdog.sh # # Actions par seuil : # - Swap > 70% : vider les caches # - Swap > 85% : redemarrer photobooth-app # - Swap > 95% : reboot du Pi # ============================================================================= LOG_TAG="ram-watchdog" log_info() { logger -t "$LOG_TAG" "[INFO] $1"; } log_warn() { logger -t "$LOG_TAG" "[WARN] $1"; } log_error() { logger -t "$LOG_TAG" "[ERROR] $1"; } # --- Lire les valeurs memoire --- SWAP_TOTAL=$(awk '/SwapTotal/ {print $2}' /proc/meminfo) SWAP_FREE=$(awk '/SwapFree/ {print $2}' /proc/meminfo) MEM_AVAILABLE=$(awk '/MemAvailable/ {print $2}' /proc/meminfo) # Eviter division par zero if [ "$SWAP_TOTAL" -eq 0 ]; then exit 0 fi SWAP_USED=$((SWAP_TOTAL - SWAP_FREE)) SWAP_PERCENT=$((SWAP_USED * 100 / SWAP_TOTAL)) MEM_AVAILABLE_MB=$((MEM_AVAILABLE / 1024)) # --- Seuil 1 : Swap > 70% -> vider les caches --- if [ "$SWAP_PERCENT" -ge 70 ] && [ "$SWAP_PERCENT" -lt 85 ]; then log_warn "Swap a ${SWAP_PERCENT}% (RAM dispo: ${MEM_AVAILABLE_MB}Mo) - Vidage des caches" sync echo 3 > /proc/sys/vm/drop_caches 2>/dev/null || true fi # --- Seuil 2 : Swap > 85% -> redemarrer photobooth-app --- if [ "$SWAP_PERCENT" -ge 85 ] && [ "$SWAP_PERCENT" -lt 95 ]; then log_error "Swap a ${SWAP_PERCENT}% (RAM dispo: ${MEM_AVAILABLE_MB}Mo) - Redemarrage photobooth-app" # Redemarrer photobooth-app en tant que l'utilisateur pi REAL_USER="pi" XDG_RUNTIME_DIR="/run/user/$(id -u "$REAL_USER")" DBUS_SESSION_BUS_ADDRESS="unix:path=${XDG_RUNTIME_DIR}/bus" runuser -u "$REAL_USER" -- env \ XDG_RUNTIME_DIR="$XDG_RUNTIME_DIR" \ DBUS_SESSION_BUS_ADDRESS="$DBUS_SESSION_BUS_ADDRESS" \ systemctl --user restart photobooth-app 2>/dev/null || true log_warn "photobooth-app redemarre" # Attendre et vider les caches sleep 5 sync echo 3 > /proc/sys/vm/drop_caches 2>/dev/null || true fi # --- Seuil 3 : Swap > 95% -> reboot --- if [ "$SWAP_PERCENT" -ge 95 ]; then log_error "CRITIQUE: Swap a ${SWAP_PERCENT}% (RAM dispo: ${MEM_AVAILABLE_MB}Mo) - REBOOT" sync sleep 2 reboot fi