feat(deploy): add an isolated demo stand with synthetic seed and guarded reset
This commit is contained in:
1 parent
bd23c839fd
commit
e1df4ff77c
26 files changed
+3292
-2
No files matched your search
@@ -0,0 +1,148 @@
|
||||
#!/usr/bin/env bash
|
||||
# Operator actions of the isolated demonstration stand.
|
||||
#
|
||||
# The stand is a dedicated Compose project (DEMO_PROJECT, lincodex-demo by
|
||||
# default) of docker-compose.yml with docker-compose.demo.yml. Every action
|
||||
# requires DEMO_MODE=isolated and addresses only that project; the ordinary
|
||||
# project (APP_PROJECT) and its volumes are never touched.
|
||||
#
|
||||
# Usage: demo.sh seed|reset|down
|
||||
# seed start the demo project when needed, run the idempotent seed, and
|
||||
# print the inventory of its records
|
||||
# reset check that the demo database holds no account outside the
|
||||
# synthetic domain, discard the demo project with its volumes,
|
||||
# start it again, and seed
|
||||
# down stop the demo project and keep its volumes
|
||||
#
|
||||
# Environment (deploy/Makefile sets it):
|
||||
# DEMO_MODE must be "isolated"
|
||||
# DEMO_PROJECT Compose project of the demo stand; contains "demo" and
|
||||
# differs from APP_PROJECT
|
||||
# APP_PROJECT the ordinary project, only compared against
|
||||
# ENV_FILE root env file with the stand secrets
|
||||
# DEMO_ENV_FILE demo env file with DEMO_ACCOUNT_PASSWORD
|
||||
# DEMO_HTTP_PORT host port of the demo frontend
|
||||
# DEMO_PUBLIC_URL public origin of the demo stand
|
||||
# DEMO_SUBNET, DEMO_FRONTEND_IP pinned network of the demo project
|
||||
# DEMO_ACTOR operator:<handle> that the seed records
|
||||
# DOCKER docker CLI
|
||||
set -euo pipefail
|
||||
|
||||
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||
compose_file="$root/deploy/docker/docker-compose.yml"
|
||||
demo_file="$root/deploy/docker/docker-compose.demo.yml"
|
||||
docker_cli="${DOCKER:-docker}"
|
||||
demo_label='org.lincodex.demo-mode'
|
||||
ready_attempts=120
|
||||
|
||||
fail() {
|
||||
printf 'demo: %s\n' "$1" >&2
|
||||
exit 2
|
||||
}
|
||||
|
||||
if [[ "$#" -ne 1 ]]; then
|
||||
fail 'usage: demo.sh seed|reset|down'
|
||||
fi
|
||||
action=$1
|
||||
case "$action" in
|
||||
seed | reset | down) ;;
|
||||
*) fail 'usage: demo.sh seed|reset|down' ;;
|
||||
esac
|
||||
|
||||
# The guards run before any Docker command.
|
||||
if [[ "${DEMO_MODE:-}" != isolated ]]; then
|
||||
fail "refusing to $action: set DEMO_MODE=isolated; the demo targets act only on an isolated demo stand"
|
||||
fi
|
||||
project="${DEMO_PROJECT:-lincodex-demo}"
|
||||
ordinary_project="${APP_PROJECT:-app}"
|
||||
if [[ ! "$project" =~ ^[a-z0-9][a-z0-9_-]*$ || "$project" != *demo* ]]; then
|
||||
fail "refusing to $action: DEMO_PROJECT must be a Compose project name that contains 'demo'"
|
||||
fi
|
||||
if [[ "$project" == "$ordinary_project" ]]; then
|
||||
fail "refusing to $action: DEMO_PROJECT must differ from the ordinary project APP_PROJECT=$ordinary_project"
|
||||
fi
|
||||
env_file="${ENV_FILE:-$root/.env}"
|
||||
demo_env_file="${DEMO_ENV_FILE:-$root/deploy/demo/demo.env.example}"
|
||||
[[ -f "$env_file" ]] || fail "missing $env_file; copy .env.example to .env and replace the placeholder passwords"
|
||||
[[ -f "$demo_env_file" ]] || fail "missing demo env file $demo_env_file"
|
||||
actor="${DEMO_ACTOR:-operator:demo-seed}"
|
||||
[[ "$actor" =~ ^operator:[a-z0-9][a-z0-9._-]*$ ]] || fail 'DEMO_ACTOR must be operator:<handle>'
|
||||
port="${DEMO_HTTP_PORT:-8090}"
|
||||
[[ "$port" =~ ^[1-9][0-9]{0,4}$ ]] || fail 'DEMO_HTTP_PORT must be a port number'
|
||||
public_url="${DEMO_PUBLIC_URL:-http://localhost:$port}"
|
||||
subnet="${DEMO_SUBNET:-172.29.84.0/24}"
|
||||
frontend_ip="${DEMO_FRONTEND_IP:-172.29.84.10}"
|
||||
|
||||
# The shell values override the env files, so the root .env cannot point the
|
||||
# demo project at the ordinary project's names, network, or port.
|
||||
compose() {
|
||||
APP_PROJECT="$project" APP_NETWORK="${project}_default" APP_STORAGE_NETWORK="${project}_storage" \
|
||||
APP_HTTP_PORT="$port" APP_SUBNET="$subnet" APP_FRONTEND_IP="$frontend_ip" APP_PUBLIC_URL="$public_url" \
|
||||
DEMO_MODE=isolated "$docker_cli" compose \
|
||||
--env-file "$env_file" --env-file "$demo_env_file" \
|
||||
-p "$project" -f "$compose_file" -f "$demo_file" "$@"
|
||||
}
|
||||
|
||||
volume_exists() {
|
||||
"$docker_cli" volume inspect "$1" >/dev/null 2>&1
|
||||
}
|
||||
|
||||
# A volume carries the demo label only when the demo overlay created it, so a
|
||||
# volume of an ordinary stand under this name is never adopted or discarded.
|
||||
check_volumes() {
|
||||
local volume label
|
||||
for volume in "${project}_postgres_data" "${project}_seaweedfs_data" "${project}_kafka_data"; do
|
||||
if volume_exists "$volume"; then
|
||||
label=$("$docker_cli" volume inspect --format "{{ index .Labels \"$demo_label\" }}" "$volume")
|
||||
if [[ "$label" != isolated ]]; then
|
||||
fail "refusing to $action: volume $volume was not created by the demo overlay"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
start_stand() {
|
||||
compose up -d --build --wait --wait-timeout 300
|
||||
local attempt response
|
||||
for ((attempt = 1; attempt <= ready_attempts; attempt++)); do
|
||||
response=$(compose exec -T frontend wget -q -O - http://backend:8080/readyz 2>/dev/null || true)
|
||||
if [[ "$response" == '{"status":"ready"}' ]]; then
|
||||
return 0
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
fail "the backend of $project did not become ready"
|
||||
}
|
||||
|
||||
run_command() {
|
||||
compose --profile demo-seed run --rm --build demo-seed "$@"
|
||||
}
|
||||
|
||||
# The inventory after the seed lets two runs be compared line by line.
|
||||
seed() {
|
||||
start_stand
|
||||
run_command seed --actor "$actor"
|
||||
run_command inventory
|
||||
printf 'demo: the stand %s serves %s; the password is DEMO_ACCOUNT_PASSWORD of %s\n' \
|
||||
"$project" "$public_url" "$demo_env_file"
|
||||
}
|
||||
|
||||
check_volumes
|
||||
case "$action" in
|
||||
seed)
|
||||
seed
|
||||
;;
|
||||
reset)
|
||||
if volume_exists "${project}_postgres_data"; then
|
||||
start_stand
|
||||
if ! run_command check-reset; then
|
||||
fail "reset refused for $project; nothing was deleted"
|
||||
fi
|
||||
fi
|
||||
compose down --volumes --remove-orphans
|
||||
seed
|
||||
;;
|
||||
down)
|
||||
compose down
|
||||
;;
|
||||
esac
|
||||
@@ -0,0 +1,215 @@
|
||||
"""Guards of the isolated demo targets and the boundary of the demo overlay.
|
||||
|
||||
The script tests run demo.sh against a recording stub of the docker CLI, so
|
||||
they prove which Docker commands a refusal never reaches. The render tests
|
||||
need the docker CLI and are skipped without it.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import tempfile
|
||||
import textwrap
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
DEPLOY = ROOT / "deploy"
|
||||
SCRIPT = DEPLOY / "scripts" / "demo.sh"
|
||||
DOCKER = os.environ.get("DOCKER", "docker")
|
||||
|
||||
# The stub answers like a running demo stand: volumes exist with the label
|
||||
# given in STUB_LABEL, the backend is ready, and check-reset exits with
|
||||
# STUB_CHECK_RESET. Every call is appended to STUB_LOG.
|
||||
STUB = textwrap.dedent(
|
||||
"""\
|
||||
#!/usr/bin/env bash
|
||||
printf '%s\\n' "$*" >> "$STUB_LOG"
|
||||
args=" $* "
|
||||
if [[ "$args" == *" volume inspect --format "* ]]; then
|
||||
printf '%s\\n' "${STUB_LABEL:-}"
|
||||
exit 0
|
||||
fi
|
||||
if [[ "$args" == *" volume inspect "* ]]; then
|
||||
exit "${STUB_VOLUME_STATUS:-0}"
|
||||
fi
|
||||
if [[ "$args" == *" wget "* ]]; then
|
||||
printf '%s' '{"status":"ready"}'
|
||||
exit 0
|
||||
fi
|
||||
if [[ "$args" == *" check-reset "* ]]; then
|
||||
exit "${STUB_CHECK_RESET:-0}"
|
||||
fi
|
||||
exit 0
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
class DemoScriptGuardTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.directory = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.directory.cleanup)
|
||||
base = Path(self.directory.name)
|
||||
self.stub = base / "docker"
|
||||
self.stub.write_text(STUB)
|
||||
self.stub.chmod(self.stub.stat().st_mode | stat.S_IXUSR)
|
||||
self.log = base / "calls.log"
|
||||
self.log.write_text("")
|
||||
self.env_file = base / "root.env"
|
||||
self.env_file.write_text("POSTGRES_USER=demo\n")
|
||||
self.demo_env = base / "demo.env"
|
||||
self.demo_env.write_text("DEMO_ACCOUNT_PASSWORD=synthetic demo stand only 2026\n")
|
||||
|
||||
def run_script(self, action, **overrides):
|
||||
environment = {
|
||||
"PATH": os.environ.get("PATH", ""),
|
||||
"HOME": os.environ.get("HOME", ""),
|
||||
"DOCKER": str(self.stub),
|
||||
"STUB_LOG": str(self.log),
|
||||
"DEMO_MODE": "isolated",
|
||||
"DEMO_PROJECT": "lincodex-demo-test",
|
||||
"APP_PROJECT": "app",
|
||||
"ENV_FILE": str(self.env_file),
|
||||
"DEMO_ENV_FILE": str(self.demo_env),
|
||||
"STUB_LABEL": "isolated",
|
||||
}
|
||||
for key, value in overrides.items():
|
||||
if value is None:
|
||||
environment.pop(key, None)
|
||||
else:
|
||||
environment[key] = value
|
||||
return subprocess.run(
|
||||
["bash", str(SCRIPT), action], capture_output=True, text=True, env=environment, check=False
|
||||
)
|
||||
|
||||
def calls(self):
|
||||
return [line for line in self.log.read_text().splitlines() if line]
|
||||
|
||||
def test_every_action_refuses_without_the_isolated_mode_before_docker(self):
|
||||
for action in ("seed", "reset", "down"):
|
||||
for mode in (None, "", "production", "ISOLATED"):
|
||||
with self.subTest(action=action, mode=mode):
|
||||
result = self.run_script(action, DEMO_MODE=mode)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
self.assertIn("DEMO_MODE=isolated", result.stderr)
|
||||
self.assertEqual(self.calls(), [])
|
||||
|
||||
def test_the_project_must_be_a_separate_demo_project(self):
|
||||
cases = (
|
||||
{"DEMO_PROJECT": "app"},
|
||||
{"DEMO_PROJECT": "lincodex-demo-test", "APP_PROJECT": "lincodex-demo-test"},
|
||||
{"DEMO_PROJECT": "lincodex"},
|
||||
{"DEMO_PROJECT": "Demo Stand"},
|
||||
{"DEMO_ACTOR": "alice"},
|
||||
{"ENV_FILE": str(Path(self.directory.name) / "missing.env")},
|
||||
)
|
||||
for overrides in cases:
|
||||
with self.subTest(overrides=overrides):
|
||||
result = self.run_script("reset", **overrides)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
self.assertEqual(self.calls(), [])
|
||||
|
||||
def test_a_volume_without_the_demo_label_is_never_used(self):
|
||||
for action in ("seed", "reset"):
|
||||
with self.subTest(action=action):
|
||||
result = self.run_script(action, STUB_LABEL="")
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
self.assertIn("was not created by the demo overlay", result.stderr)
|
||||
self.assertFalse([call for call in self.calls() if call.startswith("compose")])
|
||||
|
||||
def test_reset_stops_before_down_when_the_check_refuses(self):
|
||||
result = self.run_script("reset", STUB_CHECK_RESET="2")
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
self.assertIn("nothing was deleted", result.stderr)
|
||||
calls = self.calls()
|
||||
self.assertTrue(any(" check-reset" in call for call in calls))
|
||||
self.assertFalse([call for call in calls if " down" in call])
|
||||
|
||||
def test_reset_discards_only_the_demo_project_and_seeds_again(self):
|
||||
result = self.run_script("reset")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
compose_calls = [call for call in self.calls() if call.startswith("compose")]
|
||||
down = [call for call in compose_calls if " down --volumes" in call]
|
||||
self.assertEqual(len(down), 1)
|
||||
for call in compose_calls:
|
||||
self.assertIn("-p lincodex-demo-test ", call)
|
||||
self.assertIn("docker-compose.demo.yml", call)
|
||||
self.assertLess(compose_calls.index(next(call for call in compose_calls if " check-reset" in call)), compose_calls.index(down[0]))
|
||||
self.assertIn(" seed --actor operator:demo-seed", compose_calls[-2])
|
||||
self.assertTrue(compose_calls[-1].endswith(" inventory"))
|
||||
|
||||
def test_down_keeps_the_volumes(self):
|
||||
result = self.run_script("down")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
compose_calls = [call for call in self.calls() if call.startswith("compose")]
|
||||
self.assertEqual(len(compose_calls), 1)
|
||||
self.assertTrue(compose_calls[0].endswith(" down"))
|
||||
|
||||
|
||||
def render_demo(project="lincodex-demo-render"):
|
||||
environment = dict(
|
||||
os.environ,
|
||||
APP_PROJECT=project,
|
||||
APP_NETWORK=f"{project}_default",
|
||||
APP_STORAGE_NETWORK=f"{project}_storage",
|
||||
APP_HTTP_PORT="8090",
|
||||
APP_SUBNET="172.29.84.0/24",
|
||||
APP_FRONTEND_IP="172.29.84.10",
|
||||
IDENTITY_KEY_SECRET="render-only-identity-key-secret",
|
||||
DEMO_ACCOUNT_PASSWORD="render-only-demo-account-password",
|
||||
DEMO_MODE="isolated",
|
||||
)
|
||||
environment.pop("APP_HTTP_BIND", None)
|
||||
command = [
|
||||
DOCKER, "compose", "--env-file", str(ROOT / ".env.example"), "-p", project,
|
||||
"-f", str(DEPLOY / "docker" / "docker-compose.yml"), "-f", str(DEPLOY / "docker" / "docker-compose.demo.yml"),
|
||||
"--profile", "demo-seed", "config", "--format", "json",
|
||||
]
|
||||
result = subprocess.run(command, capture_output=True, text=True, env=environment, check=False)
|
||||
if result.returncode != 0:
|
||||
raise AssertionError(f"docker compose config failed: {result.stderr}")
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
class DemoOverlayTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
if shutil.which(DOCKER) is None:
|
||||
raise unittest.SkipTest("docker CLI is not available")
|
||||
cls.rendered = render_demo()
|
||||
|
||||
def test_only_the_frontend_is_published_on_loopback(self):
|
||||
published = {name: service["ports"] for name, service in self.rendered["services"].items() if service.get("ports")}
|
||||
self.assertEqual(list(published), ["frontend"])
|
||||
for port in published["frontend"]:
|
||||
self.assertEqual(port["host_ip"], "127.0.0.1")
|
||||
self.assertEqual(port["published"], "8090")
|
||||
|
||||
def test_the_seed_reaches_only_the_default_network(self):
|
||||
seed = self.rendered["services"]["demo-seed"]
|
||||
self.assertEqual(seed["profiles"], ["demo-seed"])
|
||||
self.assertEqual(list(seed["networks"]), ["default"])
|
||||
self.assertEqual(seed["build"]["dockerfile"], "Dockerfile.demo-seed")
|
||||
self.assertTrue(seed["read_only"])
|
||||
self.assertEqual(seed["environment"]["DEMO_MODE"], "isolated")
|
||||
|
||||
def test_volumes_carry_the_demo_label_and_the_project_name(self):
|
||||
for name, volume in self.rendered["volumes"].items():
|
||||
with self.subTest(volume=name):
|
||||
self.assertEqual(volume["labels"]["org.lincodex.demo-mode"], "isolated")
|
||||
self.assertTrue(volume["name"].startswith("lincodex-demo-render_"))
|
||||
|
||||
def test_the_demo_backend_assigns_synthetic_categories(self):
|
||||
backend = self.rendered["services"]["backend"]
|
||||
self.assertEqual(backend["environment"]["ASSESSMENT_DEMO_CATEGORIES_ENABLED"], "true")
|
||||
self.assertEqual(backend["labels"]["org.lincodex.demo-mode"], "isolated")
|
||||
|
||||
def test_release_and_ordinary_images_never_contain_the_seed(self):
|
||||
for dockerfile in ("Dockerfile", "Dockerfile.e2e"):
|
||||
self.assertNotIn("demo-seed", (ROOT / "backend" / dockerfile).read_text())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user