summaryrefslogtreecommitdiff
path: root/playbooks/roles/outbound/templates/proxy/nginx/dont-die-until-conn-closed.sh
blob: 967c2c02a2dcf3cefb669fc95d683ae28b9fbcde (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/bin/bash

echo "[/] sleeping to wait for some time for container to be marked as stop."
# https://stackoverflow.com/a/45146086
sleep 3

pid_file="/run/nginx.pid"
max_wait_seconds=30

if [ ! -f "$pid_file" ]; then
  echo "[!] Nginx PID file not found at $pid_file. Assuming Nginx not running or already stopped."
  exit 0
fi

PID=$(cat "$pid_file")

# Validate PID
if [ -z "$PID" ] || ! [[ "$PID" =~ ^[0-9]+$ ]]; then
    echo "[!] Invalid PID found in $pid_file: '$PID'"
    exit 1
fi

# Check if the process actually exists before sending quit
# kill -0 PID checks if a signal can be sent.
if ! kill -0 "$PID" 2>/dev/null; then
    echo "[!] Nginx process $PID not found or already stopped."
    exit 0 # Exit successfully
fi

echo "[/] sending signal to nginx (PID: $PID) to quit"
nginx -s quit

start_time=$SECONDS
echo "[/] Waiting for Nginx (PID: $PID) to stop (max ${max_wait_seconds}s)..."

while [ -d /proc/$PID ]; do
  current_time=$SECONDS
  elapsed_time=$((current_time - start_time))

  if [ "$elapsed_time" -ge "$max_wait_seconds" ]; then
    echo "[!] Timeout: Nginx process $PID did not stop within ${max_wait_seconds} seconds."
    echo "[!] Sending SIGKILL to PID $PID."
    kill -9 "$PID" 2>/dev/null

    exit 1
  fi

  sleep 0.5
  if (( $(echo "$elapsed_time % 5" | bc) == 0 )); then
   echo "[/] Nginx (PID: $PID) still running (waited ${elapsed_time}s)..."
  fi
done

echo "[+] Nginx process $PID stopped gracefully."
echo "[+] done. goodbye."
exit 0