#!/usr/bin/env bash # Deploy the app from ~/app.git: build a commit in a new directory under # ~/releases, run ~/bin/app-release if there is one, switch ~/app to it, # restart app.target, and check that ~/app.health's paths answer. # app-deploy deploy the branch's newest commit, if it isn't live # app-deploy --force build and deploy it again (after editing ~/app.env) # app-deploy SHA deploy that commit # A push to ~/app.git runs it; with a GitHub remote, app-deploy.timer does. set -euo pipefail exec 9>"$HOME/.deploy.lock" && flock 9 # one deploy at a time set -a; . "$HOME/app.env"; set +a export GIT_DIR=$HOME/app.git branch=$(git symbolic-ref --short HEAD) if git remote get-url origin >/dev/null 2>&1; then git fetch -q origin "+refs/heads/$branch:refs/heads/$branch" fi case ${1:-} in "") rev=$(git rev-parse "$branch"); force= ;; --force) rev=$(git rev-parse "$branch"); force=1 ;; *) rev=$(git rev-parse --verify "$1^{commit}"); force=1 ;; esac if [ -z "$force" ]; then [ "$rev" != "$(cat "$HOME/app/.rev" 2>/dev/null)" ] || exit 0 # live already [ "$rev" != "$(cat "$HOME/.deploy-failed" 2>/dev/null)" ] || exit 0 # failed before fi release=$HOME/releases/$(date -u +%Y%m%d-%H%M%S)-${rev:0:7} previous=$(readlink "$HOME/app" || true) fail() { # put the previous release back, and remember the commit that failed trap - ERR echo "==> Deploy of ${rev:0:7} FAILED${1:+: $1}. Still running: ${previous:-nothing}" echo "$rev" > "$HOME/.deploy-failed" if [ -z "$previous" ]; then rm -f "$HOME/app" && sudo systemctl stop app.target elif [ "$(readlink "$HOME/app")" != "$previous" ]; then ln -sfn "$previous" "$HOME/app.new" && mv -T "$HOME/app.new" "$HOME/app" sudo systemctl restart app.target fi rm -rf "$release" exit 1 } trap fail ERR echo "==> Building ${rev:0:7} ($(git log -1 --format=%s "$rev")) in $release" mkdir -p "$release" git archive "$rev" | tar -x -C "$release" echo "$rev" > "$release/.rev" unset GIT_DIR cd "$release" "$HOME/bin/app-build" || fail "the build failed" if [ -x "$HOME/bin/app-release" ]; then echo "==> Running app-release" timeout 600 "$HOME/bin/app-release" Starting the new version" ln -sfn "$release" "$HOME/app.new" && mv -T "$HOME/app.new" "$HOME/app" sudo systemctl restart app.target for path in $(cat "$HOME/app.health" 2>/dev/null || echo /); do for _ in $(seq 30); do code=$(curl -s -o /dev/null -m 10 -w '%{http_code}' "http://localhost:8000$path" || true) case $code in 000|5??) sleep 1 ;; *) break ;; esac done case $code in 000|5??) fail "$path answers HTTP $code (journalctl -u 'app-*' -n 50)" ;; esac echo "==> $path: HTTP $code" done trap - ERR rm -f "$HOME/.deploy-failed" ls -1d "$HOME"/releases/*/ | head -n -3 | xargs -r rm -rf # keep 3 echo "==> Deployed ${rev:0:7}"