Files
Heimdall/skills/camera-toggle-acceptance/acceptance.sh
T
arnaud.dartois be1cb9b479
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Successful in 21m23s
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Successful in 10m36s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 28m8s
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 4s
Fix camera config reconciliation latency
Refs #157

Reconcile camera config changes immediately and strengthen the disposable toggle acceptance evidence.

Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-12 14:37:33 +01:00

277 lines
11 KiB
Bash
Executable File

#!/usr/bin/env bash
set -Eeuo pipefail
umask 077
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
stamp="$(date +%s)-$RANDOM"
project="heimdall-157-${stamp}"
temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")
env_file="$temp_dir/acceptance.env"
env_next="$temp_dir/acceptance.env.next"
compose_override="$temp_dir/compose.override.yml"
config_headers="$temp_dir/config.headers"
config_body="$temp_dir/config.json"
stage=setup
local_image_tags=("heimdall:${project}-central" "heimdall-agent:${project}-agent")
compose_files=(-f "$root/docker/docker-compose.yml" -f "$compose_override")
cleanup() {
status=$?
trap - EXIT
cleanup_failed=0
if (( status != 0 )); then
printf 'acceptance failed at stage=%s\n' "$stage" >&2
docker compose -p "$project" --env-file "$env_file" "${compose_files[@]}" logs --timestamps --no-color --tail 250 heimdall-agent 2>/dev/null |
grep -E 'Config update received: config\.invalidated|Full configuration fetched successfully|Stream stopped for camera|camera config ACK' | tail -40 || true
fi
docker compose -p "$project" --env-file "$env_file" "${compose_files[@]}" down --volumes --remove-orphans >/dev/null 2>&1 || cleanup_failed=1
containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
volumes=$(docker volume ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
networks=$(docker network ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
[[ -z "$containers" && -z "$volumes" && -z "$networks" ]] || cleanup_failed=1
for tag in "${local_image_tags[@]}"; do
docker image rm "$tag" >/dev/null 2>&1 || true
docker image inspect "$tag" >/dev/null 2>&1 && cleanup_failed=1
done
rm -f -- "$env_file" "$env_next" "$compose_override" "$config_headers" "$config_body" || cleanup_failed=1
rmdir -- "$temp_dir" || cleanup_failed=1
if (( cleanup_failed )); then
printf 'cleanup verification failed for %s\n' "$project" >&2
status=1
else
printf 'cleanup verified: project resources absent; exact local tags absent\n'
fi
exit "$status"
}
port=$((20000 + RANDOM % 20000))
pg_port=$((port + 1))
db_password=$(openssl rand -hex 24)
jwt_key=$(openssl rand -hex 48)
jwt_refresh=$(openssl rand -hex 48)
cat >"$env_file" <<EOF
POSTGRES_DB=heimdall_acceptance
POSTGRES_USER=acceptance
POSTGRES_PASSWORD=$db_password
POSTGRES_PORT=127.0.0.1:$pg_port
DATABASE_URL=Host=postgresql;Port=5432;Database=heimdall_acceptance;Username=acceptance;Password=$db_password
JWT__KEY=$jwt_key
JWT__REFRESHKEY=$jwt_refresh
JWT__ISSUER=heimdall-acceptance
JWT__AUDIENCE=heimdall-acceptance-api
WEB_PORT=127.0.0.1:$port
ACCEPTANCE_PROJECT=$project
DOCKER_GID=0
HEIMDALL_NETWORK_NAME=${project}-network
HEIMDALL_TEST_SITE_TOKEN=placeholder-token
EOF
cat >"$compose_override" <<'EOF'
services:
heimdall:
image: heimdall:${ACCEPTANCE_PROJECT}-central
heimdall-agent:
image: heimdall-agent:${ACCEPTANCE_PROJECT}-agent
build:
context: ..
dockerfile: docker/Dockerfile.agent
user: "1654:1654"
environment:
Agent__CentralUrl: http://heimdall:8080
Agent__AllowInsecureHttp: "true"
Agent__SiteToken: ${HEIMDALL_TEST_SITE_TOKEN:?token required}
Agent__AgentName: camera-157-agent
Agent__HeartbeatIntervalSeconds: "5"
Agent__StateDirectory: /var/lib/heimdall
Agent__DiscoveryEnabled: "false"
volumes:
- agent_state:/var/lib/heimdall
depends_on:
heimdall:
condition: service_healthy
synthetic-camera-publisher:
condition: service_started
networks:
- heimdall-net
synthetic-camera:
image: bluenviron/mediamtx:1.21.3
volumes:
- ./mediamtx.synthetic-source.yml:/mediamtx.yml:ro
networks:
- heimdall-net
synthetic-camera-publisher:
image: jrottenberg/ffmpeg:7.1-alpine
entrypoint: ["/bin/sh", "-c"]
command: ["while true; do ffmpeg -nostdin -hide_banner -loglevel error -re -f lavfi -i testsrc2=size=640x360:rate=25 -an -vf format=yuv420p -c:v libx264 -tune zerolatency -bf 0 -g 25 -f rtsp -rtsp_transport tcp rtsp://synthetic-camera:8554/synthetic; sleep 1; done"]
depends_on:
- synthetic-camera
networks:
- heimdall-net
volumes:
agent_state:
EOF
# The cleanup trap is installed before any image build or Compose start.
trap cleanup EXIT
chmod 600 "$env_file"
api="http://127.0.0.1:$port"
compose() { docker compose -p "$project" --env-file "$env_file" "${compose_files[@]}" "$@"; }
contract_failures=0
wait_http() {
for _ in $(seq 1 90); do
if curl -fsS --max-time 2 "$api/healthz" >/dev/null 2>&1; then return 0; fi
sleep 2
done
return 1
}
request() { curl -fsS --max-time 10 -H "Authorization: Bearer $admin_token" -H 'Content-Type: application/json' "$@"; }
ffmpeg_count() {
compose exec -T heimdall-agent sh -c 'n=0; for f in /proc/[0-9]*/comm; do IFS= read -r p < "$f" || continue; [ "$p" = ffmpeg ] && n=$((n+1)); done; printf "%s\n" "$n"'
}
wait_count() {
expected=$1; seconds=$2
for _ in $(seq 1 "$((seconds * 20))"); do
count=$(ffmpeg_count)
observed_at_ns=$(date +%s%N)
(( count <= 1 )) || return 1
if [[ "$count" == "$expected" ]]; then
count_observed_at_ns=$observed_at_ns
return 0
fi
sleep 0.05
done
return 1
}
wait_ack() {
expected_enabled=$1
for _ in $(seq 1 100); do
request -D "$config_headers" "$api/api/settings/agent/$agent_id" >"$config_body"
wanted=$(awk 'BEGIN{IGNORECASE=1} /^X-Camera-Config-Version:/ {gsub("\r", "", $2); print $2}' "$config_headers")
actual_enabled=$(jq -r --arg key "camera.$camera_id.enabled" '.[$key] // empty' "$config_body")
agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20")
applied=$(jq -r "[.items[]? | select(.id==\"$agent_id\")][0].lastAppliedCameraConfigVersion // empty" <<<"$agents")
if [[ -n "$wanted" && "$wanted" == "$applied" && "$actual_enabled" == "$expected_enabled" ]]; then
acknowledged_version=$wanted
return 0
fi
sleep 0.1
done
return 1
}
wait_agent_reconnected_and_ack() {
restarted_at_ns=$1
expected_version=$2
for _ in $(seq 1 60); do
agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20")
agent=$(jq -cer "[.items[]? | select(.id==\"$agent_id\")][0]" <<<"$agents")
status=$(jq -r '.status // empty' <<<"$agent")
heartbeat=$(jq -r '.lastHeartbeat // empty' <<<"$agent")
applied_version=$(jq -r '.lastAppliedCameraConfigVersion // empty' <<<"$agent")
applied_at=$(jq -r '.lastAppliedCameraConfigAt // empty' <<<"$agent")
if [[ "$status" == Online && -n "$heartbeat" && -n "$applied_at" && "$applied_version" == "$expected_version" ]]; then
heartbeat_ns=$(date -u -d "$heartbeat" +%s%N)
applied_at_ns=$(date -u -d "$applied_at" +%s%N)
if (( heartbeat_ns > restarted_at_ns && applied_at_ns > restarted_at_ns )); then
return 0
fi
fi
sleep 1
done
return 1
}
printf 'project=%s central_tag=%s agent_tag=%s\n' "$project" "${local_image_tags[0]}" "${local_image_tags[1]}"
stage=build
compose build heimdall heimdall-agent
stage=central-startup
compose up -d postgresql heimdall
wait_http
stage=bootstrap
admin_password="Tst!$(openssl rand -hex 20)A9"
bootstrap=$(curl -fsS --max-time 10 -H 'Content-Type: application/json' -d "{\"email\":\"admin-${stamp}@heimdall.test\",\"password\":\"$admin_password\",\"displayName\":\"Acceptance Admin\"}" "$api/api/auth/bootstrap-admin")
admin_token=$(jq -er '.accessToken' <<<"$bootstrap")
printf 'synthetic Admin bootstrap accepted\n'
site=$(request -X POST -d '{"name":"Camera toggle acceptance","timezone":"UTC"}' "$api/api/sites")
site_id=$(jq -er '.id' <<<"$site")
printf 'synthetic site created\n'
site_token=$(request -X POST "$api/api/sites/$site_id/tokens" | jq -er '.token')
grep -v '^HEIMDALL_TEST_SITE_TOKEN=' "$env_file" >"$env_next"
printf 'HEIMDALL_TEST_SITE_TOKEN=%s\n' "$site_token" >>"$env_next"
mv "$env_next" "$env_file"
camera=$(request -X POST -d "{\"siteId\":\"$site_id\",\"name\":\"Synthetic camera\",\"rtspUrl\":\"rtsp://synthetic-camera:8554/synthetic\"}" "$api/api/cameras")
camera_id=$(jq -er '.id' <<<"$camera")
[[ $(jq -r '.status' <<<"$camera") == Disabled ]]
printf 'synthetic camera created\n'
stage=agent-startup
compose up -d synthetic-camera synthetic-camera-publisher heimdall-agent
agent_id=
for _ in $(seq 1 60); do
agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20")
agent_id=$(jq -r '[.items[]? | select(.name=="camera-157-agent")][0].id // empty' <<<"$agents")
[[ -n "$agent_id" ]] && break
sleep 1
done
[[ -n "$agent_id" ]]
printf 'Agent registered\n'
request -X POST -d "{\"cameraId\":\"$camera_id\",\"agentId\":\"$agent_id\",\"reason\":\"synthetic acceptance\"}" "$api/api/assignments" >/dev/null
stage=initial-on
request -X POST "$api/api/cameras/$camera_id/toggle-status" >/dev/null
wait_count 1 10
wait_ack true
off_once() {
started=$(date +%s%N)
result=$(request -X POST "$api/api/cameras/$camera_id/toggle-status")
response_ms=$((( $(date +%s%N) - started ) / 1000000))
[[ $(jq -r '.status' <<<"$result") == Disabled ]]
within_contract=1
if ! wait_count 0 2; then
within_contract=0
wait_count 0 10 || return 1
fi
elapsed_ms=$((( count_observed_at_ns - started ) / 1000000))
printf 'OFF API response=%sms; process release=%sms; under-2s=%s\n' "$response_ms" "$elapsed_ms" "$within_contract"
if (( ! within_contract || elapsed_ms >= 2000 )); then
contract_failures=$((contract_failures + 1))
fi
wait_ack false
}
for iteration in 1 2 3; do
stage="cycle-${iteration}-off"
off_once
stage="cycle-${iteration}-on"
request -X POST "$api/api/cameras/$camera_id/toggle-status" >/dev/null
wait_count 1 10
wait_ack true
count=$(ffmpeg_count)
[[ "$count" == 1 ]]
done
stage=agent-restart-on
compose restart heimdall-agent
wait_count 1 10
agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20")
old_agent_id=$(jq -er '[.items[]? | select(.name=="camera-157-agent")][0].id' <<<"$agents")
[[ "$old_agent_id" == "$agent_id" ]]
wait_ack true
stage=final-off
off_once
agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20")
old_agent_id=$(jq -er '[.items[]? | select(.name=="camera-157-agent")][0].id' <<<"$agents")
compose restart heimdall-agent
post_off_restart_returned_ns=$(date +%s%N)
wait_count 0 10
wait_agent_reconnected_and_ack "$post_off_restart_returned_ns" "$acknowledged_version"
stage=central-restart-off
compose restart heimdall
central_restart_returned_ns=$(date +%s%N)
wait_http
sleep 2
[[ $(ffmpeg_count) == 0 ]]
camera=$(request "$api/api/cameras/$camera_id")
[[ $(jq -r '.status' <<<"$camera") == Disabled ]]
wait_ack false
wait_agent_reconnected_and_ack "$central_restart_returned_ns" "$acknowledged_version"
printf 'restart OFF persisted; camera config digest acknowledged\n'
if (( contract_failures > 0 )); then
printf 'contract failures=%s\n' "$contract_failures" >&2
exit 1
fi