mydocker/watchdog.sh

56 lines
2.0 KiB
Bash
Executable File

#!/bin/bash
# Watchdog: sprawdza kontenery compose, restartuje dead/exited, wysyła Telegram
COMPOSE_DIR="/home/seba/mydocker"
LOG="/var/log/docker-watchdog.log"
STATE_FILE="/tmp/docker-watchdog-state"
# Telegram - z .env (grep żeby uniknąć nadpisania pustymi duplikatami)
TELEGRAM_BOT_TOKEN=$(grep -m1 '^TELEGRAM_BOT_TOKEN=.\+' "$COMPOSE_DIR/.env" | cut -d= -f2-)
TELEGRAM_CHAT_ID=$(grep -m1 '^TELEGRAM_CHAT_ID=.\+' "$COMPOSE_DIR/.env" | cut -d= -f2-)
telegram_notify() {
local msg="$1"
curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
-d chat_id="${TELEGRAM_CHAT_ID}" \
-d text="$msg" \
-d parse_mode="HTML" > /dev/null 2>&1
}
cd "$COMPOSE_DIR" || exit 1
# Pobierz listę kontenerów i ich stan
declare -A current_states
while IFS= read -r line; do
name=$(echo "$line" | awk '{print $1}')
state=$(echo "$line" | awk '{print $2}')
[ -n "$name" ] && current_states["$name"]="$state"
done < <(docker compose ps -a --format "{{.Name}} {{.State}}" 2>/dev/null | grep -v "^$")
restarted=()
for name in "${!current_states[@]}"; do
state="${current_states[$name]}"
if [[ "$state" == "exited" || "$state" == "dead" || "$state" == "created" ]]; then
echo "[$(date)] $name jest $state - restartuję..." >> "$LOG"
docker compose up -d "$name" >> "$LOG" 2>&1
new_state=$(docker inspect --format '{{.State.Status}}' "$name" 2>/dev/null)
if [[ "$new_state" == "running" ]]; then
echo "[$(date)] $name uruchomiony." >> "$LOG"
restarted+=("$name (był: $state)")
else
echo "[$(date)] $name - nie udało się uruchomić (stan: $new_state)." >> "$LOG"
restarted+=("$name BŁĄD (był: $state, teraz: $new_state)")
fi
fi
done
if [ ${#restarted[@]} -gt 0 ]; then
msg="🐳 <b>Docker watchdog - acemagic</b>%0A"
msg+="Zrestartowane kontenery:%0A"
for r in "${restarted[@]}"; do
msg+="- $r%0A"
done
telegram_notify "$msg"
fi