steid

@jamesgill /

steid/deploy.sh
Bourne Again Shell (bash)16.9 KBCode·Blame·History·Raw
1#!/usr/bin/env bash
2# Deploy a build of Steid to a running instance.
3#
4# ./deploy.sh # build, upload, upgrade, verify
5# ./deploy.sh --skip-build # use whatever is already in dist/
6# ./deploy.sh --host steid --domain jpgill.dev
7# ./deploy.sh --publish # also publish dist/ for strangers to download
8# ./deploy.sh --publish-s3-only # publish to releases.steid.dev and nothing else
9#
10# This is the operator's script, not the stranger's — `install.sh` is what someone
11# else runs to install Steid for the first time. This one assumes an instance
12# already exists and you want it running a newer build.
13#
14# WHY IT DOES MORE THAN scp-AND-RUN. An upgrade replaces the binary of a live
15# service. Three things can go wrong and each is silent: the new build might not
16# boot, the state might not survive, and a mistake leaves nothing to go back to.
17# So it snapshots the database and the current binary first, upgrades, then
18# *checks the site actually works* — and restores if it does not.
19#
20# MIGRATIONS RUN THEMSELVES, ON BOOT, AND THIS SCRIPT CANNOT UNDO THEM. The
21# rollback below restores the binary, never the schema — so a migration that the
22# previous release cannot read leaves a rolled-back instance broken. Expand,
23# deploy, contract: see "Migrations" in plans/architecture.md. And a previous
24# release older than 0.8.1 refuses to boot on ANY migration it does not know, so
25# rolling back across a migration onto 0.8.0 or earlier never comes up.
26#
27# WHY --publish IS OFF BY DEFAULT. Deploying and publishing are not the same
28# event. A deploy happens whenever a build is worth running; a publish changes
29# what strangers get, permanently and for a version number that can never be
30# re-cut. Publishing on every deploy would put half-finished builds behind a
31# version other people install, and would publish only the one architecture a
32# deploy happens to have built. So it is opt-in — and, so it stops being
33# forgotten, it is one flag on the command that was going to be run anyway.
34#
35# WHERE A PUBLISH GOES, AND WHY IT IS TWO PLACES. Since 0.6.0 the release host
36# is **https://releases.steid.dev** — an S3 bucket (`steid-releases`) behind
37# CloudFront, which is what `install.sh` defaults to and what the control plane's
38# cloud-init downloads from headlessly. Before that, releases came off this box:
39# jpgill.dev is the author's own Steid instance and served its own artefacts, and
40# every link handed out since 0.4.0 points there. So a publish writes both, and
41# the box keeps its copy as a **mirror**. That mirror is temporary: it goes when
42# milestone 2 of the control plane moves the author's instance onto the managed
43# fleet and jpgill.dev stops being a hand-run box. See
44# plans/decisions/0009-releases-from-releases-steid-dev.md.
45#
46# `--publish-s3-only` publishes to the releases host without touching this box at
47# all — no deploy, no ssh, no mirror. That is the one to run when the box is
48# somebody's live site and the release has nothing to do with it.
49#
50# THE PUBLISH CREDENTIAL IS A NAMED AWS PROFILE AND NEVER A VALUE. `--profile
51# ${STEID_AWS_PROFILE:-steid}` on every call; the profile assumes a role into the
52# Steid Cloud account and is configured on the operator's laptop. Nothing in this
53# repository holds a key, an account id or a role ARN, and this repository is
54# public.
55
56set -euo pipefail
57
58HOST="steid" # an ssh alias or user@address
59DOMAIN="jpgill.dev"
60TARGET="x86_64-unknown-linux-gnu"
61SKIP_BUILD=0
62PUBLISH=0
63DEPLOY=1
64MIRROR=1
65VERSION=""
66
67# The releases host: bucket, public hostname, and the distribution in front of
68# it. The distribution id is LOOKED UP by alias rather than written down —
69# hard-coding it would mean this script silently publishes into the wrong (or a
70# deleted) distribution after any rebuild of the estate, and the lookup is one
71# call. --distribution, or STEID_RELEASES_DISTRIBUTION, skips it.
72AWS_PROFILE_NAME="${STEID_AWS_PROFILE:-steid}"
73RELEASES_BUCKET="${STEID_RELEASES_BUCKET:-steid-releases}"
74RELEASES_HOST="${STEID_RELEASES_HOST:-releases.steid.dev}"
75DISTRIBUTION="${STEID_RELEASES_DISTRIBUTION:-}"
76
77# Where the artefacts are served from on the box. NOT under /var/lib/steid: that
78# directory is the instance's state and its whole backup surface — the snapshot
79# below tars it on every deploy, so release tarballs living there would be copied
80# into every backup forever. It is also mode 750 steid:steid, and Caddy runs as
81# `caddy`, so serving from inside it would mean loosening the directory that
82# protects steid.db. Caddy's `handle_path` blocks point here; see deploy/Caddyfile.
83DIST_DIR="/srv/steid-dist"
84
85die() { echo "deploy.sh: $*" >&2; exit 1; }
86say() { echo "==> $*"; }
87
88while [ $# -gt 0 ]; do
89 case "$1" in
90 --host) HOST="${2:?--host needs a value}"; shift 2 ;;
91 --domain) DOMAIN="${2:?--domain needs a value}"; shift 2 ;;
92 --target) TARGET="${2:?--target needs a triple}"; shift 2 ;;
93 --version) VERSION="${2:?--version needs a value}"; shift 2 ;;
94 --skip-build) SKIP_BUILD=1; shift ;;
95 --publish) PUBLISH=1; shift ;;
96 # Publish to the releases host and do nothing else: no deploy, no ssh,
97 # no mirror. Separating these is the point — the mirror lives on a box
98 # that is also a live website, and cutting a release must not need it.
99 --publish-s3-only) PUBLISH=1; DEPLOY=0; MIRROR=0; shift ;;
100 --no-mirror) MIRROR=0; shift ;;
101 --distribution) DISTRIBUTION="${2:?--distribution needs an id}"; shift 2 ;;
102 -h|--help) sed -n '2,19p' "$0" | sed 's/^#\{1,2\} \{0,1\}//'; exit 0 ;;
103 *) die "unknown argument: $1" ;;
104 esac
105done
106
107cd "$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)"
108
109[ -n "$VERSION" ] || VERSION="$(grep -m1 '^version *= *"' Cargo.toml | sed 's/.*"\(.*\)".*/\1/')"
110NAME="steid-${VERSION}-${TARGET}"
111TARBALL="dist/${NAME}.tar.gz"
112
113# Refuse to deploy a working tree that is not what is committed. The instance
114# should always be running a commit you can point at, or debugging it later means
115# guessing what was on the machine that built it.
116if [ -n "$(git status --porcelain)" ]; then
117 die "working tree is dirty — commit first, so the deployed build has a commit to name"
118fi
119COMMIT="$(git rev-parse --short HEAD)"
120
121if [ "$SKIP_BUILD" = 0 ]; then
122 say "building ${NAME} from ${COMMIT}"
123 ./release.sh --target "$TARGET" --version "$VERSION" >/dev/null
124else
125 say "skipping build (--skip-build)"
126fi
127[ -f "$TARBALL" ] || die "no ${TARBALL} — build it, or drop --skip-build"
128
129# --- deploy, unless this run is only cutting a release ----------------------
130
131if [ "$DEPLOY" = 0 ]; then
132 say "not deploying (--publish-s3-only): this box is not touched"
133else
134 say "checking the instance is reachable"
135 ssh -o BatchMode=yes "$HOST" true || die "cannot ssh to ${HOST}"
136
137 # --- snapshot, so there is something to go back to --------------------------
138
139 STAMP="$(date +%Y%m%d-%H%M%S)"
140 say "snapshotting state and the current binary (${STAMP})"
141 ssh -o BatchMode=yes "$HOST" "
142 set -e
143 sudo mkdir -p /var/backups/steid
144 sudo tar czf /var/backups/steid/state-${STAMP}.tar.gz -C /var/lib steid
145 sudo tar czf /var/backups/steid/binary-${STAMP}.tar.gz -C /opt steid
146 sudo find /var/backups/steid -name '*.tar.gz' -mtime +14 -delete
147 "
148
149 # --- upgrade ----------------------------------------------------------------
150
151 say "uploading"
152 scp -q -o BatchMode=yes "$TARBALL" "${TARBALL}.sha256" install.sh "${HOST}:"
153
154 say "upgrading"
155 ssh -o BatchMode=yes "$HOST" "sudo sh ./install.sh --domain '${DOMAIN}' --tarball './${NAME}.tar.gz'" \
156 | grep -E '^==>|is running' || true
157
158 # --- verify, and roll back if it is not actually serving --------------------
159
160 say "verifying https://${DOMAIN}"
161 OK=0
162 for _ in $(seq 1 15); do
163 sleep 2
164 if [ "$(curl -s -o /dev/null -m 10 -w '%{http_code}' "https://${DOMAIN}/healthz")" = "200" ]; then
165 OK=1; break
166 fi
167 done
168
169 if [ "$OK" = 1 ]; then
170 say "healthy — ${VERSION} (${COMMIT}) is live at https://${DOMAIN}"
171 ssh -o BatchMode=yes "$HOST" "systemctl is-active steid caddy | paste -sd' ' -" | sed 's/^/ steid caddy: /'
172 else
173 echo "deploy.sh: the new build is NOT serving. Rolling back." >&2
174 ssh -o BatchMode=yes "$HOST" "
175 set -e
176 sudo systemctl stop steid
177 sudo rm -rf /opt/steid
178 sudo tar xzf /var/backups/steid/binary-${STAMP}.tar.gz -C /opt
179 sudo systemctl start steid
180 "
181 sleep 4
182 ROLLED="$(curl -s -o /dev/null -m 10 -w '%{http_code}' "https://${DOMAIN}/healthz")"
183 echo "deploy.sh: rolled back to the previous binary (healthz ${ROLLED})." >&2
184 echo "deploy.sh: state was NOT restored — the database is untouched by an upgrade," >&2
185 echo " and /var/backups/steid/state-${STAMP}.tar.gz holds it if you need it." >&2
186 exit 1
187 fi
188fi
189
190# --- publish, so the release the box is running is the one strangers get -----
191
192if [ "$PUBLISH" = 1 ]; then
193
194 # Every target install.sh can ask for, which is what `release.sh --all`
195 # builds. A missing one is not fatal — publishing the architecture you have
196 # beats publishing nothing — but it is called out, because the failure lands
197 # on a stranger as a 404 halfway through an install that looked fine, and it
198 # reads as a broken host rather than a missing file.
199 PUBLISH_TARGETS="x86_64-unknown-linux-gnu aarch64-unknown-linux-gnu"
200 FILES=""
201 for t in $PUBLISH_TARGETS; do
202 f="dist/steid-${VERSION}-${t}.tar.gz"
203 if [ -f "$f" ] && [ -f "${f}.sha256" ]; then
204 FILES="${FILES} ${f} ${f}.sha256"
205 else
206 echo "deploy.sh: no ${f} — anyone whose 'uname -m' picks ${t} gets a 404." >&2
207 echo " Build it first: ./release.sh --target ${t} --version ${VERSION}" >&2
208 fi
209 done
210 [ -n "$FILES" ] || die "nothing to publish for ${VERSION}"
211
212 # --- the releases host: S3 behind CloudFront -----------------------------
213
214 command -v aws >/dev/null 2>&1 || die "no aws CLI, and the releases host is S3.
215 Install it, or pass --host/--no-mirror flags to publish only the mirror."
216
217 say "publishing v${VERSION} to s3://${RELEASES_BUCKET} (profile ${AWS_PROFILE_NAME})"
218
219 # An explicit content type on every object, and --no-guess-mime-type so the
220 # CLI does not add one of its own. Python's mimetypes — which is what the
221 # guess is — reports `.tar.gz` as type application/x-tar *with encoding gzip*,
222 # and the CLI turns that into `Content-Encoding: gzip`. A browser then
223 # silently gunzips the download, so the file on disk is a .tar wearing a
224 # .tar.gz name and its sha256 no longer matches the .sha256 beside it. That
225 # failure looks exactly like a tampered artefact, which is the one thing a
226 # checksum exists to tell you about.
227 for f in $FILES; do
228 case "$f" in
229 *.sha256) CT="text/plain" ;;
230 *) CT="application/gzip" ;;
231 esac
232 KEY="v${VERSION}/$(basename "$f")"
233 aws --profile "$AWS_PROFILE_NAME" s3 cp "$f" "s3://${RELEASES_BUCKET}/${KEY}" \
234 --no-guess-mime-type --content-type "$CT" --only-show-errors \
235 || die "upload failed: ${KEY}"
236 echo " s3://${RELEASES_BUCKET}/${KEY}"
237 done
238
239 # install.sh sits at the root: the URL a stranger is handed is
240 # https://<host>/install.sh and there is nowhere else for it.
241 aws --profile "$AWS_PROFILE_NAME" s3 cp install.sh "s3://${RELEASES_BUCKET}/install.sh" \
242 --no-guess-mime-type --content-type "text/x-shellscript" --only-show-errors \
243 || die "upload failed: install.sh"
244 echo " s3://${RELEASES_BUCKET}/install.sh"
245
246 # The distribution is found by its alias rather than written down here. An
247 # id in the repository is a fact about one estate that rots the first time
248 # the estate is rebuilt, and the wrong id means a publish that "succeeded"
249 # and a host still serving the old install.sh.
250 if [ -z "$DISTRIBUTION" ]; then
251 DISTRIBUTION="$(aws --profile "$AWS_PROFILE_NAME" cloudfront list-distributions \
252 --query "DistributionList.Items[?contains(Aliases.Items, '${RELEASES_HOST}')].Id | [0]" \
253 --output text 2>/dev/null || true)"
254 fi
255 [ -n "$DISTRIBUTION" ] && [ "$DISTRIBUTION" != "None" ] \
256 || die "no CloudFront distribution has the alias ${RELEASES_HOST}.
257 Pass --distribution <id>, or set STEID_RELEASES_DISTRIBUTION."
258
259 # The cache policy is CloudFront's managed CachingOptimized: up to 24 hours.
260 # install.sh is overwritten on every publish, so without an invalidation the
261 # world keeps installing the previous version for a day — and the version
262 # prefix is invalidated too, because a re-upload of an artefact that already
263 # existed has the same problem and costs nothing to cover. Invalidations are
264 # free for the first 1,000 paths a month; these are two.
265 say "invalidating /install.sh and /v${VERSION}/* on ${DISTRIBUTION}"
266 INVALIDATION="$(aws --profile "$AWS_PROFILE_NAME" cloudfront create-invalidation \
267 --distribution-id "$DISTRIBUTION" \
268 --paths "/install.sh" "/v${VERSION}/*" \
269 --query 'Invalidation.Id' --output text)" || die "could not create an invalidation"
270 echo " ${INVALIDATION}"
271 # Waited for, not fired and forgotten: the verification below is worthless
272 # against a cached copy of the previous publish.
273 aws --profile "$AWS_PROFILE_NAME" cloudfront wait invalidation-completed \
274 --distribution-id "$DISTRIBUTION" --id "$INVALIDATION" \
275 || die "invalidation ${INVALIDATION} did not complete"
276
277 # Fetched back over HTTPS rather than trusted from the bucket listing. What
278 # matters is not that the bytes are in S3 but that the host serves them: the
279 # bucket is private and reachable only through the distribution's origin
280 # access control, and a policy that denies a prefix is a silent 403 rather
281 # than an error at upload time.
282 say "verifying the published URLs"
283 for f in $FILES; do
284 URL="https://${RELEASES_HOST}/v${VERSION}/$(basename "$f")"
285 CODE="$(curl -s -o /dev/null -m 120 -w '%{http_code}' "$URL")"
286 [ "$CODE" = "200" ] || die "published but not served: ${URL} (HTTP ${CODE}).
287 Does the bucket policy let the distribution read this prefix?"
288 echo " ${CODE} ${URL}"
289 done
290 CODE="$(curl -s -o /dev/null -m 30 -w '%{http_code}' "https://${RELEASES_HOST}/install.sh")"
291 [ "$CODE" = "200" ] || die "published but not served: https://${RELEASES_HOST}/install.sh (HTTP ${CODE})"
292 echo " ${CODE} https://${RELEASES_HOST}/install.sh"
293
294 # --- the mirror on the author's own instance -----------------------------
295 #
296 # Temporary, and kept because every link handed out between 0.4.0 and 0.6.0
297 # points at it. It needs ssh to a box that is also a live website, so it is
298 # skippable on its own: --no-mirror, or --publish-s3-only.
299 if [ "$MIRROR" = 1 ]; then
300 say "mirroring v${VERSION} to ${HOST}:${DIST_DIR}"
301
302 # Upload to the login user's home, then `sudo install` into place: the served
303 # directory is root-owned and scp cannot elevate. `install` rather than `mv`
304 # so the mode is stated outright instead of inherited from whatever umask the
305 # upload happened to run under — these files are world-readable on purpose.
306 # shellcheck disable=SC2086 # FILES is a deliberate word-split list.
307 scp -q -o BatchMode=yes $FILES install.sh "${HOST}:"
308 REMOTE="set -e; sudo install -d -m 755 -o root -g root ${DIST_DIR}/v${VERSION};"
309 for f in $FILES; do
310 REMOTE="${REMOTE} sudo install -m 644 -o root -g root ./$(basename "$f") ${DIST_DIR}/v${VERSION}/;"
311 done
312 REMOTE="${REMOTE} sudo install -m 644 -o root -g root ./install.sh ${DIST_DIR}/install.sh"
313 ssh -o BatchMode=yes "$HOST" "$REMOTE"
314
315 # Fetched back over HTTPS for the same reason as above: the two
316 # distribution blocks in /etc/caddy/Caddyfile are easy to not have
317 # enabled, and a silent 404 there is the failure this checks for.
318 say "verifying the mirrored URLs"
319 for f in $FILES; do
320 URL="https://${DOMAIN}/jamesgill/repos/steid/releases/v${VERSION}/$(basename "$f")"
321 CODE="$(curl -s -o /dev/null -m 60 -w '%{http_code}' "$URL")"
322 [ "$CODE" = "200" ] || die "mirrored but not served: ${URL} (HTTP ${CODE}).
323 Are the distribution handle_path blocks in /etc/caddy/Caddyfile? See deploy/Caddyfile."
324 echo " ${CODE} ${URL}"
325 done
326 CODE="$(curl -s -o /dev/null -m 30 -w '%{http_code}' "https://${DOMAIN}/install.sh")"
327 [ "$CODE" = "200" ] || die "mirrored but not served: https://${DOMAIN}/install.sh (HTTP ${CODE})"
328 echo " ${CODE} https://${DOMAIN}/install.sh"
329 else
330 say "skipping the ${DOMAIN} mirror"
331 fi
332
333 say "published. A stranger now installs this version with:"
334 echo " curl -fsSL https://${RELEASES_HOST}/install.sh | sh -s -- --domain <their-host> --version ${VERSION}"
335fi