Compare commits
4
Commits
2ba35f6d12
...
1.0.6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3ef030086d | ||
|
|
060239d10e | ||
|
|
aa5ca868db | ||
|
|
be1cb9b479 |
No files matched your search
@@ -39,7 +39,7 @@ L’installateur Linux est servi par Central avec son superviseur. Il installe l
|
||||
|
||||
Sous Windows, copiez la commande PowerShell générée dans l’IHM pour le site, en mode processus utilisateur ou service Windows. Elle télécharge le script depuis Central et applique `ExecutionPolicy Bypass` à la session PowerShell courante uniquement; elle ne change pas la stratégie persistante de la machine. L’installation comme service exige une session PowerShell élevée. Une stratégie imposée par une stratégie de groupe peut toujours interdire l’exécution.
|
||||
|
||||
Pour un Agent Docker, le Compose généré par l’IHM contient le dépôt, le digest et la clé publique issus des métadonnées de release vérifiées par Central. Le parcours CPU est sélectionné par défaut. Le parcours CUDA est proposé quand la release fournit l’image GPU signée; il demande aussi le NVIDIA Container Toolkit sur l’hôte. Aucun fichier de clé n’est à créer manuellement. L’Agent refuse la mise à jour si la signature manque, si le digest d’image diffère du manifeste signé, ou si le registre ne fournit pas l’image au digest annoncé. Les Agents configurés sur CUDA continuent de sélectionner l’image GPU pendant les mises à jour.
|
||||
Pour un Agent Docker, le Compose et les commandes `docker run` générés par l’IHM installent le dépôt d’image avec le tag `latest`; Compose et `docker run` vérifient le registre au démarrage. Le parcours CPU est sélectionné par défaut. Le parcours CUDA est proposé quand la release fournit l’image GPU signée; il demande aussi le NVIDIA Container Toolkit sur l’hôte. Aucun fichier de clé n’est à créer manuellement. Pour les mises à jour déclenchées ensuite par Central, l’Agent vérifie la signature et le digest d’image du manifeste signé avant de remplacer le conteneur. Les Agents configurés sur CUDA continuent de sélectionner l’image GPU pendant les mises à jour.
|
||||
|
||||
## Rotation
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# Docker Compose deployment
|
||||
|
||||
The required stack is PostgreSQL and Heimdall Central. The Agent is deployed
|
||||
separately on each camera-network host; the Central UI supplies a
|
||||
digest-pinned Agent Compose file for each site. RustFS, ntfy, Ollama, TURN,
|
||||
separately on each camera-network host; the Central UI supplies an Agent
|
||||
Compose file using the `latest` tag for each site. RustFS, ntfy, Ollama, TURN,
|
||||
Redis and scheduled backups have separate Compose files and can be left out.
|
||||
|
||||
## Central and database
|
||||
@@ -135,11 +135,13 @@ in [`skills/deployment-guide-acceptance/SKILL.md`](../skills/deployment-guide-ac
|
||||
## Agent
|
||||
|
||||
Prefer the Compose shown in the Central UI's site installation panel. It uses
|
||||
the image reference and digest from Central's verified release manifest and
|
||||
includes the site token, public Central URL, Agent name and release public key.
|
||||
Save it as `docker-compose.yml`, then run `docker compose up -d`. The generated
|
||||
Compose contains the pinned trust key; no separate PEM file is required. Do
|
||||
not substitute a mutable image tag for the digest.
|
||||
the Agent image's `latest` tag and includes the site token, public Central URL,
|
||||
Agent name and release public key. Compose uses `pull_policy: always` so an
|
||||
explicit `docker compose up` checks for the latest image. Save it as
|
||||
`docker-compose.yml`, then run `docker compose up -d`. The generated Compose
|
||||
contains the pinned trust key; no separate PEM file is required. Updates
|
||||
dispatched later by Central continue to verify the digest in the signed release
|
||||
manifest before replacing the running container.
|
||||
|
||||
The Agent Compose is generated by Central's UI for the selected site; there is
|
||||
no production Agent Compose in this repository. For local development only,
|
||||
|
||||
+1
-1
@@ -281,7 +281,7 @@ Lancer
|
||||
└──────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
Docker Compose affiche le YAML comme une étape « Configuration », suivie des commandes pour démarrer et vérifier l'Agent. Chaque bloc a une copie intégrée en haut à droite; après copie, l'icône devient une coche. Les commandes d'installation restent masquées tant que la release signée correspondante n'est pas disponible. Docker exige aussi une référence d'image vérifiée par digest. En cas d'indisponibilité, le panneau montre une alerte explicite à la place des commandes.
|
||||
Docker Compose affiche le YAML comme une étape « Configuration », suivie des commandes pour démarrer et vérifier l'Agent. Chaque bloc a une copie intégrée en haut à droite; après copie, l'icône devient une coche. Les commandes d'installation restent masquées tant que la release signée correspondante n'est pas disponible. Docker exige aussi les métadonnées d'image vérifiées de la release, puis installe l'image publiée avec le tag `latest`; les remplacements déclenchés par Central restent vérifiés par digest signé. En cas d'indisponibilité, le panneau montre une alerte explicite à la place des commandes.
|
||||
|
||||
### États — Détail Site
|
||||
|
||||
|
||||
@@ -350,6 +350,7 @@ if ($startCore) {
|
||||
}
|
||||
|
||||
foreach ($service in $selected) {
|
||||
$composeProjectDirectory = if ($service -eq 'backup') { $optionalDirectory } else { $destination }
|
||||
switch ($service) {
|
||||
'rustfs' {
|
||||
$accessKeyPath = Join-Path $optionalSecretsDirectory 'rustfs_access_key'
|
||||
@@ -379,7 +380,7 @@ foreach ($service in $selected) {
|
||||
}
|
||||
}
|
||||
if ($startCore -and (Read-YesNo "Démarrer le service optionnel $service ?" 'o')) {
|
||||
Invoke-DockerCompose @('--project-name', "heimdall-$service", '--env-file', $envPath,
|
||||
Invoke-DockerCompose @('--project-directory', $composeProjectDirectory, '--project-name', "heimdall-$service", '--env-file', $envPath,
|
||||
'-f', (Join-Path $optionalDirectory "docker-compose.$service.yml"), 'up', '-d')
|
||||
} else {
|
||||
Write-Host "Service $service préparé dans $optionalDirectory."
|
||||
|
||||
@@ -296,6 +296,10 @@ if [[ "$(ask 'Démarrer PostgreSQL et Heimdall maintenant ?' 'o')" =~ ^([oO]|[oO
|
||||
fi
|
||||
|
||||
for service in "${selected[@]}"; do
|
||||
compose_project_directory="$destination"
|
||||
if [[ "$service" == backup ]]; then
|
||||
compose_project_directory="$destination/optional"
|
||||
fi
|
||||
case "$service" in
|
||||
rustfs)
|
||||
printf '%s' "heimdall$(openssl rand -hex 8)" > "$destination/optional/secrets/rustfs_access_key"
|
||||
@@ -318,7 +322,8 @@ for service in "${selected[@]}"; do
|
||||
;;
|
||||
esac
|
||||
if [[ "$start_core" == yes ]] && [[ "$(ask "Démarrer le service optionnel ${service} ?" 'o')" =~ ^([oO]|[oO][uU][iI]|[yY]|[yY][eE][sS])$ ]]; then
|
||||
docker compose --project-name "heimdall-${service}" --env-file "$destination/.env" \
|
||||
docker compose --project-directory "$compose_project_directory" --project-name "heimdall-${service}" \
|
||||
--env-file "$destination/.env" \
|
||||
-f "$destination/optional/docker-compose.${service}.yml" up -d
|
||||
else
|
||||
say "Service ${service} préparé dans $destination/optional/."
|
||||
|
||||
@@ -87,7 +87,7 @@ Windows, copiez la commande affichée sur l’hôte distant : elle télécharge
|
||||
script depuis le Central et l’exécute avec les identifiants propres à ce site.
|
||||
L’installation Linux peut créer un service systemd; l’installation Windows
|
||||
peut créer un service Windows (PowerShell administrateur requis). Pour Docker,
|
||||
utilisez le Compose généré par l’IHM, épinglé au digest signé. Aucun fichier de
|
||||
utilisez le Compose généré par l’IHM, qui suit le tag `latest`. Aucun fichier de
|
||||
clé ni Compose de production ne doit être copié depuis le dépôt. Voir le
|
||||
[guide de signature et de mise à jour Agent](docs/agent-release-signing.md).
|
||||
Le Compose Docker monte le socket Docker de l’hôte pour permettre les mises à
|
||||
|
||||
@@ -73,6 +73,18 @@ class PublicationWorkflowTests(unittest.TestCase):
|
||||
self.assertNotIn('secrets.GITEA_TOKEN', workflow.split(' publish:\n', 1)[0])
|
||||
|
||||
class PowerShellInstallerTests(unittest.TestCase):
|
||||
def test_optional_compose_commands_resolve_paths_from_install_root(self):
|
||||
linux_installer = (REPO_ROOT/'install/install-server.sh').read_text()
|
||||
windows_installer = (REPO_ROOT/'install/install-server.ps1').read_text()
|
||||
self.assertIn('compose_project_directory="$destination"', linux_installer)
|
||||
self.assertIn('compose_project_directory="$destination/optional"', linux_installer)
|
||||
self.assertIn('docker compose --project-directory "$compose_project_directory"',
|
||||
linux_installer)
|
||||
self.assertIn("$composeProjectDirectory = if ($service -eq 'backup') { $optionalDirectory } else { $destination }",
|
||||
windows_installer)
|
||||
self.assertIn("Invoke-DockerCompose @('--project-directory', $composeProjectDirectory,",
|
||||
windows_installer)
|
||||
|
||||
@unittest.skipUnless(shutil.which('pwsh'), 'PowerShell is not installed')
|
||||
def test_server_installer_has_valid_powershell_syntax(self):
|
||||
parser = "$tokens=$null; $errors=$null; [void][System.Management.Automation.Language.Parser]::ParseFile((Resolve-Path 'install/install-server.ps1'), [ref]$tokens, [ref]$errors); if ($errors.Count) { $errors | ForEach-Object { Write-Error $_.Message }; exit 1 }"
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
name: agent-startup-composition
|
||||
description: Validate Heimdall Agent dependency-injection composition by starting its source-built container without a Central dependency.
|
||||
---
|
||||
|
||||
# Agent startup composition
|
||||
|
||||
`src/Heimdall.Agent/Program.cs` constructs `SnapshotPipelineServiceOptions` in
|
||||
the service-registration factory before registering the hosted service. Do not
|
||||
register `SnapshotPipelineService` with the generic `AddHostedService<T>()`
|
||||
unless every constructor dependency, including that options record, is
|
||||
registered in DI. A missing dependency can prevent `Host.StartAsync` and leave
|
||||
the Agent container unable to start.
|
||||
|
||||
## Acceptance
|
||||
|
||||
Run `bash skills/agent-startup-composition/acceptance.sh` from the repository
|
||||
root. The recipe builds only the CPU Agent image from the current checkout with
|
||||
a unique local tag and starts it in a disposable Compose project with generated
|
||||
site-token data and an internal-only network. Its Central URL points to the
|
||||
Agent container's own unused loopback port; it cannot reach a deployment.
|
||||
|
||||
The recipe proves that:
|
||||
|
||||
1. The Agent host starts and remains running with its production service
|
||||
registrations, including `SnapshotPipelineService`.
|
||||
2. `/health/live` responds successfully before registration with Central; the
|
||||
readiness endpoint `/healthz` is intentionally not used because it reports
|
||||
Unhealthy until Central registration succeeds.
|
||||
3. Startup logs do not contain the missing
|
||||
`SnapshotPipelineServiceOptions` dependency or a host-start failure.
|
||||
4. Cleanup removes the exact Compose project, generated state volume/network,
|
||||
and this recipe's one exact Agent image tag, then verifies their absence.
|
||||
|
||||
This checks DI and host startup only. It does not validate Central registration,
|
||||
camera discovery, model inference, a published Agent, or a deployed installation.
|
||||
The EXIT trap preserves the test result, attempts each cleanup independently,
|
||||
and reports cleanup failures. The Dockerfile's shared .NET base images remain.
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
repo_root=$(git rev-parse --show-toplevel)
|
||||
project="heimdall-agent-startup-$(date -u +%Y%m%d%H%M%S)-$(openssl rand -hex 3)"
|
||||
image_tag="heimdall-agent:${project}-agent"
|
||||
temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")
|
||||
env_file="$temp_dir/acceptance.env"
|
||||
compose_file="$temp_dir/compose.yaml"
|
||||
local_image_tags=("$image_tag")
|
||||
|
||||
cleanup() {
|
||||
status=$?
|
||||
trap - EXIT
|
||||
cleanup_failed=0
|
||||
|
||||
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" \
|
||||
down --volumes --remove-orphans >/dev/null 2>&1 || cleanup_failed=1
|
||||
|
||||
containers=
|
||||
volumes=
|
||||
networks=
|
||||
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
|
||||
if docker image inspect "$tag" >/dev/null 2>&1; then
|
||||
cleanup_failed=1
|
||||
fi
|
||||
done
|
||||
|
||||
rm -f -- "$env_file" "$compose_file" || cleanup_failed=1
|
||||
rmdir -- "$temp_dir" || cleanup_failed=1
|
||||
|
||||
if (( cleanup_failed )); then
|
||||
printf 'Disposable Agent startup cleanup failed for project %s\n' "$project" >&2
|
||||
status=1
|
||||
else
|
||||
printf 'Cleanup verified: project=%s; containers/volumes/networks absent; image tag %s absent.\n' \
|
||||
"$project" "$image_tag"
|
||||
fi
|
||||
|
||||
exit "$status"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
umask 077
|
||||
cat >"$env_file" <<EOF
|
||||
PROJECT=$project
|
||||
SOURCE_ROOT=$repo_root
|
||||
IMAGE_TAG=$image_tag
|
||||
SYNTHETIC_SITE_TOKEN=$(openssl rand -hex 32)
|
||||
EOF
|
||||
|
||||
cat >"$compose_file" <<'EOF'
|
||||
services:
|
||||
agent:
|
||||
image: ${IMAGE_TAG}
|
||||
build:
|
||||
context: ${SOURCE_ROOT}
|
||||
dockerfile: docker/Dockerfile.agent
|
||||
network: host
|
||||
restart: "no"
|
||||
environment:
|
||||
Agent__CentralUrl: http://127.0.0.1:1
|
||||
Agent__AllowInsecureHttp: "true"
|
||||
Agent__SiteToken: ${SYNTHETIC_SITE_TOKEN}
|
||||
Agent__AgentName: ${PROJECT}
|
||||
Agent__RegistrationMaxRetries: "20"
|
||||
Agent__HeartbeatIntervalSeconds: "5"
|
||||
Agent__DiscoveryEnabled: "false"
|
||||
Agent__UpdateCheckIntervalHours: "0"
|
||||
Agent__StateDirectory: /var/lib/heimdall
|
||||
Sentry__Dsn: ""
|
||||
volumes:
|
||||
- agent_state:/var/lib/heimdall
|
||||
networks:
|
||||
- isolated
|
||||
|
||||
volumes:
|
||||
agent_state:
|
||||
|
||||
networks:
|
||||
isolated:
|
||||
internal: true
|
||||
EOF
|
||||
|
||||
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" \
|
||||
up --build --detach agent
|
||||
|
||||
container_id=$(docker compose -p "$project" --env-file "$env_file" -f "$compose_file" ps -q agent)
|
||||
[[ -n "$container_id" ]] || { printf 'Agent container was not created.\n' >&2; exit 1; }
|
||||
|
||||
deadline=$((SECONDS + 90))
|
||||
live_ready=0
|
||||
while (( SECONDS < deadline )); do
|
||||
running=$(docker inspect --format '{{.State.Running}}' "$container_id" 2>/dev/null || true)
|
||||
if [[ "$running" != true ]]; then
|
||||
printf 'Agent container exited before its live endpoint became ready.\n' >&2
|
||||
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" ps >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if docker compose -p "$project" --env-file "$env_file" -f "$compose_file" \
|
||||
exec -T agent wget -q --tries=1 --spider http://127.0.0.1:8080/health/live >/dev/null 2>&1; then
|
||||
live_ready=1
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
(( live_ready == 1 )) || { printf 'Agent /health/live did not become ready.\n' >&2; exit 1; }
|
||||
|
||||
restart_count=$(docker inspect --format '{{.RestartCount}}' "$container_id")
|
||||
[[ "$restart_count" == 0 ]] || { printf 'Agent container restarted unexpectedly.\n' >&2; exit 1; }
|
||||
|
||||
if docker compose -p "$project" --env-file "$env_file" -f "$compose_file" logs agent 2>&1 |
|
||||
rg -q "Unable to resolve service for type 'Heimdall\.Agent\.Services\.SnapshotPipelineServiceOptions'|Hosting failed to start"; then
|
||||
printf 'Agent startup log contains a dependency-injection or host-start failure.\n' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
printf 'Agent host started; /health/live returned success; container remained running without restart.\n'
|
||||
printf 'Project: %s\nLocal image tag: %s\n' "$project" "$image_tag"
|
||||
@@ -14,6 +14,7 @@ Read `AGENTS.md`, the Toggle caméra #59/#199 Gitea issue, `skills/heimdall-dotn
|
||||
- `AppDbContext.SaveChangesAsync` publishes a payload-free config invalidation after camera/assignment/profile changes. Agent refetches its authorized full camera snapshot over its ConfigHub/API path and acknowledges the digest.
|
||||
- `GetEffectiveAgentConfigQuery` emits `camera.<id>.enabled` from the persisted status. `CameraConfigStore` atomically replaces the snapshot and raises `Changed`.
|
||||
- `SnapshotPipelineService` reconciles enabled assignments with `CameraStreamService`; disabling/removing an assignment kills FFmpeg, awaits its read loop cleanup and releases its stream permit. Enabling starts the stream. Keep central status authoritative; an Agent status report must not re-enable a disabled camera.
|
||||
- `SnapshotPipelineService` reconciles configuration on `CameraConfigStore.Changed`, while retaining a one-second config-change poll and the existing 30-second full resync as recovery. Coalesce notifications and ensure there is only one waiter on the config signal.
|
||||
- Camera counts and lists consider only Online cameras connected. An enabled Offline/Error camera remains enabled in the Agent configuration but is not counted as Online. UI toggle messages treat every status except Disabled as enabled.
|
||||
- Agent identity and API key are protected in `AgentState` under the configured state directory. Mount a project-scoped volume there so a restart reuses the same Agent identity and the Central configuration is refetched from persistent camera state.
|
||||
|
||||
@@ -31,6 +32,8 @@ These tests cover session idempotence, process termination, and synchronization
|
||||
|
||||
## Central + Agent disposable acceptance
|
||||
|
||||
Run `skills/camera-toggle-acceptance/acceptance.sh` from the repository root. It builds both application images from source, bootstraps synthetic Central/site/camera data, registers the real Agent container, repeats three ON/OFF cycles, checks the OFF PID bound, restarts Agent and Central while OFF, correlates the final applied config digest, and verifies exact project/tag cleanup in its EXIT trap.
|
||||
|
||||
- Build Central and Agent from this checkout with unique tags recorded before the first build. Retain upstream Postgres, MediaMTX, FFmpeg, SDK and ASP.NET base images.
|
||||
- Use a fresh project-scoped database, JWT/site credentials, loopback-only Central/Postgres ports, network and volumes. Add a project network Agent and a synthetic MediaMTX RTSP publisher. Do not use host networking or real camera credentials.
|
||||
- Bootstrap a synthetic Admin/site, create a camera pointed at the synthetic RTSP path, register the actual Agent container with the generated site token, and assign the camera to that Agent.
|
||||
@@ -46,7 +49,7 @@ This acceptance proves the source-built Central/Agent software lifecycle with a
|
||||
- Do not count `docker top` output when the runtime's `top` implementation differs. Prefer an in-container process identity check (`/proc/*/comm` equals `ffmpeg`) and ensure the inspection process cannot match itself. A shell command line containing the text `ffmpeg` creates a false positive if the check scans all command lines.
|
||||
- Before asserting lifecycle timing, first confirm Agent `Online`, persisted camera assignment, effective config enabled value and version, and `LastAppliedCameraConfigVersion` acknowledgement. A failed precondition is not an OFF/ON timing result.
|
||||
- On failed acceptance, collect sanitized Central, Agent, RTSP server and publisher diagnostics before the cleanup trap runs. Then verify project resource counts and exact image tags as described above.
|
||||
- Current disposable attempts proved bootstrap, registration, assignment and Disabled config acknowledgement, but have not yet proved toggle timing or restart persistence. Treat #59/#199 as open until a corrected process measurement completes the whole cycle.
|
||||
- Earlier disposable attempts proved bootstrap, registration, assignment and Disabled config acknowledgement, but did not prove toggle timing or restart persistence. The completed source-built run below supersedes those incomplete attempts; physical camera and deployed-host validation remain external.
|
||||
|
||||
## Latest source-built run
|
||||
|
||||
@@ -54,7 +57,15 @@ The fifth disposable Compose attempt used `/proc/*/comm == ffmpeg`, avoiding sel
|
||||
|
||||
## Sixth source-built run
|
||||
|
||||
The sixth run kept the FFmpeg process deadline separate from the config ACK deadline and verified exact initial digest equality between the Central config version and Agent `LastAppliedCameraConfigVersion`. It failed the OFF process bound: Central and Agent effective config both showed Disabled, but `/proc/*/comm` reached zero only after the two-second assertion timed out. No restart-OFF/persisted identity acceptance ran. Treat OFF <2 seconds and OFF restart persistence as unverified; investigate the measured delay before changing the acceptance threshold.
|
||||
The sixth historical run kept the FFmpeg process deadline separate from the config ACK deadline and verified exact initial digest equality between the Central config version and Agent `LastAppliedCameraConfigVersion`. It failed the OFF process bound and did not run restart-OFF acceptance. The subsequent 2026-11-12 acceptance below supersedes that incomplete result for current source.
|
||||
|
||||
## Immediate config reconciliation regression test
|
||||
|
||||
`SnapshotPipelineServiceTests.CameraConfigChanged_ReconcilesWithoutWaitingForPeriodicSync` starts the pipeline, lets its initial synchronization complete, then changes the Central snapshot and requires the assigned camera's Error report (FFmpeg deliberately unavailable) within 500ms. This proves event-driven reconciliation ahead of the one-second config-change poll and 30-second full resync; it does not prove process termination or the full camera lifecycle. Run it with the focused camera stream suite before Compose acceptance.
|
||||
|
||||
## Source-built acceptance — 2026-11-12
|
||||
|
||||
`acceptance.sh` passed with project `heimdall-157-1794488199-31533`, Central tag `heimdall:heimdall-157-1794488199-31533-central`, and Agent tag `heimdall-agent:heimdall-157-1794488199-31533-agent`. Central and PostgreSQL published only on `127.0.0.1`. After confirming the ON config digest ACK, it exercised three ON/OFF cycles with FFmpeg release at 1,386ms, 555ms, and 410ms, then a final OFF at 810ms before restart. Each transition verified the exact Central config digest ACK and expected `camera.<id>.enabled` value. The process monitor rejected counts above one. After Agent restart while OFF, the same Agent reported Online with a heartbeat and config ACK timestamp newer than the Compose restart command's return; after Central restart it again reported Online with a fresh ACK for the persisted Disabled digest newer than the restart command's return. Agent restart while ON preserved its identity and resumed capture. Cleanup verified zero project containers, volumes, and networks and absence of both exact local image tags. This is synthetic source-built software evidence, not camera hardware or deployed-host timing.
|
||||
|
||||
## Camera status contract acceptance
|
||||
|
||||
|
||||
+276
@@ -0,0 +1,276 @@
|
||||
#!/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
|
||||
@@ -45,7 +45,7 @@ For installer, Compose, image, and documentation work that can proceed independe
|
||||
|
||||
## Acceptance
|
||||
|
||||
Run `bash -n install/install-server.sh`, validate PowerShell syntax when `pwsh` is available, and run `docker compose config --quiet` for both the installer output and `docker/docker-compose.prod.yml`. Exercise a first install and a second run against an isolated temporary directory: confirm secrets and nondefault `.env` values are byte-for-byte unchanged, the old Compose is backed up, missing new variables are added once, and no volume removal command appears. For the Site Install UI, assert generated CPU/GPU Compose and `docker run` references use the signed `image@sha256:` digest, mount `/var/run/docker.sock`, and pass the socket group to the non-root Agent (`DOCKER_GID` in Compose; detected socket GID for Linux `docker run`). Then follow `skills/compose-disposable-recipe/SKILL.md` with a unique project, generated credentials, isolated ports/volumes, and an EXIT cleanup trap installed before build/start. Never connect the recipe to a deployed Docker daemon or production data.
|
||||
Run `bash -n install/install-server.sh`, validate PowerShell syntax when `pwsh` is available, and run `docker compose config --quiet` for both the installer output and `docker/docker-compose.prod.yml`. Exercise a first install and a second run against an isolated temporary directory: confirm secrets and nondefault `.env` values are byte-for-byte unchanged, the old Compose is backed up, missing new variables are added once, and no volume removal command appears. For the Site Install UI, assert generated CPU/GPU Compose and `docker run` references use the corresponding `:latest` Agent image, Compose sets `pull_policy: always`, Docker Run commands set `--pull always`, all paths mount `/var/run/docker.sock`, and the non-root Agent receives the socket group (`DOCKER_GID` in Compose; detected socket GID for Linux `docker run`). Keep signed digest validation for updates dispatched by Central. Then follow `skills/compose-disposable-recipe/SKILL.md` with a unique project, generated credentials, isolated ports/volumes, and an EXIT cleanup trap installed before build/start. Never connect the recipe to a deployed Docker daemon or production data.
|
||||
|
||||
When a runtime Dockerfile changes for OS security updates, source-build and health-check the corresponding Central/Agent image, then scan its saved image archive with the pinned Trivy version and the same `HIGH,CRITICAL` severities used by CI. Record the finding IDs and fixed package versions; do not hide a nonzero scan behind application acceptance.
|
||||
|
||||
|
||||
@@ -5,13 +5,13 @@ description: Keep installer-managed RustFS and coturn Compose services aligned w
|
||||
|
||||
# Installer-managed optional services
|
||||
|
||||
The Linux and Windows server installers run optional Compose files with the installation root as the current directory. They save service secrets in `optional/secrets/` and pass the root `.env` for interpolation. Therefore, Compose secret `file:` entries must use `./optional/secrets/<name>`, not `./secrets/<name>` or paths relative to `optional/`.
|
||||
The Linux and Windows server installers save service secrets in `<install-root>/optional/secrets/`, backup scripts in `<install-root>/optional/scripts/`, and pass the root `.env` for interpolation. Compose resolves relative paths from its project directory, which otherwise defaults to the directory containing the first `-f` file. RustFS and coturn Compose files reference `./optional/secrets/<name>`, so start them with `--project-directory <install-root>`. The backup Compose references `./scripts` and `./secrets/db_password`, so start it with `--project-directory <install-root>/optional`. Preserve these service-specific bases; applying the installation root to every optional Compose breaks the backup mounts.
|
||||
|
||||
## RustFS
|
||||
|
||||
- Keep `rustfs_access_key` and `rustfs_secret_key` file paths aligned with the generated files from both installers.
|
||||
- Installers create these bind-mounted secret files as owner-only (`0600`), which the official RustFS process (`10001:10001`) cannot read directly. Keep a short root initializer, copy the files into the service's private tmpfs, `chown` the copies to UID/GID 10001, then drop to the `rustfs` account before executing the upstream entrypoint. Keep the root filesystem read-only and provide tmpfs only for runtime paths that RustFS writes (`/logs`, `/tmp`, and its secret copies).
|
||||
- Verify Compose config from the install-root working directory and ensure Docker secrets are sourced from those files.
|
||||
- Verify actual optional-service invocations use the right project directory: `<install-root>` for RustFS/coturn and `<install-root>/optional` for backup. Confirm normalized secret and script bind sources point to exact generated files/directories. A successful `config` without checking normalized source paths is insufficient because Compose can accept an unintended path that happens to exist.
|
||||
- Keep the named data volume and shared `heimdall-net` behavior intact.
|
||||
|
||||
## coturn
|
||||
@@ -26,4 +26,4 @@ The Linux and Windows server installers run optional Compose files with the inst
|
||||
|
||||
## Acceptance
|
||||
|
||||
Run `skills/optional-server-services/acceptance.sh`. It creates a uniquely named disposable Compose project, generated owner-only secrets, an isolated install root, unique listener and relay ports, then validates Compose using that root. It verifies RustFS `/health`, signs a real S3 bucket-creation request with the generated keys, and runs `turnutils_uclient` inside the Compose network with TURN REST credentials. This proves local container-network allocation only; it does not prove external firewall/NAT reachability. The trap tears down only that project and verifies its containers, volumes, and networks are absent. The recipe builds no local images and retains upstream images.
|
||||
Run `skills/optional-server-services/acceptance.sh`. It creates a uniquely named disposable Compose project, generated owner-only secrets, an isolated install root, unique listener and relay ports, then validates Compose with each installer's explicit project directory. It asserts the normalized RustFS/coturn secret paths and backup secret/script bind sources exactly match the generated files before starting containers. It verifies RustFS `/health`, signs a real S3 bucket-creation request with the generated keys, and runs `turnutils_uclient` inside the Compose network with TURN REST credentials. This proves local container-network allocation only; it does not prove external firewall/NAT reachability. The trap tears down only that project and verifies its containers, volumes, and networks are absent. The recipe builds no local images and retains upstream images.
|
||||
@@ -7,13 +7,16 @@ project="heimdall-optional-services-${suffix}"
|
||||
temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")
|
||||
install_root="$temp_dir/install-root"
|
||||
secret_dir="$install_root/optional/secrets"
|
||||
backup_scripts_dir="$install_root/optional/scripts"
|
||||
env_file="$temp_dir/acceptance.env"
|
||||
override_file="$temp_dir/compose.override.yml"
|
||||
turn_log="$temp_dir/turn-client.log"
|
||||
rustfs_compose="$repo_root/docker/docker-compose.rustfs.yml"
|
||||
coturn_compose="$repo_root/docker/docker-compose.coturn.yml"
|
||||
backup_compose="$repo_root/docker/docker-compose.backup.yml"
|
||||
backup_scripts=(backup.sh backup-protected-data.sh backup-rustfs.sh restore.sh restore-protected-data.sh)
|
||||
local_image_tags=()
|
||||
mkdir -p "$secret_dir"
|
||||
mkdir -p "$secret_dir" "$backup_scripts_dir"
|
||||
|
||||
compose() {
|
||||
docker compose --project-directory "$install_root" --env-file "$env_file" \
|
||||
@@ -59,8 +62,11 @@ cleanup() {
|
||||
done
|
||||
rm -f -- "$env_file" "$override_file" "$turn_log" \
|
||||
"$secret_dir/rustfs_access_key" "$secret_dir/rustfs_secret_key" \
|
||||
"$secret_dir/coturn_secret" || cleanup_failed=1
|
||||
rmdir -- "$secret_dir" "$install_root/optional" "$install_root" || cleanup_failed=1
|
||||
"$secret_dir/coturn_secret" "$secret_dir/db_password" || cleanup_failed=1
|
||||
for name in "${backup_scripts[@]}"; do
|
||||
rm -f -- "$backup_scripts_dir/$name" || cleanup_failed=1
|
||||
done
|
||||
rmdir -- "$backup_scripts_dir" "$secret_dir" "$install_root/optional" "$install_root" || cleanup_failed=1
|
||||
rmdir -- "$temp_dir" || cleanup_failed=1
|
||||
if ((cleanup_failed)); then
|
||||
printf 'Disposable optional-service cleanup failed for %s\n' "$project" >&2
|
||||
@@ -116,6 +122,10 @@ coturn_username=acceptance
|
||||
printf '%s' "$rustfs_access_key" > "$secret_dir/rustfs_access_key"
|
||||
printf '%s' "$rustfs_secret_key" > "$secret_dir/rustfs_secret_key"
|
||||
printf '%s' "$coturn_secret" > "$secret_dir/coturn_secret"
|
||||
printf 'acceptance-db-password-%s' "$(od -An -N16 -tx1 /dev/urandom | tr -d ' \\n')" > "$secret_dir/db_password"
|
||||
for name in "${backup_scripts[@]}"; do
|
||||
cp "$repo_root/docker/scripts/$name" "$backup_scripts_dir/$name"
|
||||
done
|
||||
chmod 600 "$secret_dir"/*
|
||||
cat > "$env_file" <<EOF
|
||||
RUSTFS_API_PORT=$rustfs_api_port
|
||||
@@ -129,6 +139,7 @@ COTURN_USERNAME=$coturn_username
|
||||
RUSTFS_ACCESS_KEY=$rustfs_access_key
|
||||
RUSTFS_SECRET_KEY=$rustfs_secret_key
|
||||
ACCEPTANCE_NETWORK=${project}-heimdall-net
|
||||
HEIMDALL_DATA_VOLUME=${project}-heimdall-data
|
||||
EOF
|
||||
chmod 600 "$env_file"
|
||||
cat > "$override_file" <<'EOF'
|
||||
@@ -155,6 +166,35 @@ EOF
|
||||
|
||||
printf 'Disposable project: %s\nLocal images built: none\n' "$project"
|
||||
compose config --quiet
|
||||
compose config --format json | INSTALL_ROOT="$install_root" python3 -c '
|
||||
import json, os, sys
|
||||
config = json.load(sys.stdin)
|
||||
root = os.environ["INSTALL_ROOT"]
|
||||
expected = {
|
||||
"rustfs_access_key": os.path.join(root, "optional/secrets/rustfs_access_key"),
|
||||
"rustfs_secret_key": os.path.join(root, "optional/secrets/rustfs_secret_key"),
|
||||
"coturn_secret": os.path.join(root, "optional/secrets/coturn_secret"),
|
||||
}
|
||||
actual = {name: config["secrets"][name]["file"] for name in expected}
|
||||
if actual != expected:
|
||||
raise SystemExit("Compose secret bind mounts do not resolve under the installer root")
|
||||
print("Verified RustFS and coturn secret bind mounts resolve under the installer root.")
|
||||
'
|
||||
docker compose --project-directory "$install_root/optional" --env-file "$env_file" \
|
||||
-f "$backup_compose" --project-name "${project}-backup" config --format json |
|
||||
BACKUP_PROJECT_DIRECTORY="$install_root/optional" python3 -c '
|
||||
import json, os, sys
|
||||
config = json.load(sys.stdin)
|
||||
project_directory = os.environ["BACKUP_PROJECT_DIRECTORY"]
|
||||
expected_secret = os.path.join(project_directory, "secrets/db_password")
|
||||
expected_scripts = os.path.join(project_directory, "scripts")
|
||||
actual_secret = config["secrets"]["db_password"]["file"]
|
||||
scripts_mount = next((mount for mount in config["services"]["backup"]["volumes"]
|
||||
if mount.get("target") == "/scripts"), None)
|
||||
if actual_secret != expected_secret or scripts_mount is None or scripts_mount.get("source") != expected_scripts:
|
||||
raise SystemExit("Backup secret or script bind mounts do not resolve under optional/")
|
||||
print("Verified backup secret and scripts resolve under the installer optional directory.")
|
||||
'
|
||||
compose up -d rustfs coturn
|
||||
|
||||
base_url="http://127.0.0.1:$rustfs_api_port"
|
||||
|
||||
@@ -27,7 +27,7 @@ Heimdall's connected Penpot file is part of the UI source of truth. Whenever a c
|
||||
|
||||
## Installer design reference
|
||||
|
||||
The installer should follow the interaction hierarchy represented by `site-agent-installer-ui/SKILL.md`: platform choices, platform-specific method choices, optional configuration, then titled command cards with deliberate copy controls. For the current Agent installer, keep the design aligned with supported Linux, Windows, and Docker options, release signing/update-key gates, digest-pinned Docker image requirements, and the actual command builders. Keep desktop and mobile layouts, plus release-unavailable states, represented. Update the existing installer frame and any relevant variations in the connected file on every behavior or layout change.
|
||||
The installer should follow the interaction hierarchy represented by `site-agent-installer-ui/SKILL.md`: platform choices, platform-specific method choices, optional configuration, then titled command cards with deliberate copy controls. For the current Agent installer, keep the design aligned with supported Linux, Windows, and Docker options, release signing/update-key gates, Docker installation from the `latest` image tag, signed digest validation for updates dispatched by Central, and the actual command builders. Keep desktop and mobile layouts, plus release-unavailable states, represented. Update the existing installer frame and any relevant variations in the connected file on every behavior or layout change.
|
||||
|
||||
## Acceptance evidence
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ Keep the site Agent installer in `src/Heimdall.Web/Components/SiteInstallPanel.r
|
||||
|
||||
- Offer only Heimdall-supported platforms: Linux, Windows, and Docker. Keep method choices mapped in `AvailableMethods` and reset to that platform's sensible default in `SelectOperatingSystem`.
|
||||
- Keep generated command content in the existing builders and `Commands` projection. Platform selection controls the builders; do not duplicate generated commands in markup.
|
||||
- Native install commands require a latest signed release with update key, signed manifest, signature, and Agent archive assets. Docker commands additionally require a digest-pinned image reference and update key. Preserve these gates so the panel never offers a nonfunctional installer.
|
||||
- Native install commands require a latest signed release with update key, signed manifest, signature, and Agent archive assets. Docker commands additionally require verified CPU/GPU image metadata and the update key, but install the corresponding published `:latest` image. Generated Compose uses `pull_policy: always`; generated Docker Run commands use `--pull always`. Preserve signed digest validation for Agent updates dispatched later by Central.
|
||||
- Treat site tokens and generated configuration as secrets: show them only in the authenticated site's installer view and copy only after a deliberate click. Do not log generated content.
|
||||
- For live installer verification, use the authenticated Orca browser session. Check for the dedicated Heimdall login only in the user secret store at `~/.config/heimdall/credentials.json`; never put account passwords in this skill, repository config, shell arguments, or Orca `fill` commands. The file fallback is owner-only (`0700` directory, `0600` file) and base64-encoded, not encrypted. If it is absent, provide the user-run masked helper `~/.local/bin/store-heimdall-credentials`; do not report the credentials as persisted until that helper succeeds. If Orca has no safe autofill path, ask the user to enter the password in the visible browser.
|
||||
- Keep all visible strings in `SharedResources.resx`, `SharedResources.en.resx`, and `SharedResources.fr.resx`.
|
||||
|
||||
@@ -53,6 +53,7 @@ public sealed class SnapshotPipelineService : BackgroundService
|
||||
private readonly FrameResizer? _resizer;
|
||||
private readonly ILogger<SnapshotPipelineService> _logger;
|
||||
private readonly SemaphoreSlim _syncLock = new(1, 1);
|
||||
private readonly SemaphoreSlim _configChanged = new(0, 1);
|
||||
private readonly Dictionary<Guid, string> _streamUrls = new();
|
||||
private readonly ConcurrentDictionary<Guid, FrameMotionDetector> _motionDetectors = new();
|
||||
private readonly ConcurrentDictionary<Guid, SceneState> _reportedSceneState = new();
|
||||
@@ -154,8 +155,18 @@ public sealed class SnapshotPipelineService : BackgroundService
|
||||
// (e.g. camera settings applied before we subscribed).
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken);
|
||||
if (Interlocked.Exchange(ref _configDirty, 0) != 0 || DateTime.UtcNow.Second % 30 == 0)
|
||||
var periodicSyncDue = false;
|
||||
using (var wait = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken))
|
||||
{
|
||||
wait.CancelAfter(TimeSpan.FromSeconds(1));
|
||||
try { await _configChanged.WaitAsync(wait.Token); }
|
||||
catch (OperationCanceledException) when (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
periodicSyncDue = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (Interlocked.Exchange(ref _configDirty, 0) != 0 || periodicSyncDue && DateTime.UtcNow.Second % 30 == 0)
|
||||
await SyncStreamsAsync(stoppingToken);
|
||||
}
|
||||
}
|
||||
@@ -181,6 +192,8 @@ public sealed class SnapshotPipelineService : BackgroundService
|
||||
private void OnCameraConfigChanged(object? sender, EventArgs e)
|
||||
{
|
||||
Interlocked.Exchange(ref _configDirty, 1);
|
||||
try { _configChanged.Release(); }
|
||||
catch (SemaphoreFullException) { }
|
||||
}
|
||||
|
||||
private async Task SyncStreamsAsync(CancellationToken ct)
|
||||
|
||||
@@ -246,15 +246,15 @@ else if (_method == "windows-service")
|
||||
release?.Assets.Count > 0;
|
||||
if (!string.IsNullOrWhiteSpace(release?.ContainerImage) &&
|
||||
!string.IsNullOrWhiteSpace(release.ContainerImageDigest))
|
||||
_agentImageReference = $"{release.ContainerImage}@{release.ContainerImageDigest}";
|
||||
_agentImageReference = LatestImageReference(release.ContainerImage);
|
||||
if (!string.IsNullOrWhiteSpace(release?.ContainerImageGpu) &&
|
||||
!string.IsNullOrWhiteSpace(release.ContainerImageGpuDigest))
|
||||
_agentGpuImageReference = $"{release.ContainerImageGpu}@{release.ContainerImageGpuDigest}";
|
||||
_agentGpuImageReference = LatestImageReference(release.ContainerImageGpu);
|
||||
_updatePublicKeyPem = release?.UpdatePublicKeyPem;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Native installers fetch signed release metadata directly; Docker needs a verified image reference and key.
|
||||
// Native installers fetch signed release metadata directly; Docker needs verified image metadata and key.
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -262,6 +262,14 @@ else if (_method == "windows-service")
|
||||
}
|
||||
}
|
||||
|
||||
private static string LatestImageReference(string image)
|
||||
{
|
||||
var lastSlash = image.LastIndexOf('/');
|
||||
var lastColon = image.LastIndexOf(':');
|
||||
var repository = lastColon > lastSlash ? image[..lastColon] : image;
|
||||
return $"{repository}:latest";
|
||||
}
|
||||
|
||||
private string ComposeYaml
|
||||
{
|
||||
get
|
||||
@@ -277,6 +285,7 @@ else if (_method == "windows-service")
|
||||
services:
|
||||
heimdall-agent:
|
||||
image: {{image}}
|
||||
pull_policy: always
|
||||
container_name: heimdall-agent-{{safeName}}
|
||||
restart: unless-stopped
|
||||
user: "1654:1654"
|
||||
@@ -307,6 +316,7 @@ else if (_method == "windows-service")
|
||||
|
||||
agent-state-init:
|
||||
image: {{image}}
|
||||
pull_policy: always
|
||||
user: "0:0"
|
||||
entrypoint: ["chown", "-R", "1654:1654", "/state"]
|
||||
volumes:
|
||||
@@ -337,7 +347,7 @@ else if (_method == "windows-service")
|
||||
var name = "heimdall-agent-" + Slugify(SiteName);
|
||||
var volume = "heimdall-agent-state-" + Slugify(SiteName);
|
||||
var image = _useGpuImage ? _agentGpuImageReference : _agentImageReference;
|
||||
return $"docker run -d --name {name} --restart unless-stopped --network host --user 1654:1654 " +
|
||||
return $"docker run --pull always -d --name {name} --restart unless-stopped --network host --user 1654:1654 " +
|
||||
(_useGpuImage ? "--gpus all " : "") +
|
||||
"--group-add \"$(stat -c '%g' /var/run/docker.sock)\" " +
|
||||
"-v /var/run/docker.sock:/var/run/docker.sock " +
|
||||
@@ -370,7 +380,7 @@ else if (_method == "windows-service")
|
||||
var name = "heimdall-agent-" + Slugify(SiteName);
|
||||
var volume = "heimdall-agent-state-" + Slugify(SiteName);
|
||||
var image = _useGpuImage ? _agentGpuImageReference : _agentImageReference;
|
||||
var args = new List<string> { "run", "-d", "--name", name, "--restart", "unless-stopped", "--user", "1654:1654", "--publish", "127.0.0.1:8081:8080", "--group-add", "0", "-v", "/var/run/docker.sock:/var/run/docker.sock" };
|
||||
var args = new List<string> { "run", "--pull", "always", "-d", "--name", name, "--restart", "unless-stopped", "--user", "1654:1654", "--publish", "127.0.0.1:8081:8080", "--group-add", "0", "-v", "/var/run/docker.sock:/var/run/docker.sock" };
|
||||
if (_useGpuImage) args.AddRange(["--gpus", "all"]);
|
||||
args.AddRange([
|
||||
"-e", "Agent__CentralUrl=" + CentralUrl,
|
||||
|
||||
@@ -4078,7 +4078,7 @@
|
||||
<value>Check</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_DockerUpdateNote" xml:space="preserve">
|
||||
<value>Container updates use Docker or Kubernetes. Heimdall pins each image to its signed digest. Docker mode mounts the host Docker socket, giving the Agent broad control of that host. On Linux, before Compose, set DOCKER_GID to the socket GID: export DOCKER_GID="$(stat -c '%g' /var/run/docker.sock)".</value>
|
||||
<value>Docker installation uses the latest image. Updates dispatched by Central verify the signed digest before replacing the Agent. Docker mode mounts the host Docker socket, giving the Agent broad control of that host. On Linux, before Compose, set DOCKER_GID to the socket GID: export DOCKER_GID="$(stat -c '%g' /var/run/docker.sock)".</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_WindowsConsoleNote" xml:space="preserve">
|
||||
<value>The Agent starts in the background so you can check it from this PowerShell session. Choose Windows Service to restart it after logoff or reboot.</value>
|
||||
|
||||
@@ -4078,7 +4078,7 @@
|
||||
<value>Vérifier</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_DockerUpdateNote" xml:space="preserve">
|
||||
<value>Les mises à jour des conteneurs passent par Docker ou Kubernetes. Heimdall épingle chaque image sur son digest signé. Le mode Docker monte le socket Docker de l’hôte, ce qui donne à l’Agent un contrôle étendu sur cet hôte. Sous Linux, avant Compose, définissez DOCKER_GID avec le GID du socket : export DOCKER_GID="$(stat -c '%g' /var/run/docker.sock)".</value>
|
||||
<value>L’installation Docker utilise l’image latest. Les mises à jour déclenchées par Central vérifient le digest signé avant de remplacer l’Agent. Le mode Docker monte le socket Docker de l’hôte, ce qui donne à l’Agent un contrôle étendu sur cet hôte. Sous Linux, avant Compose, définissez DOCKER_GID avec le GID du socket : export DOCKER_GID="$(stat -c '%g' /var/run/docker.sock)".</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_WindowsConsoleNote" xml:space="preserve">
|
||||
<value>L’Agent démarre en arrière-plan pour permettre la vérification depuis cette console. Le mode Service Windows le relance après fermeture de session ou redémarrage.</value>
|
||||
|
||||
@@ -4078,7 +4078,7 @@
|
||||
<value>Check</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_DockerUpdateNote" xml:space="preserve">
|
||||
<value>Container updates use Docker or Kubernetes. Heimdall pins each image to its signed digest. Docker mode mounts the host Docker socket, giving the Agent broad control of that host. On Linux, before Compose, set DOCKER_GID to the socket GID: export DOCKER_GID="$(stat -c '%g' /var/run/docker.sock)".</value>
|
||||
<value>Docker installation uses the latest image. Updates dispatched by Central verify the signed digest before replacing the Agent. Docker mode mounts the host Docker socket, giving the Agent broad control of that host. On Linux, before Compose, set DOCKER_GID to the socket GID: export DOCKER_GID="$(stat -c '%g' /var/run/docker.sock)".</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_WindowsConsoleNote" xml:space="preserve">
|
||||
<value>The Agent starts in the background so you can check it from this PowerShell session. Choose Windows Service to restart it after logoff or reboot.</value>
|
||||
|
||||
@@ -9,7 +9,7 @@ public class SnapshotPipelineServiceTests
|
||||
{
|
||||
private const string FfmpegNotFound = "/usr/bin/nonexistent-ffmpeg";
|
||||
|
||||
private static (SnapshotPipelineService Service, AgentState State, CameraConfigStore Store, CameraStreamService Streams, FrameAnalyzerService Analyzer) CreatePipeline(
|
||||
private static (SnapshotPipelineService Service, AgentState State, CameraConfigStore Store, CameraStreamService Streams, FrameAnalyzerService Analyzer, ICameraStatusReporter StatusReporter) CreatePipeline(
|
||||
List<AgentCameraOptions>? cameras = null,
|
||||
AnalysisMode analysisMode = AnalysisMode.Local,
|
||||
string? brokerUrl = null)
|
||||
@@ -34,13 +34,13 @@ public class SnapshotPipelineServiceTests
|
||||
state, options, store, streams, analyzer, new SceneStateTracker(), statusReporter, detectionReporter,
|
||||
Substitute.For<ILogger<SnapshotPipelineService>>(),
|
||||
DegradationManager: degradationManager, Metrics: metrics));
|
||||
return (service, state, store, streams, analyzer);
|
||||
return (service, state, store, streams, analyzer, statusReporter);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartStop_WithoutRegistration_StopsGracefully()
|
||||
{
|
||||
var (service, state, _, _, _) = CreatePipeline();
|
||||
var (service, state, _, _, _, _) = CreatePipeline();
|
||||
state.AgentId = Guid.Empty; // never registered
|
||||
|
||||
await service.StartAsync(CancellationToken.None);
|
||||
@@ -52,7 +52,7 @@ public class SnapshotPipelineServiceTests
|
||||
[Fact]
|
||||
public async Task StartStop_WithNoCameras_DoesNotStartStreams()
|
||||
{
|
||||
var (service, _, _, streams, _) = CreatePipeline();
|
||||
var (service, _, _, streams, _, _) = CreatePipeline();
|
||||
await service.StartAsync(CancellationToken.None);
|
||||
try
|
||||
{
|
||||
@@ -72,7 +72,7 @@ public class SnapshotPipelineServiceTests
|
||||
{
|
||||
new() { Name = "Cam 1", RtspUrl = "rtsp://cam1/stream" },
|
||||
};
|
||||
var (service, _, store, streams, _) = CreatePipeline(cameras);
|
||||
var (service, _, store, streams, _, _) = CreatePipeline(cameras);
|
||||
|
||||
await service.StartAsync(CancellationToken.None);
|
||||
try
|
||||
@@ -93,10 +93,45 @@ public class SnapshotPipelineServiceTests
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CameraConfigChanged_ReconcilesWithoutWaitingForPeriodicSync()
|
||||
{
|
||||
var (service, _, store, streams, _, statusReporter) = CreatePipeline();
|
||||
var cameraId = Guid.NewGuid();
|
||||
await service.StartAsync(CancellationToken.None);
|
||||
try
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(1100));
|
||||
statusReporter.ClearReceivedCalls();
|
||||
store.ReplaceCentral(new Dictionary<string, string>
|
||||
{
|
||||
[$"camera.{cameraId}.enabled"] = "true",
|
||||
[$"camera.{cameraId}.rtsp"] = "rtsp://camera/test",
|
||||
});
|
||||
|
||||
// The full periodic resync runs every 30 seconds. A config event
|
||||
// must instead reconcile this transition on the event signal.
|
||||
var deadline = DateTime.UtcNow.AddMilliseconds(500);
|
||||
while (DateTime.UtcNow < deadline && !statusReporter.ReceivedCalls().Any())
|
||||
await Task.Delay(10);
|
||||
|
||||
streams.ActiveStreamCount.ShouldBe(0); // FFmpeg is intentionally absent.
|
||||
// Error is reported only after the enabled assignment is reconciled.
|
||||
statusReporter.ReceivedCalls().Any(call =>
|
||||
call.GetMethodInfo().Name == nameof(ICameraStatusReporter.ReportAsync) &&
|
||||
Equals(call.GetArguments()[0], cameraId) &&
|
||||
Equals(call.GetArguments()[1], "Error")).ShouldBeTrue();
|
||||
}
|
||||
finally
|
||||
{
|
||||
await service.StopAsync(CancellationToken.None);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SnapshotWrittenToChannel_IsForwardedToAnalyzer()
|
||||
{
|
||||
var (service, _, store, streams, analyzer) = CreatePipeline();
|
||||
var (service, _, store, streams, analyzer, _) = CreatePipeline();
|
||||
var id = Guid.NewGuid();
|
||||
store.ReplaceCentral(new Dictionary<string, string>
|
||||
{
|
||||
@@ -128,7 +163,7 @@ public class SnapshotPipelineServiceTests
|
||||
[Fact]
|
||||
public async Task StopAsync_WithoutStart_DoesNotThrow()
|
||||
{
|
||||
var (service, _, _, _, _) = CreatePipeline();
|
||||
var (service, _, _, _, _, _) = CreatePipeline();
|
||||
await service.StopAsync(CancellationToken.None);
|
||||
service.ShouldNotBeNull();
|
||||
}
|
||||
@@ -136,7 +171,7 @@ public class SnapshotPipelineServiceTests
|
||||
[Fact]
|
||||
public void IsRemoteMode_LocalMode_ReturnsFalse()
|
||||
{
|
||||
var (service, _, _, _, _) = CreatePipeline(analysisMode: AnalysisMode.Local);
|
||||
var (service, _, _, _, _, _) = CreatePipeline(analysisMode: AnalysisMode.Local);
|
||||
service.IsRemoteMode.ShouldBeFalse();
|
||||
}
|
||||
|
||||
@@ -144,14 +179,14 @@ public class SnapshotPipelineServiceTests
|
||||
public void IsRemoteMode_RemoteMode_NoBroker_ReturnsFalse()
|
||||
{
|
||||
// Remote mode but no broker service injected → not actually remote
|
||||
var (service, _, _, _, _) = CreatePipeline(analysisMode: AnalysisMode.Remote);
|
||||
var (service, _, _, _, _, _) = CreatePipeline(analysisMode: AnalysisMode.Remote);
|
||||
service.IsRemoteMode.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RemoteSubmissions_InitiallyZero()
|
||||
{
|
||||
var (service, _, _, _, _) = CreatePipeline();
|
||||
var (service, _, _, _, _, _) = CreatePipeline();
|
||||
service.RemoteSubmissions.ShouldBe(0);
|
||||
service.RemoteFallbacks.ShouldBe(0);
|
||||
}
|
||||
|
||||
@@ -82,7 +82,8 @@ public class SiteDetailTests : PageTestBase
|
||||
cut.Markup.ShouldContain("Agent__SiteToken");
|
||||
cut.Markup.ShouldContain("Régénérer");
|
||||
var compose = cut.Find("pre code").TextContent;
|
||||
compose.ShouldContain("registry.example/heimdall-agent@sha256:");
|
||||
compose.ShouldContain("image: registry.example/heimdall-agent:latest");
|
||||
compose.ShouldContain("pull_policy: always");
|
||||
compose.ShouldContain("network_mode: host");
|
||||
compose.ShouldContain("Agent__CentralUrl: \"http://localhost\"");
|
||||
compose.ShouldContain("Agent__SiteToken: \"tok-detail-42\"");
|
||||
@@ -93,6 +94,9 @@ public class SiteDetailTests : PageTestBase
|
||||
compose.ShouldNotContain("ollama");
|
||||
var agent = GetAgentService(ParseCompose(compose));
|
||||
agent.Children.ShouldNotContainKey(new YamlScalarNode("deploy"));
|
||||
((YamlScalarNode)agent.Children[new YamlScalarNode("image")]).Value
|
||||
.ShouldBe("registry.example/heimdall-agent:latest");
|
||||
((YamlScalarNode)agent.Children[new YamlScalarNode("pull_policy")]).Value.ShouldBe("always");
|
||||
var volumes = (YamlSequenceNode)agent.Children[new YamlScalarNode("volumes")];
|
||||
volumes.Children.Select(node => ((YamlScalarNode)node).Value)
|
||||
.ShouldContain("/var/run/docker.sock:/var/run/docker.sock");
|
||||
@@ -102,6 +106,19 @@ public class SiteDetailTests : PageTestBase
|
||||
var environment = (YamlMappingNode)agent.Children[new YamlScalarNode("environment")];
|
||||
((YamlScalarNode)environment.Children[new YamlScalarNode("Agent__InferenceExecutionProvider")]).Value.ShouldBe("CPU");
|
||||
});
|
||||
|
||||
cut.FindAll("button").Single(b => b.TextContent.Contains("Docker Run", StringComparison.OrdinalIgnoreCase)).Click();
|
||||
cut.WaitForAssertion(() =>
|
||||
{
|
||||
var commands = cut.FindAll("pre code").Select(code => code.TextContent).ToArray();
|
||||
commands.Length.ShouldBe(6);
|
||||
commands[0].ShouldContain("docker pull registry.example/heimdall-agent:latest");
|
||||
commands[1].ShouldContain("--pull always");
|
||||
commands[1].ShouldContain("registry.example/heimdall-agent:latest");
|
||||
commands[3].ShouldContain("docker pull 'registry.example/heimdall-agent:latest'");
|
||||
commands[4].ShouldContain("'--pull','always'");
|
||||
commands[4].ShouldContain("'registry.example/heimdall-agent:latest'");
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -143,14 +160,16 @@ public class SiteDetailTests : PageTestBase
|
||||
cut.WaitForAssertion(() =>
|
||||
{
|
||||
var compose = cut.Find("pre code").TextContent;
|
||||
compose.ShouldContain("image: registry.example/heimdall-agent-gpu@sha256:" + new string('b', 64));
|
||||
compose.ShouldContain("image: registry.example/heimdall-agent-gpu:latest");
|
||||
compose.ShouldContain("pull_policy: always");
|
||||
compose.ShouldContain("Agent__InferenceExecutionProvider: CUDA");
|
||||
compose.ShouldContain("driver: nvidia");
|
||||
compose.ShouldContain("capabilities: [gpu]");
|
||||
compose.ShouldContain("\n deploy:\n resources:\n reservations:");
|
||||
var agent = GetAgentService(ParseCompose(compose));
|
||||
((YamlScalarNode)agent.Children[new YamlScalarNode("image")]).Value.ShouldBe(
|
||||
"registry.example/heimdall-agent-gpu@sha256:" + new string('b', 64));
|
||||
"registry.example/heimdall-agent-gpu:latest");
|
||||
((YamlScalarNode)agent.Children[new YamlScalarNode("pull_policy")]).Value.ShouldBe("always");
|
||||
var deploy = (YamlMappingNode)agent.Children[new YamlScalarNode("deploy")];
|
||||
var resources = (YamlMappingNode)deploy.Children[new YamlScalarNode("resources")];
|
||||
var reservations = (YamlMappingNode)resources.Children[new YamlScalarNode("reservations")];
|
||||
@@ -165,9 +184,12 @@ public class SiteDetailTests : PageTestBase
|
||||
var run = commands[1];
|
||||
run.ShouldContain("--gpus all");
|
||||
run.ShouldContain("Agent__InferenceExecutionProvider=CUDA");
|
||||
run.ShouldContain("registry.example/heimdall-agent-gpu@sha256:" + new string('b', 64));
|
||||
run.ShouldContain("--pull always");
|
||||
run.ShouldContain("registry.example/heimdall-agent-gpu:latest");
|
||||
run.ShouldContain("--group-add \"$(stat -c '%g' /var/run/docker.sock)\"");
|
||||
run.ShouldContain("-v /var/run/docker.sock:/var/run/docker.sock");
|
||||
commands[4].ShouldContain("'--pull','always'");
|
||||
commands[4].ShouldContain("'registry.example/heimdall-agent-gpu:latest'");
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user