From 6d6aa9ffe8a516c8d79135f992acea201c03af9b Mon Sep 17 00:00:00 2001 From: TakuyaYagam1 Date: Sun, 11 Oct 2026 22:59:34 +0300 Subject: [PATCH] fix(deploy): isolate demo settings and monitoring --- deploy/Makefile | 50 +++++++++--- deploy/demo/demo.env.example | 17 ++-- deploy/scripts/demo-monitoring.sh | 127 ++++++++++++++++++++++++++++++ deploy/scripts/demo.sh | 43 +++++++--- deploy/scripts/test_demo.py | 120 ++++++++++++++++++++++++++-- docs/en/DEPLOYMENT.md | 5 +- docs/ru/DEPLOYMENT.md | 5 +- 7 files changed, 331 insertions(+), 36 deletions(-) create mode 100644 deploy/scripts/demo-monitoring.sh diff --git a/deploy/Makefile b/deploy/Makefile index 826a8d8..c325032 100644 --- a/deploy/Makefile +++ b/deploy/Makefile @@ -47,7 +47,7 @@ LINCODEX_RELEASE_TAG ?= $(shell PYTHONDONTWRITEBYTECODE=1 python3 "$(RELEASE_SCR # Isolated demonstration stand (deploy/scripts/demo.sh). Every demo target # needs DEMO_MODE=isolated on the command line and acts only on DEMO_PROJECT. DEMO_MODE ?= -DEMO_PROJECT ?= lincodex-demo +DEMO_PROJECT ?= DEMO_HTTP_PORT ?= 8090 DEMO_PUBLIC_URL ?= http://localhost:$(DEMO_HTTP_PORT) DEMO_SUBNET ?= 172.29.84.0/24 @@ -62,6 +62,8 @@ DEMO_SCRIPT_ENV = DOCKER="$(DOCKER)" DEMO_MODE="$(DEMO_MODE)" DEMO_PROJECT="$(DE ENV_FILE="$(ENV_FILE)" DEMO_ENV_FILE="$(DEMO_ENV)" DEMO_HTTP_PORT="$(DEMO_HTTP_PORT)" DEMO_PUBLIC_URL="$(DEMO_PUBLIC_URL)" \ DEMO_SUBNET="$(DEMO_SUBNET)" DEMO_FRONTEND_IP="$(DEMO_FRONTEND_IP)" DEMO_ACTOR="$(DEMO_ACTOR)" \ DEMO_RELEASE_MANIFEST="$(DEMO_RELEASE_MANIFEST)" +DEMO_MONITORING_SCRIPT_ENV = DOCKER="$(DOCKER)" DEMO_MODE="$(DEMO_MODE)" DEMO_PROJECT="$(DEMO_PROJECT)" \ + DEMO_ENV_FILE="$(DEMO_ENV)" APP_PROJECT="$(APP_PROJECT)" MONITORING_PROJECT="$(MONITORING_PROJECT)" PLAYWRIGHT_VERSION := $(shell sed -n 's/^ *"@playwright\/test": "\([^"]*\)",\{0,1\}$$/\1/p' "$(ROOT)/frontend/package.json") .PHONY: help config build up down logs monitoring-config monitoring-up monitoring-down monitoring-logs ml-config ml-build ml-up ml-down ml-logs runner-dev-config runner-dev-build runner-dev-up runner-dev-down runner-dev-logs check-runner-dev check-runner-vm check check-workflows check-release check-perimeter check-e2e-mail check-demo perimeter-test smoke test-e2e test-e2e-registration release-build release-smoke release-e2e release-manifest release-manifest-verify release-manifest-check release-up release-down release-clean demo-seed demo-reset demo-down @@ -99,20 +101,44 @@ logs: ## Follow core service logs @test -f "$(ENV_FILE)" || { printf 'Missing %s.\n' "$(ENV_FILE)" >&2; exit 2; } APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" $(DOCKER) compose --env-file "$(ENV_FILE)" -p "$(APP_PROJECT)" -f "$(CORE_FILE)" logs -f -monitoring-config: ## Render the separate monitoring Compose file - APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(MONITORING_PROJECT)" -f "$(MONITORING_FILE)" config --quiet +monitoring-config: ## Render core monitoring, or the isolated demo with DEMO_MODE=isolated + @if [ "$(DEMO_MODE)" = isolated ]; then \ + ENV_FILE="$(CHECK_ENV_FILE)" $(DEMO_MONITORING_SCRIPT_ENV) bash scripts/demo-monitoring.sh config; \ + elif [ -n "$(DEMO_MODE)" ]; then \ + printf 'Refusing monitoring config: DEMO_MODE must be isolated.\n' >&2; exit 2; \ + else \ + APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(MONITORING_PROJECT)" -f "$(MONITORING_FILE)" config --quiet; \ + fi -monitoring-up: ## Start monitoring as a separate Compose project - @test -f "$(ENV_FILE)" || { printf 'Missing %s. Copy .env.example to .env and replace the placeholder passwords.\n' "$(ENV_FILE)" >&2; exit 2; } - APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" $(DOCKER) compose --env-file "$(ENV_FILE)" -p "$(MONITORING_PROJECT)" -f "$(MONITORING_FILE)" up -d +monitoring-up: ## Start core monitoring, or the isolated demo with DEMO_MODE=isolated + @if [ "$(DEMO_MODE)" = isolated ]; then \ + ENV_FILE="$(ENV_FILE)" $(DEMO_MONITORING_SCRIPT_ENV) bash scripts/demo-monitoring.sh up; \ + elif [ -n "$(DEMO_MODE)" ]; then \ + printf 'Refusing monitoring up: DEMO_MODE must be isolated.\n' >&2; exit 2; \ + else \ + test -f "$(ENV_FILE)" || { printf 'Missing %s. Copy .env.example to .env and replace the placeholder passwords.\n' "$(ENV_FILE)" >&2; exit 2; }; \ + APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" $(DOCKER) compose --env-file "$(ENV_FILE)" -p "$(MONITORING_PROJECT)" -f "$(MONITORING_FILE)" up -d; \ + fi -monitoring-down: ## Stop monitoring and keep named volumes - @test -f "$(ENV_FILE)" || { printf 'Missing %s.\n' "$(ENV_FILE)" >&2; exit 2; } - APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" $(DOCKER) compose --env-file "$(ENV_FILE)" -p "$(MONITORING_PROJECT)" -f "$(MONITORING_FILE)" down +monitoring-down: ## Stop core monitoring, or the isolated demo with DEMO_MODE=isolated + @if [ "$(DEMO_MODE)" = isolated ]; then \ + ENV_FILE="$(ENV_FILE)" $(DEMO_MONITORING_SCRIPT_ENV) bash scripts/demo-monitoring.sh down; \ + elif [ -n "$(DEMO_MODE)" ]; then \ + printf 'Refusing monitoring down: DEMO_MODE must be isolated.\n' >&2; exit 2; \ + else \ + test -f "$(ENV_FILE)" || { printf 'Missing %s.\n' "$(ENV_FILE)" >&2; exit 2; }; \ + APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" $(DOCKER) compose --env-file "$(ENV_FILE)" -p "$(MONITORING_PROJECT)" -f "$(MONITORING_FILE)" down; \ + fi -monitoring-logs: ## Follow monitoring service logs - @test -f "$(ENV_FILE)" || { printf 'Missing %s.\n' "$(ENV_FILE)" >&2; exit 2; } - APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" $(DOCKER) compose --env-file "$(ENV_FILE)" -p "$(MONITORING_PROJECT)" -f "$(MONITORING_FILE)" logs -f +monitoring-logs: ## Follow core monitoring logs, or the isolated demo with DEMO_MODE=isolated + @if [ "$(DEMO_MODE)" = isolated ]; then \ + ENV_FILE="$(ENV_FILE)" $(DEMO_MONITORING_SCRIPT_ENV) bash scripts/demo-monitoring.sh logs; \ + elif [ -n "$(DEMO_MODE)" ]; then \ + printf 'Refusing monitoring logs: DEMO_MODE must be isolated.\n' >&2; exit 2; \ + else \ + test -f "$(ENV_FILE)" || { printf 'Missing %s.\n' "$(ENV_FILE)" >&2; exit 2; }; \ + APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" $(DOCKER) compose --env-file "$(ENV_FILE)" -p "$(MONITORING_PROJECT)" -f "$(MONITORING_FILE)" logs -f; \ + fi ml-config: ## Render the separate ML Compose file APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(ML_PROJECT)" -f "$(ML_FILE)" config --quiet diff --git a/deploy/demo/demo.env.example b/deploy/demo/demo.env.example index 66c4c57..b1a8f61 100644 --- a/deploy/demo/demo.env.example +++ b/deploy/demo/demo.env.example @@ -1,8 +1,15 @@ -# Settings of the synthetic demo accounts on an isolated demo stand. Copy this -# file to demo.env next to it to use another password; demo.env is local and -# ignored by Git. Without demo.env, make -C deploy demo-seed reads this -# example. The value is a published demo credential of synthetic accounts on -# a stand without real people, not a secret: never reuse it anywhere else. +# Local settings for the isolated demo stand. Copy this file to demo.env next +# to it to change these values; demo.env is local and ignored by Git. The +# example is loaded before demo.env, so omitted local values keep these +# defaults. APP_HTTP_BIND overrides the value in the root .env. + +DEMO_PROJECT=lincodex-demo +APP_HTTP_BIND=127.0.0.1 +# Keep demo Grafana separate from core monitoring when both are running. +DEMO_GRAFANA_PORT=3001 + +# The value below is a published demo credential for synthetic accounts on a +# stand without real people, not a secret. Never reuse it anywhere else. # # Shared password of every synthetic account the seed creates (at least 15 # characters). It applies when an account is created; change it by editing diff --git a/deploy/scripts/demo-monitoring.sh b/deploy/scripts/demo-monitoring.sh new file mode 100644 index 0000000..9a278f5 --- /dev/null +++ b/deploy/scripts/demo-monitoring.sh @@ -0,0 +1,127 @@ +#!/usr/bin/env bash +# Run the separate monitoring project against the isolated demo stand. +set -euo pipefail + +root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +monitoring_file="$root/deploy/docker/docker-compose.monitoring.yml" +demo_example_file="$root/deploy/demo/demo.env.example" +docker_cli="${DOCKER:-docker}" + +fail() { + printf 'demo monitoring: %s\n' "$1" >&2 + exit 2 +} + +read_env_value() { + local file=$1 key=$2 line value='' + while IFS= read -r line || [[ -n "$line" ]]; do + if [[ "$line" == "$key="* ]]; then + value=${line#*=} + fi + done < "$file" + printf '%s' "$value" +} + +if [[ "$#" -ne 1 ]]; then + fail 'usage: demo-monitoring.sh config|up|down|logs' +fi +action=$1 +case "$action" in + config | up | down | logs) ;; + *) fail 'usage: demo-monitoring.sh config|up|down|logs' ;; +esac + +if [[ "${DEMO_MODE:-}" != isolated ]]; then + fail 'refusing to use demo monitoring: set DEMO_MODE=isolated' +fi + +env_file="${ENV_FILE:-$root/.env}" +demo_env_file="${DEMO_ENV_FILE:-$root/deploy/demo/demo.env}" +[[ -f "$env_file" ]] || fail "missing env file $env_file" +[[ -f "$demo_example_file" ]] || fail "missing demo env example $demo_example_file" +[[ -f "$demo_env_file" ]] || fail "missing demo env file $demo_env_file" + +configured_project=$(read_env_value "$demo_env_file" DEMO_PROJECT) +if [[ -z "$configured_project" && "$demo_env_file" != "$demo_example_file" ]]; then + configured_project=$(read_env_value "$demo_example_file" DEMO_PROJECT) +fi +project="${DEMO_PROJECT:-${configured_project:-lincodex-demo}}" +ordinary_project="${APP_PROJECT:-app}" +configured_ordinary_project=$(read_env_value "$env_file" APP_PROJECT) +if [[ ! "$project" =~ ^[a-z0-9][a-z0-9_-]*$ || "$project" != *demo* ]]; then + fail 'refusing to use demo monitoring: DEMO_PROJECT must be a Compose project name that contains demo' +fi +if [[ "$project" == "$ordinary_project" || ( -n "$configured_ordinary_project" && "$project" == "$configured_ordinary_project" ) ]]; then + fail 'refusing to use demo monitoring: DEMO_PROJECT must differ from the ordinary project APP_PROJECT' +fi + +monitoring_project="${project}-monitoring" +ordinary_monitoring_project="${MONITORING_PROJECT:-monitoring}" +if [[ "$monitoring_project" == "$ordinary_monitoring_project" ]]; then + fail 'refusing to use demo monitoring: its Compose project must differ from MONITORING_PROJECT' +fi + +grafana_port=$(read_env_value "$demo_env_file" DEMO_GRAFANA_PORT) +if [[ -z "$grafana_port" && "$demo_env_file" != "$demo_example_file" ]]; then + grafana_port=$(read_env_value "$demo_example_file" DEMO_GRAFANA_PORT) +fi +grafana_port="${grafana_port:-3001}" +[[ "$grafana_port" =~ ^[1-9][0-9]{0,4}$ ]] || fail 'DEMO_GRAFANA_PORT must be a port number' +(( grafana_port <= 65535 )) || fail 'DEMO_GRAFANA_PORT must be between 1 and 65535' + +resolve_socket() { + local endpoint context configured_socket socket_path + configured_socket="${DOCKER_SOCKET_PATH:-$(read_env_value "$env_file" DOCKER_SOCKET_PATH)}" + if [[ -n "${DEMO_DOCKER_SOCKET_PATH:-}" ]]; then + socket_path=$DEMO_DOCKER_SOCKET_PATH + elif [[ -n "$configured_socket" && "$configured_socket" != /var/run/docker.sock ]]; then + socket_path=$configured_socket + else + endpoint="${DOCKER_HOST:-}" + if [[ -z "$endpoint" ]]; then + context=$("$docker_cli" context show) || fail 'could not read the active Docker context' + endpoint=$("$docker_cli" context inspect "$context" --format '{{ (index .Endpoints "docker").Host }}') || + fail 'could not read the Docker endpoint from the active context' + fi + case "$endpoint" in + unix://*) socket_path=${endpoint#unix://} ;; + *) fail 'demo monitoring requires a local Unix Docker socket; the active Docker endpoint is not local' ;; + esac + fi + + case "$socket_path" in + unix://*) socket_path=${socket_path#unix://} ;; + esac + [[ "$socket_path" == /* ]] || fail 'the Docker socket path must be absolute' + if [[ "$action" != config && ! -S "$socket_path" ]]; then + fail "Docker socket not found at $socket_path; check the active Docker context" + fi + printf '%s' "$socket_path" +} + +socket_path=$(resolve_socket) +env_files=(--env-file "$env_file" --env-file "$demo_example_file") +if [[ "$demo_env_file" != "$demo_example_file" ]]; then + env_files+=(--env-file "$demo_env_file") +fi + +compose() { + APP_PROJECT="$project" APP_NETWORK="${project}_default" APP_STORAGE_NETWORK="${project}_storage" \ + DOCKER_SOCKET_PATH="$socket_path" GRAFANA_PORT="$grafana_port" \ + "$docker_cli" compose "${env_files[@]}" -p "$monitoring_project" -f "$monitoring_file" "$@" +} + +case "$action" in + config) + compose config --quiet + ;; + up) + compose up -d + ;; + down) + compose down + ;; + logs) + compose logs -f + ;; +esac diff --git a/deploy/scripts/demo.sh b/deploy/scripts/demo.sh index 47b43cc..b8f0b66 100644 --- a/deploy/scripts/demo.sh +++ b/deploy/scripts/demo.sh @@ -20,7 +20,8 @@ # 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_ENV_FILE local demo env file; the example supplies defaults +# APP_HTTP_BIND comes from the demo env file so the core bind is ignored # 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 @@ -45,6 +46,16 @@ fail() { exit 2 } +read_env_value() { + local file=$1 key=$2 line value='' + while IFS= read -r line || [[ -n "$line" ]]; do + if [[ "$line" == "$key="* ]]; then + value=${line#*=} + fi + done < "$file" + printf '%s' "$value" +} + if [[ "$#" -ne 1 ]]; then fail 'usage: demo.sh seed|reset|down' fi @@ -58,18 +69,25 @@ esac 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}" +env_file="${ENV_FILE:-$root/.env}" +demo_example_file="$root/deploy/demo/demo.env.example" +demo_env_file="${DEMO_ENV_FILE:-$root/deploy/demo/demo.env}" +[[ -f "$env_file" ]] || fail "missing $env_file; copy .env.example to .env and replace the placeholder passwords" +[[ -f "$demo_example_file" ]] || fail "missing demo env example $demo_example_file" +[[ -f "$demo_env_file" ]] || fail "missing demo env file $demo_env_file" +configured_project=$(read_env_value "$demo_env_file" DEMO_PROJECT) +if [[ -z "$configured_project" && "$demo_env_file" != "$demo_example_file" ]]; then + configured_project=$(read_env_value "$demo_example_file" DEMO_PROJECT) +fi +project="${DEMO_PROJECT:-${configured_project:-lincodex-demo}}" +configured_ordinary_project=$(read_env_value "$env_file" APP_PROJECT) 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" +if [[ "$project" == "$ordinary_project" || ( -n "$configured_ordinary_project" && "$project" == "$configured_ordinary_project" ) ]]; then + fail "refusing to $action: DEMO_PROJECT must differ from the ordinary project APP_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:' port="${DEMO_HTTP_PORT:-8090}" @@ -78,18 +96,23 @@ 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}" release_manifest="${DEMO_RELEASE_MANIFEST:-}" +env_files=(--env-file "$env_file" --env-file "$demo_example_file") +if [[ "$demo_env_file" != "$demo_example_file" ]]; then + env_files+=(--env-file "$demo_env_file") +fi compose_files=(-f "$compose_file" -f "$demo_file") # From the current sources by default; pinned by the release override below. up_args=(--build) run_args=(--build) # 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. +# demo project at the ordinary project's names, network, or port. The demo +# env file is loaded last to override core-only settings such as APP_HTTP_BIND. 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" \ + "${env_files[@]}" \ -p "$project" "${compose_files[@]}" "$@" } diff --git a/deploy/scripts/test_demo.py b/deploy/scripts/test_demo.py index f989446..aabc5fe 100644 --- a/deploy/scripts/test_demo.py +++ b/deploy/scripts/test_demo.py @@ -1,13 +1,13 @@ """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. +Script and Make target tests use a recording Docker stub. Render tests need the +Docker CLI and are skipped without it. """ import json import os import shutil +import socket import stat import subprocess import tempfile @@ -46,6 +46,22 @@ STUB = textwrap.dedent( """ ) +MAKE_STUB = textwrap.dedent( + """\ + #!/usr/bin/env bash + printf '%s\\t%s\\t%s\\t%s\\t%s\\n' \\ + "${APP_PROJECT:-}" "${APP_NETWORK:-}" "${APP_STORAGE_NETWORK:-}" \\ + "${APP_HTTP_BIND-}" "$*" >> "$STUB_LOG" + if [[ "$*" == *"volume inspect --format"* ]]; then + printf '%s\\n' isolated + fi + if [[ "$*" == *"exec -T frontend wget"* ]]; then + printf '%s' '{"status":"ready"}' + fi + exit 0 + """ +) + class DemoScriptGuardTest(unittest.TestCase): def setUp(self): @@ -166,7 +182,88 @@ class DemoScriptGuardTest(unittest.TestCase): self.assertTrue(compose_calls[0].endswith(" down")) -def render_demo(project="lincodex-demo-render", release_tag=None): +class MakeTargetTest(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(MAKE_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_PASSWORD=test-only\nAPP_HTTP_BIND=0.0.0.0\n") + self.demo_env = DEPLOY / "demo" / "demo.env.example" + self.socket_path = base / "docker.sock" + self.docker_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.docker_socket.bind(str(self.socket_path)) + self.addCleanup(self.docker_socket.close) + + def run_make(self, target, demo_mode=None): + command = [ + "make", + "-C", + str(DEPLOY), + target, + f"DOCKER={self.stub}", + f"ENV_FILE={self.env_file}", + f"DEMO_ENV={self.demo_env}", + ] + if demo_mode is not None: + command.append(f"DEMO_MODE={demo_mode}") + environment = os.environ.copy() + for key in ( + "APP_HTTP_BIND", + "APP_PROJECT", + "APP_NETWORK", + "APP_STORAGE_NETWORK", + "DEMO_MODE", + "DEMO_PROJECT", + "DEMO_DOCKER_SOCKET_PATH", + ): + environment.pop(key, None) + environment["STUB_LOG"] = str(self.log) + environment["DEMO_DOCKER_SOCKET_PATH"] = str(self.socket_path) + result = subprocess.run(command, capture_output=True, text=True, env=environment, check=False) + return result + + def compose_calls(self): + calls = [] + for line in self.log.read_text().splitlines(): + app_project, app_network, storage_network, http_bind, args = line.split("\t", 4) + if args.startswith("compose "): + calls.append((app_project, app_network, storage_network, http_bind, args)) + return calls + + def test_demo_seed_target_needs_no_http_bind_override(self): + result = self.run_make("demo-seed", demo_mode="isolated") + self.assertEqual(result.returncode, 0, result.stderr) + calls = self.compose_calls() + self.assertTrue(calls) + self.assertTrue(all(call[:3] == ("lincodex-demo", "lincodex-demo_default", "lincodex-demo_storage") for call in calls)) + self.assertTrue(any("up -d" in call[4] for call in calls)) + self.assertTrue(all(f"--env-file {self.env_file} --env-file {self.demo_env}" in call[4] for call in calls)) + + def test_monitoring_uses_demo_network_only_when_requested(self): + isolated = self.run_make("monitoring-up", demo_mode="isolated") + self.assertEqual(isolated.returncode, 0, isolated.stderr) + isolated_calls = self.compose_calls() + self.assertEqual(len(isolated_calls), 1) + self.assertEqual(isolated_calls[0][:3], ("lincodex-demo", "lincodex-demo_default", "lincodex-demo_storage")) + self.assertIn("-p lincodex-demo-monitoring", isolated_calls[0][4]) + + self.log.write_text("") + ordinary = self.run_make("monitoring-up") + self.assertEqual(ordinary.returncode, 0, ordinary.stderr) + ordinary_calls = self.compose_calls() + self.assertEqual(len(ordinary_calls), 1) + self.assertEqual(ordinary_calls[0][:2], ("app", "app_default")) + self.assertEqual(ordinary_calls[0][2], "") + self.assertIn("-p monitoring", ordinary_calls[0][4]) + + +def render_demo(project="lincodex-demo-render", release_tag=None, env_files=None): environment = dict( os.environ, APP_PROJECT=project, @@ -184,7 +281,10 @@ def render_demo(project="lincodex-demo-render", release_tag=None): if release_tag: environment["LINCODEX_RELEASE_TAG"] = release_tag files = ["docker-compose.yml", "docker-compose.release.yml", "docker-compose.demo.yml", "docker-compose.demo.release.yml"] - command = [DOCKER, "compose", "--env-file", str(ROOT / ".env.example"), "-p", project] + command = [DOCKER, "compose"] + for env_file in env_files or (ROOT / ".env.example",): + command += ["--env-file", str(env_file)] + command += ["-p", project] for name in files: command += ["-f", str(DEPLOY / "docker" / name)] command += ["--profile", "demo-seed", "config", "--format", "json"] @@ -208,6 +308,16 @@ class DemoOverlayTest(unittest.TestCase): self.assertEqual(port["host_ip"], "127.0.0.1") self.assertEqual(port["published"], "8090") + def test_demo_env_overrides_the_core_bind(self): + with tempfile.TemporaryDirectory() as directory: + root_env = Path(directory) / "root.env" + example = (ROOT / ".env.example").read_text() + self.assertIn("APP_HTTP_BIND=127.0.0.1", example) + root_env.write_text(example.replace("APP_HTTP_BIND=127.0.0.1", "APP_HTTP_BIND=0.0.0.0", 1)) + rendered = render_demo(env_files=[root_env, DEPLOY / "demo" / "demo.env.example"]) + frontend = rendered["services"]["frontend"] + self.assertEqual(frontend["ports"][0]["host_ip"], "127.0.0.1") + def test_the_seed_reaches_only_the_default_network(self): seed = self.rendered["services"]["demo-seed"] self.assertEqual(seed["profiles"], ["demo-seed"]) diff --git a/docs/en/DEPLOYMENT.md b/docs/en/DEPLOYMENT.md index 432731c..f989b21 100644 --- a/docs/en/DEPLOYMENT.md +++ b/docs/en/DEPLOYMENT.md @@ -75,10 +75,11 @@ Templates and rendering live in `backend/internal/usecase/notification/mailtempl ```sh make -C deploy demo-seed DEMO_MODE=isolated make -C deploy monitoring-up DEMO_MODE=isolated +make -C deploy monitoring-down DEMO_MODE=isolated make -C deploy demo-down DEMO_MODE=isolated ``` -The seed creates a separate `lincodex-demo` project, bank, and synthetic accounts; repeated runs are idempotent. The local frontend is available at `http://localhost:8090`; you do not need to pass `APP_HTTP_BIND` on the command line. The target uses the root `.env` and `deploy/demo/demo.env`, falling back to the public example if the latter is absent. The command prints logins; `DEMO_ACCOUNT_PASSWORD` sets their password. For external access, choose your own password and share it separately with participants. +The seed creates a separate `lincodex-demo` project, bank, and synthetic accounts; repeated runs are idempotent. The local frontend is available at `http://localhost:8090`; you do not need to pass `APP_HTTP_BIND` on the command line. Settings load in this order: the root `.env`, `deploy/demo/demo.env.example`, then local `deploy/demo/demo.env` if it exists. Copy the example to `demo.env` to set local values; without that file, the example provides the defaults. The command prints logins; `DEMO_ACCOUNT_PASSWORD` sets their password. For external access, choose your own password and share it separately with participants. The guide is at `/demo`. Main accounts: `candidate@demo.lincodex.test`, `prepared-1@demo.lincodex.test` through `prepared-6@demo.lincodex.test`, `employer-alpha@demo.lincodex.test`, and `employer-beta@demo.lincodex.test`. Follow the candidate from assessment to result, then send an invitation as the employer and accept it as the candidate with selected contacts. @@ -170,7 +171,7 @@ make -C deploy monitoring-logs make -C deploy monitoring-down ``` -By default, the project joins the core network. After starting the demo, run `make -C deploy monitoring-up DEMO_MODE=isolated` to connect it to the `lincodex-demo` network. Grafana is bound to loopback; Prometheus, Loki, Alloy, and exporters remain internal. Dashboards cover Go, PostgreSQL, Redis, SeaweedFS, the host, and product metrics. Kafka has no dedicated scrape yet. The React telemetry SDK is not connected. Alert rules exist; notification delivery needs separate configuration. +By default, the project joins the core network. After starting the demo, run `make -C deploy monitoring-up DEMO_MODE=isolated` to connect it to the `lincodex-demo` network. Demo Grafana is available by default at `http://localhost:3001`; set `DEMO_GRAFANA_PORT` to change the port. Stop this monitoring project with `make -C deploy monitoring-down DEMO_MODE=isolated`. Grafana is bound to loopback; Prometheus, Loki, Alloy, and exporters remain internal. Dashboards cover Go, PostgreSQL, Redis, SeaweedFS, the host, and product metrics. Kafka has no dedicated scrape yet. The React telemetry SDK is not connected. Alert rules exist; notification delivery needs separate configuration. Prometheus retains metrics for 14 days with a 4 GB cap; Loki retains logs for 7 days. Keep contacts, resumes, raw URLs, and user identifiers out of labels. Alloy accesses the Docker API through a restricted socket proxy; even read-only Docker API access can expose sensitive container configuration. Treat this component as privileged. diff --git a/docs/ru/DEPLOYMENT.md b/docs/ru/DEPLOYMENT.md index 312a7d1..a60d2d0 100644 --- a/docs/ru/DEPLOYMENT.md +++ b/docs/ru/DEPLOYMENT.md @@ -75,10 +75,11 @@ Resend отправляет подтверждение адреса и подд ```sh make -C deploy demo-seed DEMO_MODE=isolated make -C deploy monitoring-up DEMO_MODE=isolated +make -C deploy monitoring-down DEMO_MODE=isolated make -C deploy demo-down DEMO_MODE=isolated ``` -Seed создает отдельный проект `lincodex-demo`, банк и аккаунты с синтетическими данными; повторный запуск идемпотентен. Локальный frontend доступен на `http://localhost:8090`; передавать `APP_HTTP_BIND` в командной строке не нужно. Цель использует корневой `.env` и `deploy/demo/demo.env`, а при отсутствии последнего - публичный пример. Логины печатает команда, пароль задает `DEMO_ACCOUNT_PASSWORD`. Для внешнего доступа выберите свой пароль и передайте его участникам отдельно. +Seed создает отдельный проект `lincodex-demo`, банк и аккаунты с синтетическими данными; повторный запуск идемпотентен. Локальный frontend доступен на `http://localhost:8090`; передавать `APP_HTTP_BIND` в командной строке не нужно. Настройки загружаются по порядку: корневой `.env`, `deploy/demo/demo.env.example`, затем локальный `deploy/demo/demo.env`, если он существует. Скопируйте пример в `demo.env`, чтобы задать свои значения; без него используются значения примера. Логины печатает команда, пароль задает `DEMO_ACCOUNT_PASSWORD`. Для внешнего доступа выберите свой пароль и передайте его участникам отдельно. Гид находится на `/demo`. Основные аккаунты: `candidate@demo.lincodex.test`, `prepared-1@demo.lincodex.test` - `prepared-6@demo.lincodex.test`, `employer-alpha@demo.lincodex.test` и `employer-beta@demo.lincodex.test`. Пройдите путь кандидата от теста до результата, затем от работодателя отправьте приглашение и примите его кандидатом с выбранными контактами. @@ -170,7 +171,7 @@ make -C deploy monitoring-logs make -C deploy monitoring-down ``` -По умолчанию проект подключается к сети core. После запуска демо используйте `make -C deploy monitoring-up DEMO_MODE=isolated`, чтобы подключить его к сети `lincodex-demo`. Grafana доступна только на loopback; Prometheus, Loki, Alloy и exporters остаются внутри. Дашборды охватывают Go, PostgreSQL, Redis, SeaweedFS, хост и продуктовые метрики. Kafka пока не имеет собственного scrape. React SDK телеметрии пока не подключен. Alert rules есть, доставка уведомлений требует отдельной настройки. +По умолчанию проект подключается к сети core. После запуска демо используйте `make -C deploy monitoring-up DEMO_MODE=isolated`, чтобы подключить его к сети `lincodex-demo`. Grafana демостенда по умолчанию доступна на `http://localhost:3001`; порт задает `DEMO_GRAFANA_PORT`. Остановите этот monitoring-проект командой `make -C deploy monitoring-down DEMO_MODE=isolated`. Grafana доступна только на loopback; Prometheus, Loki, Alloy и exporters остаются внутри. Дашборды охватывают Go, PostgreSQL, Redis, SeaweedFS, хост и продуктовые метрики. Kafka пока не имеет собственного scrape. React SDK телеметрии пока не подключен. Alert rules есть, доставка уведомлений требует отдельной настройки. Prometheus хранит метрики 14 дней с пределом 4 GB, Loki - логи 7 дней. В labels нельзя добавлять контакты, резюме, сырые URL или идентификаторы пользователей. Alloy получает Docker API через ограниченный socket proxy; даже read-only доступ к Docker API позволяет читать чувствительную конфигурацию контейнеров. Считайте этот контур привилегированным.