forked from mtusi2026/mtusi2026lab6
54 lines
2.1 KiB
Bash
Executable File
54 lines
2.1 KiB
Bash
Executable File
#!/bin/sh
|
|
# Active readiness bridge for open-source Nginx. No Docker socket or credentials.
|
|
set -eu
|
|
probe() {
|
|
if wget -T 1 -q -O /dev/null "http://$1:8080/health/ready" 2>/dev/null; then
|
|
echo up > "/tmp/$1.health"
|
|
else
|
|
echo down > "/tmp/$1.health"
|
|
fi
|
|
}
|
|
control() { cat "/tmp/control-$1" 2>/dev/null || echo serve:boot; }
|
|
echo $$ > /tmp/healthwatch.pid
|
|
while :; do
|
|
sleep 1
|
|
probe api-a &
|
|
first=$!
|
|
probe api-b &
|
|
second=$!
|
|
wait "$first"
|
|
wait "$second"
|
|
# Read desired state AFTER probes. A generation is acknowledged only after
|
|
# the matching upstream configuration has been applied, never from a stale probe.
|
|
a_control=$(control api-a)
|
|
b_control=$(control api-b)
|
|
a_state=$(cat /tmp/api-a.health)
|
|
b_state=$(cat /tmp/api-b.health)
|
|
case "$a_control" in drain:*) a_state=down;; esac
|
|
case "$b_control" in drain:*) b_state=down;; esac
|
|
: > /tmp/upstreams.next
|
|
for service in api-a api-b; do
|
|
if [ "$service" = api-a ]; then state=$a_state; else state=$b_state; fi
|
|
suffix=''
|
|
[ "$state" = up ] || suffix=' down'
|
|
printf 'server %s:8080 resolve max_fails=1 fail_timeout=2s%s;\n' "$service" "$suffix" >> /tmp/upstreams.next
|
|
done
|
|
if ! cmp -s /tmp/upstreams.next /etc/nginx/upstreams.conf; then
|
|
cp /etc/nginx/upstreams.conf /tmp/upstreams.previous
|
|
# Rename on the same filesystem: readers never see missing/partial config.
|
|
cp /tmp/upstreams.next /etc/nginx/upstreams.next
|
|
mv -f /etc/nginx/upstreams.next /etc/nginx/upstreams.conf
|
|
if nginx -t && nginx -s reload; then
|
|
echo 'readiness upstream set updated'
|
|
else
|
|
cp /tmp/upstreams.previous /etc/nginx/upstreams.next
|
|
mv -f /etc/nginx/upstreams.next /etc/nginx/upstreams.conf
|
|
exit 1
|
|
fi
|
|
fi
|
|
printf '%s %s\n' "$a_control" "$a_state" > /tmp/applied-api-a.next
|
|
mv -f /tmp/applied-api-a.next /tmp/applied-api-a
|
|
printf '%s %s\n' "$b_control" "$b_state" > /tmp/applied-api-b.next
|
|
mv -f /tmp/applied-api-b.next /tmp/applied-api-b
|
|
done
|