diff --git a/AGENTS.md b/AGENTS.md index 154fa6d..59df025 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,3 +13,4 @@ See [skills/heimdall-dotnet/SKILL.md](skills/heimdall-dotnet/SKILL.md) for project-specific implementation guidance. For database access, also follow [skills/ef-core-persistence/SKILL.md](skills/ef-core-persistence/SKILL.md); the CI persistence policy checks production source for direct database commands and requires documented provider-specific exceptions. For behavior changes, use [skills/compose-disposable-recipe/SKILL.md](skills/compose-disposable-recipe/SKILL.md); account bootstrap changes also use [skills/first-admin-bootstrap/SKILL.md](skills/first-admin-bootstrap/SKILL.md). +For Central installer, Compose, or server image update changes, also use [skills/central-auto-updates/SKILL.md](skills/central-auto-updates/SKILL.md). diff --git a/docker/docker-compose.backup.yml b/docker/docker-compose.backup.yml index 0de539b..0bf4cc5 100644 --- a/docker/docker-compose.backup.yml +++ b/docker/docker-compose.backup.yml @@ -3,6 +3,7 @@ services: backup: image: postgres:17-alpine + pull_policy: always restart: unless-stopped environment: POSTGRES_HOST: postgresql diff --git a/docker/docker-compose.coturn.yml b/docker/docker-compose.coturn.yml index acc4e6d..d5bb00b 100644 --- a/docker/docker-compose.coturn.yml +++ b/docker/docker-compose.coturn.yml @@ -2,6 +2,7 @@ services: coturn: image: coturn/coturn:4.6 + pull_policy: always command: > -n --use-auth-secret --static-auth-secret-file=/run/secrets/coturn_secret diff --git a/docker/docker-compose.ntfy.yml b/docker/docker-compose.ntfy.yml index 5ec2af8..9eb2361 100644 --- a/docker/docker-compose.ntfy.yml +++ b/docker/docker-compose.ntfy.yml @@ -2,6 +2,7 @@ services: ntfy: image: binwiederhier/ntfy:latest + pull_policy: always restart: unless-stopped command: ["serve"] environment: diff --git a/docker/docker-compose.ollama.yml b/docker/docker-compose.ollama.yml index 765eb6d..b752f25 100644 --- a/docker/docker-compose.ollama.yml +++ b/docker/docker-compose.ollama.yml @@ -2,6 +2,7 @@ services: ollama: image: ollama/ollama:latest + pull_policy: always restart: unless-stopped ports: - "${OLLAMA_PORT:-11434}:11434" diff --git a/docker/docker-compose.prod.yml b/docker/docker-compose.prod.yml index 24e243b..c86591f 100644 --- a/docker/docker-compose.prod.yml +++ b/docker/docker-compose.prod.yml @@ -11,6 +11,7 @@ x-logging: &default-logging services: postgresql: image: postgres:17-alpine + pull_policy: always environment: POSTGRES_DB: ${POSTGRES_DB:-heimdall} POSTGRES_USER: ${POSTGRES_USER:-heimdall} @@ -34,6 +35,9 @@ services: heimdall: image: eltruncho/heimdall:latest + pull_policy: always + labels: + com.centurylinklabs.watchtower.enable: "true" environment: DATABASE_URL: ${DATABASE_URL:?DATABASE_URL is required} JWT__Issuer: ${JWT__ISSUER:-heimdall} @@ -56,7 +60,7 @@ services: postgresql: condition: service_healthy healthcheck: - test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/healthz"] + test: ["CMD", "wget", "--no-verbose", "--tries=1", "--output-document=/dev/null", "http://127.0.0.1:8080/healthz"] interval: 30s timeout: 10s retries: 3 @@ -66,6 +70,17 @@ services: networks: - heimdall-net + watchtower: + image: nickfedor/watchtower:1.23.2 + pull_policy: always + command: ["--cleanup", "--label-enable", "--interval", "86400"] + volumes: + - /var/run/docker.sock:/var/run/docker.sock + restart: unless-stopped + logging: *default-logging + networks: + - heimdall-net + volumes: pgdata: heimdall_data: diff --git a/docker/docker-compose.redis.yml b/docker/docker-compose.redis.yml index db79fa8..8530ed9 100644 --- a/docker/docker-compose.redis.yml +++ b/docker/docker-compose.redis.yml @@ -2,6 +2,7 @@ services: redis: image: redis:7-alpine + pull_policy: always command: ["redis-server", "--appendonly", "yes", "--requirepass", "${REDIS_PASSWORD:?Set REDIS_PASSWORD}"] environment: REDISCLI_AUTH: ${REDIS_PASSWORD:?Set REDIS_PASSWORD} diff --git a/docker/docker-compose.rustfs.yml b/docker/docker-compose.rustfs.yml index d7063cc..cb10a36 100644 --- a/docker/docker-compose.rustfs.yml +++ b/docker/docker-compose.rustfs.yml @@ -3,6 +3,7 @@ services: rustfs: image: rustfs/rustfs:latest + pull_policy: always restart: unless-stopped ports: - "${RUSTFS_API_PORT:-9000}:9000" diff --git a/docs/docker-compose.md b/docs/docker-compose.md index 56f1add..8f933c8 100644 --- a/docs/docker-compose.md +++ b/docs/docker-compose.md @@ -14,15 +14,38 @@ repository; cloning the repository is not required: curl -fsSL https://sources.tordais.cc/arnaud.dartois/Heimdall/raw/branch/main/install/install-server.sh | bash ``` -The installer uses the server image `eltruncho/heimdall:latest` from Docker Hub, -creates a minimal Central + PostgreSQL Compose project, generates PostgreSQL -and JWT secrets, and writes them to a mode-600 `.env` and secret file in the -chosen installation directory. It asks which optional services to prepare and -whether to start each one. Selected optional Compose files and backup scripts -are fetched individually; no repository checkout is created. Integration URLs -and credentials remain configured in Central's UI. The script requires an -interactive terminal and reads prompts from it even when downloaded with a -pipe. +The installer uses `eltruncho/heimdall:latest` from Docker Hub, creates a +minimal Central + PostgreSQL Compose project, and configures the maintained +`nickfedor/watchtower` fork to check the explicitly labelled Central container +every 24 hours. Watchtower uses `--cleanup` to remove the previous Central +image after updating; it does not remove PostgreSQL data or named volumes. +`pull_policy: always` also makes each `docker compose up` pull the configured +images, including optional service Compose files. It generates PostgreSQL and JWT secrets locally and writes them to a +mode-600 `.env` and secret file in the chosen installation directory. It asks +which optional services to prepare and whether to start each one. Selected +optional Compose files and backup scripts are fetched individually; no +repository checkout is created. Integration URLs and credentials remain +configured in Central's UI. The script requires an interactive terminal and +reads prompts from it even when downloaded with a pipe. + +Running either installer again in the same directory offers to refresh the +generated Compose. It first validates the new file, saves the previous one as +`docker-compose.yml.bak.`, and replaces it. Existing `.env`, secret +files, and Docker volumes are preserved. If the new Compose requires an env +key that is missing, the installer adds a generated secret or a default value +without changing existing entries. It does not rotate the PostgreSQL password; +the existing secret file and `DATABASE_URL` must remain paired. Declining the +update leaves the installation unchanged. Inspect custom Compose edits in the +backup before deciding whether to carry them into future generated versions. +If you choose an optional service again, its refreshed Compose or script asset +also gets a timestamped backup before replacement. + +Watchtower needs access to `/var/run/docker.sock`, which grants broad control +over the Docker host. The upstream project describes itself for homelabs and +similar setups and does not recommend it for commercial/production workloads; +automatic latest-tag updates also do not provide staged rollout or rollback. +For stricter production change control, disable/remove the Watchtower service +and deploy a reviewed image digest through an orchestrator or release process. On Windows 10/11 with Docker Desktop in Linux-container mode, use PowerShell to download and run the matching installer without cloning the repository: @@ -44,8 +67,8 @@ variable also selects the optional Compose and backup files fetched by the installer. An offline installation must also provide those selected assets. The repository's `docker/docker-compose.prod.yml` is a manual alternative for -operators who need a custom layout. It does not use files generated by the -interactive installer. Keep `docker/.env` private (mode 600) and create a +operators who need a custom layout. It includes the same scoped Watchtower +service and pull policies. Keep `docker/.env` private (mode 600) and create a PostgreSQL password file; its value must match the password in `DATABASE_URL`. The `.env.example` file contains development credentials and must not be used unchanged for a production deployment. diff --git a/install/install-server.ps1 b/install/install-server.ps1 index aaff38f..5f4f04f 100644 --- a/install/install-server.ps1 +++ b/install/install-server.ps1 @@ -50,10 +50,26 @@ function Set-PrivateAcl { Set-Acl -LiteralPath $Path -AclObject $acl } +function Ensure-EnvValue { + param([string]$Content, [string]$Name, [string]$Value) + if ($Content -match "(?m)^$([regex]::Escape($Name))=") { return $Content } + return "$($Content.TrimEnd())`r`n$Name=$Value`r`n" +} + function Get-SourceAsset { param([string]$RelativePath, [string]$DestinationPath) $assetUri = "$script:SourceBaseUrl/$RelativePath" - Invoke-WebRequest -UseBasicParsing -Uri $assetUri -OutFile $DestinationPath -TimeoutSec 60 + $assetTempPath = "$DestinationPath.tmp.$([guid]::NewGuid().ToString('N'))" + try { + Invoke-WebRequest -UseBasicParsing -Uri $assetUri -OutFile $assetTempPath -TimeoutSec 60 + if (Test-Path -LiteralPath $DestinationPath) { + $backupPath = "$DestinationPath.bak.$(Get-Date -Format 'yyyyMMddTHHmmssfffZ')" + Copy-Item -LiteralPath $DestinationPath -Destination $backupPath + } + Move-Item -LiteralPath $assetTempPath -Destination $DestinationPath -Force + } finally { + if (Test-Path -LiteralPath $assetTempPath) { Remove-Item -LiteralPath $assetTempPath -Force } + } } function Invoke-DockerCompose { @@ -72,16 +88,29 @@ if ($LASTEXITCODE -ne 0) { throw 'Le plugin Docker Compose est requis.' } Write-Host 'Installation de Heimdall Central (serveur + PostgreSQL).' $defaultDestination = Join-Path $HOME 'heimdall' $destination = [IO.Path]::GetFullPath((Read-Answer "Dossier d’installation" $defaultDestination)) -$webPortText = Read-Answer 'Port HTTP du serveur' '5000' -$corsOrigin = Read-Answer 'Origine(s) autorisée(s) par CORS' '*' -$webPort = 0 -if (-not [int]::TryParse($webPortText, [ref]$webPort) -or $webPort -lt 1 -or $webPort -gt 65535) { - throw 'Port invalide.' -} -if ($corsOrigin -notmatch '^[A-Za-z0-9*.,:/_-]+$') { throw 'Origine CORS invalide.' } -if ((Test-Path -LiteralPath (Join-Path $destination 'docker-compose.yml')) -or - (Test-Path -LiteralPath (Join-Path $destination '.env'))) { - throw "Le dossier contient déjà une installation Heimdall; aucun fichier n’a été remplacé." +$composePath = Join-Path $destination 'docker-compose.yml' +$envPath = Join-Path $destination '.env' +$dbPasswordPath = Join-Path (Join-Path $destination 'secrets') 'db_password' +$isExisting = (Test-Path -LiteralPath $composePath) -or (Test-Path -LiteralPath $envPath) +if ($isExisting) { + if (-not (Test-Path -LiteralPath $composePath) -or -not (Test-Path -LiteralPath $envPath) -or + -not (Test-Path -LiteralPath $dbPasswordPath)) { + throw 'Installation existante incomplète; aucun fichier modifié.' + } + if (-not (Read-YesNo 'Installation existante : mettre à jour le Compose (sauvegarde du précédent), en conservant .env, secrets et volumes ?' 'o')) { + Write-Host 'Installation laissée inchangée.' + return + } + $webPort = 5000 + $corsOrigin = '*' +} else { + $webPortText = Read-Answer 'Port HTTP du serveur' '5000' + $corsOrigin = Read-Answer 'Origine(s) autorisée(s) par CORS' '*' + $webPort = 0 + if (-not [int]::TryParse($webPortText, [ref]$webPort) -or $webPort -lt 1 -or $webPort -gt 65535) { + throw 'Port invalide.' + } + if ($corsOrigin -notmatch '^[A-Za-z0-9*.,:/_-]+$') { throw 'Origine CORS invalide.' } } $null = New-Item -ItemType Directory -Path $destination -Force @@ -95,14 +124,14 @@ Set-PrivateAcl -Path $secretsDirectory -IsDirectory $true Set-PrivateAcl -Path $optionalDirectory -IsDirectory $true Set-PrivateAcl -Path $optionalSecretsDirectory -IsDirectory $true -$dbPassword = New-RandomHex -$jwtKey = New-RandomHex -$jwtRefreshKey = New-RandomHex -$dbPasswordPath = Join-Path $secretsDirectory 'db_password' -[IO.File]::WriteAllText($dbPasswordPath, $dbPassword, [Text.Encoding]::ASCII) -Set-PrivateAcl -Path $dbPasswordPath - -$envContent = @" +$envContent = $null +if (-not $isExisting) { + $dbPassword = New-RandomHex + $jwtKey = New-RandomHex + $jwtRefreshKey = New-RandomHex + [IO.File]::WriteAllText($dbPasswordPath, $dbPassword, [Text.Encoding]::ASCII) + Set-PrivateAcl -Path $dbPasswordPath + $envContent = @" POSTGRES_DB=heimdall POSTGRES_USER=heimdall DATABASE_URL=Host=postgresql;Port=5432;Database=heimdall;Username=heimdall;Password=$dbPassword @@ -117,9 +146,28 @@ TZ=Europe/Paris REDIS_PASSWORD=$(New-RandomHex) HEIMDALL_DATA_VOLUME=heimdall_heimdall_data "@ -$envPath = Join-Path $destination '.env' -[IO.File]::WriteAllText($envPath, $envContent.TrimStart("`r", "`n"), [Text.Encoding]::ASCII) -Set-PrivateAcl -Path $envPath + [IO.File]::WriteAllText($envPath, $envContent.TrimStart("`r", "`n"), [Text.Encoding]::ASCII) + Set-PrivateAcl -Path $envPath +} else { + $envContent = [IO.File]::ReadAllText($envPath) + if ($envContent -notmatch '(?m)^DATABASE_URL=') { + throw 'DATABASE_URL est absent du .env existant; complète-le sans changer le mot de passe PostgreSQL avant de relancer.' + } + $envContent = Ensure-EnvValue $envContent 'JWT__KEY' (New-RandomHex) + $envContent = Ensure-EnvValue $envContent 'JWT__REFRESHKEY' (New-RandomHex) + $envContent = Ensure-EnvValue $envContent 'POSTGRES_DB' 'heimdall' + $envContent = Ensure-EnvValue $envContent 'POSTGRES_USER' 'heimdall' + $envContent = Ensure-EnvValue $envContent 'JWT__ISSUER' 'heimdall' + $envContent = Ensure-EnvValue $envContent 'JWT__AUDIENCE' 'heimdall-api' + $envContent = Ensure-EnvValue $envContent 'ASPNETCORE_ENVIRONMENT' 'Production' + $envContent = Ensure-EnvValue $envContent 'WEB_PORT' '5000' + $envContent = Ensure-EnvValue $envContent 'Cors__AllowedOrigins' '*' + $envContent = Ensure-EnvValue $envContent 'TZ' 'Europe/Paris' + $envContent = Ensure-EnvValue $envContent 'REDIS_PASSWORD' (New-RandomHex) + $envContent = Ensure-EnvValue $envContent 'HEIMDALL_DATA_VOLUME' 'heimdall_heimdall_data' + [IO.File]::WriteAllText($envPath, $envContent, [Text.Encoding]::ASCII) + Set-PrivateAcl -Path $envPath +} $composeContent = @' name: heimdall @@ -127,6 +175,7 @@ name: heimdall services: postgresql: image: postgres:17-alpine + pull_policy: always environment: POSTGRES_DB: ${POSTGRES_DB} POSTGRES_USER: ${POSTGRES_USER} @@ -144,6 +193,9 @@ services: heimdall: image: eltruncho/heimdall:latest + pull_policy: always + labels: + com.centurylinklabs.watchtower.enable: "true" environment: DATABASE_URL: ${DATABASE_URL:?missing DATABASE_URL} JWT__Issuer: ${JWT__ISSUER} @@ -161,7 +213,7 @@ services: postgresql: condition: service_healthy healthcheck: - test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/healthz"] + test: ["CMD", "wget", "--no-verbose", "--tries=1", "--output-document=/dev/null", "http://127.0.0.1:8080/healthz"] interval: 30s timeout: 10s retries: 3 @@ -169,6 +221,15 @@ services: restart: unless-stopped networks: [heimdall-net] + watchtower: + image: nickfedor/watchtower:1.23.2 + pull_policy: always + command: ["--cleanup", "--label-enable", "--interval", "86400"] + volumes: + - /var/run/docker.sock:/var/run/docker.sock + restart: unless-stopped + networks: [heimdall-net] + volumes: pgdata: heimdall_data: @@ -182,9 +243,9 @@ networks: name: heimdall-net driver: bridge '@ -$composePath = Join-Path $destination 'docker-compose.yml' -[IO.File]::WriteAllText($composePath, $composeContent, [Text.Encoding]::ASCII) -Set-PrivateAcl -Path $composePath +$composeTempPath = Join-Path $destination ".docker-compose.$([guid]::NewGuid().ToString('N')).tmp" +[IO.File]::WriteAllText($composeTempPath, $composeContent, [Text.Encoding]::ASCII) +Set-PrivateAcl -Path $composeTempPath $selected = [Collections.Generic.List[string]]::new() foreach ($service in @('ollama', 'ntfy', 'rustfs', 'coturn', 'redis', 'backup')) { @@ -202,7 +263,17 @@ foreach ($service in @('ollama', 'ntfy', 'rustfs', 'coturn', 'redis', 'backup')) Write-Host "Compose généré dans $composePath" Write-Host "Variables protégées dans $envPath et secret PostgreSQL dans secrets (ACL utilisateur uniquement)." Write-Host 'Validation du Compose avant démarrage…' -Invoke-DockerCompose @('--env-file', $envPath, '-f', $composePath, 'config', '--quiet') +try { + Invoke-DockerCompose @('--env-file', $envPath, '-f', $composeTempPath, 'config', '--quiet') + if ($isExisting) { + $backupPath = "$composePath.bak.$(Get-Date -Format 'yyyyMMddTHHmmssfffZ')" + Copy-Item -LiteralPath $composePath -Destination $backupPath + Write-Host "Ancien Compose sauvegardé dans $backupPath" + } + Move-Item -LiteralPath $composeTempPath -Destination $composePath -Force +} finally { + if (Test-Path -LiteralPath $composeTempPath) { Remove-Item -LiteralPath $composeTempPath -Force } +} $startCore = Read-YesNo 'Démarrer PostgreSQL et Heimdall maintenant ?' 'o' if ($startCore) { Invoke-DockerCompose @('--env-file', $envPath, '-f', $composePath, 'up', '-d') diff --git a/install/install-server.sh b/install/install-server.sh index dd5ac6b..8930a26 100755 --- a/install/install-server.sh +++ b/install/install-server.sh @@ -32,37 +32,54 @@ done docker compose version >/dev/null copy_source_asset() { - local relative_path="$1" destination_path="$2" + local relative_path="$1" destination_path="$2" asset_tmp="${2}.tmp.$$" if [[ -n "$REPO_ROOT" && -f "$REPO_ROOT/$relative_path" ]]; then - cp "$REPO_ROOT/$relative_path" "$destination_path" + cp "$REPO_ROOT/$relative_path" "$asset_tmp" else - curl --fail --silent --show-error --location \ - "$SOURCE_BASE_URL/$relative_path" --output "$destination_path" + if ! curl --fail --silent --show-error --location \ + "$SOURCE_BASE_URL/$relative_path" --output "$asset_tmp"; then + rm -f "$asset_tmp" + return 1 + fi fi + if [[ -e "$destination_path" ]]; then + cp -p "$destination_path" "$destination_path.bak.$(date -u +%Y%m%dT%H%M%SZ)" + fi + mv -f "$asset_tmp" "$destination_path" } say "Installation de Heimdall Central (serveur + PostgreSQL)." destination="$(ask 'Dossier d’installation' "$HOME/heimdall")" -web_port="$(ask 'Port HTTP du serveur' '5000')" -cors_origin="$(ask 'Origine(s) autorisée(s) par CORS' '*')" -[[ "$web_port" =~ ^[0-9]{1,5}$ ]] && (( web_port >= 1 && web_port <= 65535 )) || { echo "Port invalide." >&2; exit 1; } -[[ "$cors_origin" =~ ^[A-Za-z0-9*.,:/_-]+$ ]] || { echo "Origine CORS invalide." >&2; exit 1; } - -mkdir -p "$destination/secrets" "$destination/optional" -mkdir -p "$destination/optional/secrets" -chmod 700 "$destination" "$destination/secrets" "$destination/optional" -if [[ -e "$destination/docker-compose.yml" || -e "$destination/.env" ]]; then - echo "Le dossier contient déjà une installation Heimdall; aucun fichier n’a été remplacé." >&2 - exit 1 +compose_path="$destination/docker-compose.yml" +env_path="$destination/.env" +is_existing=no +if [[ -e "$compose_path" || -e "$env_path" ]]; then + if [[ ! -f "$compose_path" || ! -f "$env_path" || ! -f "$destination/secrets/db_password" ]]; then + echo "Installation existante incomplète; aucun fichier n’a été modifié." >&2 + exit 1 + fi + if [[ "$(ask 'Installation existante : mettre à jour le Compose (sauvegarde du précédent), en conservant .env, secrets et volumes ?' 'o')" =~ ^([nN]|[nN][oO][nN]?)$ ]]; then + say "Installation laissée inchangée." + exit 0 + fi + is_existing=yes +else + web_port="$(ask 'Port HTTP du serveur' '5000')" + cors_origin="$(ask 'Origine(s) autorisée(s) par CORS' '*')" + [[ "$web_port" =~ ^[0-9]{1,5}$ ]] && (( web_port >= 1 && web_port <= 65535 )) || { echo "Port invalide." >&2; exit 1; } + [[ "$cors_origin" =~ ^[A-Za-z0-9*.,:/_-]+$ ]] || { echo "Origine CORS invalide." >&2; exit 1; } fi -db_password="$(openssl rand -hex 32)" -jwt_key="$(openssl rand -hex 32)" -jwt_refresh_key="$(openssl rand -hex 32)" -printf '%s' "$db_password" > "$destination/secrets/db_password" -chmod 600 "$destination/secrets/db_password" +mkdir -p "$destination/secrets" "$destination/optional" "$destination/optional/secrets" +chmod 700 "$destination" "$destination/secrets" "$destination/optional" -cat > "$destination/.env" < "$destination/secrets/db_password" + chmod 600 "$destination/secrets/db_password" + cat > "$env_path" <> "$env_path" + fi + } + if ! grep -q '^DATABASE_URL=' "$env_path"; then + echo "DATABASE_URL est absent du .env existant; complète-le sans changer le mot de passe PostgreSQL avant de relancer." >&2 + exit 1 + fi + ensure_env_value JWT__KEY "$(openssl rand -hex 32)" + ensure_env_value JWT__REFRESHKEY "$(openssl rand -hex 32)" + ensure_env_value POSTGRES_DB heimdall + ensure_env_value POSTGRES_USER heimdall + ensure_env_value JWT__ISSUER heimdall + ensure_env_value JWT__AUDIENCE heimdall-api + ensure_env_value ASPNETCORE_ENVIRONMENT Production + ensure_env_value WEB_PORT 5000 + ensure_env_value Cors__AllowedOrigins '*' + ensure_env_value TZ Europe/Paris + ensure_env_value REDIS_PASSWORD "$(openssl rand -hex 32)" + ensure_env_value HEIMDALL_DATA_VOLUME heimdall_heimdall_data + chmod 600 "$env_path" +fi -cat > "$destination/docker-compose.yml" <<'COMPOSE' +compose_tmp="$(mktemp "$destination/.docker-compose.yml.XXXXXX")" +trap 'rm -f "${compose_tmp:-}"' EXIT +cat > "$compose_tmp" <<'COMPOSE' name: heimdall services: postgresql: image: postgres:17-alpine + pull_policy: always environment: POSTGRES_DB: ${POSTGRES_DB} POSTGRES_USER: ${POSTGRES_USER} @@ -102,6 +147,9 @@ services: heimdall: image: eltruncho/heimdall:latest + pull_policy: always + labels: + com.centurylinklabs.watchtower.enable: "true" environment: DATABASE_URL: ${DATABASE_URL:?missing DATABASE_URL} JWT__Issuer: ${JWT__ISSUER} @@ -119,7 +167,7 @@ services: postgresql: condition: service_healthy healthcheck: - test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/healthz"] + test: ["CMD", "wget", "--no-verbose", "--tries=1", "--output-document=/dev/null", "http://127.0.0.1:8080/healthz"] interval: 30s timeout: 10s retries: 3 @@ -127,6 +175,15 @@ services: restart: unless-stopped networks: [heimdall-net] + watchtower: + image: nickfedor/watchtower:1.23.2 + pull_policy: always + command: ["--cleanup", "--label-enable", "--interval", "86400"] + volumes: + - /var/run/docker.sock:/var/run/docker.sock + restart: unless-stopped + networks: [heimdall-net] + volumes: pgdata: heimdall_data: @@ -140,7 +197,16 @@ networks: name: heimdall-net driver: bridge COMPOSE -chmod 600 "$destination/docker-compose.yml" +chmod 600 "$compose_tmp" +docker compose --env-file "$env_path" -f "$compose_tmp" config --quiet +if [[ "$is_existing" == yes ]]; then + backup_path="$compose_path.bak.$(date -u +%Y%m%dT%H%M%SZ)" + cp -p "$compose_path" "$backup_path" + say "Ancien Compose sauvegardé dans $backup_path" +fi +mv -f "$compose_tmp" "$compose_path" +compose_tmp="" +trap - EXIT declare -a selected=() for service in ollama ntfy rustfs coturn redis backup; do @@ -160,10 +226,9 @@ done say "Compose généré dans $destination/docker-compose.yml" say "Variables protégées dans $destination/.env (mode 600), secret PostgreSQL dans secrets/ (mode 600)." say "Validation du Compose avant démarrage…" -docker compose --env-file "$destination/.env" -f "$destination/docker-compose.yml" config --quiet start_core=no if [[ "$(ask 'Démarrer PostgreSQL et Heimdall maintenant ?' 'o')" =~ ^([oO]|[oO][uU][iI]|[yY]|[yY][eE][sS])$ ]]; then - docker compose --env-file "$destination/.env" -f "$destination/docker-compose.yml" up -d + docker compose --env-file "$env_path" -f "$compose_path" up -d start_core=yes fi diff --git a/skills/central-auto-updates/SKILL.md b/skills/central-auto-updates/SKILL.md new file mode 100644 index 0000000..9c02a15 --- /dev/null +++ b/skills/central-auto-updates/SKILL.md @@ -0,0 +1,27 @@ +--- +name: central-auto-updates +description: Maintain Central server installation, Compose refresh, and Docker image auto-updates for Heimdall deployments. +--- + +# Central installation and image updates + +Use this skill when changing the Linux or Windows Central installer, its generated Compose, or Central container update behavior. + +## Deployment behavior + +- Keep the installer-generated core stack limited to PostgreSQL, Central, and the updater. Only Central receives the Watchtower enable label; do not update PostgreSQL automatically. +- Use the maintained `nickfedor/watchtower` image at an explicit version, `--label-enable`, a 24-hour interval, and `--cleanup`. Cleanup removes superseded images after an update; it must never remove Docker volumes or database files. +- Apply `pull_policy: always` to published Docker images in deployment Compose files so a manual `docker compose up` checks the registry. Leave local development-only images alone and keep the updater itself version-pinned. +- The Docker socket mount grants Watchtower broad control of the host. Document this risk and the lack of staged rollout/rollback; do not describe automatic updates as a production-safe rollback system. + +## Re-running the installer + +- A complete existing install can regenerate its Compose after validating the candidate. Keep a timestamped backup of the previous Compose before atomic replacement. +- If the operator selects an existing optional service again, refresh its source assets through a temporary file and back up each replaced local asset. +- Preserve `.env`, the PostgreSQL secret file, and Docker named volumes. Do not rotate existing credentials during an update. +- When a newer Compose needs an absent env key, append a generated secret or documented default only if that key is missing. Never print secret values. Refuse to continue if the existing database URL or password file needed by PostgreSQL is missing. +- If the user declines the Compose refresh, exit without changing the install. If only part of an install is present, stop and explain what is missing instead of creating a second set of credentials. + +## 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. Then follow `skills/compose-disposable-recipe/SKILL.md` with a unique project, generated credentials, isolated ports/volumes, and scoped teardown. Never connect the recipe to a deployed Docker daemon or production data. diff --git a/todo.md b/todo.md index 7dcabe8..4fe3b4a 100644 --- a/todo.md +++ b/todo.md @@ -28,9 +28,9 @@ 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 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é. La PR #114 retire 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. La PR #117 ajoute l’installateur interactif Linux Central + PostgreSQL et fixe les images à Docker Hub; sa CI PR #394 a passé tests et scans des deux images ainsi que `CI policy`, puis a été fusionnée sur `main` (`d1f3f1a`). Restent l’installation des clés de signature CI et la validation réelle de la génération IHM, digest/signature Agent, mise à jour native/Docker, arrêt propre et rollback. +- [ ] **OPS-05 / AGENT-06** Les Compose sont simplifiés en un noyau Central + PostgreSQL (avec Watchtower pour la mise à jour Central), 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é. La PR #114 retire 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. La PR #117 ajoute l’installateur interactif Linux Central + PostgreSQL et fixe les images à Docker Hub; sa CI PR #394 a passé tests et scans des deux images ainsi que `CI policy`, puis a été fusionnée sur `main` (`d1f3f1a`). Restent l’installation des clés de signature CI et la validation réelle de la génération IHM, digest/signature Agent, mise à jour native/Docker, arrêt propre et rollback. - [ ] **Installateurs Agent / mises à jour façon Pangolin** La PR #120 ajoute les choix d’OS et méthodes supportés dans l’IHM, les commandes Bash/PowerShell qui téléchargent les scripts depuis Central, les installs natives Linux/Windows vérifiant signature et digest, le mode service, le rollback après contrôle de démarrage, le réglage global avec surcharge nullable de site, et les mises à jour natives après 24 h de stabilité (les conteneurs restent gérés par l’orchestrateur). La migration conserve les choix existants. La PR #127 rend la commande PowerShell compatible avec les postes `Restricted` en appliquant le contournement d’exécution à la session courante seulement; une GPO peut encore prévaloir. Le run PR #437 a passé tests/build, scans des deux images et `CI policy`. Restent les validations réelles d’installation, mise à jour et rollback sur hôtes Linux et Windows. -- [ ] **Installateur Central sans clone (Linux/Windows)** Les scripts `install/install-server.sh` et `install/install-server.ps1` peuvent être téléchargés depuis la branche `main` et exécutés directement; ils créent le Compose Central + PostgreSQL, les secrets locaux protégés et téléchargent seulement les Compose facultatifs choisis. L’installation PowerShell vise Windows 10/11 avec Docker Desktop configuré pour les conteneurs Linux. Restent à valider les deux commandes bootstrap sur des hôtes propres, le démarrage, les ACL Windows, les services facultatifs et l’absence de checkout du dépôt. +- [ ] **Installateur Central sans clone (Linux/Windows)** Les scripts `install/install-server.sh` et `install/install-server.ps1` peuvent être téléchargés depuis la branche `main` et exécutés directement; ils créent le Compose Central + PostgreSQL + Watchtower, les secrets locaux protégés et téléchargent seulement les Compose facultatifs choisis. Les images publiées des Compose d’exploitation utilisent `pull_policy: always`; Watchtower (fork actif `nickfedor/watchtower`) ne surveille que Central, vérifie toutes les 24 h et supprime les anciennes images après mise à jour (`--cleanup`), sans effacer les volumes. Une réexécution peut sauvegarder/remplacer le Compose, sauvegarder les fichiers optionnels sélectionnés et compléter uniquement les variables absentes, en conservant `.env`, secrets existants et volumes. La recette Linux première installation + réexécution a passé; le Compose Central/PostgreSQL/Watchtower a passé la recette jetable, le health check Central et le nettoyage ciblé. Restent la validation Windows réelle/ACL, les hôtes propres et les services facultatifs démarrés. - [ ] **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.