steid

@jamesgill /

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