chessbaseLinux/website/deploy/deploy.sh

78 lines
2.9 KiB
Bash
Raw Normal View History

#!/usr/bin/env bash
# Updates the website on production (run only with the owner's go-ahead):
# website/deploy/deploy.sh build the committed website, ship and start it
# website/deploy/deploy.sh rollback start the previously deployed image again
# website/deploy/deploy.sh status what runs there now
# The image travels over ssh (docker save | docker load), tagged with the commit; the
# last few stay on the server for a rollback. The server's .env and data/ are never touched.
set -euo pipefail
host="${DEPLOY_HOST:-docker-prodVM}"
dir="${DEPLOY_DIR:-/home/vrubel/services/ChessPenguinSite}"
port=8140
here="$(cd "$(dirname "$0")" && pwd)"
site="$(dirname "${here}")"
remote() { ssh -o BatchMode=yes "${host}" bash -s -- "$@"; }
wait_healthy() {
remote "${dir}" "${port}" <<'SH'
for i in $(seq 60); do
if curl -fsS -o /dev/null "http://127.0.0.1:$2/healthz"; then
echo "healthy: $(docker inspect -f '{{.Config.Image}}' chesspenguin-site)"
exit 0
fi
sleep 5
done
echo "not healthy after 5 minutes; logs:"; cd "$1" && docker compose logs --tail 40; exit 1
SH
}
case "${1:-deploy}" in
status)
remote "${dir}" <<'SH'
cd "$1" && docker compose ps
echo "deployed: $(cat .deployed 2>/dev/null) previous: $(cat .previous 2>/dev/null)"
docker image ls chesspenguin-site --format '{{.Tag}} {{.CreatedSince}}'
SH
;;
rollback)
remote "${dir}" <<'SH'
set -e; cd "$1"
prev="$(cat .previous)"; cur="$(cat .deployed)"
docker tag "chesspenguin-site:${prev}" chesspenguin-site:current
docker compose up -d
echo "${prev}" > .deployed; echo "${cur}" > .previous
SH
wait_healthy
;;
deploy)
if [[ -n "$(git -C "${site}" status --porcelain -- .)" ]]; then
echo "website/ has uncommitted changes; commit them first" >&2
exit 1
fi
tag="$(git -C "${site}" rev-parse --short=12 HEAD)"
echo "== build chesspenguin-site:${tag}"
docker build -q -t "chesspenguin-site:${tag}" "${site}"
echo "== ship to ${host}"
docker save "chesspenguin-site:${tag}" | gzip -1 | ssh -o BatchMode=yes "${host}" 'gzip -dc | docker load -q'
ssh -o BatchMode=yes "${host}" "mkdir -p '${dir}'"
scp -q "${here}/docker-compose.yml" "${host}:${dir}/docker-compose.yml"
echo "== start"
remote "${dir}" "${tag}" <<'SH'
set -e; cd "$1"
[ -f .env ] || { echo ".env is missing in $1 (see .env.example)"; exit 1; }
cur="$(cat .deployed 2>/dev/null || true)"
docker tag "chesspenguin-site:$2" chesspenguin-site:current
docker compose up -d
if [ -n "${cur}" ] && [ "${cur}" != "$2" ]; then echo "${cur}" > .previous; fi
echo "$2" > .deployed
# Keep the three newest images for rollbacks.
docker image ls chesspenguin-site --format '{{.Tag}}' | tail -n +4 | grep -vx -e current -e "$2" -e "${cur}" \
| xargs -r -I{} docker image rm -f "chesspenguin-site:{}" >/dev/null || true
SH
wait_healthy
;;
*)
echo "usage: $0 [deploy|rollback|status]" >&2; exit 2 ;;
esac