#!/usr/bin/env bash
# Real demos for P113 "How a Load Balancer Works with HAProxy". Made on the Mac (Docker Desktop).
# A city marathon's sign-up site: five containers from one stock Ubuntu 24.04 image with systemd as PID 1
# (lab/Dockerfile), on one Docker network:
#   lb      10.13.0.10  the load balancer: Ubuntu's own HAProxy 2.8 as a systemd service, the address runners use
#                       (network alias race.lan); its config versions are copied in from lab/steps off camera
#   web1-3  10.13.0.11-13  three copies of the sign-up app (lab/signup.py: Flask under gunicorn, Ubuntu's packages,
#                       a systemd service), each pinned to one CPU core of its own (nproc says 1); web3's data folder is a small 4 MB disk of its own
#   laptop  10.13.0.50  Ben's laptop, a runner signing up: curl and wrk
# Every command shown is typed into a real interactive bash in a pty, one window per machine (demo_driver.py);
# every answer, log line and number is real. Ports 18113 (the site) and 18404 (HAProxy's stats page) on the Mac reach
# the load balancer for the browser captures.
set -euo pipefail
cd "$(dirname "$0")"
cleanup() {
  docker rm -f -v ce-p113-lb ce-p113-web1 ce-p113-web2 ce-p113-web3 ce-p113-laptop >/dev/null 2>&1 || true
  docker network rm ce-p113-net >/dev/null 2>&1 || true
}
cleanup
[ -n "${KEEP:-}" ] || trap cleanup EXIT
docker build -q -t ce-p113 lab >/dev/null
docker network create --subnet 10.13.0.0/24 ce-p113-net >/dev/null
box() {  # box NAME IP [docker run options]
  local n=$1 ip=$2; shift 2
  docker run -d --name ce-p113-$n --hostname $n --privileged --cgroupns=private --tmpfs /run --tmpfs /run/lock \
    --network ce-p113-net --ip $ip --network-alias $n "$@" ce-p113 >/dev/null
}
box web1 10.13.0.11 --cpuset-cpus 1
box web2 10.13.0.12 --cpuset-cpus 2
box web3 10.13.0.13 --cpuset-cpus 3 --mount type=tmpfs,destination=/var/lib/signup,tmpfs-size=4m,tmpfs-mode=1777
box lb 10.13.0.10 --network-alias race.lan -p 127.0.0.1:18113:80 -p 127.0.0.1:18404:8404 --cpuset-cpus 4-5
box laptop 10.13.0.50 --cpuset-cpus 6-9
for b in lb web1 web2 web3 laptop; do
  for i in $(seq 60); do docker exec ce-p113-$b systemctl is-system-running 2>/dev/null | grep -qE 'running|degraded' && break; sleep 1; done
done
for w in web1 web2 web3; do
  docker exec ce-p113-$w bash -c 'chown signup:signup /var/lib/signup && systemctl enable -q --now signup'
done
python3 demo_driver.py
