Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/scripts/release_gate.sh
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 18 minutes ago History
release_gate.sh · 19.5 KB · 441 lines
1#!/usr/bin/env bash
2#
3# Release gate: the checks the normal test run cannot make. Run it before a push that will be
4# deployed and before a tag.
5#
6# scripts/release_gate.sh all every stage (default)
7# scripts/release_gate.sh fresh a brand-new box: empty data dir, real-box flags, one-click order
8# scripts/release_gate.sh upgrade an existing box (previous release's data) survives this tree
9# scripts/release_gate.sh node the node-marked tests, run where node exists
10#
11# What each stage proves, and what it does not, is in CONTRIBUTING.md ("Release gate").
12#
13# Docker only: nothing is installed on the host. Everything it creates is named gate-<run id>-... and
14# removed on exit (containers, volumes, images, the temp directory). It never touches anything else.
15# Building the images uses the network (base images, apt, pip); every test step runs offline.
16#
17set -euo pipefail
18
19ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
20RUN_ID="$(date +%H%M%S)-$$"
21PREFIX="gate-${RUN_ID}"
22WORK="$(mktemp -d "${TMPDIR:-/tmp}/${PREFIX}.XXXXXX")"
23random_hex() { head -c "$1" /dev/urandom | od -An -tx1 | tr -d ' \n'; }
24TOKEN="$(random_hex 20)"
25PASSWORD="gate-password-$(random_hex 6)"
26
27REGISTRY="${WORK}/created" # a file, not arrays: stages run in subshells
28: >"$REGISTRY"
29RESULTS=()
30FAILED=0
31
32say() { printf '\033[1;36m==>\033[0m %s\n' "$*"; }
33ok() { printf ' \033[32mok\033[0m %s\n' "$*"; }
34fail() { printf ' \033[1;31mFAIL\033[0m %s\n' "$*" >&2; return 1; }
35
36cleanup() {
37 local status=$?
38 set +e
39 local kind k name
40 # only names this run created (all start with the gate- prefix); containers first, images last
41 for kind in container volume image; do
42 while read -r k name; do
43 [[ "$k" == "$kind" && "$name" == "${PREFIX}-"* ]] || continue
44 case "$kind" in
45 container) docker rm -f "$name" >/dev/null 2>&1 ;;
46 volume) docker volume rm -f "$name" >/dev/null 2>&1 ;;
47 image) docker rmi -f "$name" >/dev/null 2>&1 ;;
48 esac
49 done <"$REGISTRY"
50 done
51 rm -rf "$WORK"
52 exit "$status"
53}
54trap cleanup EXIT
55trap 'exit 130' INT TERM
56
57
58# ---- helpers ---------------------------------------------------------------------------------
59
60# env a real box runs with (admin token generated per run; no override env)
61box_env() {
62 printf '%s\n' -e "DBBASIC_ADMIN_TOKEN=${TOKEN}" \
63 -e DBBASIC_ENABLE_PASSWORD_LOGIN=true \
64 -e DBBASIC_ENABLE_PERMISSION_ENFORCEMENT=true \
65 -e DBBASIC_ENABLE_PACKAGE_INSTALLS=true "$@"
66}
67
68new_volumes() { # NAME -> sets DATA_VOL OBJ_VOL
69 DATA_VOL="${PREFIX}-$1-data"; OBJ_VOL="${PREFIX}-$1-objects"
70 docker volume create "$DATA_VOL" >/dev/null; docker volume create "$OBJ_VOL" >/dev/null
71 echo "volume $DATA_VOL" >>"$REGISTRY"; echo "volume $OBJ_VOL" >>"$REGISTRY"
72}
73
74build_image() { # TAG CONTEXT_DIR [extra docker build args]
75 local tag="$1" ctx="$2"; shift 2
76 say "Building image $tag"
77 docker build -q -t "$tag" --build-arg "BUILD_COMMIT=$(git -C "$ROOT" rev-parse --short HEAD 2>/dev/null || true)" "$@" "$ctx" >/dev/null
78 echo "image $tag" >>"$REGISTRY"
79}
80
81export_tree() { # DEST: the working tree as it stands (tracked files, including uncommitted edits)
82 mkdir -p "$1"
83 ( cd "$ROOT" && git ls-files -z --cached --others --exclude-standard | tar --null -T - -cf - 2>/dev/null ) | tar -xf - -C "$1"
84}
85
86start_box() { # NAME IMAGE [extra env args...] -> sets CID PORT; uses DATA_VOL OBJ_VOL
87 local name="${PREFIX}-$1" image="$2"; shift 2
88 local args=()
89 while IFS= read -r line; do args+=("$line"); done < <(box_env)
90 CID="$name"
91 echo "container $name" >>"$REGISTRY"
92 docker run -d --name "$name" -v "${DATA_VOL}:/data/state" -v "${OBJ_VOL}:/data/objects" \
93 -p 127.0.0.1::8001 "${args[@]}" "$@" "$image" >/dev/null
94 PORT="$(docker port "$name" 8001/tcp | head -1 | sed 's/.*://')"
95 wait_healthy
96}
97
98wait_healthy() {
99 local i
100 for i in $(seq 1 60); do
101 if [[ "$(docker inspect -f '{{.State.Running}}' "$CID")" != true ]]; then
102 docker logs "$CID" 2>&1 | tail -25 >&2
103 fail "the server container exited instead of starting"; return 1
104 fi
105 if curl -fsS --max-time 3 "http://127.0.0.1:${PORT}/health" >/dev/null 2>&1; then return 0; fi
106 sleep 1
107 done
108 docker logs "$CID" 2>&1 | tail -25 >&2
109 fail "the server did not answer /health within 60 seconds"; return 1
110}
111
112stop_box() { docker rm -f "$CID" >/dev/null; }
113
114# http METHOD PATH [curl args...] -> HTTP_STATUS, HTTP_BODY (file), HTTP_HEADERS (file)
115http() {
116 local method="$1" path="$2"; shift 2
117 HTTP_BODY="$WORK/body"; HTTP_HEADERS="$WORK/headers"
118 HTTP_STATUS="$(curl -sS --max-time 60 -o "$HTTP_BODY" -D "$HTTP_HEADERS" -w '%{http_code}' \
119 -X "$method" "http://127.0.0.1:${PORT}${path}" "$@")"
120}
121admin() { local m="$1" p="$2"; shift 2; http "$m" "$p" -H "Authorization: Token ${TOKEN}" "$@"; }
122json() { printf '%s' "$1"; }
123
124expect() { # DESCRIPTION WANTED_STATUS_REGEX (after an http call)
125 if [[ "$HTTP_STATUS" =~ ^($2)$ ]]; then ok "$1 ($HTTP_STATUS)"; return 0; fi
126 echo " expected status $2, got $HTTP_STATUS: $(head -c 400 "$HTTP_BODY")" >&2
127 fail "$1"
128}
129
130py_in() { # IMAGE PYTHON_CODE [args]: run python as the service user on the current volumes, offline
131 local image="$1" code="$2"; shift 2
132 docker run --rm --network none --user dbbasic --entrypoint python \
133 -v "${DATA_VOL}:/data/state" -v "${OBJ_VOL}:/data/objects" "$image" -c "$code" "$@"
134}
135
136starter_policy_and_code() { # IMAGE: the one-click order, before the first start -> SETUP_CODE
137 SETUP_CODE="$(py_in "$1" '
138import os, object_setup, object_permission_store as s
139base = os.environ["DBBASIC_DATA_DIR"]
140code = object_setup.new_code()
141path = object_setup.code_path(base)
142path.parent.mkdir(parents=True, exist_ok=True)
143path.write_text(object_setup.code_hash(code) + "\n", encoding="ascii")
144s.replace_policy(s.starter_policy_payload(), base_dir=base)
145print(code)')"
146 [[ -n "$SETUP_CODE" ]]
147}
148
149one_click_apps() { # the list and order scripts/one-click-install.sh installs on a fresh box
150 awk '/for app in \(/{on=1} on{print} /\):/{if(on) exit}' "$ROOT/scripts/one-click-install.sh" \
151 | grep -o '"app-[a-z0-9-]*"' | tr -d '"'
152}
153
154make_restore_point() { # one backup, reused by every install (docs/single-vm-deployment.md)
155 admin POST /admin/backups
156 expect "took one backup for the installs" '200|201' || return 1
157 BACKUP="$(grep -o '"id": *"[^"]*"' "$HTTP_BODY" | head -1 | sed 's/.*: *"\(.*\)"/\1/')"
158 [[ -n "$BACKUP" ]] || { fail "no backup id in: $(head -c 300 "$HTTP_BODY")"; return 1; }
159}
160
161install_one() { # PKG: 0 when the install answered ok
162 admin POST "/packages/$1/install" -H 'Content-Type: application/json' \
163 -d "{\"allow_replace\": true, \"restore_point\": \"${BACKUP}\"}"
164 [[ "$HTTP_STATUS" =~ ^(200|201)$ ]] && grep -q '"status": "ok"' "$HTTP_BODY"
165}
166
167install_all() { # install each named package, in the order given; assert each succeeds
168 local pkg failed=() again=0
169 for pkg in "$@"; do
170 if install_one "$pkg"; then ok "installed $pkg"; else
171 echo " $pkg: HTTP $HTTP_STATUS $(head -c 300 "$HTTP_BODY")" >&2; failed+=("$pkg"); fi
172 done
173 (( ${#failed[@]} )) || return 0
174 # Informational: would a second pass over the failures have worked? (It says whether the failure is an
175 # ordering problem between packages or a package that cannot install at all.)
176 for pkg in "${failed[@]}"; do install_one "$pkg" && again=$((again + 1)); done
177 echo " ${#failed[@]} install(s) failed in the first pass: ${failed[*]}" >&2
178 echo " a second pass over just those: ${again} of ${#failed[@]} then succeeded" >&2
179 fail "${#failed[@]} of $# package installs failed"
180}
181
182make_collection() { # NAME FIELD: a collection with one text field, made through the admin API
183 admin PUT "/schemas/$1" -H 'Content-Type: application/json' \
184 -d "{\"schema\": {\"title\": \"$1\", \"fields\": [{\"name\": \"$2\", \"type\": \"text\"}]}}"
185 expect "created collection $1" '200|201'
186}
187
188# install_pass OUTFILE_OK OUTFILE_BAD PKG...: try each package once; names that installed go to OK, others to BAD
189install_pass() {
190 local ok_file="$1" bad_file="$2" pkg; shift 2
191 : >"$ok_file"; : >"$bad_file"
192 for pkg in "$@"; do
193 admin POST "/packages/${pkg}/install" -H 'Content-Type: application/json' \
194 -d "{\"allow_replace\": true, \"restore_point\": \"${BACKUP}\"}"
195 if [[ "$HTTP_STATUS" =~ ^(200|201)$ ]] && grep -q '"status": "ok"' "$HTTP_BODY"; then
196 echo "$pkg" >>"$ok_file"
197 else
198 echo "$pkg $(head -c 160 "$HTTP_BODY" | tr '\n' ' ')" >>"$bad_file"
199 fi
200 done
201}
202
203# install_everything PKG...: the packages on a fresh box depend on each other, and a box that has only some of
204# them installed cannot take the rest in directory order. Repeat the failed ones until a pass adds nothing.
205# Sets INSTALLED (file of names) and NOT_INSTALLED (file of "name<TAB>reason").
206install_everything() {
207 local pending=("$@") before
208 INSTALLED="$WORK/installed.list"; NOT_INSTALLED="$WORK/not_installed.list"
209 : >"$INSTALLED"
210 while :; do
211 before=${#pending[@]}
212 install_pass "$WORK/pass.ok" "$WORK/pass.bad" "${pending[@]}"
213 cat "$WORK/pass.ok" >>"$INSTALLED"
214 pending=(); while IFS=$'\t' read -r name _; do [[ -n "$name" ]] && pending+=("$name"); done <"$WORK/pass.bad"
215 cp "$WORK/pass.bad" "$NOT_INSTALLED"
216 (( ${#pending[@]} == 0 || ${#pending[@]} == before )) && break
217 done
218}
219
220form_post() { # PATH key=value... -> like http, as a form
221 local path="$1"; shift
222 local args=()
223 for kv in "$@"; do args+=(--data-urlencode "$kv"); done
224 http POST "$path" "${args[@]}"
225}
226
227session_cookie() { grep -i '^set-cookie:' "$HTTP_HEADERS" | head -1 | sed 's/^[^:]*: *//; s/;.*//' | tr -d '\r'; }
228
229# ---- stage: fresh ----------------------------------------------------------------------------
230
231stage_fresh() {
232 local tree="$WORK/current" image="${PREFIX}-current"
233 export_tree "$tree"
234 build_image "$image" "$tree"
235
236 say "fresh A: empty data dir, real-box flags, no override env, admin token only"
237 new_volumes freshA
238 start_box freshA "$image"
239 ok "became healthy on an empty data dir"
240 make_collection gate_private title || return 1
241 admin POST /collections/gate_private/records -H 'Content-Type: application/json' -d '{"id":"p1","title":"private"}'
242 expect "admin token can write a record" '200|201' || return 1
243 http GET /collections/gate_private/records
244 expect "anonymous read of a private collection is denied" '401|403' || return 1
245 http GET /identity/users
246 expect "anonymous read of the user list is denied" '401|403' || return 1
247 admin GET /collections/gate_private/records
248 expect "admin token reads the private collection" 200 || return 1
249 make_restore_point || return 1
250 local apps; apps="$(one_click_apps)"
251 [[ -n "$apps" ]] || { fail "could not read the app list from scripts/one-click-install.sh"; return 1; }
252 # shellcheck disable=SC2086
253 install_all $apps || return 1
254 stop_box
255
256 say "fresh B: the one-click order (starter policy saved first, setup code waiting)"
257 new_volumes freshB
258 starter_policy_and_code "$image"
259 ok "starter policy and setup code written before the first start"
260 start_box freshB "$image"
261 ok "became healthy waiting for setup"
262 http GET /health
263 expect "/health answers" 200 || return 1
264 grep -q '"waiting"' "$HTTP_BODY" || { fail "/health does not say setup is waiting: $(cat "$HTTP_BODY")"; return 1; }
265 ok "/health says setup is waiting"
266 http GET /setup -H 'Accept: text/html'
267 expect "/setup answers" 200 || return 1
268 local path
269 for path in /objects/site_home /collections/contacts/records /identity/users /login; do
270 http GET "$path"
271 expect "before setup, anonymous $path is held back" 503 || return 1
272 done
273 make_collection contacts name || return 1
274 admin POST /collections/contacts/records -H 'Content-Type: application/json' -d '{"id":"1","name":"Alice"}'
275 expect "the admin token still works while waiting" '200|201' || return 1
276 form_post /setup "code=${SETUP_CODE}" "email=owner@example.org" "password=${PASSWORD}"
277 expect "setup completes with the code" '200|303' || return 1
278 form_post /login "email=owner@example.org" "password=${PASSWORD}"
279 expect "the owner signs in with the password" 303 || return 1
280 local cookie; cookie="$(session_cookie)"
281 [[ -n "$cookie" ]] || { fail "login set no session cookie"; return 1; }
282 http GET /collections/contacts/records -H "Cookie: ${cookie}"
283 expect "the signed-in owner reads the private record" 200 || return 1
284 http GET /collections/contacts/records
285 expect "anonymous still cannot read the private record" '401|403' || return 1
286}
287
288# ---- stage: upgrade --------------------------------------------------------------------------
289
290skip() { printf '%s' "$1" >"$WORK/skip"; }
291
292stage_upgrade() {
293 local tag
294 tag="$(cd "$ROOT" && git tag --sort=-version:refname 2>/dev/null | head -1 || true)"
295 if [[ -z "$tag" ]]; then skip "no git tag to use as the previous release"; return 0; fi
296 say "upgrade: previous release $tag -> current tree"
297 local prev_tree="$WORK/prev" cur_tree="$WORK/current-up"
298 mkdir -p "$prev_tree"
299 ( cd "$ROOT" && git archive "$tag" ) | tar -xf - -C "$prev_tree"
300 export_tree "$cur_tree"
301 local prev_image="${PREFIX}-prev" cur_image="${PREFIX}-current-up"
302 build_image "$prev_image" "$prev_tree"
303 build_image "$cur_image" "$cur_tree"
304
305 new_volumes upgrade
306 local envx=(-e DBBASIC_ENABLE_SOURCE_WRITES=true)
307
308 # Bootstrap the previous release. A failure here is the old release's own flow, not this tree.
309 local rc=0 install_rc=0
310 bootstrap_previous "$prev_image" "$tag" "${envx[@]}" || rc=$?
311 if (( rc == 3 )); then
312 skip "the previous release ($tag) could not complete the bootstrap flow on its own, so nothing was learned about the current tree (see the output above)"
313 return 0
314 fi
315 (( rc == 0 )) || return 1
316 docker rm -f "${PREFIX}-prev-box" >/dev/null 2>&1 || true
317
318 start_box upgraded "$cur_image" "${envx[@]}"
319 ok "the current image became healthy on the previous release's data"
320 make_restore_point || return 1
321 # the deploy procedure: reinstall every package. Each one that installed on the previous release must again.
322 local pkgs; pkgs="$(sort "$WORK/prev_installed.list" | tr '\n' ' ')"
323 # shellcheck disable=SC2086
324 install_all $pkgs || install_rc=1 # keep going: the data checks below are worth having either way
325 admin GET /collections/gate_notes/records
326 expect "the old records are still there" 200 || return 1
327 grep -q 'before-upgrade' "$HTTP_BODY" || { fail "the old record is missing: $(head -c 300 "$HTTP_BODY")"; return 1; }
328 ok "the old record reads back"
329 admin GET /objects/gate_hello
330 expect "the old object still runs" 200 || return 1
331 grep -q 'hello-before-upgrade' "$HTTP_BODY" || { fail "object output changed: $(head -c 300 "$HTTP_BODY")"; return 1; }
332 ok "the old object returns what it did"
333 form_post /login "email=upgrade@example.org" "password=${PASSWORD}"
334 expect "the existing user still signs in with the old password" 303 || return 1
335 local cookie; cookie="$(session_cookie)"
336 http GET /collections/gate_notes/records -H "Cookie: ${cookie}"
337 expect "the signed-in user reads the old record" 200 || return 1
338 http GET /collections/gate_notes/records
339 expect "anonymous is still denied" '401|403' || return 1
340 return "$install_rc"
341}
342
343bootstrap_previous() { # PREV_IMAGE TAG [env]: returns 3 when the OLD release itself cannot do the step
344 local image="$1" tag="$2"; shift 2
345 py_in "$image" '
346import os, object_permission_store as s
347s.replace_policy(s.starter_policy_payload(), base_dir=os.environ["DBBASIC_DATA_DIR"])' \
348 || { echo " previous release cannot save the starter policy" >&2; return 3; }
349 start_box prev-box "$image" "$@" || return 3
350 ok "previous release $tag became healthy"
351 printf '%s\n' "$PASSWORD" | docker exec -i -u dbbasic "$CID" python object_identity_cli.py create-superuser \
352 --user-id gateuser --email upgrade@example.org --password-stdin >/dev/null \
353 || { echo " previous release cannot create a user from the CLI" >&2; return 3; }
354 ok "created a user with a password"
355 make_restore_point || return 1
356 # shellcheck disable=SC2046
357 install_everything $(docker run --rm --network none --entrypoint ls "$image" /opt/dbbasic-object-server/packages)
358 ok "installed $(wc -l <"$INSTALLED" | tr -d ' ') packages on the previous release"
359 if [[ -s "$NOT_INSTALLED" ]]; then
360 echo " these did not install on the previous release either (not counted against the current tree):" >&2
361 sed 's/^/ /' "$NOT_INSTALLED" >&2
362 fi
363 cp "$INSTALLED" "$WORK/prev_installed.list"; cp "$NOT_INSTALLED" "$WORK/prev_not_installed.list"
364 make_collection gate_notes title || return 1
365 admin POST /collections/gate_notes/records -H 'Content-Type: application/json' -d '{"id":"n1","title":"before-upgrade"}'
366 expect "wrote a record" '200|201' || return 1
367 admin POST /objects -H 'Content-Type: application/json' \
368 -d '{"object_id":"gate_hello","code":"def GET(request):\n return {\"say\": \"hello-before-upgrade\"}\n","author":"gate","message":"gate"}'
369 expect "created an object" '200|201' || return 1
370 http GET /objects/gate_hello -H "Authorization: Token ${TOKEN}"
371 grep -q 'hello-before-upgrade' "$HTTP_BODY" || { echo " the object does not run on the previous release" >&2; return 3; }
372 ok "the object runs"
373}
374
375# ---- stage: node -----------------------------------------------------------------------------
376
377stage_node() {
378 local ctx="$WORK/node" image="${PREFIX}-node"
379 export_tree "$ctx/src"
380 cat >"$ctx/Dockerfile" <<'EOF'
381FROM python:3.14-slim
382RUN apt-get update -qq && apt-get install -y -qq --no-install-recommends nodejs >/dev/null \
383 && rm -rf /var/lib/apt/lists/* \
384 && python -m pip install --no-cache-dir -q "pytest>=7.4.0" "uvicorn>=0.30.0" "websockets>=12.0"
385COPY src /src
386WORKDIR /src
387EOF
388 build_image "$image" "$ctx"
389 say "node: the node-marked tests, offline, with node $(docker run --rm --network none --entrypoint node "$image" --version)"
390 local out="$WORK/node.log" status=0
391 echo "container ${PREFIX}-node-run" >>"$REGISTRY"
392 docker run --rm --network none --name "${PREFIX}-node-run" "$image" \
393 python -m pytest -m "node and not conformance and not bench and not e2e" -rs -q -p no:cacheprovider \
394 >"$out" 2>&1 || status=$?
395 tail -15 "$out"
396 (( status == 0 )) || { fail "the node tests failed (exit $status)"; return 1; }
397 if grep -Eq '(^| )[0-9]+ skipped|^SKIPPED' "$out"; then fail "node tests were skipped inside a container that has node"; return 1; fi
398 grep -Eq '[0-9]+ passed' "$out" || { fail "no node test ran"; return 1; }
399 ok "$(grep -E '[0-9]+ passed' "$out" | tail -1)"
400}
401
402# ---- runner ----------------------------------------------------------------------------------
403
404run_stage() { # NAME
405 local name="$1" start end rc=0 reason
406 rm -f "$WORK/skip"
407 start=$(date +%s)
408 echo
409 say "stage: $name"
410 set +e
411 ( set -e; "stage_${name}" )
412 rc=$?
413 set -e
414 end=$(date +%s)
415 if (( rc != 0 )); then RESULTS+=("FAIL $name ($((end - start))s)"); FAILED=1
416 elif [[ -s "$WORK/skip" ]]; then reason="$(cat "$WORK/skip")"; RESULTS+=("skipped $name: ${reason} ($((end - start))s)")
417 else RESULTS+=("pass $name ($((end - start))s)"); fi
418}
419
420main() {
421 local which="${1:-all}" stages
422 case "$which" in
423 all) stages=(fresh upgrade node) ;;
424 fresh|upgrade|node) stages=("$which") ;;
425 -h|--help|help) sed -n 2,12p "${BASH_SOURCE[0]}"; exit 0 ;;
426 *) echo "usage: scripts/release_gate.sh [fresh|upgrade|node|all]" >&2; exit 2 ;;
427 esac
428 command -v docker >/dev/null || { echo "docker is required" >&2; exit 2; }
429 docker info >/dev/null 2>&1 || { echo "the docker daemon is not reachable" >&2; exit 2; }
430 local s
431 for s in "${stages[@]}"; do
432 run_stage "$s"
433 done
434 echo
435 say "release gate summary"
436 printf ' %s\n' "${RESULTS[@]}"
437 if (( FAILED )); then echo "RELEASE GATE: FAILED" >&2; exit 1; fi
438 echo "RELEASE GATE: passed"
439}
440
441main "$@"