#!/usr/bin/env bash # Starts an isolated core stack and, as a separate Compose project, the # monitoring stack; sends a successful and failing API requests and a fixture # mail delivery through the outbox, the relay, and the delivery consumer; # checks the product metrics in Prometheus and the product dashboard through # Grafana; and confirms that the fixture address appears in neither the # metrics nor the logs in Loki. Everything it creates is removed on exit. # # Mail: EMAIL_PROVIDER=resend with a placeholder key, so the quota gauges # exist. The sending worker sends only verification and password # reset mail; the stored fixture delivery is a notification, which stays # pending until product notification sending is implemented, and no call reaches # Resend. set -euo pipefail root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) core_file="$root/deploy/docker/docker-compose.yml" monitoring_file="$root/deploy/docker/docker-compose.monitoring.yml" env_file="$root/.env.example" project=lincodex-metrics-check monitoring_project=lincodex-metrics-check-monitoring app_network="${project}_default" storage_network="${project}_storage" port="${METRICS_CHECK_HTTP_PORT:-18085}" grafana_port="${METRICS_CHECK_GRAFANA_PORT:-13085}" grafana="http://127.0.0.1:$grafana_port" # Example-config credentials of the throwaway Grafana. grafana_auth="admin:replace-this-grafana-password" fixture_email="Metrics.Check.Fixture@example.com" fixture_email_lower=$(printf '%s' "$fixture_email" | tr '[:upper:]' '[:lower:]') evidence_dir="${METRICS_CHECK_EVIDENCE_DIR:-$(mktemp -d)}" core_started=0 # .env.example has no usable IDENTITY_KEY_SECRET; the throwaway stack draws its own. identity_key_secret=$(od -An -N24 -tx1 /dev/urandom | tr -d ' \n') monitoring_started=0 core() { APP_PROJECT="$project" APP_NETWORK="$app_network" APP_STORAGE_NETWORK="$storage_network" APP_HTTP_PORT="$port" \ APP_SUBNET=172.29.83.0/24 APP_FRONTEND_IP=172.29.83.10 \ APP_PUBLIC_URL="http://localhost:$port" EMAIL_PROVIDER=resend RESEND_API_KEY=re_placeholder_not_a_key \ EMAIL_ACCOUNT=metrics-check IDENTITY_KEY_SECRET="$identity_key_secret" docker compose --env-file "$env_file" -p "$project" -f "$core_file" "$@" } monitoring() { APP_PROJECT="$project" APP_NETWORK="$app_network" APP_STORAGE_NETWORK="$storage_network" GRAFANA_PORT="$grafana_port" \ docker compose --env-file "$env_file" -p "$monitoring_project" -f "$monitoring_file" "$@" } fail() { printf 'FAIL: %s\n' "$*" >&2 exit 1 } for volume in "${project}_postgres_data" "${project}_seaweedfs_data" "${project}_kafka_data" \ "${monitoring_project}_prometheus_data" "${monitoring_project}_loki_data" "${monitoring_project}_grafana_data"; do if docker volume inspect "$volume" >/dev/null 2>&1; then fail "refusing to use the existing volume $volume" fi done for existing in "$app_network" "$storage_network" "${monitoring_project}_observability"; do if docker network inspect "$existing" >/dev/null 2>&1; then fail "refusing to use the existing network $existing" fi done cleanup() { local result=$? trap - EXIT if (( result != 0 )) && [[ "${METRICS_CHECK_KEEP_ON_FAILURE:-}" == 1 ]]; then printf 'Kept projects %s and %s for inspection; remove them with docker compose down --volumes.\n' "$project" "$monitoring_project" >&2 exit "$result" fi if (( monitoring_started )); then monitoring down --volumes --remove-orphans || result=1 fi if (( core_started )); then core down --volumes --remove-orphans --rmi local || result=1 fi printf 'Evidence kept in %s\n' "$evidence_dir" exit "$result" } trap cleanup EXIT core config --quiet monitoring config --quiet core_started=1 core up --build -d --wait --wait-timeout 180 monitoring_started=1 # node-exporter is left out: it reads host metrics only, and its rslave # root mount fails on Docker Desktop. Every service that the product metrics, # the dashboard, and the log path need is started. monitoring up -d prometheus-targets prometheus postgres-exporter redis-exporter loki alloy docker-socket-proxy grafana wait_for() { local description=$1 shift local attempt for attempt in $(seq 1 90); do if "$@" >/dev/null 2>&1; then return 0 fi sleep 2 done fail "timed out waiting for $description" } wait_for "the API" curl --fail --silent "http://127.0.0.1:$port/api/v1/healthz" wait_for "Grafana" curl --fail --silent "$grafana/api/health" # Requests: one success, one unknown route, one operation that requires a # session, one unsupported method, and an operation with a path parameter. attempt_id=0199b4f2-7c1e-7d3a-9f00-aabbccddeeff expect_status() { local method=$1 path=$2 want=$3 got got=$(curl --silent --output /dev/null --write-out '%{http_code}' -X "$method" "http://127.0.0.1:$port$path") [[ "$got" == "$want" ]] || fail "$method $path returned $got, want $want" printf '%s %s -> %s\n' "$method" "$path" "$got" } expect_status GET /api/v1/healthz 200 expect_status GET /api/v1/missing 404 expect_status GET /api/v1/identity/me 401 expect_status POST /api/v1/healthz 405 expect_status GET "/api/v1/me/assessment-attempts/$attempt_id" 401 # Requests that carry the fixture address. The query goes through Nginx, # which logs the path without the query. No API path holds an address, and # Nginx would log one verbatim, so the path request goes straight to the # backend from inside the core network; it stands for any client-made path. query_request_id=$(curl --silent --output /dev/null --dump-header - \ "http://127.0.0.1:$port/api/v1/healthz?email=$fixture_email" | tr -d '\r' | sed -n 's/^[Xx]-[Rr]equest-[Ii][Dd]: //p') [[ -n "$query_request_id" ]] || fail "the API returned no request ID" printf 'GET /api/v1/healthz?email= -> request %s\n' "$query_request_id" path_request_id=metrics-check-path-$(date +%s) core exec -T frontend wget -q -O /dev/null --header "X-Request-ID: $path_request_id" \ "http://backend:8080/api/v1/users/$fixture_email" >/dev/null 2>&1 || true printf 'GET backend:/api/v1/users/ -> request %s\n' "$path_request_id" # The fixture delivery: a verified account, a mail request, and the outbox # event that announces it, written in one transaction like MailRequester # does. The relay publishes the event and the notification_delivery consumer # stores the delivery. user_id=$(python3 -c 'import uuid; print(uuid.uuid4())') request_id=$(python3 -c 'import uuid; print(uuid.uuid4())') event_id=$(python3 -c 'import uuid; print(uuid.uuid4())') psql() { core exec -T postgres sh -ec 'psql -v ON_ERROR_STOP=1 -At -U "$POSTGRES_USER" -d "$POSTGRES_DB"' "$@" } psql </dev/null 2>&1 && fail "the duplicate account was accepted" postgres_logs=$(core logs --no-color postgres) [[ "$postgres_logs" == *"duplicate key value violates unique constraint"* ]] || fail "PostgreSQL did not log the unique violation" if grep -qiF "$fixture_email_lower" <<<"$postgres_logs"; then fail "the PostgreSQL log quotes the fixture address" fi printf '%s\n' 'PostgreSQL logged the unique violation without its key value' delivery_stored() { [[ "$(printf "SELECT status FROM deliveries WHERE id = '%s'" "$request_id" | psql)" == pending ]] } wait_for "the fixture delivery" delivery_stored printf 'Fixture delivery %s stored as pending\n' "$request_id" stored_address=$(printf "SELECT count(*) FROM deliveries WHERE id = '%s' AND recipient_email = '%s'" "$request_id" "$fixture_email" | psql) [[ "$stored_address" == 1 ]] || fail "the fixture delivery does not hold the fixture address" # Prometheus through the Grafana datasource proxy. prometheus_get() { curl --fail --silent --show-error -u "$grafana_auth" -G "$grafana/api/datasources/proxy/uid/prometheus$1" "${@:2}" } query_value() { prometheus_get /api/v1/query --data-urlencode "query=$1" | python3 -c 'import json, sys; result = json.load(sys.stdin)["data"]["result"]; print(sum(float(item["value"][1]) for item in result) if result else "none")' } expect_at_least() { local query=$1 minimum=$2 value value=$(query_value "$query") [[ "$value" != none ]] && python3 -c "import sys; sys.exit(0 if float('$value') >= $minimum else 1)" || fail "$query = $value, want at least $minimum" printf '%s = %s\n' "$query" "$value" } delivery_scraped() { [[ "$(query_value 'max(lincodex_mail_deliveries{job="backend",kind="notification",status="pending"})')" == 1.0 ]] } wait_for "the delivery gauge in Prometheus" delivery_scraped { expect_at_least 'sum(lincodex_http_requests_total{job="backend",route="/api/v1/healthz",status="200"})' 1 expect_at_least 'sum(lincodex_http_requests_total{job="backend",route="/api/v1/*",status="404"})' 1 expect_at_least 'sum(lincodex_http_requests_total{job="backend",route="/api/v1/me/assessment-attempts/{attempt_id}",status="401"})' 1 expect_at_least 'sum(lincodex_http_problems_total{job="backend",code="unauthenticated"})' 2 expect_at_least 'sum(lincodex_http_problems_total{job="backend",code="not_found",route="/api/v1/*"})' 1 expect_at_least 'sum(lincodex_http_problems_total{job="backend",code="method_not_allowed"})' 1 expect_at_least 'sum(lincodex_http_request_duration_seconds_count{job="backend",status_class="2xx"})' 1 expect_at_least 'sum(lincodex_outbox_relay_events_total{job="backend",outcome="published"})' 1 expect_at_least 'count(lincodex_outbox_relay_oldest_pending_age_seconds{job="backend"})' 1 expect_at_least 'sum(lincodex_event_consumer_records_total{job="backend",consumer="notification_delivery",outcome="applied"})' 1 expect_at_least 'max(lincodex_mail_deliveries{job="backend",kind="notification",status="pending"})' 1 expect_at_least 'count(lincodex_mail_deliveries{job="backend"})' 15 expect_at_least 'max(lincodex_mail_quota_limit_recipients{job="backend",provider="resend",window="day"})' 100 expect_at_least 'count(lincodex_mail_quota_used_recipients{job="backend"})' 2 } | tee "$evidence_dir/prometheus-values.txt" prometheus_get /api/v1/rules >"$evidence_dir/rules.json" grep -q LincodexOutboxRelayLagging "$evidence_dir/rules.json" || fail "Prometheus did not load the alert rules" # The dashboard: provisioned, and every panel query is accepted by # Prometheus. curl --fail --silent --show-error -u "$grafana_auth" "$grafana/api/dashboards/uid/lincodex-product" >"$evidence_dir/dashboard.json" python3 - "$evidence_dir/dashboard.json" <<'PY' >"$evidence_dir/panel-queries.txt" import json, sys dashboard = json.load(open(sys.argv[1]))["dashboard"] for panel in dashboard["panels"]: for target in panel.get("targets", []): print(panel["title"] + "\t" + target["expr"]) PY panels=0 while IFS=$'\t' read -r title expr; do status=$(prometheus_get /api/v1/query --data-urlencode "query=$expr" | python3 -c 'import json, sys; data = json.load(sys.stdin); print(data["status"], len(data["data"]["result"]))') [[ "$status" == success* ]] || fail "panel $title query failed: $status" printf '%s\t%s\n' "$title" "$status" >>"$evidence_dir/panel-results.txt" panels=$((panels + 1)) done <"$evidence_dir/panel-queries.txt" printf 'Dashboard lincodex-product: %d panel queries accepted\n' "$panels" cat "$evidence_dir/panel-results.txt" # Privacy: the whole metric exposition of the backend, every series and # label value in Prometheus, and the federated sample values must not hold # the fixture address, and the logs in Loki must not either. core exec -T frontend wget -q -O - http://backend:9090/metrics >"$evidence_dir/backend-metrics.txt" prometheus_get /api/v1/series --data-urlencode 'match[]={job=~".+"}' >"$evidence_dir/series.json" monitoring exec -T prometheus wget -q -O - 'http://localhost:9090/federate?match[]=%7Bjob%3D~%22.%2B%22%7D' >"$evidence_dir/federate.txt" : >"$evidence_dir/label-values.txt" for label in $(prometheus_get /api/v1/labels | python3 -c 'import json, sys; print("\n".join(json.load(sys.stdin)["data"]))'); do prometheus_get "/api/v1/label/$label/values" >>"$evidence_dir/label-values.txt" done now=$(date +%s) loki_get() { curl --fail --silent --show-error -u "$grafana_auth" -G "$grafana/api/datasources/proxy/uid/loki/loki/api/v1/query_range" \ --data-urlencode "query=$1" --data-urlencode "start=$(((now - 3600) * 1000000000))" \ --data-urlencode "end=$(((now + 60) * 1000000000))" --data-urlencode limit=5000 } logs_collected() { local request_id for request_id in "$query_request_id" "$path_request_id"; do loki_get "{service=\"backend\"} |= \"$request_id\"" | grep -qF "$request_id" || return 1 done } # The backend logged both requests that carried the fixture address; seeing # them proves that this run's logs reached Loki, so the absence check below # is not vacuous. wait_for "the backend request logs in Loki" logs_collected loki_get '{service=~".+"}' >"$evidence_dir/loki.json" log_lines=$(python3 -c 'import json, sys; print(sum(len(s["values"]) for s in json.load(open(sys.argv[1]))["data"]["result"]))' "$evidence_dir/loki.json") printf 'Loki returned %s log lines of the core services\n' "$log_lines" for file in backend-metrics.txt series.json federate.txt label-values.txt loki.json; do if grep -qiF "$fixture_email" "$evidence_dir/$file"; then fail "$file contains the fixture address" fi if grep -qF "$user_id" "$evidence_dir/$file" && [[ "$file" != loki.json ]]; then fail "$file contains the fixture user ID" fi printf 'No fixture address in %s (%s bytes)\n' "$file" "$(wc -c <"$evidence_dir/$file" | tr -d ' ')" done if grep -qF "$attempt_id" "$evidence_dir/backend-metrics.txt" "$evidence_dir/label-values.txt"; then fail "a path parameter reached the metric labels" fi printf '%s\n' 'Product metrics check passed.'