refactor(docker): separate core and optional compose services #114

Merged
arnaud.dartois merged 3 commits from refactor/compose-core-optional-services into main 2026-10-26 07:13:40 +01:00
33 changed files with 560 additions and 821 deletions

No files matched your search

+11 -23
View File
@@ -1,18 +1,19 @@
# ─── Heimdall — Environment Variables ──────────────────────────────
# Copy this file to .env and adjust for your deployment
# Development examples only. Copy to docker/.env for a local deployment.
# Never commit real values; docker/.env and docker/secrets/ are ignored by Git.
#
# The heimdall service serves the Blazor UI, REST API, SignalR hubs,
# and Hangfire background jobs in a single process on port 5000.
#
# PRODUCTION: Use Docker secrets (docker/secrets/) for sensitive values.
# See docker-compose.prod.yml header for instructions.
# Production core is PostgreSQL + Central. Use docker/secrets/db_password for
# the database and set JWT keys only in the host environment or ignored env file.
# Install Agents from the digest-pinned Compose supplied by Central's UI.
# Development example only: replace all credentials before exposure.
# Database
POSTGRES_PASSWORD=heimdall
DATABASE_URL=Host=postgresql;Port=5432;Database=heimdall;Username=heimdall;Password=heimdall
SERVER_IMAGE_REFERENCE=eltruncho/heimdall:latest
UPDATES_RELEASE_API_URL=https://sources.tordais.cc/api/v1/repos/arnaud.dartois/Heimdall/releases/latest
# Set SERVER_IMAGE_REFERENCE from docker/server-image.json before production deployment.
# JWT (change in production!)
# JWT__Key is used for access tokens, JWT__RefreshKey for refresh tokens.
@@ -41,30 +42,17 @@ RUSTFS_BUCKET=heimdall
# Primary: Sentry__Dsn (ASP.NET Core config convention)
# Fallback: SENTRY_DSN (legacy, for backward compatibility)
# When unset/empty, the Sentry SDK is not initialized (graceful no-op).
Sentry__Dsn=https://db94b9...dc73@glitchtip.tordais.cc/6
Sentry__TracesSampleRate=0.05
Sentry__Release=heimdall@1.0.0
SENTRY_DSN=
SENTRY_TRACES_SAMPLE_RATE=0.05
SENTRY_RELEASE=heimdall@1.0.0
# Agent (set per agent instance)
# Agent (for local development only; production Compose is supplied by Central)
HEIMDALL_CENTRAL_URL=http://localhost:5000
HEIMDALL_SITE_TOKEN=replace-with-actual-token
HEIMDALL_AGENT_NAME=agent-01
HEIMDALL_HEARTBEAT_INTERVAL=30
HEIMDALL_REGISTRATION_RETRIES=5
# Email (SMTP) — notifications
EMAIL__SMTP_HOST=smtp.example.com
EMAIL__SMTP_PORT=587
EMAIL__USERNAME=
EMAIL__PASSWORD=
EMAIL__FROM_ADDRESS=noreply@heimdall.local
EMAIL__FROM_NAME=Heimdall
EMAIL__USE_SSL=true
# ntfy push notifications
NTFY__BASE_URL=http://ntfy:80
NTFY__TOKEN=
# Coturn (TURN relay for WebRTC)
COTURN_SECRET=ChangeMeAtLeast32BytesLongCoturnSecret!
COTURN_REALM=heimdall.local
@@ -74,4 +62,4 @@ OLLAMA_PORT=11434
# Redis (SignalR backplane, optional — scaling)
REDIS_PORT=6379
REDIS_PASSWORD=
REDIS_PASSWORD=replace-with-a-long-unique-password
+18 -12
View File
@@ -1,6 +1,6 @@
# ─── Heimdall — Development & Deployment ──────────────────────────
.DEFAULT_GOAL := help
.PHONY: help build test test-watch clean docker-up docker-down docker-build docker-logs docker-ps docker-reset deploy version version-tag version-tag-agent migration-add migration-remove dev-api dev-web backup backup-rustfs restore restore-file backup-test backup-up backup-down backup-logs
.PHONY: help build test test-watch clean docker-up docker-down docker-build docker-logs docker-ps docker-reset docker-agent-up docker-agent-down deploy version version-tag version-tag-agent migration-add migration-remove dev-api dev-web backup backup-rustfs restore restore-file backup-test backup-up backup-down backup-logs
help: ## Show this help
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | \
@@ -20,23 +20,29 @@ clean: ## Clean build artifacts
# ─── Docker ──────────────────────────────────────────────────────
docker-up: ## Start all services (dev)
docker compose -f docker/docker-compose.yml up -d
docker-up: ## Start Central and PostgreSQL (dev)
docker compose --env-file docker/.env -f docker/docker-compose.yml up -d
docker-down: ## Stop all services
docker compose -f docker/docker-compose.yml down
docker compose --env-file docker/.env -f docker/docker-compose.yml down
docker-build: ## Rebuild images without cache
docker compose -f docker/docker-compose.yml build --no-cache
docker compose --env-file docker/.env -f docker/docker-compose.yml build --no-cache
docker-logs: ## Tail logs
docker compose -f docker/docker-compose.yml logs -f
docker compose --env-file docker/.env -f docker/docker-compose.yml logs -f
docker-ps: ## List running services
docker compose -f docker/docker-compose.yml ps
docker compose --env-file docker/.env -f docker/docker-compose.yml ps
docker-reset: ## Stop and remove everything
docker compose -f docker/docker-compose.yml down -v --rmi all
docker-reset: ## Stop Central and PostgreSQL and remove their volumes
docker compose --env-file docker/.env -f docker/docker-compose.yml down -v --rmi all
docker-agent-up: ## Build and start a local Agent (set HEIMDALL_SITE_TOKEN)
docker compose --env-file docker/.env -f docker/docker-compose.agent.dev.yml up -d --build
docker-agent-down: ## Stop the local Agent
docker compose --env-file docker/.env -f docker/docker-compose.agent.dev.yml down
# ─── Deployment ──────────────────────────────────────────────────
@@ -110,10 +116,10 @@ backup-test: ## Run backup/restore E2E test (isolated PostgreSQL)
./docker/scripts/test-backup-restore.sh
backup-up: ## Start backup cron service (daily PG + weekly RustFS mirror)
docker compose -f docker/docker-compose.yml -f docker/docker-compose.backup.yml up -d backup
docker compose --env-file docker/.env -f docker/docker-compose.backup.yml up -d
backup-down: ## Stop backup cron service
docker compose -f docker/docker-compose.yml -f docker/docker-compose.backup.yml down backup
docker compose --env-file docker/.env -f docker/docker-compose.backup.yml down
backup-logs: ## Tail backup service logs
docker compose -f docker/docker-compose.yml -f docker/docker-compose.backup.yml logs -f backup
docker compose --env-file docker/.env -f docker/docker-compose.backup.yml logs -f backup
+7 -14
View File
@@ -12,24 +12,17 @@ Sauvegarde automatisée de PostgreSQL (quotidien) et RustFS/S3 (hebdomadaire) av
## Activation
### Option 1 — Overlay docker-compose (recommandé)
### Compose facultatif séparé
```bash
cd docker/
docker compose -f docker-compose.yml -f docker-compose.backup.yml up -d
docker compose --env-file .env -f docker-compose.backup.yml up -d
```
Le service `backup` tourne dans un conteneur PostgreSQL 17-alpine avec crontab interne.
Les dumps sont stockés dans le volume `backup_data` et uploadés vers RustFS/S3 si configuré.
### Option 2 — Profil dans docker-compose.prod.yml
```bash
cd docker/
docker compose --profile backup -f docker-compose.prod.yml up -d
```
Le service backup est activé via le profil Docker Compose `backup`.
Le Central et PostgreSQL doivent d'abord être démarrés. Le service `backup`
rejoint le réseau partagé et tourne dans un conteneur PostgreSQL 17-alpine
avec crontab interne. Les dumps sont stockés dans `backup_data`; l'upload
RustFS/S3 est facultatif.
## Variables d'environnement
@@ -39,7 +32,7 @@ Le service backup est activé via le profil Docker Compose `backup`.
| `POSTGRES_PORT` | `5432` | Port PostgreSQL |
| `POSTGRES_DB` | `heimdall` | Nom de la base |
| `POSTGRES_USER` | `heimdall` | Utilisateur PostgreSQL |
| `POSTGRES_PASSWORD` | `heimdall` | Mot de passe PostgreSQL |
| `docker/secrets/db_password` | fichier hôte requis | Mot de passe PostgreSQL partagé avec le Compose Central |
| `RUSTFS_ENDPOINT` | `http://rustfs:9000` (Compose) | Endpoint S3/RustFS |
| `RUSTFS_ACCESS_KEY` | — | Clé d'accès S3 |
| `RUSTFS_SECRET_KEY` | — | Clé secrète S3 |
+43
View File
@@ -0,0 +1,43 @@
# Local standalone Agent for development. The Central must be running first.
services:
heimdall-agent:
image: heimdall-agent:local
build:
context: ..
dockerfile: docker/Dockerfile.agent
restart: unless-stopped
user: "1654:1654"
network_mode: host
environment:
ASPNETCORE_URLS: http://127.0.0.1:8081
Agent__CentralUrl: ${HEIMDALL_CENTRAL_URL:-http://localhost:5000}
Agent__AllowInsecureHttp: "true"
Agent__SiteToken: ${HEIMDALL_SITE_TOKEN:?HEIMDALL_SITE_TOKEN is required}
Agent__AgentName: ${HEIMDALL_AGENT_NAME:-agent-dev}
Agent__HeartbeatIntervalSeconds: ${HEIMDALL_HEARTBEAT_INTERVAL:-30}
Agent__StateDirectory: /var/lib/heimdall
volumes:
- agent_state:/var/lib/heimdall
healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://127.0.0.1:8081/healthz"]
interval: 30s
timeout: 5s
retries: 3
start_period: 15s
depends_on:
agent-state-init:
condition: service_completed_successfully
agent-state-init:
image: heimdall-agent:local
build:
context: ..
dockerfile: docker/Dockerfile.agent
user: "0:0"
entrypoint: ["chown", "-R", "1654:1654", "/state"]
volumes:
- agent_state:/state
restart: "no"
volumes:
agent_state:
+23 -42
View File
@@ -1,70 +1,51 @@
# ─── Heimdall — Backup Cron Service ──────────────────────────────
# Overlay for docker-compose.yml: adds a cron container that runs
# PostgreSQL backups daily and RustFS mirrors weekly.
#
# Usage:
# docker compose -f docker/docker-compose.yml -f docker/docker-compose.backup.yml up -d
#
# The cron service mounts the scripts directory and a backup volume.
# PostgreSQL dumps are uploaded to RustFS/S3 when configured.
#
# Requires: .env with DATABASE_URL, S3 credentials (optional for local-only backups)
# ──────────────────────────────────────────────────────────────────
# Optional scheduled backup container. Requires the core PostgreSQL service
# and its shared heimdall-net to be running first.
services:
backup:
image: postgres:17-alpine
container_name: heimdall-backup
restart: unless-stopped
environment:
# Pass through all env vars needed by backup scripts
POSTGRES_HOST: postgresql
POSTGRES_PORT: "5432"
POSTGRES_DB: ${POSTGRES_DB:-heimdall}
POSTGRES_USER: ${POSTGRES_USER:-heimdall}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required}
# S3/RustFS config (optional — backup works local-only without these)
POSTGRES_PASSWORD_FILE: /run/secrets/db_password
RUSTFS_ENDPOINT: ${RUSTFS_ENDPOINT:-http://rustfs:9000}
RUSTFS_ACCESS_KEY: ${RUSTFS_ACCESS_KEY:-${S3_ACCESS_KEY:-}}
RUSTFS_SECRET_KEY: ${RUSTFS_SECRET_KEY:-${S3_SECRET_KEY:-}}
RUSTFS_BUCKET: ${RUSTFS_BUCKET:-${S3_BUCKET:-heimdall}}
# Backup config
RUSTFS_ACCESS_KEY: ${RUSTFS_ACCESS_KEY:-}
RUSTFS_SECRET_KEY: ${RUSTFS_SECRET_KEY:-}
RUSTFS_BUCKET: ${RUSTFS_BUCKET:-heimdall}
BACKUP_RETENTION_DAYS: ${BACKUP_RETENTION_DAYS:-30}
BACKUP_RETENTION_WEEKS: ${BACKUP_RETENTION_WEEKS:-12}
BACKUP_LOCAL_DIR: /backups
# Timezone
TZ: Europe/Paris
TZ: ${TZ:-Europe/Paris}
secrets:
- db_password
volumes:
- ./scripts:/scripts:ro
- backup_data:/backups
depends_on:
postgresql:
condition: service_healthy
networks:
- heimdall-net
entrypoint: ["/bin/sh", "-c"]
command:
- |
# Install mc (MinIO client) for S3 uploads
apk add --no-cache curl bash > /dev/null 2>&1 || true
curl -sSL https://dl.min.io/client/mc/release/linux-amd64/mc -o /usr/local/bin/mc 2>/dev/null || true
export POSTGRES_PASSWORD="$$(cat /run/secrets/db_password)"
apk add --no-cache curl bash >/dev/null 2>&1 || true
curl -fsSL https://dl.min.io/client/mc/release/linux-amd64/mc -o /usr/local/bin/mc || true
chmod +x /usr/local/bin/mc 2>/dev/null || true
chmod +x /scripts/*.sh
# Create crontab
echo "# Daily PostgreSQL backup at 02:00 UTC" > /tmp/crontab.txt
echo "0 2 * * * /scripts/backup.sh >> /var/log/backup.log 2>&1" >> /tmp/crontab.txt
echo "# Weekly RustFS mirror on Sundays at 03:00 UTC" >> /tmp/crontab.txt
echo "0 3 * * 0 /scripts/backup-rustfs.sh >> /var/log/backup-rustfs.log 2>&1" >> /tmp/crontab.txt
echo "# Log rotation weekly" >> /tmp/crontab.txt
echo "0 4 * * 0 if [ -f /var/log/backup.log ]; then mv /var/log/backup.log /var/log/backup.log.\$$(date +\%Y\%W); fi" >> /tmp/crontab.txt
echo '0 2 * * * /scripts/backup.sh >> /var/log/backup.log 2>&1' > /tmp/crontab.txt
echo '0 3 * * 0 /scripts/backup-rustfs.sh >> /var/log/backup-rustfs.log 2>&1' >> /tmp/crontab.txt
crontab /tmp/crontab.txt
echo "Crontab installed:"
crontab -l
# Run crond in foreground
exec crond -f -l 2
volumes:
backup_data:
driver: local
secrets:
db_password:
file: ./secrets/db_password
networks:
heimdall-net:
name: heimdall-net
external: true
+17
View File
@@ -0,0 +1,17 @@
# Optional TURN relay, used only by a future/externally integrated WebRTC setup.
services:
coturn:
image: coturn/coturn:4.6
command: >
-n --use-auth-secret
--static-auth-secret-file=/run/secrets/coturn_secret
--realm=${COTURN_REALM:-heimdall.local}
--fingerprint --no-tlsv1 --no-tlsv1_1 --log-file=stdout
network_mode: host
secrets:
- coturn_secret
restart: unless-stopped
secrets:
coturn_secret:
file: ./secrets/coturn_secret
-18
View File
@@ -1,18 +0,0 @@
# ─── Heimdall — Override: use locally-built image with current fixes ───
# Use locally-built images rather than the production release images.
# Usage: AGENT_IMAGE_REFERENCE=heimdall-agent:local docker compose --env-file docker/.env -f docker/docker-compose.prod.yml -f docker/docker-compose.local.yml up -d
services:
heimdall:
image: heimdall:local
build:
context: ..
dockerfile: docker/Dockerfile
heimdall-agent:
image: heimdall-agent:local
build:
context: ..
dockerfile: docker/Dockerfile.agent
agent-state-init:
image: heimdall-agent:local
+23
View File
@@ -0,0 +1,23 @@
# Optional self-hosted ntfy service. Central's default URL is http://ntfy:80.
services:
ntfy:
image: binwiederhier/ntfy:latest
restart: unless-stopped
command: ["serve"]
environment:
TZ: ${TZ:-Europe/Paris}
NTFY_AUTH_FILE: /var/lib/ntfy/auth
ports:
- "${NTFY_PORT:-8080}:80"
volumes:
- ntfy_data:/var/lib/ntfy
networks:
- heimdall-net
volumes:
ntfy_data:
networks:
heimdall-net:
name: heimdall-net
external: true
+25
View File
@@ -0,0 +1,25 @@
# Optional local Ollama backend. Configure http://ollama:11434 in Central settings.
services:
ollama:
image: ollama/ollama:latest
restart: unless-stopped
ports:
- "${OLLAMA_PORT:-11434}:11434"
volumes:
- ollama_data:/root/.ollama
healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:11434/api/tags"]
interval: 30s
timeout: 10s
retries: 3
start_period: 30s
networks:
- heimdall-net
volumes:
ollama_data:
networks:
heimdall-net:
name: heimdall-net
external: true
+8 -297
View File
@@ -1,31 +1,11 @@
# ─── Heimdall — Production Docker Compose ─────────────────────────
# Pulls pre-built images from Docker Hub instead of building locally.
# Usage: docker compose -f docker/docker-compose.prod.yml up -d
# Prerequisite: cp .env.example .env && edit secrets
#
# Secrets are stored in docker/secrets/ (gitignored). Create them with:
# mkdir -p docker/secrets
# openssl rand -base64 32 > docker/secrets/jwt_signing_key
# openssl rand -base64 32 > docker/secrets/jwt_refresh_key
# openssl rand -base64 32 > docker/secrets/coturn_secret
# echo -n "your-db-password" > docker/secrets/db_password
# openssl rand -hex 12 > docker/secrets/rustfs_access_key
# openssl rand -base64 32 > docker/secrets/rustfs_secret_key
# echo -n "your-smtp-password" > docker/secrets/smtp_password
# cp /path/from/trusted-release-channel/agent-release-public.pem docker/secrets/agent-release-public.pem
# chmod 644 docker/secrets/agent-release-public.pem
#
# Set SERVER_IMAGE_REFERENCE to the server image selected for this deployment.
# Its repository is configured in docker/server-image.json.
#
# The heimdall service serves the Blazor UI, REST API, SignalR hubs,
# and Hangfire background jobs (heartbeat monitor, agent failover)
# in a single process.
# Production core: PostgreSQL and Heimdall Central only.
# Usage: docker compose --env-file docker/.env -f docker/docker-compose.prod.yml up -d
# Optional software has its own Compose file; see docs/docker-compose.md.
x-logging: &default-logging
driver: "json-file"
driver: json-file
options:
max-size: "10m"
max-size: 10m
max-file: "3"
services:
@@ -52,59 +32,20 @@ services:
networks:
- heimdall-net
rustfs:
image: rustfs/rustfs:latest
restart: unless-stopped
ports:
- "${RUSTFS_API_PORT:-9000}:9000"
- "${RUSTFS_CONSOLE_PORT:-9001}:9001"
environment:
RUSTFS_VOLUMES: /data
RUSTFS_ADDRESS: 0.0.0.0:9000
RUSTFS_CONSOLE_ADDRESS: 0.0.0.0:9001
RUSTFS_CONSOLE_ENABLE: "true"
RUSTFS_ACCESS_KEY_FILE: /run/secrets/rustfs_access_key
RUSTFS_SECRET_KEY_FILE: /run/secrets/rustfs_secret_key
secrets:
- rustfs_access_key
- rustfs_secret_key
volumes:
- rustfs_data:/data
logging: *default-logging
networks:
- heimdall-net
heimdall:
image: ${SERVER_IMAGE_REFERENCE:?Set SERVER_IMAGE_REFERENCE from docker/server-image.json}
environment:
# Database (password from secret, rest from env)
DATABASE_URL: ${DATABASE_URL:?DATABASE_URL is required}
# JWT (keys from secrets)
JWT__Issuer: ${JWT__ISSUER:-heimdall}
JWT__Audience: ${JWT__AUDIENCE:-heimdall-api}
# ASP.NET
JWT__KEY: ${JWT__KEY:?JWT__KEY is required}
JWT__REFRESHKEY: ${JWT__REFRESHKEY:?JWT__REFRESHKEY is required}
ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT:-Production}
ASPNETCORE_URLS: http://+:8080
# CORS (for external agents and API clients)
Cors__AllowedOrigins: ${Cors__AllowedOrigins:-*}
# Monolith: internal HTTP calls (circuit-triggered) must target the
# container's own listener, NOT the host-mapped origin the browser sees.
API_BASE_URL: ${API_BASE_URL:-http://localhost:8080}
# Central selects the release source; agents obtain the image and digest from Central.
Updates__ReleaseApiUrl: ${UPDATES_RELEASE_API_URL:?Set the Central release API URL}
# Ollama (optional — daily summaries)
Ollama__Endpoint: http://ollama:11434
# Coturn (WebRTC relay)
Coturn__Url: turns:coturn:3478
# Redis (SignalR backplane, optional — scaling)
ConnectionStrings__Redis: redis:6379
# Sentry / GlitchTip (error tracking)
Sentry__Dsn: ${SENTRY_DSN:-}
Sentry__TracesSampleRate: ${SENTRY_TRACES_SAMPLE_RATE:-0.05}
Sentry__Release: ${SENTRY_RELEASE:-}
secrets:
- jwt_signing_key
- jwt_refresh_key
ports:
- "${WEB_PORT:-5000}:8080"
volumes:
@@ -113,8 +54,6 @@ services:
depends_on:
postgresql:
condition: service_healthy
redis:
condition: service_healthy
healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/healthz"]
interval: 30s
@@ -126,244 +65,16 @@ services:
networks:
- heimdall-net
ntfy:
image: binwiederhier/ntfy:latest
container_name: heimdall-ntfy
restart: unless-stopped
command:
- "serve"
environment:
- TZ=Europe/Paris
- NTFY_AUTH_FILE=/var/lib/ntfy/auth
volumes:
- ntfy_data:/var/lib/ntfy
networks:
- heimdall-net
heimdall-agent:
# Pin the exact image reference supplied by the Central release manifest.
image: ${AGENT_IMAGE_REFERENCE:?Set AGENT_IMAGE_REFERENCE from the Central agent image manifest}
# Host network: the agent must see the real camera LAN to run discovery.
# On a bridge network it only sees 172.x → the scanner skips (no local subnet).
network_mode: host
environment:
# Diagnostics are loopback-only; 8081 avoids conflicts with ntfy.
ASPNETCORE_URLS: http://127.0.0.1:8081
# Host network: Docker DNS names don't resolve → point HEIMDALL_CENTRAL_URL
# to the Central's public URL (e.g. https://heimdall.tordais.cc)
Agent__CentralUrl: ${HEIMDALL_CENTRAL_URL:?HEIMDALL_CENTRAL_URL is required (public URL of the Central, e.g. https://heimdall.tordais.cc)}
Agent__SiteToken: ${HEIMDALL_SITE_TOKEN:?HEIMDALL_SITE_TOKEN is required}
Agent__AgentName: ${HEIMDALL_AGENT_NAME:-agent-01}
Agent__HeartbeatIntervalSeconds: ${HEIMDALL_HEARTBEAT_INTERVAL:-30}
Agent__StateDirectory: /var/lib/heimdall
Agent__UpdatePublicKeyPath: /run/secrets/agent-release-public.pem
# The published Agent image runs ONNX inference on CPU. Optional GPU
# passthrough overlays are only for device inventory/experimentation.
healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://127.0.0.1:8081/healthz"]
interval: 30s
timeout: 5s
retries: 3
start_period: 15s
volumes:
- agent_state:/var/lib/heimdall
- type: bind
source: ./secrets/agent-release-public.pem
target: /run/secrets/agent-release-public.pem
read_only: true
bind:
create_host_path: false
user: "1654:1654"
depends_on:
heimdall:
condition: service_started
agent-state-init:
condition: service_completed_successfully
restart: unless-stopped
logging: *default-logging
# no networks: host networking
# Migrate existing root-owned state before starting the non-root agent.
agent-state-init:
image: ${AGENT_IMAGE_REFERENCE:?Set AGENT_IMAGE_REFERENCE from the Central agent image manifest}
user: "0:0"
entrypoint: ["chown", "-R", "1654:1654", "/state"]
volumes:
- agent_state:/state
restart: "no"
# ── Backup service (opt-in via --profile backup) ───────────────
backup:
image: postgres:17-alpine
container_name: heimdall-backup
profiles:
- backup
environment:
POSTGRES_HOST: postgresql
POSTGRES_PORT: "5432"
POSTGRES_DB: ${POSTGRES_DB:-heimdall}
POSTGRES_USER: ${POSTGRES_USER:-heimdall}
POSTGRES_PASSWORD_FILE: /run/secrets/db_password
# S3/RustFS config (optional — backup works local-only without these)
RUSTFS_ENDPOINT: ${RUSTFS_ENDPOINT:-http://rustfs:9000}
RUSTFS_ACCESS_KEY: ${RUSTFS_ACCESS_KEY:-}
RUSTFS_SECRET_KEY: ${RUSTFS_SECRET_KEY:-}
RUSTFS_BUCKET: ${RUSTFS_BUCKET:-heimdall}
# Backup config
BACKUP_RETENTION_DAYS: ${BACKUP_RETENTION_DAYS:-30}
BACKUP_RETENTION_WEEKS: ${BACKUP_RETENTION_WEEKS:-12}
BACKUP_LOCAL_DIR: /backups
TZ: Europe/Paris
secrets:
- db_password
- rustfs_access_key
- rustfs_secret_key
volumes:
- ./scripts:/scripts:ro
- backup_data:/backups
depends_on:
postgresql:
condition: service_healthy
networks:
- heimdall-net
restart: unless-stopped
logging: *default-logging
entrypoint: ["/bin/sh", "-c"]
command:
- |
# Read password from Docker secret file
if [ -f /run/secrets/db_password ]; then
export POSTGRES_PASSWORD="$(cat /run/secrets/db_password)"
fi
if [ -f /run/secrets/rustfs_access_key ]; then
export RUSTFS_ACCESS_KEY="$(cat /run/secrets/rustfs_access_key)"
fi
if [ -f /run/secrets/rustfs_secret_key ]; then
export RUSTFS_SECRET_KEY="$(cat /run/secrets/rustfs_secret_key)"
fi
apk add --no-cache curl bash > /dev/null 2>&1 || true
curl -sSL https://dl.min.io/client/mc/release/linux-amd64/mc -o /usr/local/bin/mc 2>/dev/null || true
chmod +x /usr/local/bin/mc 2>/dev/null || true
chmod +x /scripts/*.sh
# Create crontab
echo "# Daily PostgreSQL backup at 02:00 UTC" > /tmp/crontab.txt
echo "0 2 * * * /scripts/backup.sh >> /var/log/backup.log 2>&1" >> /tmp/crontab.txt
echo "# Weekly RustFS mirror on Sundays at 03:00 UTC" >> /tmp/crontab.txt
echo "0 3 * * 0 /scripts/backup-rustfs.sh >> /var/log/backup-rustfs.log 2>&1" >> /tmp/crontab.txt
echo "# Log rotation weekly" >> /tmp/crontab.txt
echo "0 4 * * 0 if [ -f /var/log/backup.log ]; then mv /var/log/backup.log /var/log/backup.log.\$$(date +\%Y\%W); fi" >> /tmp/crontab.txt
crontab /tmp/crontab.txt
echo "Crontab installed:"
crontab -l
# Run crond in foreground
exec crond -f -l 2
# ── Optional services ──────────────────────────────────────────
coturn:
image: coturn/coturn:4.6
# TURN relay for WebRTC — network_mode host required for UDP ports.
command: >
-n --use-auth-secret
--static-auth-secret-file=/run/secrets/coturn_secret
--realm=${COTURN_REALM:-heimdall.local}
--fingerprint
--no-tlsv1
--no-tlsv1_1
--log-file=stdout
network_mode: host
secrets:
- coturn_secret
restart: unless-stopped
logging: *default-logging
ollama:
image: ollama/ollama:latest
# Local LLM for daily summaries and event analysis.
# GPU passthrough: add --gpus all or mount /dev/dri for Intel/AMD.
restart: unless-stopped
ports:
- "${OLLAMA_PORT:-11434}:11434"
volumes:
- ollama_data:/root/.ollama
healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:11434/api/tags"]
interval: 30s
timeout: 10s
retries: 3
start_period: 30s
logging: *default-logging
networks:
- heimdall-net
# Uncomment for GPU passthrough:
# deploy:
# resources:
# reservations:
# devices:
# - driver: nvidia
# count: all
# capabilities: [gpu]
redis:
image: redis:7-alpine
# SignalR backplane (scaling) + cache.
command: redis-server --requirepass ${REDIS_PASSWORD:-} --appendonly yes
ports:
- "${REDIS_PORT:-6379}:6379"
volumes:
- redis_data:/data
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 5
start_period: 10s
restart: unless-stopped
logging: *default-logging
networks:
- heimdall-net
volumes:
pgdata:
driver: local
rustfs_data:
driver: local
agent_state:
driver: local
heimdall_data:
driver: local
ntfy_data:
driver: local
dataprotection_keys:
driver: local
ollama_data:
driver: local
redis_data:
driver: local
backup_data:
driver: local
secrets:
db_password:
file: ./secrets/db_password
jwt_signing_key:
file: ./secrets/jwt_signing_key
jwt_refresh_key:
file: ./secrets/jwt_refresh_key
coturn_secret:
file: ./secrets/coturn_secret
rustfs_access_key:
file: ./secrets/rustfs_access_key
rustfs_secret_key:
file: ./secrets/rustfs_secret_key
smtp_password:
file: ./secrets/smtp_password
networks:
heimdall-net:
name: heimdall-net
driver: bridge
+26
View File
@@ -0,0 +1,26 @@
# Optional standalone Redis service. Heimdall currently does not require it.
services:
redis:
image: redis:7-alpine
command: ["redis-server", "--appendonly", "yes", "--requirepass", "${REDIS_PASSWORD:?Set REDIS_PASSWORD}"]
environment:
REDISCLI_AUTH: ${REDIS_PASSWORD:?Set REDIS_PASSWORD}
volumes:
- redis_data:/data
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 5
start_period: 10s
restart: unless-stopped
networks:
- heimdall-net
volumes:
redis_data:
networks:
heimdall-net:
name: heimdall-net
external: true
+39
View File
@@ -0,0 +1,39 @@
# Optional S3-compatible object store. Start the core Compose first so the
# shared heimdall-net exists, then configure storage in Central to use rustfs.
services:
rustfs:
image: rustfs/rustfs:latest
restart: unless-stopped
ports:
- "${RUSTFS_API_PORT:-9000}:9000"
- "${RUSTFS_CONSOLE_PORT:-9001}:9001"
environment:
RUSTFS_VOLUMES: /data
RUSTFS_ADDRESS: 0.0.0.0:9000
RUSTFS_CONSOLE_ADDRESS: 0.0.0.0:9001
RUSTFS_CONSOLE_ENABLE: "true"
RUSTFS_ACCESS_KEY_FILE: /run/secrets/rustfs_access_key
RUSTFS_SECRET_KEY_FILE: /run/secrets/rustfs_secret_key
secrets:
- rustfs_access_key
- rustfs_secret_key
volumes:
- rustfs_data:/data
networks:
heimdall-net:
aliases:
- rustfs
volumes:
rustfs_data:
secrets:
rustfs_access_key:
file: ./secrets/rustfs_access_key
rustfs_secret_key:
file: ./secrets/rustfs_secret_key
networks:
heimdall-net:
name: heimdall-net
external: true
+11 -181
View File
@@ -1,18 +1,5 @@
# ─── Heimdall — Development Docker Compose ─────────────────────────
# Builds image from local source. For production with pre-built images,
# use: docker compose -f docker/docker-compose.prod.yml up -d
# For development with hot-reload, start the required dependencies only and run
# the combined API, Blazor UI and background jobs with `make dev-web`.
#
# The heimdall service serves the Blazor UI, REST API, SignalR hubs,
# and Hangfire background jobs (heartbeat monitor, agent failover)
# in a single process.
x-logging: &default-logging
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
# Local development core: PostgreSQL and Heimdall Central only.
# The Agent and optional software have separate Compose files.
services:
postgresql:
@@ -32,26 +19,6 @@ services:
retries: 5
start_period: 30s
restart: unless-stopped
logging: *default-logging
networks:
- heimdall-net
rustfs:
image: rustfs/rustfs:latest
restart: unless-stopped
ports:
- "${RUSTFS_API_PORT:-9000}:9000"
- "${RUSTFS_CONSOLE_PORT:-9001}:9001"
environment:
RUSTFS_VOLUMES: /data
RUSTFS_ADDRESS: 0.0.0.0:9000
RUSTFS_CONSOLE_ADDRESS: 0.0.0.0:9001
RUSTFS_CONSOLE_ENABLE: "true"
RUSTFS_ACCESS_KEY: ${RUSTFS_ACCESS_KEY:?RUSTFS_ACCESS_KEY is required}
RUSTFS_SECRET_KEY: ${RUSTFS_SECRET_KEY:?RUSTFS_SECRET_KEY is required}
volumes:
- rustfs_data:/data
logging: *default-logging
networks:
- heimdall-net
@@ -59,34 +26,23 @@ services:
build:
context: ..
dockerfile: docker/Dockerfile
image: heimdall:latest
image: heimdall:local
environment:
# Database
DATABASE_URL: ${DATABASE_URL:?DATABASE_URL is required}
# JWT
JWT__Key: ${JWT__KEY:?JWT__KEY is required}
JWT__RefreshKey: ${JWT__REFRESHKEY:?JWT__REFRESHKEY is required}
JWT__Issuer: ${JWT__ISSUER:-heimdall}
JWT__Audience: ${JWT__AUDIENCE:-heimdall-api}
# ASP.NET
ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT:-Production}
JWT__KEY: ${JWT__KEY:?JWT__KEY is required}
JWT__REFRESHKEY: ${JWT__REFRESHKEY:?JWT__REFRESHKEY is required}
JWT__ISSUER: ${JWT__ISSUER:-heimdall}
JWT__AUDIENCE: ${JWT__AUDIENCE:-heimdall-api}
ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT:-Development}
ASPNETCORE_URLS: http://+:8080
# CORS (for external agents and API clients)
Cors__AllowedOrigins: ${Cors__AllowedOrigins:-*}
# Ollama (optional — daily summaries)
Ollama__Endpoint: http://ollama:11434
# Coturn (WebRTC relay)
Coturn__Url: turns:coturn:3478
# Redis (SignalR backplane, optional — scaling)
ConnectionStrings__Redis: redis:6379
# Error tracking
ports:
- "${WEB_PORT:-5000}:8080"
volumes:
- heimdall_data:/var/lib/heimdall
depends_on:
postgresql:
condition: service_healthy
volumes:
- heimdall_data:/var/lib/heimdall
healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/healthz"]
interval: 30s
@@ -94,140 +50,14 @@ services:
retries: 3
start_period: 60s
restart: unless-stopped
logging: *default-logging
networks:
- heimdall-net
ntfy:
image: binwiederhier/ntfy
container_name: heimdall-ntfy
restart: unless-stopped
command:
- "serve"
environment:
- TZ=Europe/Paris
volumes:
- ntfy_data:/var/lib/ntfy
ports:
- "8080:80"
networks:
- heimdall-net
heimdall-agent:
image: heimdall-agent:latest
build:
context: ..
dockerfile: docker/Dockerfile.agent
# Host network: the agent must see the real camera LAN to run discovery.
# On a bridge network it only sees 172.x → the scanner skips (no local subnet).
network_mode: host
environment:
# Diagnostics are loopback-only; 8081 avoids conflicts with ntfy.
ASPNETCORE_URLS: http://127.0.0.1:8081
# Host network: Docker DNS names don't resolve → reach the Central via
# a host-reachable URL (same machine: http://localhost:5010)
Agent__CentralUrl: ${HEIMDALL_CENTRAL_URL:-http://localhost:5010}
# This development profile uses local plain HTTP; never enable this in production.
Agent__AllowInsecureHttp: "true"
Agent__SiteToken: ${HEIMDALL_SITE_TOKEN:?HEIMDALL_SITE_TOKEN is required}
Agent__AgentName: ${HEIMDALL_AGENT_NAME:-agent-01}
Agent__HeartbeatIntervalSeconds: ${HEIMDALL_HEARTBEAT_INTERVAL:-30}
Agent__StateDirectory: /var/lib/heimdall
Agent__RegistrationMaxRetries: ${HEIMDALL_REGISTRATION_RETRIES:-5}
volumes:
- agent_state:/var/lib/heimdall
user: "1654:1654"
healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://127.0.0.1:8081/healthz"]
interval: 30s
timeout: 5s
retries: 3
start_period: 15s
depends_on:
heimdall:
condition: service_started
agent-state-init:
condition: service_completed_successfully
restart: unless-stopped
logging: *default-logging
# no networks: host networking
# Migrate existing root-owned state before starting the non-root agent.
agent-state-init:
image: heimdall-agent:latest
user: "0:0"
entrypoint: ["chown", "-R", "1654:1654", "/state"]
volumes:
- agent_state:/state
restart: "no"
# ── Optional services (dev) ────────────────────────────────────
coturn:
image: coturn/coturn:4.6
command: >
-n --use-auth-secret
--static-auth-secret=${COTURN_SECRET:?COTURN_SECRET is required}
--realm=${COTURN_REALM:-heimdall.local}
--fingerprint
--no-tlsv1
--no-tlsv1_1
--log-file=stdout
network_mode: host
restart: unless-stopped
logging: *default-logging
ollama:
image: ollama/ollama:latest
restart: unless-stopped
ports:
- "${OLLAMA_PORT:-11434}:11434"
volumes:
- ollama_data:/root/.ollama
healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:11434/api/tags"]
interval: 30s
timeout: 10s
retries: 3
start_period: 30s
logging: *default-logging
networks:
- heimdall-net
redis:
image: redis:7-alpine
command: redis-server --appendonly yes
ports:
- "${REDIS_PORT:-6379}:6379"
volumes:
- redis_data:/data
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 5
start_period: 10s
restart: unless-stopped
logging: *default-logging
networks:
- heimdall-net
volumes:
pgdata:
driver: local
rustfs_data:
driver: local
agent_state:
driver: local
heimdall_data:
driver: local
ntfy_data:
driver: local
ollama_data:
driver: local
redis_data:
driver: local
networks:
heimdall-net:
name: heimdall-net
driver: bridge
+17 -102
View File
@@ -1238,18 +1238,15 @@ Phase 11 — Hangfire Foundation + Jobs Multi-Site
│ → C'EST L'OBJECTIF DE L'ÉTAPE 1 │
└──────────────────────────────────────────────────────────────────┘
Phase 12 — Agent Foundation (Docker-only)
├── Docker-only : heimdall/agent:latest
Phase 12 — Agent Foundation (multi-format installation)
├── Images Agent configurées par docker/agent-image.json
├── Installation Linux native via install/install-agent.sh et systemd
├── Compose Docker généré dans l'IHM depuis le manifeste signé Central
├── AgentRegistrationService (register via API au premier démarrage)
├── HeartbeatSenderJob (Hangfire InMemory Central, 30s)
├── Agent → Central : API Key auth (X-Api-Key header)
├── Central → Agent : heartbeat OK renouvelle le statut Online
├── docker-compose.yml minimal pour l'Agent :
│ docker run -e HEIMDALL_CENTRAL_URL=https://central.example.com \
│ -e HEIMDALL_SITE_TOKEN=abc123def456 \
│ -e HEIMDALL_API_KEY=heimdall_sk_abc123def456 \
│ -e HEIMDALL_AGENT_NAME=agent-paris-01 \
│ heimdall/agent:latest
├── L'Agent Docker utilise le réseau hôte pour accéder au LAN des caméras
├── Verify: Agent démarre → register → heartbeat 30s
│
✅ Fonctionnel à la fin de cette phase :
@@ -2115,104 +2112,22 @@ Plan détaillé : docs/pwa.md
## PARTIE 11 : Déploiement Docker
### 11.1 docker-compose.yml (production)
### 11.1 Compose de déploiement
> **L'Agent est distribué EXCLUSIVEMENT via Docker.** Pas de binaire standalone,
> pas d'installation manuelle. La commande Docker est générée par l'UI Admin
> avec le token et l'API Key pré-remplis : `docker run -e HEIMDALL_SITE_TOKEN=... -e HEIMDALL_API_KEY=... heimdall/agent:latest`.
```yaml
services:
heimdall-central:
image: heimdall/central:latest
ports:
- "5000:5000" # HTTPS
environment:
- ConnectionStrings__PostgreSQL=Server=postgresql;Database=heimdall;...
- ConnectionStrings__Hangfire=Server=postgresql;Database=heimdall_hangfire;...
- ConnectionStrings__Redis=redis:6379
- S3 endpoint: http://rustfs:9000 (même API S3)
# L'IA est exécutée par les agents (ONNX Runtime) — plus de service central
- Ollama__Endpoint=http://ollama:11434
- Coturn__Url=turns:coturn:3478
- Coturn__Secret=${COTURN_SECRET}
volumes:
- dataprotection_keys:/root/.aspnet/DataProtection-Keys
secrets:
- jwt_signing_key
- coturn_secret
- smtp_password
heimdall-agent:
image: heimdall/agent:latest
environment:
- HEIMDALL_CENTRAL_URL=https://heimdall-central:5000
- HEIMDALL_SITE_TOKEN=${HEIMDALL_SITE_TOKEN}
- HEIMDALL_API_KEY=${HEIMDALL_API_KEY}
- HEIMDALL_AGENT_NAME=${HEIMDALL_AGENT_NAME}
volumes:
- /dev/dri:/dev/dri # GPU Intel/AMD (optionnel)
- /tmp/heimdall:/tmp/heimdall # Cache snapshots local
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: all
capabilities: [gpu]
depends_on:
postgresql:
condition: service_healthy
rustfs:
condition: service_started
postgresql:
image: postgres:17
environment:
POSTGRES_USER: heimdall
POSTGRES_PASSWORD: ${DB_PASSWORD}
POSTGRES_DB: heimdall
volumes:
- pgdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U heimdall"]
ports:
- "5432:5432"
rustfs:
image: rustfs/rustfs:latest
ports:
- "9000:9000" # S3 API
- "9001:9001" # Console
environment:
RUSTFS_VOLUMES: /data
RUSTFS_ADDRESS: 0.0.0.0:9000
RUSTFS_CONSOLE_ADDRESS: 0.0.0.0:9001
RUSTFS_CONSOLE_ENABLE: "true"
RUSTFS_ACCESS_KEY: ${RUSTFS_ACCESS_KEY}
RUSTFS_SECRET_KEY: ${RUSTFS_SECRET_KEY}
volumes:
- rustfs_data:/data
coturn:
image: coturn/coturn:4.6
command: >
-n --use-auth-secret
--static-auth-secret=${COTURN_SECRET}
--realm=heimdall.local
--fingerprint
--no-tlsv1
--no-tlsv1_1
network_mode: host # nécessaire pour TURN (ports UDP)
```
La configuration déployable est maintenue dans `docker/` et décrite dans
[docker-compose.md](docker-compose.md). Le noyau obligatoire contient
uniquement Central et PostgreSQL (`docker-compose.prod.yml`). Pour chaque site,
l’IHM génère le Compose Agent épinglé au digest du manifeste signé Central. Le
dépôt ne garde qu’un Compose Agent de développement local.
RustFS, ntfy, Ollama, Coturn, Redis et les sauvegardes disposent chacun d'un
Compose facultatif. Les overlays GPU ciblent uniquement les Agents et
n'activent pas l'inférence ONNX GPU dans l'image publiée.
### 11.2 GPU Passthrough
| Conteneur | GPU | Docker Compose |
|---|---|---|
| agent GPU | NVIDIA/AMD/Intel | profiles compose GPU (nvidia/rocm/vaapi) — cf. docker |
| `heimdall-agent` | NVIDIA/Intel/AMD | `--gpus all` ou `/dev/dri:/dev/dri` |
| `ollama` | NVIDIA (optionnel) | `--gpus all` |
Les fichiers `docker-compose.gpu-*.yml` exposent le matériel au Compose Agent
pour l'inventaire seulement. L'image Agent publiée embarque le fournisseur ONNX
CPU; l'inférence GPU nécessite encore une image et un runtime dédiés.
---
+2
View File
@@ -36,6 +36,7 @@ vidéosurveillance IA locale, multi-site, auto-hébergée.
| **Hangfire (jobs)** | `docs/hangfire-usage.md` | Configuration actuelle et jobs présents; vérifier l'état des parcours dans l'audit |
| **SignalR (temps réel)** | `docs/signalr-usage.md` | Hubs et contrats documentés; état du streaming live dans l'audit |
| **Déploiement Docker** | `docs/specs.md` (§30) | Containers, GPU passthrough, docker-compose |
| **Docker Compose** | [Déploiement séparé](docker-compose.md) | Central + PostgreSQL requis; Agent et logiciels optionnels séparés |
| **GPU Agent** | [Accès matériel et état de l'inférence](gpu-runtime.md) | Profils facultatifs; l'inférence ONNX publiée reste CPU |
## 📐 Structure du projet
@@ -61,6 +62,7 @@ Heimdall/
|---|---|
| `specs.md` | Spécification complète : vision, architecture, features, déploiement |
| `implementation.md` | Plan historique du MVP (juillet 2026); statuts non représentatifs de l'état actuel |
| `docker-compose.md` | Déploiement Central, Agents autonomes et logiciels facultatifs |
| `ui-pages.md` | Pages Blazor (MudBlazor) : maquettes ASCII, composants, états |
| `pwa.md` | Audit PWA du serveur Blazor, architecture cible et plan de réalisation |
| `auth-roles.md` | Auth : 2 user types, permissions, site-scope, UI visibility |
+1 -1
View File
@@ -31,7 +31,7 @@ sudo bash install/install-agent.sh \
Le script lit le manifeste signé via Central, vérifie la signature et l’archive, puis installe la release sous `/opt/heimdall/agent/releases/`. Le service utilise le lien `current`; lors d’une mise à jour, le superviseur accorde jusqu’à 180 secondes au démarrage, exige ensuite 60 secondes de réponse continue de `/api/version` pour la version attendue et rétablit la release précédente si cette validation échoue. Garder ensemble `install-agent.sh` et `agent-supervisor.py` lors d’une installation depuis une copie des scripts.
Pour un Agent Docker déployé avec `docker/docker-compose.prod.yml`, copier la clé reçue par un canal de confiance indépendant de Central vers `docker/secrets/agent-release-public.pem` avant le démarrage. Le compose la monte en lecture seule sur `/run/secrets/agent-release-public.pem` et configure `Agent__UpdatePublicKeyPath`; le fichier doit être lisible par l’UID 1654 (par exemple `chmod 644`). Pour le compose généré dans l’interface, déposer le fichier `agent-release-public.pem` à côté de `docker-compose.yml`. Les deux montages échouent explicitement si le fichier est absent. L’Agent refuse la mise à jour si le chemin ou 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é.
Pour un Agent Docker, déposer la clé reçue par un canal de confiance indépendant de Central dans `agent-release-public.pem`, à côté du Compose généré par l’IHM. Celui-ci la monte en lecture seule sur `/run/secrets/agent-release-public.pem` et configure `Agent__UpdatePublicKeyPath`; le fichier doit être lisible par l’UID 1654 (par exemple `chmod 644`). Le démarrage échoue explicitement si le fichier est absent. L’Agent refuse la mise à jour si le chemin ou 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é.
## Rotation
+70
View File
@@ -0,0 +1,70 @@
# 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,
Redis and scheduled backups have separate Compose files and can be left out.
## Central and database
Copy `.env.example` to the ignored `docker/.env`, replace every example value,
and create the PostgreSQL password file and JWT keys before production use.
The database password in `DATABASE_URL` must match `docker/secrets/db_password`.
```sh
mkdir -p -m 700 docker/secrets
openssl rand -base64 32 > docker/secrets/db_password
cp .env.example docker/.env
# Set DATABASE_URL, JWT__KEY, JWT__REFRESHKEY and SERVER_IMAGE_REFERENCE
# in docker/.env. Configure integrations and the release API in Central's UI.
docker compose --env-file docker/.env -f docker/docker-compose.prod.yml up -d
```
The development Compose builds Central from the local source and starts only
Central plus PostgreSQL:
```sh
docker compose --env-file docker/.env -f docker/docker-compose.yml up -d
```
## 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 and Agent name. Save it as
`docker-compose.yml` beside the trusted `agent-release-public.pem`, then run
`docker compose up -d`. Do not substitute a mutable image tag for the digest.
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,
use `docker/docker-compose.agent.dev.yml` with a development site token and the
local Central URL. The published Agent image uses CPU inference. The optional
NVIDIA, AMD and Intel overlays expose hardware for inventory; they do not
enable GPU inference.
## Optional software
Start Central first to create the shared `heimdall-net` network. Optional
services then join that network where applicable, so their Compose projects
remain separate while Central can resolve their service names.
```sh
docker compose --env-file docker/.env -f docker/docker-compose.ollama.yml up -d
docker compose --env-file docker/.env -f docker/docker-compose.ntfy.yml up -d
docker compose --env-file docker/.env -f docker/docker-compose.rustfs.yml up -d
docker compose --env-file docker/.env -f docker/docker-compose.coturn.yml up -d
docker compose --env-file docker/.env -f docker/docker-compose.redis.yml up -d
docker compose --env-file docker/.env -f docker/docker-compose.backup.yml up -d
```
Configure Ollama at `http://ollama:11434` in Central's AI settings when enabled.
Choose RustFS as the storage provider in Central and use `http://rustfs:9000` as
its endpoint. Configure the ntfy server URL in Central's notification settings.
TURN is not required until WebRTC is enabled.
Redis is provided as a standalone service but is not currently required by
Central. Backups are independent of the core startup and require the core
network and PostgreSQL service to be running.
See [GPU Agent notes](gpu-runtime.md) and
[Agent update signing](agent-release-signing.md) for device access and
trusted-key setup.
+14 -13
View File
@@ -4,31 +4,32 @@ The default Agent uses `CPUExecutionProvider`. The published Agent image only
contains the CPU ONNX Runtime package. GPU detection and inventory report host
hardware; they do not mean that frame inference is running on that hardware.
The default Compose files do not require a GPU. Optional overlays expose a
device to the Agent for inventory and hardware experiments:
The production Agent Compose is generated in Central's UI. Save that file as
`docker-compose.yml` on the camera host. To expose hardware for inventory,
copy the matching optional overlay from this repository beside it, then run:
```sh
# NVIDIA
docker compose --env-file docker/.env \
-f docker/docker-compose.yml \
-f docker/docker-compose.gpu-nvidia.yml \
docker compose \
-f docker-compose.yml \
-f docker-compose.gpu-nvidia.yml \
--profile gpu-nvidia-inventory up -d heimdall-agent
# AMD ROCm devices
docker compose --env-file docker/.env \
-f docker/docker-compose.yml \
-f docker/docker-compose.gpu-amd.yml \
docker compose \
-f docker-compose.yml \
-f docker-compose.gpu-amd.yml \
--profile gpu-amd-inventory up -d heimdall-agent
# Intel render device
docker compose --env-file docker/.env \
-f docker/docker-compose.yml \
-f docker/docker-compose.gpu-intel.yml \
docker compose \
-f docker-compose.yml \
-f docker-compose.gpu-intel.yml \
--profile gpu-intel-inventory up -d heimdall-agent
```
Use the same overlay with `docker/docker-compose.prod.yml` in place of the
development file. For Intel and AMD hosts, set `VIDEO_GID` and `RENDER_GID` to
For local development, use the same overlay with
`docker/docker-compose.agent.dev.yml`. For Intel and AMD hosts, set `VIDEO_GID` and `RENDER_GID` to
the host group IDs that can access `/dev/dri`. The NVIDIA option requires the
NVIDIA Container Toolkit and Docker Compose GPU device reservations.
+3 -2
View File
@@ -70,8 +70,9 @@ Heimdall/
├── docker/
│ ├── Dockerfile.central # Multi-stage ✅
│ ├── Dockerfile.agent # Multi-stage ✅
│ ├── docker-compose.yml # PostgreSQL + RustFS + Central + Agent + Workers ✅
│ └── docker-compose.local.yml # Local compose overrides
│ ├── docker-compose.yml # Central de développement + PostgreSQL
│ ├── docker-compose.prod.yml # Central de production + PostgreSQL
│ └── docker-compose.<service>.yml # Logiciels optionnels isolés
├── docs/
│ ├── MASTER_SPECIFICATION.md # Spec complète
│ ├── implementation.md # ← ce fichier
+23 -23
View File
@@ -38,13 +38,16 @@ Heimdall.Web (Api + Blazor UI) Heimdall.Agent
### 1. Production (images Docker Hub)
```bash
cp .env.example .env
# Éditer les secrets (JWT__Key, mots de passe)
nano .env
docker compose -f docker/docker-compose.prod.yml up -d
cp .env.example docker/.env
# Remplacer les valeurs d'exemple et préparer docker/secrets/db_password.
docker compose --env-file docker/.env -f docker/docker-compose.prod.yml up -d
```
Ce Compose démarre uniquement PostgreSQL et Central. Installez chaque Agent
depuis le Compose généré dans l'IHM du site; ses images sont épinglées au
digest publié par Central. Les services facultatifs ont chacun leur Compose;
voir [le guide de déploiement](docs/docker-compose.md).
**Accès** :
| Service | URL |
@@ -52,16 +55,14 @@ docker compose -f docker/docker-compose.prod.yml up -d
| Web UI + API | http://localhost:5000 |
| API | http://localhost:5000/api |
| API Docs (dev) | http://localhost:5000/scalar |
| RustFS Console | http://localhost:9001 |
### 2. Build local (développement)
```bash
cp .env.example .env
# Éditer les secrets
nano .env
cp .env.example docker/.env
# Éditer les valeurs locales dans docker/.env
docker compose -f docker/docker-compose.yml up -d
docker compose --env-file docker/.env -f docker/docker-compose.yml up -d
```
### 3. Développement avec hot-reload
@@ -69,8 +70,8 @@ docker compose -f docker/docker-compose.yml up -d
Prérequis : .NET 10 SDK, Docker
```bash
# Démarrer les dépendances locales sans lancer le serveur conteneurisé
docker compose -f docker/docker-compose.yml up -d postgresql rustfs
# Démarrer PostgreSQL sans lancer le serveur conteneurisé
docker compose --env-file docker/.env -f docker/docker-compose.yml up -d postgresql
# L'API, l'UI Blazor et les jobs tournent dans le même processus
make dev-web
@@ -99,16 +100,17 @@ Le dossier `docker/` contient tout nécessaire pour déployer Heimdall :
| Fichier | Usage | Description |
|---------|-------|-------------|
| `docker-compose.yml` | Développement | Build local des images et services de développement |
| `docker-compose.prod.yml` | Production | Images de production, agent épinglé sur la référence fournie par le Central |
| `docker-compose.local.yml` | Surcharges locales | Ajustements optionnels, par exemple l'exposition d'un GPU |
| `docker-compose.yml` | Développement | PostgreSQL et Central local |
| `docker-compose.prod.yml` | Production | PostgreSQL et Central depuis les images configurées |
| `docker-compose.agent.dev.yml` | Développement Agent | Agent local autonome, connecté au Central de développement |
| `docker-compose.{rustfs,ntfy,ollama,coturn,redis}.yml` | Logiciels facultatifs | Un Compose isolé par logiciel |
| `Dockerfile` | Build | Image Central (UI + API + jobs) |
| `Dockerfile.agent` | Build | Image agent avec FFmpeg |
| `docker/server-image.json` | Publication | Dépôt de l’image Central à publier |
| `docker/agent-image.json` | Publication | Dépôt d’image agent à publier ; sa référence et son digest sont joints au manifeste de release |
| `docker/secrets/` | Production | Clés secrètes (JWT, DB, Coturn, etc.) |
| `docker/secrets/` | Production | Fichiers secrets PostgreSQL, stockage et TURN; JWT dans `docker/.env` ignoré par Git |
Pour une installation de production, définissez `SERVER_IMAGE_REFERENCE` depuis `docker/server-image.json`. Définissez `AGENT_IMAGE_REFERENCE` sur la valeur `image@digest` du compose généré par le Central. Le dépôt et le digest agent proviennent du manifeste signé `agent-image.json` de la release ; le compose n’utilise pas de tag mutable.
Pour une installation de production, définissez `SERVER_IMAGE_REFERENCE` depuis `docker/server-image.json`. Installez l'Agent avec le Compose `image@digest` généré dans l'IHM du Central ; aucun Compose Agent de production statique n'est conservé dans le dépôt. Le dépôt et le digest proviennent du manifeste signé `agent-image.json` de la release. Le détail des installations se trouve dans [docs/docker-compose.md](docs/docker-compose.md).
### Services
@@ -193,10 +195,10 @@ l'ancien volume ou service.
**Les conteneurs ne démarrent pas :**
```bash
# Voir les logs de tous les services
docker compose -f docker/docker-compose.yml logs -f
docker compose --env-file docker/.env -f docker/docker-compose.yml logs -f
# Vérifier l'état
docker compose -f docker/docker-compose.yml ps
docker compose --env-file docker/.env -f docker/docker-compose.yml ps
```
**PostgreSQL n'est pas prêt :** Le healthcheck attend 30s avant de considérer
@@ -214,10 +216,8 @@ Générer un token via `POST /api/sites/{id}/tokens` sur l'API.
## Authentification
La source des mises à jour est configurée côté Central par `Updates:ReleaseApiUrl`
(`UPDATES_RELEASE_API_URL` dans le Compose de production, ou
`Updates__ReleaseApiUrl` directement). Cette valeur est requise au déploiement
et peut être changée sans recompiler le serveur. L'agent lit le nom et le digest
La source des mises à jour se configure dans les paramètres globaux de Central.
L'agent lit le nom et le digest
de l'image dans le manifeste authentifié de Central ; le dépôt d'image Agent est
défini dans `docker/agent-image.json` et celui du serveur dans
`docker/server-image.json`.
Regular → Executable
+47 -13
View File
@@ -1,18 +1,52 @@
#!/usr/bin/env bash
set -euo pipefail
# Never print the rendered configuration: it contains credentials.
docker compose --env-file .env.example -f docker/docker-compose.yml config --quiet
AGENT_IMAGE_REFERENCE=heimdall-agent:ci docker compose --env-file .env.example -f docker/docker-compose.prod.yml config --quiet
docker compose --env-file .env.example -f docker/docker-compose.yml -f docker/docker-compose.backup.yml config --quiet
docker compose --env-file .env.example -f docker/docker-compose.yml -f docker/docker-compose.gpu-nvidia.yml --profile gpu-nvidia-inventory config --quiet
docker compose --env-file .env.example -f docker/docker-compose.yml -f docker/docker-compose.gpu-amd.yml --profile gpu-amd-inventory config --quiet
docker compose --env-file .env.example -f docker/docker-compose.yml -f docker/docker-compose.gpu-intel.yml --profile gpu-intel-inventory config --quiet
AGENT_IMAGE_REFERENCE=heimdall-agent:ci docker compose --env-file .env.example -f docker/docker-compose.prod.yml -f docker/docker-compose.gpu-nvidia.yml --profile gpu-nvidia-inventory config --quiet
AGENT_IMAGE_REFERENCE=heimdall-agent:ci docker compose --env-file .env.example -f docker/docker-compose.prod.yml -f docker/docker-compose.gpu-amd.yml --profile gpu-amd-inventory config --quiet
AGENT_IMAGE_REFERENCE=heimdall-agent:ci docker compose --env-file .env.example -f docker/docker-compose.prod.yml -f docker/docker-compose.gpu-intel.yml --profile gpu-intel-inventory config --quiet
for required in JWT__KEY JWT__REFRESHKEY HEIMDALL_SITE_TOKEN DATABASE_URL POSTGRES_PASSWORD RUSTFS_ACCESS_KEY RUSTFS_SECRET_KEY COTURN_SECRET; do
if env "$required=" docker compose --env-file .env.example -f docker/docker-compose.yml config --quiet >/dev/null 2>&1; then
echo "Compose accepted missing required variable: $required" >&2
# Never print the rendered configuration: it may contain credentials.
compose() {
docker compose --env-file .env.example "$@" config --quiet
}
export SERVER_IMAGE_REFERENCE=heimdall:ci
export AGENT_IMAGE_REFERENCE=heimdall-agent:ci
compose -f docker/docker-compose.yml
compose -f docker/docker-compose.prod.yml
compose -f docker/docker-compose.agent.dev.yml
for optional in rustfs ntfy ollama coturn redis backup; do
compose -f "docker/docker-compose.$optional.yml"
done
for gpu in nvidia amd intel; do
compose -f docker/docker-compose.agent.dev.yml \
-f "docker/docker-compose.gpu-$gpu.yml" \
--profile "gpu-$gpu-inventory"
done
for required in DATABASE_URL POSTGRES_PASSWORD JWT__KEY JWT__REFRESHKEY; do
if env "$required=" docker compose --env-file .env.example \
-f docker/docker-compose.yml config --quiet >/dev/null 2>&1; then
echo "Development Compose accepted missing required variable: $required" >&2
exit 1
fi
done
for required in SERVER_IMAGE_REFERENCE DATABASE_URL JWT__KEY JWT__REFRESHKEY; do
if env "$required=" docker compose \
--env-file .env.example -f docker/docker-compose.prod.yml config --quiet >/dev/null 2>&1; then
echo "Production Compose accepted missing required variable: $required" >&2
exit 1
fi
done
for forbidden in API_BASE_URL UPDATES_RELEASE_API_URL EMAIL__SMTP_HOST EMAIL__SMTP_PORT EMAIL__USERNAME EMAIL__PASSWORD EMAIL__FROM_ADDRESS EMAIL__FROM_NAME EMAIL__USE_SSL OLLAMA_URL NTFY__BASE_URL NTFY__TOKEN STORAGE__PROVIDER; do
if rg -q "$forbidden" docker/docker-compose.yml docker/docker-compose.prod.yml; then
echo "Central Compose must not configure IHM-managed setting: $forbidden" >&2
exit 1
fi
done
if env HEIMDALL_SITE_TOKEN= docker compose --env-file .env.example \
-f docker/docker-compose.agent.dev.yml config --quiet >/dev/null 2>&1; then
echo "Development Agent Compose accepted a missing site token" >&2
exit 1
fi
@@ -85,7 +85,7 @@ public sealed class AiHealthCheck : IHealthCheck
return HealthCheckResult.Healthy("AI backend not configured");
}
/// <summary>AppSettings (ai.*) d'abord, fallback env (migration douce, ticket #80).</summary>
/// <summary>Les URL de service IA sont lues dans les AppSettings globaux.</summary>
private async Task<(string? Cpai, string? Ollama)> ResolveUrlsAsync(CancellationToken ct)
{
using var scope = _services.CreateScope();
@@ -94,8 +94,7 @@ public sealed class AiHealthCheck : IHealthCheck
var cpai = await AppSettingReader.GetAsync(db, "ai.cpaiUrl", ct).ConfigureAwait(false)
?? Environment.GetEnvironmentVariable("CPAI_URL");
var ollama = await AppSettingReader.GetAsync(db, "ai.ollamaUrl", ct).ConfigureAwait(false)
?? Environment.GetEnvironmentVariable("OLLAMA_URL");
var ollama = await AppSettingReader.GetAsync(db, "ai.ollamaUrl", ct).ConfigureAwait(false);
return (cpai, ollama);
}
@@ -3,7 +3,6 @@ using System.Net.Mail;
using Heimdall.Application.Common;
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Settings;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
@@ -13,12 +12,10 @@ public class EmailService : IEmailService
{
private readonly ILogger<EmailService> _logger;
private readonly IServiceProvider _services;
private readonly IConfiguration _configuration;
public EmailService(IServiceProvider services, IConfiguration configuration, ILogger<EmailService> logger)
public EmailService(IServiceProvider services, ILogger<EmailService> logger)
{
_services = services;
_configuration = configuration;
_logger = logger;
}
@@ -69,9 +66,8 @@ public class EmailService : IEmailService
}
/// <summary>
/// Source de vérité : AppSettings en base (email.*), avec fallback
/// config/appsettings puis env (migration douce, ticket #80). Relu à
/// chaque envoi pour prendre en compte les modifications de l'UI.
/// Source de vérité : AppSettings globaux en base (email.*), relus à
/// chaque envoi pour prendre en compte les modifications de l'IHM.
/// </summary>
private async Task<(string? SmtpHost, int SmtpPort, string? Username, string? Password,
string? FromAddress, string? FromName, bool UseSsl)> ResolveConfigAsync(CancellationToken ct)
@@ -79,37 +75,23 @@ public class EmailService : IEmailService
using var scope = _services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<IApplicationDbContext>();
var smtpHost = await AppSettingReader.GetAsync(db, "email.smtpHost", ct).ConfigureAwait(false)
?? _configuration.GetValue<string>("Email:SmtpHost")
?? Environment.GetEnvironmentVariable("EMAIL__SMTP_HOST");
var smtpHost = await AppSettingReader.GetAsync(db, "email.smtpHost", ct).ConfigureAwait(false);
var smtpPort = await AppSettingReader.GetIntAsync(db, "email.smtpPort", -1, ct).ConfigureAwait(false);
if (smtpPort < 0)
smtpPort = _configuration.GetValue<int?>("Email:SmtpPort")
?? (int.TryParse(Environment.GetEnvironmentVariable("EMAIL__SMTP_PORT"), out var port) ? port : 587);
smtpPort = 587;
var username = await AppSettingReader.GetAsync(db, "email.username", ct).ConfigureAwait(false)
?? _configuration.GetValue<string>("Email:Username")
?? Environment.GetEnvironmentVariable("EMAIL__USERNAME");
var username = await AppSettingReader.GetAsync(db, "email.username", ct).ConfigureAwait(false);
var password = await AppSettingReader.GetAsync(db, "email.password", ct).ConfigureAwait(false)
?? _configuration.GetValue<string>("Email:Password")
?? Environment.GetEnvironmentVariable("EMAIL__PASSWORD");
var password = await AppSettingReader.GetAsync(db, "email.password", ct).ConfigureAwait(false);
var fromAddress = await AppSettingReader.GetAsync(db, "email.fromAddress", ct).ConfigureAwait(false)
?? _configuration.GetValue<string>("Email:FromAddress")
?? Environment.GetEnvironmentVariable("EMAIL__FROM_ADDRESS") ?? "noreply@heimdall.local";
?? "noreply@heimdall.local";
var fromName = await AppSettingReader.GetAsync(db, "email.fromName", ct).ConfigureAwait(false)
?? _configuration.GetValue<string>("Email:FromName")
?? Environment.GetEnvironmentVariable("EMAIL__FROM_NAME") ?? "Heimdall";
?? "Heimdall";
var useSsl = await AppSettingReader.GetBoolAsync(db, "email.useSsl", true, ct).ConfigureAwait(false);
if (_configuration.GetValue<bool?>("Email:UseSsl") is { } cfgSsl)
useSsl = cfgSsl;
else if (bool.TryParse(Environment.GetEnvironmentVariable("EMAIL__USE_SSL"), out var envSsl))
useSsl = envSsl;
return (smtpHost, smtpPort, username, password, fromAddress, fromName, useSsl);
}
}
@@ -4,7 +4,6 @@ using System.Text.Json;
using Heimdall.Application.Common;
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Settings;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
@@ -14,15 +13,13 @@ public class NtfyService : INtfyService
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly IServiceProvider _services;
private readonly IConfiguration _configuration;
private readonly ILogger<NtfyService> _logger;
public NtfyService(IHttpClientFactory httpClientFactory, IServiceProvider services,
IConfiguration configuration, ILogger<NtfyService> logger)
ILogger<NtfyService> logger)
{
_httpClientFactory = httpClientFactory;
_services = services;
_configuration = configuration;
_logger = logger;
}
@@ -77,9 +74,8 @@ public class NtfyService : INtfyService
}
/// <summary>
/// Source de vérité : AppSettings en base (ntfy.*), avec fallback
/// config/appsettings puis env (migration douce, ticket #80). Relu à
/// chaque envoi pour prendre en compte les modifications de l'UI.
/// Source de vérité : AppSettings globaux en base (ntfy.*), relus à
/// chaque envoi pour prendre en compte les modifications de l'IHM.
/// </summary>
private async Task<(string BaseUrl, string? Token)> ResolveConfigAsync(CancellationToken ct)
{
@@ -87,13 +83,9 @@ public class NtfyService : INtfyService
var db = scope.ServiceProvider.GetRequiredService<IApplicationDbContext>();
var baseUrl = await AppSettingReader.GetAsync(db, "ntfy.baseurl", ct).ConfigureAwait(false)
?? _configuration.GetValue<string>("Ntfy:BaseUrl")
?? Environment.GetEnvironmentVariable("NTFY__BASE_URL")
?? "http://ntfy:80";
?? string.Empty;
var token = await AppSettingReader.GetAsync(db, "ntfy.token", ct).ConfigureAwait(false)
?? _configuration.GetValue<string>("Ntfy:Token")
?? Environment.GetEnvironmentVariable("NTFY__TOKEN");
var token = await AppSettingReader.GetAsync(db, "ntfy.token", ct).ConfigureAwait(false);
return (baseUrl, token);
}
@@ -10,8 +10,7 @@ namespace Heimdall.Infrastructure.Storage;
/// <summary>
/// Resolves the active storage provider from the global settings
/// (<c>storage.provider</c> = Local | S3) with env fallback
/// (<c>STORAGE__PROVIDER</c>). Reads the DB each resolution so a change made
/// (<c>storage.provider</c> = Local | S3). Reads the DB each resolution so a change made
/// in the UI is picked up without restart (broadcast reload on top).
/// </summary>
public sealed class StorageProviderFactory : IStorageProvider, Heimdall.Application.Common.IStorageObjectDeletion
@@ -55,8 +54,6 @@ public sealed class StorageProviderFactory : IStorageProvider, Heimdall.Applicat
using var scope = _services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<IApplicationDbContext>();
var provider = GetSetting(db, "storage.provider");
if (string.IsNullOrWhiteSpace(provider))
provider = Environment.GetEnvironmentVariable("STORAGE__PROVIDER");
if (string.IsNullOrWhiteSpace(provider))
provider = "Local";
@@ -277,12 +274,11 @@ public sealed class StorageProviderFactory : IStorageProvider, Heimdall.Applicat
var db = scope.ServiceProvider.GetRequiredService<IApplicationDbContext>();
var configuredProvider = GetSetting(db, "storage.provider");
var environmentProvider = Environment.GetEnvironmentVariable("STORAGE__PROVIDER");
var provider = !string.IsNullOrWhiteSpace(providerOverride)
? providerOverride
: !string.IsNullOrWhiteSpace(configuredProvider)
? configuredProvider
: !string.IsNullOrWhiteSpace(environmentProvider) ? environmentProvider : "Local";
: "Local";
if (provider.Equals("S3", StringComparison.OrdinalIgnoreCase))
{
@@ -23,6 +23,7 @@
</MudText>
<StorageSettingsSection />
<UpdatesSettingsSection />
<NotificationSettingsSection />
<AiSettingsSection />
<AgentDefaultsSection />
@@ -0,0 +1,58 @@
@namespace Heimdall.Web.Components.Settings
@inject HeimdallApiClient Api
@inject ISnackbar Snackbar
<MudPaper Elevation="1" Class="pa-4 mb-4" Style="border-radius: var(--hmd-radius-lg);">
<MudText Typo="Typo.h6" Class="mb-2"><i class="fas fa-arrows-rotate mr-2"></i>Mises à jour</MudText>
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-3">
Source globale des versions et des manifestes d’images Heimdall. L’URL doit être une adresse HTTPS absolue.
</MudText>
<MudTextField T="string" Label="API de publication" Variant="Variant.Outlined"
Value="@_url" ValueChanged="SaveUrlAsync"
Placeholder="https://forge.example/api/v1/repos/owner/repo/releases/latest" />
</MudPaper>
@code {
private const string SettingKey = "updates.releaseapiurl";
private List<AppSettingItem> _settings = [];
private string _url = string.Empty;
protected override async Task OnInitializedAsync()
{
try
{
_settings = await Api.GetSettingsAsync();
_url = _settings.FirstOrDefault(s => s.Key.Equals(SettingKey, StringComparison.OrdinalIgnoreCase))?.Value ?? string.Empty;
}
catch
{
_settings = [];
}
}
private async Task SaveUrlAsync(string value)
{
value = value?.Trim() ?? string.Empty;
if (value.Length > 0 && (!Uri.TryCreate(value, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps))
{
Snackbar.Add("L’URL doit être une adresse HTTPS absolue.", Severity.Warning);
return;
}
var existing = _settings.FirstOrDefault(s => s.Key.Equals(SettingKey, StringComparison.OrdinalIgnoreCase));
try
{
if (existing is null)
await Api.CreateSettingAsync(new CreateAppSettingRequest(SettingKey, value, "updates", "API de publication Heimdall", "string", null, false));
else
await Api.UpdateSettingAsync(existing.Key, new UpdateAppSettingRequest(value, existing.Description, "updates", "string", null, false));
_url = value;
_settings = await Api.GetSettingsAsync();
Snackbar.Add("Source des mises à jour enregistrée.", Severity.Success);
}
catch (Exception ex)
{
Snackbar.Add($"Impossible d’enregistrer la source des mises à jour : {ex.Message}", Severity.Error);
}
}
}
@@ -88,6 +88,8 @@
container_name: heimdall-agent-{{safeName}}
restart: unless-stopped
user: "1654:1654"
# Required for camera LAN discovery and RTSP access.
network_mode: host
environment:
Agent__CentralUrl: {{CentralUrl}}
Agent__SiteToken: {{SiteToken}}
@@ -3,7 +3,9 @@ using System.Security.Cryptography;
using System.Text.Json;
using System.Text.Json.Serialization;
using Heimdall.Infrastructure.Security;
using Heimdall.Infrastructure.Settings;
using Heimdall.Application.Services;
using Heimdall.Application.Common;
using Heimdall.Api.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@@ -20,7 +22,7 @@ public class UpdatesController : ControllerBase
private readonly ILogger<UpdatesController> _logger;
private readonly IConfigBroadcastService _configBroadcast;
private readonly ResourceAccess _resourceAccess;
private readonly IConfiguration _configuration;
private readonly IServiceProvider _services;
private static readonly JsonSerializerOptions Json = new()
{
@@ -32,13 +34,13 @@ public class UpdatesController : ControllerBase
private static LatestReleaseCache? _cache;
private static readonly TimeSpan CacheDuration = TimeSpan.FromHours(1);
public UpdatesController(IHttpClientFactory httpClientFactory, ILogger<UpdatesController> logger,
IConfigBroadcastService configBroadcast, ResourceAccess resourceAccess, IConfiguration configuration)
IConfigBroadcastService configBroadcast, ResourceAccess resourceAccess, IServiceProvider services)
{
_httpClientFactory = httpClientFactory;
_logger = logger;
_configBroadcast = configBroadcast;
_resourceAccess = resourceAccess;
_configuration = configuration;
_services = services;
}
[AllowAnonymous]
@@ -46,15 +48,16 @@ public class UpdatesController : ControllerBase
[ProducesResponseType(typeof(LatestReleaseResponse), StatusCodes.Status200OK)]
public async Task<IActionResult> GetLatestRelease(CancellationToken ct)
{
var cached = GetCached(_configuration["Updates:ReleaseApiUrl"]);
var source = await GetReleaseApiUrlAsync(ct);
var cached = GetCached(source);
if (cached is not null && !IsStale(cached))
return Ok(cached.Response);
if (cached is not null && IsStale(cached))
{
_ = RefreshCacheAsync(ct);
_ = RefreshCacheAsync(source, ct);
return Ok(cached.Response);
}
var result = await FetchLatestReleaseAsync(ct);
var result = await FetchLatestReleaseAsync(source, ct);
if (result is null)
return StatusCode(502, new { error = "Failed to fetch release info" });
return Ok(result);
@@ -68,14 +71,15 @@ public class UpdatesController : ControllerBase
{
var requester = await _resourceAccess.ResolveAsync(User, ct);
if (requester is null || requester.Kind != RequesterKind.Agent) return Forbid();
var cached = GetCached(_configuration["Updates:ReleaseApiUrl"]);
var source = await GetReleaseApiUrlAsync(ct);
var cached = GetCached(source);
if (cached is not null && !IsStale(cached)) return Ok(cached.Response);
if (cached is not null)
{
_ = RefreshCacheAsync(ct);
_ = RefreshCacheAsync(source, ct);
return Ok(cached.Response);
}
var result = await FetchLatestReleaseAsync(ct);
var result = await FetchLatestReleaseAsync(source, ct);
return result is null ? StatusCode(502, new { error = "Failed to fetch release info" }) : Ok(result);
}
@@ -85,8 +89,9 @@ public class UpdatesController : ControllerBase
public async Task<IActionResult> TriggerAgentUpdate(Guid id, CancellationToken ct)
{
_logger.LogInformation("Manual update requested for agent {AgentId}", id);
var cached = GetCached(_configuration["Updates:ReleaseApiUrl"]);
var release = cached is not null && !IsStale(cached) ? cached.Response : await FetchLatestReleaseAsync(ct);
var source = await GetReleaseApiUrlAsync(ct);
var cached = GetCached(source);
var release = cached is not null && !IsStale(cached) ? cached.Response : await FetchLatestReleaseAsync(source, ct);
if (release is null)
return StatusCode(502, new { error = "Failed to fetch release info" });
if (!await _configBroadcast.RequestAgentUpdate(id, ct))
@@ -94,14 +99,20 @@ public class UpdatesController : ControllerBase
return Accepted(new { agentId = id, command = "update-check", dispatched = true, release });
}
private async Task<LatestReleaseResponse?> FetchLatestReleaseAsync(CancellationToken ct)
private async Task<string?> GetReleaseApiUrlAsync(CancellationToken ct)
{
using var scope = _services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<IApplicationDbContext>();
return await AppSettingReader.GetAsync(db, "updates.releaseapiurl", ct).ConfigureAwait(false);
}
private async Task<LatestReleaseResponse?> FetchLatestReleaseAsync(string? source, CancellationToken ct)
{
var source = _configuration["Updates:ReleaseApiUrl"];
if (!Uri.TryCreate(source, UriKind.Absolute, out var sourceUri) ||
sourceUri.Scheme != Uri.UriSchemeHttps || !string.IsNullOrEmpty(sourceUri.UserInfo) ||
!string.IsNullOrEmpty(sourceUri.Fragment))
{
_logger.LogError("Updates:ReleaseApiUrl must be an absolute HTTPS URL without credentials or fragment");
_logger.LogError("The global release API setting must be an absolute HTTPS URL without credentials or fragment");
return null;
}
try
@@ -219,7 +230,10 @@ public class UpdatesController : ControllerBase
[JsonPropertyName("digest")] public string Digest { get; init; } = string.Empty;
}
private async Task RefreshCacheAsync(CancellationToken ct) { try { await FetchLatestReleaseAsync(ct); } catch { } }
private async Task RefreshCacheAsync(string? source, CancellationToken ct)
{
try { await FetchLatestReleaseAsync(source, ct); } catch { }
}
private static LatestReleaseCache? GetCached(string? source)
{
lock (_cacheLock) return _cache?.Source == source ? _cache : null;
+15 -12
View File
@@ -264,7 +264,7 @@ public partial class Program
{
var defaults = new Dictionary<string, string?>
{
["storage.provider"] = Environment.GetEnvironmentVariable("STORAGE__PROVIDER") ?? "Local",
["storage.provider"] = "Local",
["storage.local.path"] = Environment.GetEnvironmentVariable("STORAGE__LOCAL__PATH") ?? "./data/storage",
["storage.s3.endpoint"] = Environment.GetEnvironmentVariable("ALARIK_ENDPOINT")
?? Environment.GetEnvironmentVariable("S3_ENDPOINT"),
@@ -302,17 +302,18 @@ public partial class Program
var defaults = new Dictionary<string, string?>
{
["ntfy.baseUrl"] = Environment.GetEnvironmentVariable("NTFY__BASE_URL") ?? "https://ntfy.sh",
["ntfy.token"] = Environment.GetEnvironmentVariable("NTFY__TOKEN"),
["email.fromAddress"] = Environment.GetEnvironmentVariable("EMAIL__FROM_ADDRESS"),
["email.fromName"] = Environment.GetEnvironmentVariable("EMAIL__FROM_NAME"),
["email.smtpHost"] = Environment.GetEnvironmentVariable("EMAIL__SMTP_HOST"),
["email.smtpPort"] = Environment.GetEnvironmentVariable("EMAIL__SMTP_PORT") ?? "587",
["email.username"] = Environment.GetEnvironmentVariable("EMAIL__USERNAME"),
["email.password"] = Environment.GetEnvironmentVariable("EMAIL__PASSWORD"),
["email.useSsl"] = Environment.GetEnvironmentVariable("EMAIL__USE_SSL") ?? "true",
["ntfy.baseUrl"] = string.Empty,
["ntfy.token"] = string.Empty,
["email.fromAddress"] = string.Empty,
["email.fromName"] = "Heimdall",
["email.smtpHost"] = string.Empty,
["email.smtpPort"] = "587",
["email.username"] = string.Empty,
["email.password"] = string.Empty,
["email.useSsl"] = "true",
["ai.cpaiUrl"] = Environment.GetEnvironmentVariable("CPAI_URL"),
["ai.ollamaUrl"] = Environment.GetEnvironmentVariable("OLLAMA_URL"),
["ai.ollamaUrl"] = string.Empty,
["updates.releaseapiurl"] = string.Empty,
["ai.detection.enabled"] = Environment.GetEnvironmentVariable("AI__DETECTION__ENABLED") ?? "true",
["log.level"] = Environment.GetEnvironmentVariable("LOG__LEVEL") ?? "info",
["log.retentionDays"] = Environment.GetEnvironmentVariable("LOG__RETENTION_DAYS") ?? "7",
@@ -332,7 +333,8 @@ public partial class Program
if (existingKeys.Contains(key)) continue;
var agentScoped = !(key.StartsWith("ntfy.", StringComparison.Ordinal)
|| key.StartsWith("email.", StringComparison.Ordinal)
|| key.StartsWith("sentry.", StringComparison.Ordinal));
|| key.StartsWith("sentry.", StringComparison.Ordinal)
|| key.StartsWith("updates.", StringComparison.Ordinal));
var category = ResolveCategory(key);
groupDb.AppSettings.Add(new Heimdall.Domain.Entities.AppSetting(
key, value ?? string.Empty,
@@ -350,6 +352,7 @@ public partial class Program
"email.useSsl" => "Utiliser SSL/TLS pour SMTP",
"ai.cpaiUrl" => "URL CodeProject.AI",
"ai.ollamaUrl" => "URL Ollama",
"updates.releaseapiurl" => "API des versions Heimdall (HTTPS)",
"ai.detection.enabled" => "Détection IA activée par défaut",
"log.level" => "Niveau de log global (agents + central)",
"log.retentionDays" => "Rétention des logs agents (jours)",
@@ -23,8 +23,7 @@ public static class ApiBaseUrlResolver
/// <summary>Returns the explicitly configured URL, or null when unset.</summary>
public static string? ResolveConfigured(IConfiguration configuration) =>
configuration.GetValue<string>("ApiBaseUrl")
?? Environment.GetEnvironmentVariable("API_BASE_URL");
configuration.GetValue<string>("ApiBaseUrl");
/// <summary>
/// Effective origin for the current request (scheme://host). Returns null
@@ -61,6 +61,12 @@ public class SiteDetailTests : PageTestBase
cut.Markup.ShouldContain("Docker Compose");
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("network_mode: host");
compose.ShouldContain("Agent__SiteToken: tok-detail-42");
compose.ShouldNotContain("postgresql");
compose.ShouldNotContain("ollama");
});
}
+2 -2
View File
@@ -24,7 +24,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant
- [ ] **Heartbeat / failover** La PR #87 aligne le délai Offline sur la fréquence configurée (globalement ou par Agent), supprime le job concurrent qui pouvait empêcher la réaffectation, et relance celle-ci pour les Agents Offline qui gardent des caméras actives. La plage est limitée à 5–300 s comme côté Agent (timeout effectif maximal : 660 s). Les fixtures de failover utilisent un heartbeat vieux de 900 s pour tester un Agent effectivement expiré. Le run PR #276 a validé build/tests et les scans des images serveur et Agent; la validation sur plusieurs Agents reste à faire.
- [ ] **PIPE-10 / FEAT-05** La PR #74 fait remonter les erreurs ntfy; la PR #76 ajoute une outbox SQL atomique avec état, leases, reprise périodique et unicité par notification/canal. Sa CI (run #242) a validé les tests et scans d’images. La PR #110 ajoute des tests PostgreSQL du succès, du backoff après erreur, de la reprise de lease expirée, de l’ignorance des livraisons différées ou déjà prises et du routage Hangfire par canal. Le run PR #332 a passé les 155 tests d’intégration et les 35 E2E sans test ignoré, les builds/scans des deux images et `CI policy`; la publication Docker Hub a été ignorée comme prévu. Restent les essais SMTP/ntfy réels. La livraison reste au moins une fois : une panne après acceptation fournisseur mais avant l’acquittement SQL peut produire un doublon; aucune garantie exactement une fois n’est possible avec ces interfaces.
- [ ] **OPS-02** Les PR #62, #63 et #106 protègent les références de caméras supprimées logiquement, enregistrent l'inventaire des destinations avant upload et font parcourir ces destinations par le nettoyage final. Le run PR #317 a passé les 284 tests Infrastructure, dont les scénarios de changement de destination (snapshot référencé conservé, puis orphelin supprimé) et de S3 historique inaccessible (références conservées). Restent les objets recording tant que FEAT-02 n'a pas de producteur, les lignes historiques sans provenance (ne pas deviner), et la validation du changement de provider sur stockage déployé.
- [ ] **OPS-05 / AGENT-06** Les deux Compose de production (principal et généré par l’interface) montent maintenant la clé publique de release depuis un fichier hôte indépendant de Central, en lecture seule, et configurent `Agent__UpdatePublicKeyPath`; l’absence du fichier empêche explicitement le démarrage Docker. Restent l’installation des clés de signature CI/publication réelle, puis la validation de release, digest/signature, mise à jour native et Docker, arrêt propre et rollback.
- [ ] **OPS-05 / AGENT-06** Les Compose sont simplifiés en un noyau Central + PostgreSQL, un Compose Agent de développement local et des Compose facultatifs séparés par logiciel. En production, le Compose Agent est fourni par l’IHM pour le site sélectionné; le Compose statique de production a été supprimé pour éviter ce doublon. Le Compose généré utilise l’image et le digest fournis par Central, et le réseau hôte nécessaire à la découverte caméra est couvert par un test. La clé publique de release reste montée depuis un fichier indépendant de Central, en lecture seule. La PR #114 retire aussi du Compose les réglages métier (SMTP, ntfy, Ollama, stockage, source des releases et URL API) pour les gérer par l’IHM avec portée globale, en laissant les destinations de notification à leur portée site/utilisateur. Restent le passage CI, l’installation des clés de signature CI/publication réelle, puis la validation de release, digest/signature, mise à jour native et Docker, arrêt propre et rollback.
- [ ] **AGENT-08** Valider reconnexion, remplacement atomique de configuration caméra et ACK persisté sur Agent déployé.
- [ ] **AGENT-09** La PR #101 aligne `heimdall.ai.pipeline.level` sur les transitions réelles (inférence lente, moteur indisponible, saturation CPU et récupération), sans ratio cumulatif périmé. La PR #102 ajoute `heimdall.ai.inference.queue.depth` et `heimdall.ai.inference.queue.rejected` pour rendre visibles le backlog ONNX et les frames rejetées quand la file est pleine. Restent à mesurer les seuils de capture et la santé d'enregistrement sous panne caméra/modèle/disque, puis valider ces alertes sur matériel représentatif.
- [ ] **AGENT-10** Tester charge, redémarrages rapides et arrêt FFmpeg/ONNX sous contrainte sur matériel représentatif.
@@ -46,7 +46,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant
- [x] **Localisation #142** Le shell, le tableau de bord, le profil et les pages/composants UI utilisent les ressources FR/EN, avec français par défaut, bascule sans rechargement et clés complètes. Les notifications d’événements, les digests, les emails d’inscription/réinitialisation et le test SMTP utilisent aussi les ressources serveur FR/EN. La CI PR #93 (run #303) a passé le build, les suites .NET (1 730 tests), les 34 tests E2E, le contrôle NuGet et les builds/scans des images serveur et Agent.
- [ ] **Métriques #14** Les endpoints Prometheus `/metrics` Web et Agent sont mappés. La PR #68 ajoute et valide `heimdall.signalr.connections_by_hub` sur les cinq hubs Web. La jauge de viewers existe, mais aucun producteur WebRTC n'existe avant FEAT-01. Restent la validation de scraping sur un déploiement et l'évolution réelle des mesures.
- [x] Ajouter `.agents/skills/secure-env-secrets/SKILL.md` : procédures pour lire/écrire les secrets fournis par l'utilisateur dans l'environnement local, avec stockage persistant optionnel hors dépôt, permissions utilisateur uniquement et sans exposer la valeur. Le skill ne configure pas les secrets des workflows distants.
- [ ] Vérifier readiness et alertes pour modèle absent, file pleine, backlog, disque, jobs bloqués, perte de configuration et échec de livraison. Le contrôle stockage est aligné sur le fournisseur actif (settings DB/env), avec probe d’écriture locale, probe du bucket S3 sélectionné et timeout borné ; les health checks IA convertissent aussi leurs timeouts internes en état dégradé tout en propageant l’annulation appelante. La PR #109 ajoute les tests de `/readyz` sain/stockage mal configuré (sans fuite de configuration), de `/health/live` avec IA optionnelle absente et de diagnostics Agent lorsque le modèle ou le flux de capture manque ; le run PR #327 a passé 383 tests Agent, 150 tests d’intégration PostgreSQL, 35 E2E sans test ignoré, les builds/scans serveur/Agent et `CI policy`. La PR #111, mergée, ajoute les diagnostics de saturation CPU et garantit que cette saturation reste `Unhealthy` même quand la capture est également périmée ; le run PR #335 a passé les tests, scans serveur/Agent et `CI policy`. La PR #112, mergée après les runs #370, ajoute les profondeurs des files snapshots et inférence ainsi que les snapshots abandonnés. La PR #113 ajoute le taux d’occupation disque au diagnostic santé Agent sans définir de seuil de dégradation ; ses contrôles seront relancés sur sa base rebasée. Restent les alertes file pleine, backlog, disque, les jobs bloqués et les pannes à valider sur déploiement réel.
- [ ] Vérifier readiness et alertes pour modèle absent, file pleine, backlog, disque, jobs bloqués, perte de configuration et échec de livraison. Le contrôle stockage est aligné sur le fournisseur actif dans les réglages DB de l’IHM, avec probe d’écriture locale, probe du bucket S3 sélectionné et timeout borné ; les health checks IA convertissent aussi leurs timeouts internes en état dégradé tout en propageant l’annulation appelante. La PR #109 ajoute les tests de `/readyz` sain/stockage mal configuré (sans fuite de configuration), de `/health/live` avec IA optionnelle absente et de diagnostics Agent lorsque le modèle ou le flux de capture manque ; le run PR #327 a passé 383 tests Agent, 150 tests d’intégration PostgreSQL, 35 E2E sans test ignoré, les builds/scans serveur/Agent et `CI policy`. La PR #111, mergée, ajoute les diagnostics de saturation CPU et garantit que cette saturation reste `Unhealthy` même quand la capture est également périmée ; le run PR #335 a passé les tests, scans serveur/Agent et `CI policy`. La PR #112, mergée après les runs #370, ajoute les profondeurs des files snapshots et inférence ainsi que les snapshots abandonnés. La PR #113, mergée, ajoute le taux d’occupation disque au diagnostic santé Agent sans définir de seuil de dégradation. Restent les alertes file pleine, backlog, disque, les jobs bloqués et les pannes à valider sur déploiement réel.
- [ ] Actualiser les guides après chaque changement d'infrastructure, routes/API et statut produit ; distinguer implémenté, validé, partiel et prévu. Vérifier une installation depuis la documentation.
## Corrections déjà livrées à préserver