Complete durable agent analysis job flow
Heimdall Gitea / Build and scan server image (pull_request) Canceled after 0s
Heimdall Gitea / Build and scan agent image (pull_request) Canceled after 0s
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Canceled after 0s
Heimdall Gitea / Publish versioned release (pull_request) Canceled after 0s
Heimdall Gitea / Build and tests (pull_request) Canceled after 12m24s
Heimdall Gitea / Build and scan server image (pull_request) Canceled after 0s
Heimdall Gitea / Build and scan agent image (pull_request) Canceled after 0s
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Canceled after 0s
Heimdall Gitea / Publish versioned release (pull_request) Canceled after 0s
Heimdall Gitea / Build and tests (pull_request) Canceled after 12m24s
This commit is contained in:
1 parent
6af7fceb03
commit
6fc8efc438
27 files changed
+689
-123
No files matched your search
@@ -11,6 +11,8 @@
|
||||
# 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
|
||||
|
||||
# JWT (change in production!)
|
||||
# JWT__Key is used for access tokens, JWT__RefreshKey for refresh tokens.
|
||||
|
||||
@@ -21,6 +21,9 @@ on:
|
||||
tags: ['v*']
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
BUILD_SERVER_URL: ${{ gitea.server_url }}
|
||||
BUILD_REPOSITORY: ${{ gitea.repository }}
|
||||
jobs:
|
||||
verify:
|
||||
name: Build and tests
|
||||
@@ -135,13 +138,14 @@ jobs:
|
||||
run: bash scripts/ci/images.sh server
|
||||
- name: Scan server image
|
||||
run: bash scripts/ci/security.sh server
|
||||
- name: Push immutable server image to Docker Hub
|
||||
- name: Push immutable server image to configured registry
|
||||
if: gitea.ref == 'refs/heads/main'
|
||||
env:
|
||||
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
DOCKERHUB_NAMESPACE: eltruncho
|
||||
run: bash scripts/ci/push-dockerhub.sh server
|
||||
IMAGE_REGISTRY_USER: ${{ secrets.IMAGE_REGISTRY_USER }}
|
||||
IMAGE_REGISTRY_TOKEN: ${{ secrets.IMAGE_REGISTRY_TOKEN }}
|
||||
run: bash scripts/ci/push-images.sh server
|
||||
- name: Reclaim build storage after job
|
||||
if: always()
|
||||
run: |
|
||||
@@ -178,13 +182,14 @@ jobs:
|
||||
run: bash scripts/ci/images.sh agent
|
||||
- name: Scan agent image
|
||||
run: bash scripts/ci/security.sh agent
|
||||
- name: Push immutable agent image to Docker Hub
|
||||
- name: Push immutable agent image to configured registry
|
||||
if: gitea.ref == 'refs/heads/main'
|
||||
env:
|
||||
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
DOCKERHUB_NAMESPACE: eltruncho
|
||||
run: bash scripts/ci/push-dockerhub.sh agent
|
||||
IMAGE_REGISTRY_USER: ${{ secrets.IMAGE_REGISTRY_USER }}
|
||||
IMAGE_REGISTRY_TOKEN: ${{ secrets.IMAGE_REGISTRY_TOKEN }}
|
||||
run: bash scripts/ci/push-images.sh agent
|
||||
- name: Reclaim build storage after job
|
||||
if: always()
|
||||
run: |
|
||||
@@ -219,8 +224,9 @@ jobs:
|
||||
env:
|
||||
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
DOCKERHUB_NAMESPACE: eltruncho
|
||||
run: bash scripts/ci/push-dockerhub.sh latest
|
||||
IMAGE_REGISTRY_USER: ${{ secrets.IMAGE_REGISTRY_USER }}
|
||||
IMAGE_REGISTRY_TOKEN: ${{ secrets.IMAGE_REGISTRY_TOKEN }}
|
||||
run: bash scripts/ci/push-images.sh latest
|
||||
- name: Reclaim build storage after job
|
||||
if: always()
|
||||
run: |
|
||||
@@ -273,6 +279,9 @@ jobs:
|
||||
AGENT_REGISTRY_TOKEN: ${{ secrets.AGENT_REGISTRY_TOKEN }}
|
||||
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
IMAGE_REGISTRY_USER: ${{ secrets.IMAGE_REGISTRY_USER }}
|
||||
IMAGE_REGISTRY_TOKEN: ${{ secrets.IMAGE_REGISTRY_TOKEN }}
|
||||
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||
RELEASE_SIGNING_KEY_B64: ${{ secrets.RELEASE_SIGNING_KEY_B64 }}
|
||||
EXPECTED_BUILD_SERVER_URL: ${{ vars.RELEASE_SERVER_URL }}
|
||||
run: bash scripts/ci/publish.sh
|
||||
@@ -13,9 +13,8 @@
|
||||
# openssl rand -base64 32 > docker/secrets/rustfs_secret_key
|
||||
# echo -n "your-smtp-password" > docker/secrets/smtp_password
|
||||
#
|
||||
# Images are published by the CI pipeline on main branch pushes:
|
||||
# eltruncho/heimdall:latest
|
||||
# image reference from the current Central agent-image.json manifest
|
||||
# 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)
|
||||
@@ -74,7 +73,7 @@ services:
|
||||
- heimdall-net
|
||||
|
||||
heimdall:
|
||||
image: eltruncho/heimdall:latest
|
||||
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}
|
||||
@@ -90,7 +89,7 @@ services:
|
||||
# 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:-https://sources.tordais.cc/api/v1/repos/arnaud.dartois/Heimdall/releases/latest}
|
||||
Updates__ReleaseApiUrl: ${UPDATES_RELEASE_API_URL:?Set the Central release API URL}
|
||||
# Ollama (optional — daily summaries)
|
||||
Ollama__Endpoint: http://ollama:11434
|
||||
# Coturn (WebRTC relay)
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"image": "eltruncho/heimdall"
|
||||
}
|
||||
@@ -14,6 +14,8 @@ base64 -w0 agent-release-private.pem
|
||||
|
||||
La dernière sortie est la valeur du secret Gitea Actions `RELEASE_SIGNING_KEY_B64`. Ne pas ajouter la clé privée au dépôt ni aux images. Distribuer `agent-release-public.pem` par un canal d’administration indépendant de Central. La publication d’une release échoue si le secret de signature manque.
|
||||
|
||||
Configurer également la variable Gitea Actions `RELEASE_SERVER_URL` avec l’origine HTTPS de la forge attendue (par exemple `https://sources.tordais.cc`, sans chemin). La publication compare cette valeur à `BUILD_SERVER_URL`, fourni par Gitea, avant toute publication. Les dépôts d’image serveur et Agent viennent de `docker/server-image.json` et `docker/agent-image.json`; fournir les secrets du registre correspondant. Central transmet à l’Agent le dépôt et le digest signés dans la release.
|
||||
|
||||
La publication génère `agent-update-manifest.json`, qui lie la version, les SHA-256 des archives Agent et le dépôt ainsi que le digest immuable de l’image Docker. Elle publie aussi `agent-update-manifest.sig`, signature ECDSA/SHA-256 du fichier JSON. La clé publique permet de vérifier ces valeurs avant tout remplacement d’agent. Une modification de l’URL de la forge ou du registre reste possible sans changer cette clé.
|
||||
|
||||
## Installer un Agent natif
|
||||
|
||||
@@ -104,10 +104,11 @@ Le dossier `docker/` contient tout nécessaire pour déployer Heimdall :
|
||||
| `docker-compose.local.yml` | Surcharges locales | Ajustements optionnels, par exemple l'exposition d'un GPU |
|
||||
| `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.) |
|
||||
|
||||
Pour une installation de production, 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 proviennent du manifeste `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`. 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.
|
||||
|
||||
### Services
|
||||
|
||||
@@ -115,7 +116,7 @@ Pour une installation de production, définissez `AGENT_IMAGE_REFERENCE` sur la
|
||||
|---|---|---|---|
|
||||
| `postgresql` | `postgres:17-alpine` | 5432 | — |
|
||||
| `rustfs` | `rustfs/rustfs:latest` | 9000 (S3), 9001 (console) | — |
|
||||
| `heimdall` | `heimdall:latest` (dev) / `eltruncho/heimdall:latest` (prod) | 5000 | postgresql (healthy) |
|
||||
| `heimdall` | `heimdall:latest` (dev) / `SERVER_IMAGE_REFERENCE` (prod) | 5000 | postgresql (healthy) |
|
||||
| `heimdall-agent` | `heimdall-agent:latest` (dev) / `AGENT_IMAGE_REFERENCE` (prod) | — | heimdall |
|
||||
| `ntfy` | `binwiederhier/ntfy` | 8080 | — |
|
||||
| `coturn` | `coturn/coturn:4.6` | 3478 | — |
|
||||
@@ -215,11 +216,11 @@ Générer un token via `POST /api/sites/{id}/tokens` sur l'API.
|
||||
|
||||
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). Elle pointe par défaut vers les releases
|
||||
du dépôt `sources.tordais.cc/arnaud.dartois/Heimdall` et peut être changée sans
|
||||
recompiler le serveur. L'agent lit le nom et le digest de l'image dans le
|
||||
manifeste authentifié de Central ; le dépôt d'image publié est défini dans
|
||||
`docker/agent-image.json` lors de la release.
|
||||
`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
|
||||
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`.
|
||||
La [procédure de signature des releases agent](docs/agent-release-signing.md)
|
||||
décrit la clé publique locale requise pour les mises à jour natives et Docker.
|
||||
|
||||
|
||||
@@ -12,18 +12,12 @@ df -i /workspace 2>/dev/null || true
|
||||
|
||||
# Images are tagged with this source by scripts/ci/images.sh. Never delete an
|
||||
# image used by a running container; docker image rm without --force refuses it.
|
||||
source_label='org.opencontainers.image.source=https://sources.tordais.cc/arnaud.dartois/Heimdall'
|
||||
while IFS= read -r reference; do
|
||||
case "$reference" in
|
||||
heimdall-server:ci-*|heimdall-agent:ci-*|\
|
||||
eltruncho/heimdall:sha-*|eltruncho/heimdall:latest|\
|
||||
eltruncho/heimdall-agent:sha-*|eltruncho/heimdall-agent:latest|\
|
||||
sources.tordais.cc/arnaud.dartois/heimdall-server:*|\
|
||||
sources.tordais.cc/arnaud.dartois/heimdall-agent:*)
|
||||
docker image rm "$reference" >/dev/null 2>&1 || true
|
||||
;;
|
||||
esac
|
||||
done < <(docker image ls --filter "label=$source_label" --format '{{.Repository}}:{{.Tag}}')
|
||||
: "${BUILD_SERVER_URL:?Gitea server URL is required}"
|
||||
: "${BUILD_REPOSITORY:?Gitea repository is required}"
|
||||
source_label="org.opencontainers.image.source=${BUILD_SERVER_URL%/}/${BUILD_REPOSITORY}"
|
||||
while IFS= read -r image_id; do
|
||||
[[ -n "$image_id" ]] && docker image rm "$image_id" >/dev/null 2>&1 || true
|
||||
done < <(docker image ls --filter "label=$source_label" --format '{{.ID}}' | sort -u)
|
||||
|
||||
# A cancelled security step may leave its dedicated Trivy database volume.
|
||||
# Docker refuses removal while a scanner container still uses the volume.
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
set -euo pipefail
|
||||
sha=$(git rev-parse HEAD)
|
||||
version=$(cat artifacts/version 2>/dev/null || printf '0.0.0-ci.%s' "${sha:0:12}")
|
||||
: "${BUILD_SERVER_URL:?Gitea server URL is required}"
|
||||
: "${BUILD_REPOSITORY:?Gitea repository is required}"
|
||||
source_url="${BUILD_SERVER_URL%/}/${BUILD_REPOSITORY}"
|
||||
case "${1:-all}" in
|
||||
all) components=(server agent) ;;
|
||||
server|agent) components=("$1") ;;
|
||||
@@ -13,6 +16,6 @@ for component in "${components[@]}"; do
|
||||
docker build --pull --platform linux/amd64 -f "$file" --build-arg "VERSION=$version" \
|
||||
--label "org.opencontainers.image.revision=$sha" \
|
||||
--label "org.opencontainers.image.version=$version" \
|
||||
--label "org.opencontainers.image.source=https://sources.tordais.cc/arnaud.dartois/Heimdall" \
|
||||
--label "org.opencontainers.image.source=$source_url" \
|
||||
-t "heimdall-$component:ci-$sha" .
|
||||
done
|
||||
+50
-11
@@ -1,12 +1,27 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
: "${REGISTRY_USER:?Dedicated registry user is required}"
|
||||
: "${REGISTRY_TOKEN:?Dedicated registry token is required}"
|
||||
: "${RELEASE_TOKEN:?Dedicated Gitea release token is required}"
|
||||
: "${RELEASE_SIGNING_KEY_B64:?Publisher ECDSA P-256 private key is required}"
|
||||
: "${BUILD_SERVER_URL:?Gitea URL is required}"
|
||||
: "${EXPECTED_BUILD_SERVER_URL:?Expected Gitea URL is required}"
|
||||
: "${BUILD_REPOSITORY:?Repository is required}"
|
||||
[[ "$BUILD_SERVER_URL" == https://sources.tordais.cc ]] || { echo 'Unexpected publication host' >&2; exit 1; }
|
||||
registry_host=$(python3 - "$BUILD_SERVER_URL" "$EXPECTED_BUILD_SERVER_URL" <<'PY'
|
||||
import sys
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
actual, expected = (urlsplit(value) for value in sys.argv[1:])
|
||||
def valid_origin(value):
|
||||
return (value.scheme == 'https' and bool(value.hostname) and
|
||||
value.path in ('', '/') and not value.query and not value.fragment and
|
||||
value.username is None and value.password is None)
|
||||
|
||||
if (not valid_origin(actual) or not valid_origin(expected) or
|
||||
actual.hostname.lower() != expected.hostname.lower() or
|
||||
(actual.port or 443) != (expected.port or 443)):
|
||||
raise SystemExit('Unexpected publication host')
|
||||
print(actual.netloc)
|
||||
PY
|
||||
)
|
||||
[[ "$BUILD_REPOSITORY" == arnaud.dartois/Heimdall ]] || { echo 'Unexpected publication repository' >&2; exit 1; }
|
||||
sha=$(git rev-parse HEAD)
|
||||
umask 077
|
||||
@@ -33,16 +48,40 @@ bash scripts/ci/images.sh
|
||||
export DOCKER_CONFIG
|
||||
DOCKER_CONFIG=$(mktemp -d)
|
||||
trap 'rm -rf "$DOCKER_CONFIG"; rm -f "$signing_key"' EXIT
|
||||
printf '%s' "$REGISTRY_TOKEN" | docker login sources.tordais.cc -u "$REGISTRY_USER" --password-stdin
|
||||
server_image=$(python3 -c 'import json; print(json.load(open("docker/server-image.json"))["image"])')
|
||||
[[ "$server_image" =~ ^[a-zA-Z0-9][a-zA-Z0-9._:/-]*$ && "${server_image##*/}" != *:* ]] || { echo 'Invalid server image repository in docker/server-image.json' >&2; exit 1; }
|
||||
agent_image=$(python3 -c 'import json; print(json.load(open("docker/agent-image.json"))["image"])')
|
||||
[[ "$agent_image" =~ ^[a-zA-Z0-9][a-zA-Z0-9._:/-]*$ && "${agent_image##*/}" != *:* ]] || { echo 'Invalid agent image repository in docker/agent-image.json' >&2; exit 1; }
|
||||
agent_registry=${agent_image%%/*}
|
||||
if [[ "$agent_registry" == "$agent_image" || ( "$agent_registry" != *.* && "$agent_registry" != *:* && "$agent_registry" != localhost* ) ]]; then
|
||||
agent_registry=docker.io
|
||||
image_registry() {
|
||||
local image="$1" registry="${1%%/*}"
|
||||
if [[ "$registry" == "$image" || ( "$registry" != *.* && "$registry" != *:* && "$registry" != localhost* ) ]]; then
|
||||
printf 'docker.io'
|
||||
else
|
||||
printf '%s' "$registry"
|
||||
fi
|
||||
}
|
||||
server_registry=$(image_registry "$server_image")
|
||||
agent_registry=$(image_registry "$agent_image")
|
||||
if [[ "$server_registry" == "$registry_host" ]]; then
|
||||
: "${REGISTRY_USER:?Registry user is required for $server_registry}"
|
||||
: "${REGISTRY_TOKEN:?Registry token is required for $server_registry}"
|
||||
printf '%s' "$REGISTRY_TOKEN" | docker login "$server_registry" -u "$REGISTRY_USER" --password-stdin
|
||||
elif [[ "$server_registry" == docker.io ]]; then
|
||||
server_registry_user=${DOCKERHUB_USERNAME:-${REGISTRY_USER:-}}
|
||||
server_registry_token=${DOCKERHUB_TOKEN:-${REGISTRY_TOKEN:-}}
|
||||
: "${server_registry_user:?Docker Hub user is required for $server_image}"
|
||||
: "${server_registry_token:?Docker Hub token is required for $server_image}"
|
||||
printf '%s' "$server_registry_token" | docker login "$server_registry" -u "$server_registry_user" --password-stdin
|
||||
else
|
||||
server_registry_user=${SERVER_REGISTRY_USER:-${IMAGE_REGISTRY_USER:-}}
|
||||
server_registry_token=${SERVER_REGISTRY_TOKEN:-${IMAGE_REGISTRY_TOKEN:-}}
|
||||
: "${server_registry_user:?Server registry user is required for $server_registry}"
|
||||
: "${server_registry_token:?Server registry token is required for $server_registry}"
|
||||
printf '%s' "$server_registry_token" | docker login "$server_registry" -u "$server_registry_user" --password-stdin
|
||||
fi
|
||||
if [[ "$agent_registry" != sources.tordais.cc ]]; then
|
||||
agent_user=${AGENT_REGISTRY_USER:-${DOCKERHUB_USERNAME:-}}
|
||||
agent_token=${AGENT_REGISTRY_TOKEN:-${DOCKERHUB_TOKEN:-}}
|
||||
if [[ "$agent_registry" != "$server_registry" ]]; then
|
||||
agent_user=${AGENT_REGISTRY_USER:-${DOCKERHUB_USERNAME:-${IMAGE_REGISTRY_USER:-}}}
|
||||
agent_token=${AGENT_REGISTRY_TOKEN:-${DOCKERHUB_TOKEN:-${IMAGE_REGISTRY_TOKEN:-}}}
|
||||
: "${agent_user:?Agent registry user is required for $agent_registry}"
|
||||
: "${agent_token:?Agent registry token is required for $agent_registry}"
|
||||
printf '%s' "$agent_token" | docker login "$agent_registry" -u "$agent_user" --password-stdin
|
||||
@@ -52,7 +91,7 @@ for component in server agent; do
|
||||
if [[ "$component" == agent ]]; then
|
||||
image=$agent_image
|
||||
else
|
||||
image="sources.tordais.cc/arnaud.dartois/heimdall-server"
|
||||
image=$server_image
|
||||
fi
|
||||
for image_tag in "sha-$sha" "${tag#v}"; do
|
||||
if docker manifest inspect "$image:$image_tag" >/dev/null 2>&1; then
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
: "${DOCKERHUB_USERNAME:?Docker Hub username is required}"
|
||||
: "${DOCKERHUB_TOKEN:?Docker Hub access token is required}"
|
||||
namespace=${DOCKERHUB_NAMESPACE:-eltruncho}
|
||||
[[ "$namespace" =~ ^[a-z0-9][a-z0-9_-]*$ ]] || { echo 'Invalid Docker Hub namespace' >&2; exit 1; }
|
||||
mode=${1:?Expected server, agent or latest}
|
||||
case "$mode" in server|agent|latest) ;; *) echo 'Usage: push-dockerhub.sh server|agent|latest' >&2; exit 2 ;; esac
|
||||
sha=$(git rev-parse HEAD)
|
||||
export DOCKER_CONFIG
|
||||
DOCKER_CONFIG=$(mktemp -d)
|
||||
trap 'rm -rf "$DOCKER_CONFIG"' EXIT
|
||||
printf '%s' "$DOCKERHUB_TOKEN" | docker login docker.io -u "$DOCKERHUB_USERNAME" --password-stdin
|
||||
repository() {
|
||||
case "$1" in
|
||||
server) printf '%s/heimdall' "$namespace" ;;
|
||||
agent) printf '%s/heimdall-agent' "$namespace" ;;
|
||||
esac
|
||||
}
|
||||
if [[ "$mode" == latest ]]; then
|
||||
# Move mutable tags only after both independently built images passed their scans.
|
||||
for component in server agent; do
|
||||
docker pull "$(repository "$component"):sha-$sha"
|
||||
done
|
||||
for component in server agent; do
|
||||
repo=$(repository "$component")
|
||||
docker tag "$repo:sha-$sha" "$repo:latest"
|
||||
docker push "$repo:latest"
|
||||
done
|
||||
else
|
||||
repo=$(repository "$mode")
|
||||
docker image inspect "heimdall-$mode:ci-$sha" >/dev/null
|
||||
docker tag "heimdall-$mode:ci-$sha" "$repo:sha-$sha"
|
||||
docker push "$repo:sha-$sha"
|
||||
fi
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
mode=${1:?Expected server, agent or latest}
|
||||
case "$mode" in server|agent|latest) ;; *) echo 'Usage: push-images.sh server|agent|latest' >&2; exit 2 ;; esac
|
||||
sha=$(git rev-parse HEAD)
|
||||
if [[ "$mode" == latest ]]; then components=(server agent); else components=("$mode"); fi
|
||||
export DOCKER_CONFIG
|
||||
DOCKER_CONFIG=$(mktemp -d)
|
||||
trap 'rm -rf "$DOCKER_CONFIG"' EXIT
|
||||
repository() {
|
||||
case "$1" in
|
||||
server) python3 -c 'import json; print(json.load(open("docker/server-image.json"))["image"])' ;;
|
||||
agent) python3 -c 'import json; print(json.load(open("docker/agent-image.json"))["image"])' ;;
|
||||
esac
|
||||
}
|
||||
registry_for() {
|
||||
local image="$1" host="${1%%/*}"
|
||||
if [[ "$host" == "$image" || ( "$host" != *.* && "$host" != *:* && "$host" != localhost* ) ]]; then
|
||||
printf 'docker.io'
|
||||
else
|
||||
printf '%s' "$host"
|
||||
fi
|
||||
}
|
||||
login_for() {
|
||||
local registry="$1" user token
|
||||
if [[ "$registry" == docker.io ]]; then
|
||||
user=${DOCKERHUB_USERNAME:-}
|
||||
token=${DOCKERHUB_TOKEN:-}
|
||||
else
|
||||
user=${IMAGE_REGISTRY_USER:-}
|
||||
token=${IMAGE_REGISTRY_TOKEN:-}
|
||||
fi
|
||||
: "${user:?Image registry user is required for $registry}"
|
||||
: "${token:?Image registry token is required for $registry}"
|
||||
printf '%s' "$token" | docker login "$registry" -u "$user" --password-stdin
|
||||
}
|
||||
for component in "${components[@]}"; do
|
||||
image=$(repository "$component")
|
||||
[[ "$image" =~ ^[a-zA-Z0-9][a-zA-Z0-9._:/-]*$ && "${image##*/}" != *:* ]] || {
|
||||
echo "Invalid $component image repository in docker/$component-image.json" >&2
|
||||
exit 1
|
||||
}
|
||||
registry=$(registry_for "$image")
|
||||
if [[ "$registry" != "${logged_registry:-}" ]]; then
|
||||
login_for "$registry"
|
||||
logged_registry=$registry
|
||||
fi
|
||||
done
|
||||
if [[ "$mode" == latest ]]; then
|
||||
# Move mutable tags only after both independently built images passed their scans.
|
||||
for component in server agent; do
|
||||
docker pull "$(repository "$component"):sha-$sha"
|
||||
done
|
||||
for component in server agent; do
|
||||
repo=$(repository "$component")
|
||||
docker tag "$repo:sha-$sha" "$repo:latest"
|
||||
docker push "$repo:latest"
|
||||
done
|
||||
else
|
||||
repo=$(repository "$mode")
|
||||
docker image inspect "heimdall-$mode:ci-$sha" >/dev/null
|
||||
docker tag "heimdall-$mode:ci-$sha" "$repo:sha-$sha"
|
||||
docker push "$repo:sha-$sha"
|
||||
fi
|
||||
@@ -126,6 +126,7 @@ builder.Services.AddSingleton<RuntimeLogLevel>();
|
||||
builder.Services.AddHostedService<AgentRegistrationService>();
|
||||
builder.Services.AddHostedService<ConfigReceiverService>();
|
||||
builder.Services.AddHostedService<AgentDiscoveryService>();
|
||||
builder.Services.AddHostedService<AnalysisJobPollingService>();
|
||||
|
||||
// Video capture pipeline (ticket #1): FFmpeg capture per assigned camera,
|
||||
// bounded snapshot channel, adaptive interval, frames → FrameAnalyzerService.
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Heimdall.Domain.Enums;
|
||||
|
||||
namespace Heimdall.Agent.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Claims one durable analysis job at a time over the agent's outbound Central connection.
|
||||
/// Central owns the lease and attempt ID; a repeated result uses that same ID.
|
||||
/// </summary>
|
||||
public sealed class AnalysisJobPollingService : BackgroundService
|
||||
{
|
||||
private static readonly TimeSpan PollInterval = TimeSpan.FromSeconds(5);
|
||||
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
|
||||
private readonly AgentState _state;
|
||||
private readonly CameraConfigStore _cameras;
|
||||
private readonly CameraStreamService _streams;
|
||||
private readonly FrameAnalyzerService _analyzer;
|
||||
private readonly IHttpClientFactory _clients;
|
||||
private readonly ILogger<AnalysisJobPollingService> _logger;
|
||||
|
||||
public AnalysisJobPollingService(AgentState state, CameraConfigStore cameras,
|
||||
CameraStreamService streams, FrameAnalyzerService analyzer, IHttpClientFactory clients,
|
||||
ILogger<AnalysisJobPollingService> logger)
|
||||
{
|
||||
_state = state;
|
||||
_cameras = cameras;
|
||||
_streams = streams;
|
||||
_analyzer = analyzer;
|
||||
_clients = clients;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_state.AgentId != Guid.Empty && !string.IsNullOrWhiteSpace(_state.ApiKey))
|
||||
await PollOnceAsync(stoppingToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Analysis job polling failed; Central will retain or retry the leased job");
|
||||
}
|
||||
|
||||
try { await Task.Delay(PollInterval, stoppingToken).ConfigureAwait(false); }
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
|
||||
}
|
||||
}
|
||||
|
||||
private async Task PollOnceAsync(CancellationToken ct)
|
||||
{
|
||||
var agentId = _state.AgentId;
|
||||
using var client = _clients.CreateClient("Central");
|
||||
client.DefaultRequestHeaders.Add("X-API-Key", _state.ApiKey);
|
||||
using var response = await client.GetAsync($"api/agents/{agentId:D}/analysis-jobs/next", ct)
|
||||
.ConfigureAwait(false);
|
||||
if (response.StatusCode == HttpStatusCode.NoContent) return;
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
_logger.LogWarning("Analysis job claim failed with HTTP {StatusCode}", (int)response.StatusCode);
|
||||
return;
|
||||
}
|
||||
|
||||
var job = await response.Content.ReadFromJsonAsync<LeasedJob>(Json, ct).ConfigureAwait(false);
|
||||
if (job is null || job.JobId == Guid.Empty || job.CameraId == Guid.Empty || job.AttemptId == Guid.Empty)
|
||||
{
|
||||
_logger.LogError("Central returned an invalid analysis job lease");
|
||||
return;
|
||||
}
|
||||
|
||||
var result = await ExecuteJobAsync(job, ct).ConfigureAwait(false);
|
||||
await SendResultAsync(client, agentId, job.JobId, result, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<AnalysisResult> ExecuteJobAsync(LeasedJob job, CancellationToken ct)
|
||||
{
|
||||
if (!IsObjectDetection(job.JobType))
|
||||
return Failure(job.AttemptId, "Unsupported analysis job type");
|
||||
|
||||
var camera = _cameras.Cameras.FirstOrDefault(c => c.CameraId == job.CameraId && c.Enabled);
|
||||
if (camera is null || !_streams.IsStreamActive(job.CameraId))
|
||||
return Failure(job.AttemptId, "Camera is not assigned, enabled, or streaming");
|
||||
if (!_analyzer.ModelAvailable)
|
||||
return Failure(job.AttemptId, "Object detection model is unavailable");
|
||||
|
||||
Snapshot? frame;
|
||||
try
|
||||
{
|
||||
frame = await _streams.CaptureNextFrameAsync(job.CameraId, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
||||
{
|
||||
frame = null;
|
||||
}
|
||||
if (frame is null)
|
||||
return Failure(job.AttemptId, "Camera frame capture failed or timed out");
|
||||
|
||||
var confidence = camera.DetectionProfile?.MinConfidence ?? FrameAnalyzerService.DefaultMinConfidence;
|
||||
var analysis = await _analyzer.AnalyzeFrameAsync(frame.JpegData, confidence, ct).ConfigureAwait(false);
|
||||
if (analysis is null)
|
||||
return Failure(job.AttemptId, "Object detection was unavailable or saturated");
|
||||
|
||||
return new AnalysisResult(job.AttemptId, true, null, analysis.Detections
|
||||
.Select(d => new AnalysisDetection(d.Label, d.Confidence, d.X, d.Y, d.Width, d.Height, d.ClassIndex))
|
||||
.ToArray());
|
||||
}
|
||||
|
||||
private async Task SendResultAsync(HttpClient client, Guid agentId, Guid jobId,
|
||||
AnalysisResult result, CancellationToken ct)
|
||||
{
|
||||
var retryDelay = TimeSpan.FromSeconds(2);
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var response = await client.PutAsJsonAsync(
|
||||
$"api/agents/{agentId:D}/analysis-jobs/{jobId:D}/result", result, Json, ct)
|
||||
.ConfigureAwait(false);
|
||||
if (response.IsSuccessStatusCode) return;
|
||||
if (response.StatusCode is HttpStatusCode.Conflict or HttpStatusCode.NotFound)
|
||||
{
|
||||
_logger.LogInformation("Analysis job {JobId} attempt {AttemptId} is no longer current",
|
||||
jobId, result.AttemptId);
|
||||
return;
|
||||
}
|
||||
_logger.LogWarning("Analysis result for job {JobId} was rejected with HTTP {StatusCode}; retrying",
|
||||
jobId, (int)response.StatusCode);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (HttpRequestException ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Analysis result delivery failed for job {JobId}; retrying", jobId);
|
||||
}
|
||||
catch (TaskCanceledException ex) when (!ct.IsCancellationRequested)
|
||||
{
|
||||
_logger.LogWarning(ex, "Analysis result delivery timed out for job {JobId}; retrying", jobId);
|
||||
}
|
||||
|
||||
await Task.Delay(retryDelay, ct).ConfigureAwait(false);
|
||||
retryDelay = TimeSpan.FromSeconds(Math.Min(retryDelay.TotalSeconds * 2, 30));
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsObjectDetection(JsonElement type) => type.ValueKind switch
|
||||
{
|
||||
JsonValueKind.String => string.Equals(type.GetString(), nameof(AnalysisJobType.ObjectDetection),
|
||||
StringComparison.OrdinalIgnoreCase),
|
||||
JsonValueKind.Number => type.TryGetInt32(out var value) && value == (int)AnalysisJobType.ObjectDetection,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
private static AnalysisResult Failure(Guid attemptId, string message) => new(attemptId, false, message, []);
|
||||
|
||||
private sealed record LeasedJob(Guid JobId, Guid CameraId, Guid AttemptId, JsonElement JobType);
|
||||
private sealed record AnalysisDetection(string Label, float Confidence, float X, float Y,
|
||||
float Width, float Height, int? ClassIndex);
|
||||
private sealed record AnalysisResult(Guid AttemptId, bool Success, string? Error,
|
||||
IReadOnlyList<AnalysisDetection> Detections);
|
||||
}
|
||||
@@ -8,6 +8,7 @@ public interface IApplicationDbContext
|
||||
DbSet<Agent> Agents { get; }
|
||||
DbSet<AgentLogEntry> AgentLogEntries { get; }
|
||||
DbSet<AgentSetting> AgentSettings { get; }
|
||||
DbSet<AnalysisJob> AnalysisJobs { get; }
|
||||
DbSet<ApiKey> ApiKeys { get; }
|
||||
DbSet<AppSetting> AppSettings { get; }
|
||||
DbSet<AppUser> Users { get; }
|
||||
|
||||
@@ -21,12 +21,14 @@ public interface IAnalysisJobSchedulerService
|
||||
CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Select the best agent for a pending job and dispatch it.
|
||||
/// Selection criteria: capabilities → site affinity → current load.
|
||||
/// Returns null if no suitable agent is available.
|
||||
/// Dispatches a pending job only to the agent currently assigned to its camera.
|
||||
/// Returns a failure if that agent is unavailable or lacks the required resources.
|
||||
/// </summary>
|
||||
Task<ServiceResult<AnalysisJob>> DispatchJobAsync(Guid jobId, CancellationToken ct);
|
||||
|
||||
/// <summary>Atomically claim the next durable job assigned to an agent.</summary>
|
||||
Task<AnalysisJob?> ClaimNextJobAsync(Guid agentId, CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// Process the next batch of pending jobs (called by the Hangfire dispatcher).
|
||||
/// Selects agents and dispatches as many jobs as possible.
|
||||
@@ -43,11 +45,17 @@ public interface IAnalysisJobSchedulerService
|
||||
/// </summary>
|
||||
Task<ServiceResult> CompleteJobAsync(Guid jobId, CancellationToken ct, string? resultJson = null);
|
||||
|
||||
/// <summary>Complete only the current attempt owned by the authenticated agent.</summary>
|
||||
Task<ServiceResult> CompleteJobAsync(Guid jobId, Guid agentId, Guid attemptId, CancellationToken ct, string? resultJson = null);
|
||||
|
||||
/// <summary>
|
||||
/// Report a job failure — triggers retry or dead-lettering.
|
||||
/// </summary>
|
||||
Task<ServiceResult> FailJobAsync(Guid jobId, string errorMessage, CancellationToken ct);
|
||||
|
||||
/// <summary>Fail only the current attempt owned by the authenticated agent.</summary>
|
||||
Task<ServiceResult> FailJobAsync(Guid jobId, Guid agentId, Guid attemptId, string errorMessage, CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// Cancel a pending or running job.
|
||||
/// </summary>
|
||||
@@ -60,8 +68,7 @@ public interface IAnalysisJobSchedulerService
|
||||
Task<IReadOnlyList<AnalysisJob>> GetTimedOutJobsAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// Get the best agent for a given job based on capabilities, site affinity, and load.
|
||||
/// Used internally and for testing/validation.
|
||||
/// Scores an agent for legacy scheduling scenarios. Camera jobs dispatch to their assigned agent.
|
||||
/// </summary>
|
||||
Task<Agent?> SelectBestAgentAsync(AnalysisJob job, CancellationToken ct);
|
||||
|
||||
|
||||
@@ -12,6 +12,8 @@ public class AnalysisJob : Entity<Guid>, IAuditableEntity
|
||||
{
|
||||
public Guid CameraId { get; private set; }
|
||||
public Guid? AssignedAgentId { get; private set; }
|
||||
/// <summary>Changes on every dispatch so late replies cannot complete a retried job.</summary>
|
||||
public Guid? AttemptId { get; private set; }
|
||||
public AnalysisJobType JobType { get; private set; }
|
||||
public AnalysisJobStatus Status { get; private set; } = AnalysisJobStatus.Pending;
|
||||
public AnalysisJobPriority Priority { get; private set; } = AnalysisJobPriority.Periodic;
|
||||
@@ -90,6 +92,7 @@ public class AnalysisJob : Entity<Guid>, IAuditableEntity
|
||||
public void Dispatch(Guid agentId)
|
||||
{
|
||||
AssignedAgentId = agentId;
|
||||
AttemptId = Guid.NewGuid();
|
||||
Status = AnalysisJobStatus.Dispatched;
|
||||
DispatchedAt = DateTime.UtcNow;
|
||||
}
|
||||
@@ -111,6 +114,10 @@ public class AnalysisJob : Entity<Guid>, IAuditableEntity
|
||||
{
|
||||
RetryCount++;
|
||||
ErrorMessage = errorMessage;
|
||||
AssignedAgentId = null;
|
||||
AttemptId = null;
|
||||
DispatchedAt = null;
|
||||
StartedAt = null;
|
||||
|
||||
if (RetryCount >= MaxRetries)
|
||||
{
|
||||
@@ -120,8 +127,6 @@ public class AnalysisJob : Entity<Guid>, IAuditableEntity
|
||||
{
|
||||
// Reset to pending for retry — agent will be re-selected
|
||||
Status = AnalysisJobStatus.Pending;
|
||||
AssignedAgentId = null;
|
||||
DispatchedAt = null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,6 +135,10 @@ public class AnalysisJob : Entity<Guid>, IAuditableEntity
|
||||
Status = AnalysisJobStatus.TimedOut;
|
||||
ErrorMessage = $"Job exceeded maximum execution time of {MaxExecutionTime.TotalSeconds}s";
|
||||
RetryCount++;
|
||||
AssignedAgentId = null;
|
||||
AttemptId = null;
|
||||
DispatchedAt = null;
|
||||
StartedAt = null;
|
||||
|
||||
if (RetryCount >= MaxRetries)
|
||||
{
|
||||
@@ -138,8 +147,6 @@ public class AnalysisJob : Entity<Guid>, IAuditableEntity
|
||||
else
|
||||
{
|
||||
Status = AnalysisJobStatus.Pending;
|
||||
AssignedAgentId = null;
|
||||
DispatchedAt = null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -68,8 +68,13 @@ public static class JobSetup
|
||||
job => job.ExecuteAsync(CancellationToken.None),
|
||||
"0 7 * * 0"); // Sunday at 7:00
|
||||
|
||||
// Legacy analysis job timeout cleanup. Dispatch stays disabled until the
|
||||
// Agent job path is implemented over the authenticated SignalR channel.
|
||||
// PostgreSQL-backed analysis jobs are dispatched durably; agents claim
|
||||
// assigned work over their authenticated outbound HTTP connection.
|
||||
manager.AddOrUpdate<AnalysisJobDispatcherJob>(
|
||||
"analysis-job-dispatch",
|
||||
job => job.ExecuteAsync(CancellationToken.None),
|
||||
"* * * * *");
|
||||
|
||||
manager.AddOrUpdate<AnalysisJobDispatcherJob>(
|
||||
"analysis-job-timeout-sweep",
|
||||
job => job.ExecuteTimeoutSweepAsync(CancellationToken.None),
|
||||
|
||||
@@ -27,6 +27,8 @@ public class AnalysisJobConfiguration : IEntityTypeConfiguration<AnalysisJob>
|
||||
.HasConversion<int>()
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(j => j.AttemptId);
|
||||
|
||||
// Capability requirements
|
||||
builder.Property(j => j.RequiredCpuCores)
|
||||
.HasDefaultValue(0);
|
||||
|
||||
@@ -70,11 +70,17 @@ public sealed class AnalysisJobDispatcherJob
|
||||
"Sweep: analysis job {JobId} stuck in {Status} since {DispatchedAt} (timeout={Timeout}s)",
|
||||
job.Id, job.Status, job.DispatchedAt, job.MaxExecutionTime.TotalSeconds);
|
||||
|
||||
await _schedulerService.FailJobAsync(
|
||||
job.Id,
|
||||
$"Sweep: execution exceeded timeout of {job.MaxExecutionTime.TotalSeconds}s",
|
||||
ct)
|
||||
.ConfigureAwait(false);
|
||||
var reason = $"Sweep: execution exceeded timeout of {job.MaxExecutionTime.TotalSeconds}s";
|
||||
if (job.AssignedAgentId is Guid agentId && job.AttemptId is Guid attemptId)
|
||||
{
|
||||
await _schedulerService.FailJobAsync(job.Id, agentId, attemptId, reason, ct)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Upgrade path for jobs dispatched before attempt IDs were added.
|
||||
await _schedulerService.FailJobAsync(job.Id, reason, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
_logger.LogInformation("Timeout sweep: {Count} jobs cleaned up", timedOutJobs.Count);
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
using Heimdall.Infrastructure.Data;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Heimdall.Infrastructure.Migrations;
|
||||
|
||||
[DbContext(typeof(AppDbContext))]
|
||||
[Migration("20261024010000_AddAnalysisJobAttempt")]
|
||||
public partial class AddAnalysisJobAttempt : Migration
|
||||
{
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
=> migrationBuilder.AddColumn<Guid>("AttemptId", "analysis_jobs", type: "uuid", nullable: true);
|
||||
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
=> migrationBuilder.DropColumn("AttemptId", "analysis_jobs");
|
||||
}
|
||||
@@ -308,6 +308,9 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Property<Guid?>("AssignedAgentId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid?>("AttemptId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("CameraId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
|
||||
@@ -9,10 +9,8 @@ using Microsoft.Extensions.Logging;
|
||||
namespace Heimdall.Infrastructure.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Schedules analysis jobs by selecting the best agent based on:
|
||||
/// 1. Capabilities (GPU, CPU, RAM) — agent must meet job requirements
|
||||
/// 2. Site affinity — prefer agents at the same site as the camera
|
||||
/// 3. Current load — prefer agents with fewer active jobs
|
||||
/// Schedules analysis jobs on the agent assigned to the camera, after checking
|
||||
/// its reported capabilities. The source frame remains on that agent.
|
||||
///
|
||||
/// Priority ordering: SecurityCritical > SecurityHigh > Periodic > Background.
|
||||
/// Timeout/retry logic: jobs that fail are retried up to MaxRetries, then dead-lettered.
|
||||
@@ -47,6 +45,9 @@ public sealed class AnalysisJobSchedulerService : IAnalysisJobSchedulerService
|
||||
if (camera is null)
|
||||
return ServiceResult<AnalysisJob>.NotFound("Camera not found");
|
||||
|
||||
if (jobType != AnalysisJobType.ObjectDetection)
|
||||
return ServiceResult<AnalysisJob>.Failure("Only ObjectDetection jobs are currently supported");
|
||||
|
||||
var job = new AnalysisJob(cameraId, camera.SiteId, jobType, priority, parametersJson);
|
||||
|
||||
// Set capability requirements based on job type
|
||||
@@ -68,13 +69,21 @@ public sealed class AnalysisJobSchedulerService : IAnalysisJobSchedulerService
|
||||
|
||||
var job = await db.AnalysisJobs
|
||||
.AsTracking()
|
||||
.Include(j => j.Camera)
|
||||
.FirstOrDefaultAsync(j => j.Id == jobId && j.Status == AnalysisJobStatus.Pending, ct)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
if (job is null)
|
||||
return ServiceResult<AnalysisJob>.NotFound("No pending job found with this ID");
|
||||
|
||||
var bestAgent = await SelectBestAgentInternalAsync(db, job, ct).ConfigureAwait(false);
|
||||
// Frames are captured locally by the camera's assigned agent. Choosing
|
||||
// another online agent would dispatch a job it cannot execute.
|
||||
var bestAgent = await db.Agents.AsNoTracking()
|
||||
.Where(a => a.Id == job.Camera.AgentId && a.SiteId == job.SiteId &&
|
||||
a.Status == AgentStatus.Online && !a.IsDeleted &&
|
||||
(!job.RequiresGpu || a.HasGpu) &&
|
||||
a.CpuCores >= job.RequiredCpuCores && a.MemoryMb >= job.RequiredMemoryMb)
|
||||
.FirstOrDefaultAsync(ct).ConfigureAwait(false);
|
||||
if (bestAgent is null)
|
||||
{
|
||||
_logger.LogDebug(
|
||||
@@ -83,8 +92,21 @@ public sealed class AnalysisJobSchedulerService : IAnalysisJobSchedulerService
|
||||
return ServiceResult<AnalysisJob>.Failure("No suitable agent available", 503);
|
||||
}
|
||||
|
||||
job.Dispatch(bestAgent.Id);
|
||||
await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
|
||||
var attemptId = Guid.NewGuid();
|
||||
var dispatchedAt = DateTime.UtcNow;
|
||||
var updated = await db.AnalysisJobs
|
||||
.Where(j => j.Id == jobId && j.Status == AnalysisJobStatus.Pending &&
|
||||
j.Camera.AgentId == bestAgent.Id)
|
||||
.ExecuteUpdateAsync(setters => setters
|
||||
.SetProperty(j => j.AssignedAgentId, bestAgent.Id)
|
||||
.SetProperty(j => j.AttemptId, attemptId)
|
||||
.SetProperty(j => j.Status, AnalysisJobStatus.Dispatched)
|
||||
.SetProperty(j => j.DispatchedAt, dispatchedAt)
|
||||
.SetProperty(j => j.StartedAt, (DateTime?)null), ct).ConfigureAwait(false);
|
||||
if (updated == 0)
|
||||
return ServiceResult<AnalysisJob>.Conflict("Job was already dispatched or camera assignment changed");
|
||||
db.Entry(job).State = EntityState.Detached;
|
||||
job = await db.AnalysisJobs.AsNoTracking().FirstAsync(j => j.Id == jobId, ct).ConfigureAwait(false);
|
||||
|
||||
_logger.LogInformation(
|
||||
"Job {JobId} dispatched to agent {AgentId} ({AgentName}) — site affinity: {SameSite}",
|
||||
@@ -93,6 +115,33 @@ public sealed class AnalysisJobSchedulerService : IAnalysisJobSchedulerService
|
||||
return ServiceResult<AnalysisJob>.Success(job);
|
||||
}
|
||||
|
||||
/// <summary>Atomically claims a dispatched job for the authenticated agent.</summary>
|
||||
public async Task<AnalysisJob?> ClaimNextJobAsync(Guid agentId, CancellationToken ct)
|
||||
{
|
||||
if (agentId == Guid.Empty) return null;
|
||||
await using var db = await _dbFactory.CreateDbContextAsync(ct);
|
||||
var candidates = await db.AnalysisJobs.AsNoTracking()
|
||||
.Where(j => j.Status == AnalysisJobStatus.Dispatched && j.AssignedAgentId == agentId &&
|
||||
j.AttemptId != null && j.Camera.AgentId == agentId && !j.Camera.IsDeleted)
|
||||
.OrderBy(j => j.Priority).ThenBy(j => j.CreatedAt)
|
||||
.Select(j => j.Id).Take(16).ToListAsync(ct).ConfigureAwait(false);
|
||||
|
||||
foreach (var jobId in candidates)
|
||||
{
|
||||
var startedAt = DateTime.UtcNow;
|
||||
var claimed = await db.AnalysisJobs
|
||||
.Where(j => j.Id == jobId && j.Status == AnalysisJobStatus.Dispatched &&
|
||||
j.AssignedAgentId == agentId && j.Camera.AgentId == agentId)
|
||||
.ExecuteUpdateAsync(setters => setters
|
||||
.SetProperty(j => j.Status, AnalysisJobStatus.Running)
|
||||
.SetProperty(j => j.StartedAt, startedAt), ct).ConfigureAwait(false);
|
||||
if (claimed == 1)
|
||||
return await db.AnalysisJobs.AsNoTracking().SingleAsync(j => j.Id == jobId, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public async Task<int> ProcessPendingJobsAsync(int maxJobs, CancellationToken ct)
|
||||
{
|
||||
var pendingJobs = await GetPendingJobsAsync(maxJobs, ct).ConfigureAwait(false);
|
||||
@@ -151,6 +200,31 @@ public sealed class AnalysisJobSchedulerService : IAnalysisJobSchedulerService
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
|
||||
/// <summary>Completes only the current attempt owned by this agent.</summary>
|
||||
public async Task<ServiceResult> CompleteJobAsync(
|
||||
Guid jobId, Guid agentId, Guid attemptId, CancellationToken ct, string? resultJson = null)
|
||||
{
|
||||
if (agentId == Guid.Empty || attemptId == Guid.Empty)
|
||||
return ServiceResult.Conflict("Invalid analysis job attempt");
|
||||
await using var db = await _dbFactory.CreateDbContextAsync(ct);
|
||||
var now = DateTime.UtcNow;
|
||||
var updated = await db.AnalysisJobs
|
||||
.Where(j => j.Id == jobId && j.Status == AnalysisJobStatus.Running &&
|
||||
j.AssignedAgentId == agentId && j.AttemptId == attemptId &&
|
||||
j.Camera.AgentId == agentId)
|
||||
.ExecuteUpdateAsync(setters => setters
|
||||
.SetProperty(j => j.Status, AnalysisJobStatus.Completed)
|
||||
.SetProperty(j => j.ResultJson, resultJson)
|
||||
.SetProperty(j => j.CompletedAt, now)
|
||||
.SetProperty(j => j.ErrorMessage, (string?)null), ct).ConfigureAwait(false);
|
||||
if (updated == 1) return ServiceResult.Success();
|
||||
|
||||
var alreadyCompleted = await db.AnalysisJobs.AsNoTracking()
|
||||
.AnyAsync(j => j.Id == jobId && j.Status == AnalysisJobStatus.Completed &&
|
||||
j.AssignedAgentId == agentId && j.AttemptId == attemptId, ct).ConfigureAwait(false);
|
||||
return alreadyCompleted ? ServiceResult.Success() : ServiceResult.Conflict("Analysis job attempt is no longer active");
|
||||
}
|
||||
|
||||
public async Task<ServiceResult> FailJobAsync(Guid jobId, string errorMessage, CancellationToken ct)
|
||||
{
|
||||
await using var db = await _dbFactory.CreateDbContextAsync(ct);
|
||||
@@ -184,6 +258,29 @@ public sealed class AnalysisJobSchedulerService : IAnalysisJobSchedulerService
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
|
||||
/// <summary>Fails only the current attempt owned by this agent.</summary>
|
||||
public async Task<ServiceResult> FailJobAsync(
|
||||
Guid jobId, Guid agentId, Guid attemptId, string errorMessage, CancellationToken ct)
|
||||
{
|
||||
if (agentId == Guid.Empty || attemptId == Guid.Empty)
|
||||
return ServiceResult.Conflict("Invalid analysis job attempt");
|
||||
await using var db = await _dbFactory.CreateDbContextAsync(ct);
|
||||
var safeError = string.IsNullOrWhiteSpace(errorMessage) ? "Agent analysis failed" : errorMessage[..Math.Min(errorMessage.Length, 2000)];
|
||||
var updated = await db.AnalysisJobs
|
||||
.Where(j => j.Id == jobId && j.Status == AnalysisJobStatus.Running &&
|
||||
j.AssignedAgentId == agentId && j.AttemptId == attemptId)
|
||||
.ExecuteUpdateAsync(setters => setters
|
||||
.SetProperty(j => j.RetryCount, j => j.RetryCount + 1)
|
||||
.SetProperty(j => j.Status, j => j.RetryCount + 1 >= j.MaxRetries
|
||||
? AnalysisJobStatus.DeadLettered : AnalysisJobStatus.Pending)
|
||||
.SetProperty(j => j.ErrorMessage, safeError)
|
||||
.SetProperty(j => j.AssignedAgentId, (Guid?)null)
|
||||
.SetProperty(j => j.AttemptId, (Guid?)null)
|
||||
.SetProperty(j => j.DispatchedAt, (DateTime?)null)
|
||||
.SetProperty(j => j.StartedAt, (DateTime?)null), ct).ConfigureAwait(false);
|
||||
return updated == 1 ? ServiceResult.Success() : ServiceResult.Conflict("Analysis job attempt is no longer active");
|
||||
}
|
||||
|
||||
public async Task<ServiceResult> CancelJobAsync(Guid jobId, CancellationToken ct)
|
||||
{
|
||||
await using var db = await _dbFactory.CreateDbContextAsync(ct);
|
||||
@@ -252,10 +349,16 @@ public sealed class AnalysisJobSchedulerService : IAnalysisJobSchedulerService
|
||||
private static async Task<Agent?> SelectBestAgentInternalAsync(
|
||||
AppDbContext db, AnalysisJob job, CancellationToken ct)
|
||||
{
|
||||
// Load all online agents that are not soft-deleted
|
||||
var assignedAgentId = await db.Cameras.AsNoTracking()
|
||||
.Where(c => c.Id == job.CameraId && !c.IsDeleted)
|
||||
.Select(c => c.AgentId).SingleOrDefaultAsync(ct).ConfigureAwait(false);
|
||||
if (assignedAgentId is null) return null;
|
||||
|
||||
// Only the assigned agent can access the local camera stream.
|
||||
var agents = await db.Agents
|
||||
.AsNoTracking()
|
||||
.Where(a => a.Status == AgentStatus.Online && !a.IsDeleted)
|
||||
.Where(a => a.Id == assignedAgentId && a.SiteId == job.SiteId &&
|
||||
a.Status == AgentStatus.Online && !a.IsDeleted)
|
||||
.ToListAsync(ct)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
@@ -347,6 +450,10 @@ public sealed class AnalysisJobSchedulerService : IAnalysisJobSchedulerService
|
||||
switch (jobType)
|
||||
{
|
||||
case AnalysisJobType.ObjectDetection:
|
||||
job.SetCapabilityRequirements(requiresGpu: false, requiredCpuCores: 2, requiredMemoryMb: 2048);
|
||||
job.SetTimeout(TimeSpan.FromMinutes(10));
|
||||
break;
|
||||
|
||||
case AnalysisJobType.FullSceneAnalysis:
|
||||
job.SetCapabilityRequirements(requiresGpu: true, requiredCpuCores: 2, requiredMemoryMb: 2048);
|
||||
job.SetTimeout(TimeSpan.FromMinutes(10));
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
using System.Text.Json;
|
||||
using Heimdall.Api.Security;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Domain.Enums;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api")]
|
||||
public sealed class AnalysisJobsController(
|
||||
IApplicationDbContext db,
|
||||
IAnalysisJobSchedulerService scheduler,
|
||||
ResourceAccess access) : ControllerBase
|
||||
{
|
||||
private static readonly JsonSerializerOptions ResultJsonOptions = new(JsonSerializerDefaults.Web);
|
||||
private const int MaxDetections = 500;
|
||||
|
||||
public sealed record CreateAnalysisJobRequest(string JobType = "ObjectDetection", string? ParametersJson = null);
|
||||
public sealed record AnalysisDetection(string Label, float Confidence, float X, float Y,
|
||||
float Width, float Height, int? ClassIndex = null);
|
||||
public sealed record SubmitAnalysisResult(Guid AttemptId, bool Success, string? Error,
|
||||
IReadOnlyList<AnalysisDetection>? Detections = null);
|
||||
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)]
|
||||
[HttpPost("cameras/{cameraId:guid}/analysis-jobs")]
|
||||
public async Task<IActionResult> Create(Guid cameraId, [FromBody] CreateAnalysisJobRequest request,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var requester = await access.ResolveAsync(User, ct);
|
||||
if (requester is null || requester.Kind != RequesterKind.Human ||
|
||||
!await access.CameraAsync(requester, cameraId, ct)) return Forbid();
|
||||
if (!Enum.TryParse<AnalysisJobType>(request.JobType, true, out var type) ||
|
||||
type != AnalysisJobType.ObjectDetection)
|
||||
return BadRequest(new { error = "Only ObjectDetection jobs are currently supported" });
|
||||
if (request.ParametersJson is { Length: > 16_384 } || !IsJsonObjectOrNull(request.ParametersJson))
|
||||
return BadRequest(new { error = "ParametersJson must be a JSON object of at most 16 KiB" });
|
||||
|
||||
var created = await scheduler.CreateJobAsync(cameraId, type, AnalysisJobPriority.SecurityHigh,
|
||||
request.ParametersJson, ct);
|
||||
return created.IsSuccess
|
||||
? AcceptedAtAction(nameof(Get), new { cameraId, jobId = created.Data!.Id },
|
||||
new { jobId = created.Data!.Id, status = created.Data.Status.ToString() })
|
||||
: StatusCode(created.StatusCode ?? 400, new { error = created.Error });
|
||||
}
|
||||
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)]
|
||||
[HttpGet("cameras/{cameraId:guid}/analysis-jobs/{jobId:guid}")]
|
||||
public async Task<IActionResult> Get(Guid cameraId, Guid jobId, CancellationToken ct)
|
||||
{
|
||||
var requester = await access.ResolveAsync(User, ct);
|
||||
if (requester is null || requester.Kind != RequesterKind.Human ||
|
||||
!await access.CameraAsync(requester, cameraId, ct)) return Forbid();
|
||||
var job = await db.AnalysisJobs.AsNoTracking()
|
||||
.Where(j => j.Id == jobId && j.CameraId == cameraId)
|
||||
.Select(j => new { j.Id, j.JobType, j.Status, j.RetryCount, j.ErrorMessage,
|
||||
j.ResultJson, j.CreatedAt, j.DispatchedAt, j.CompletedAt })
|
||||
.FirstOrDefaultAsync(ct);
|
||||
return job is null ? NotFound() : Ok(job);
|
||||
}
|
||||
|
||||
[Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)]
|
||||
[HttpGet("agents/{agentId:guid}/analysis-jobs/next")]
|
||||
public async Task<IActionResult> ClaimNext(Guid agentId, CancellationToken ct)
|
||||
{
|
||||
var requester = await access.ResolveAsync(User, ct);
|
||||
if (requester is null || requester.Kind != RequesterKind.Agent ||
|
||||
!await access.AgentAsync(requester, agentId, ct)) return Forbid();
|
||||
var job = await scheduler.ClaimNextJobAsync(agentId, ct);
|
||||
return job is null ? NoContent() : Ok(new
|
||||
{
|
||||
jobId = job.Id,
|
||||
cameraId = job.CameraId,
|
||||
attemptId = job.AttemptId,
|
||||
jobType = job.JobType.ToString(),
|
||||
parametersJson = job.ParametersJson
|
||||
});
|
||||
}
|
||||
|
||||
[Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)]
|
||||
[HttpPut("agents/{agentId:guid}/analysis-jobs/{jobId:guid}/result")]
|
||||
public async Task<IActionResult> SubmitResult(Guid agentId, Guid jobId,
|
||||
[FromBody] SubmitAnalysisResult result, CancellationToken ct)
|
||||
{
|
||||
var requester = await access.ResolveAsync(User, ct);
|
||||
if (requester is null || requester.Kind != RequesterKind.Agent ||
|
||||
!await access.AgentAsync(requester, agentId, ct)) return Forbid();
|
||||
if (result.AttemptId == Guid.Empty) return BadRequest(new { error = "AttemptId is required" });
|
||||
if (result.Success && (result.Detections?.Count ?? 0) > MaxDetections)
|
||||
return BadRequest(new { error = $"At most {MaxDetections} detections are accepted" });
|
||||
if (result.Success && result.Detections?.Any(d => string.IsNullOrWhiteSpace(d.Label) ||
|
||||
d.Label.Length > 120 || !float.IsFinite(d.Confidence) || d.Confidence is < 0 or > 1 ||
|
||||
!float.IsFinite(d.X) || !float.IsFinite(d.Y) || !float.IsFinite(d.Width) ||
|
||||
!float.IsFinite(d.Height) || d.X < 0 || d.Y < 0 || d.Width < 0 || d.Height < 0 ||
|
||||
d.X + d.Width > 1.001f || d.Y + d.Height > 1.001f) == true)
|
||||
return BadRequest(new { error = "Detection values are invalid" });
|
||||
|
||||
ServiceResult updated;
|
||||
if (result.Success)
|
||||
{
|
||||
var payload = JsonSerializer.Serialize(new { detections = result.Detections ?? [] }, ResultJsonOptions);
|
||||
updated = await scheduler.CompleteJobAsync(jobId, agentId, result.AttemptId, ct, payload);
|
||||
}
|
||||
else
|
||||
{
|
||||
var error = string.IsNullOrWhiteSpace(result.Error) ? "Agent reported analysis failure" : result.Error;
|
||||
updated = await scheduler.FailJobAsync(jobId, agentId, result.AttemptId, error[..Math.Min(error.Length, 2000)], ct);
|
||||
}
|
||||
if (updated.IsSuccess) return NoContent();
|
||||
if (updated.StatusCode == 404) return NotFound();
|
||||
if (updated.StatusCode == 409) return Conflict(new { error = updated.Error });
|
||||
return StatusCode(updated.StatusCode ?? 400, new { error = updated.Error });
|
||||
}
|
||||
|
||||
private static bool IsJsonObjectOrNull(string? value)
|
||||
{
|
||||
if (value is null) return true;
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(value);
|
||||
return document.RootElement.ValueKind == JsonValueKind.Object;
|
||||
}
|
||||
catch (JsonException) { return false; }
|
||||
}
|
||||
}
|
||||
@@ -8,9 +8,6 @@
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*",
|
||||
"Updates": {
|
||||
"ReleaseApiUrl": "https://sources.tordais.cc/api/v1/repos/arnaud.dartois/Heimdall/releases/latest"
|
||||
},
|
||||
"Sentry": {
|
||||
"Dsn": "https://db94b9fc2f36425f9eb4b9f6f347dc73@glitchtip.tordais.cc/6"
|
||||
}
|
||||
|
||||
@@ -172,11 +172,12 @@ public class AnalysisJobDispatcherJobTests : IAsyncLifetime
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var camera = new Camera(site.Id, "Main Camera", "rtsp://test");
|
||||
db.Cameras.Add(camera);
|
||||
|
||||
var agent = new Agent(site.Id, "Test Agent", "test-host", "1.0.0");
|
||||
agent.UpdateCapabilities(false, 4, 8192, GpuAcceleration.None);
|
||||
agent.UpdateHeartbeat("127.0.0.1");
|
||||
camera.AssignAgent(agent.Id);
|
||||
db.Cameras.Add(camera);
|
||||
db.Agents.Add(agent);
|
||||
|
||||
await db.SaveChangesAsync();
|
||||
@@ -191,6 +192,9 @@ public class AnalysisJobDispatcherJobTests : IAsyncLifetime
|
||||
switch (jobType)
|
||||
{
|
||||
case AnalysisJobType.ObjectDetection:
|
||||
job.SetCapabilityRequirements(requiresGpu: false, requiredCpuCores: 2, requiredMemoryMb: 2048);
|
||||
job.SetTimeout(TimeSpan.FromMinutes(10));
|
||||
break;
|
||||
case AnalysisJobType.FullSceneAnalysis:
|
||||
job.SetCapabilityRequirements(requiresGpu: true, requiredCpuCores: 2, requiredMemoryMb: 2048);
|
||||
job.SetTimeout(TimeSpan.FromMinutes(10));
|
||||
|
||||
@@ -54,7 +54,7 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime
|
||||
}
|
||||
|
||||
public static IEnumerable<object[]> GpuScenarios =>
|
||||
from type in Enum.GetValues<AnalysisJobType>()
|
||||
from type in new[] { AnalysisJobType.ObjectDetection }
|
||||
from sameSite in new[] { true, false }
|
||||
from loaded in new[] { true, false }
|
||||
select new object[] { type, sameSite, loaded };
|
||||
@@ -71,6 +71,7 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime
|
||||
agent.Register("hash", "prefix");
|
||||
agent.UpdateCapabilities(true, 8, 8192, GpuAcceleration.NvidiaCuda);
|
||||
db.Agents.Add(agent);
|
||||
(await db.Cameras.SingleAsync(c => c.Id == cameraId)).AssignAgent(agent.Id);
|
||||
if (loaded)
|
||||
{
|
||||
var active = new AnalysisJob(cameraId, siteId, type, AnalysisJobPriority.Periodic);
|
||||
@@ -79,7 +80,9 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime
|
||||
}
|
||||
await db.SaveChangesAsync();
|
||||
var created = await _service.CreateJobAsync(cameraId, type, AnalysisJobPriority.Periodic);
|
||||
(await _service.SelectBestAgentAsync(created.Data!, CancellationToken.None))!.Id.ShouldBe(agent.Id);
|
||||
var selected = await _service.SelectBestAgentAsync(created.Data!, CancellationToken.None);
|
||||
if (sameSite) selected!.Id.ShouldBe(agent.Id);
|
||||
else selected.ShouldBeNull();
|
||||
}
|
||||
|
||||
// ── CreateJob ───────────────────────────────────────────────────
|
||||
@@ -90,13 +93,13 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime
|
||||
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
|
||||
|
||||
var result = await _service.CreateJobAsync(
|
||||
cameraId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
|
||||
cameraId, AnalysisJobType.ObjectDetection, AnalysisJobPriority.Periodic);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
result.Data.ShouldNotBeNull();
|
||||
result.Data.CameraId.ShouldBe(cameraId);
|
||||
result.Data.SiteId.ShouldBe(siteId);
|
||||
result.Data.JobType.ShouldBe(AnalysisJobType.MotionDetection);
|
||||
result.Data.JobType.ShouldBe(AnalysisJobType.ObjectDetection);
|
||||
result.Data.Priority.ShouldBe(AnalysisJobPriority.Periodic);
|
||||
result.Data.Status.ShouldBe(AnalysisJobStatus.Pending);
|
||||
}
|
||||
@@ -120,7 +123,7 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime
|
||||
cameraId, AnalysisJobType.ObjectDetection, AnalysisJobPriority.SecurityCritical);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
result.Data!.RequiresGpu.ShouldBeTrue();
|
||||
result.Data!.RequiresGpu.ShouldBeFalse();
|
||||
result.Data.RequiredCpuCores.ShouldBe(2);
|
||||
result.Data.RequiredMemoryMb.ShouldBe(2048);
|
||||
}
|
||||
@@ -132,7 +135,8 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime
|
||||
{
|
||||
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
|
||||
var otherSiteId = await CreateSiteAsync("Other Site");
|
||||
await SeedAgentAsync(siteId, "Local Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
|
||||
var localAgentId = await SeedAgentAsync(siteId, "Local Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
|
||||
await AssignCameraAsync(cameraId, localAgentId);
|
||||
await SeedAgentAsync(otherSiteId, "Remote Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
|
||||
|
||||
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
|
||||
@@ -148,9 +152,11 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime
|
||||
{
|
||||
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
|
||||
await SeedAgentAsync(siteId, "CPU Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
|
||||
await SeedAgentAsync(siteId, "GPU Agent", hasGpu: true, cpuCores: 4, memoryMb: 8192);
|
||||
var gpuAgentId = await SeedAgentAsync(siteId, "GPU Agent", hasGpu: true, cpuCores: 4, memoryMb: 8192);
|
||||
await AssignCameraAsync(cameraId, gpuAgentId);
|
||||
|
||||
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.ObjectDetection, AnalysisJobPriority.SecurityCritical);
|
||||
job.SetCapabilityRequirements(requiresGpu: true, requiredCpuCores: 2, requiredMemoryMb: 2048);
|
||||
|
||||
var bestAgent = await _service.SelectBestAgentAsync(job, CancellationToken.None);
|
||||
|
||||
@@ -162,9 +168,11 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime
|
||||
public async Task SelectBestAgentAsync_ExcludesInsufficientGpu()
|
||||
{
|
||||
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
|
||||
await SeedAgentAsync(siteId, "CPU Only", hasGpu: false, cpuCores: 4, memoryMb: 8192);
|
||||
var cpuAgentId = await SeedAgentAsync(siteId, "CPU Only", hasGpu: false, cpuCores: 4, memoryMb: 8192);
|
||||
await AssignCameraAsync(cameraId, cpuAgentId);
|
||||
|
||||
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.ObjectDetection, AnalysisJobPriority.Periodic);
|
||||
job.SetCapabilityRequirements(requiresGpu: true, requiredCpuCores: 2, requiredMemoryMb: 2048);
|
||||
|
||||
var bestAgent = await _service.SelectBestAgentAsync(job, CancellationToken.None);
|
||||
|
||||
@@ -177,6 +185,7 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime
|
||||
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
|
||||
var idleAgentId = await SeedAgentAsync(siteId, "Idle Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
|
||||
var busyAgentId = await SeedAgentAsync(siteId, "Busy Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
|
||||
await AssignCameraAsync(cameraId, idleAgentId);
|
||||
|
||||
// Give busy agent 3 active jobs
|
||||
for (var i = 0; i < 3; i++)
|
||||
@@ -202,7 +211,8 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime
|
||||
public async Task SelectBestAgentAsync_ExcludesOfflineAgents()
|
||||
{
|
||||
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
|
||||
await SeedAgentAsync(siteId, "Offline Agent", hasGpu: true, cpuCores: 4, memoryMb: 8192, status: AgentStatus.Offline);
|
||||
var offlineAgentId = await SeedAgentAsync(siteId, "Offline Agent", hasGpu: true, cpuCores: 4, memoryMb: 8192, status: AgentStatus.Offline);
|
||||
await AssignCameraAsync(cameraId, offlineAgentId);
|
||||
|
||||
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
|
||||
|
||||
@@ -217,7 +227,8 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime
|
||||
public async Task DispatchJobAsync_PendingJob_DispatchesToAgent()
|
||||
{
|
||||
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
|
||||
await SeedAgentAsync(siteId, "Test Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
|
||||
var agentId = await SeedAgentAsync(siteId, "Test Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
|
||||
await AssignCameraAsync(cameraId, agentId);
|
||||
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
|
||||
|
||||
var result = await _service.DispatchJobAsync(job.Id, CancellationToken.None);
|
||||
@@ -246,7 +257,8 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime
|
||||
public async Task StartJobAsync_DispatchedJob_SetsRunning()
|
||||
{
|
||||
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
|
||||
await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
|
||||
var agentId = await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
|
||||
await AssignCameraAsync(cameraId, agentId);
|
||||
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
|
||||
await _service.DispatchJobAsync(job.Id, CancellationToken.None);
|
||||
|
||||
@@ -264,7 +276,8 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime
|
||||
public async Task CompleteJobAsync_RunningJob_SetsCompleted()
|
||||
{
|
||||
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
|
||||
await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
|
||||
var agentId = await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
|
||||
await AssignCameraAsync(cameraId, agentId);
|
||||
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
|
||||
await _service.DispatchJobAsync(job.Id, CancellationToken.None);
|
||||
await _service.StartJobAsync(job.Id, CancellationToken.None);
|
||||
@@ -284,7 +297,8 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime
|
||||
public async Task FailJobAsync_RunningJob_TriggersRetry()
|
||||
{
|
||||
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
|
||||
await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
|
||||
var agentId = await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
|
||||
await AssignCameraAsync(cameraId, agentId);
|
||||
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
|
||||
await _service.DispatchJobAsync(job.Id, CancellationToken.None);
|
||||
await _service.StartJobAsync(job.Id, CancellationToken.None);
|
||||
@@ -304,7 +318,8 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime
|
||||
public async Task FailJobAsync_ExceedsMaxRetries_DeadLetters()
|
||||
{
|
||||
var (siteId, cameraId) = await SeedSiteAndCameraAsync();
|
||||
await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
|
||||
var agentId = await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192);
|
||||
await AssignCameraAsync(cameraId, agentId);
|
||||
var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic);
|
||||
|
||||
for (var i = 0; i < 3; i++)
|
||||
@@ -384,6 +399,14 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime
|
||||
return camera.Id;
|
||||
}
|
||||
|
||||
private async Task AssignCameraAsync(Guid cameraId, Guid agentId)
|
||||
{
|
||||
await using var db = await _dbFactory.CreateDbContextAsync();
|
||||
var camera = await db.Cameras.SingleAsync(c => c.Id == cameraId);
|
||||
camera.AssignAgent(agentId);
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
private async Task<Guid> SeedAgentAsync(
|
||||
Guid siteId, string name, bool hasGpu, int cpuCores, long memoryMb,
|
||||
AgentStatus status = AgentStatus.Online)
|
||||
@@ -408,6 +431,9 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime
|
||||
switch (jobType)
|
||||
{
|
||||
case AnalysisJobType.ObjectDetection:
|
||||
job.SetCapabilityRequirements(requiresGpu: false, requiredCpuCores: 2, requiredMemoryMb: 2048);
|
||||
job.SetTimeout(TimeSpan.FromMinutes(10));
|
||||
break;
|
||||
case AnalysisJobType.FullSceneAnalysis:
|
||||
job.SetCapabilityRequirements(requiresGpu: true, requiredCpuCores: 2, requiredMemoryMb: 2048);
|
||||
job.SetTimeout(TimeSpan.FromMinutes(10));
|
||||
|
||||
@@ -10,6 +10,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant
|
||||
- [x] Retirer `build-agent` de `runner-aaja` et le réserver aux runners de build autorisés. Le run PR #193 lui avait été affecté puis annulé ; le propriétaire a confirmé le retrait du label le 24 octobre 2026. Le run PR #194 s'exécute sur `runner-odin`.
|
||||
- [x] Valider le nettoyage Docker borné avant/après CI sur `runner-odin`. Les runs PR #189 et #191 avaient échoué pendant `dotnet build` avec `No space left on device`. Le run PR #194 a récupéré 95,89 Go avant build, ramené l'utilisation du disque de 97 % à 17 %, puis libéré 7,703 Go après job ; compilation, 1 965 tests, images et sécurité sont passés. Le script retire les anciennes images Heimdall, les volumes Trivy orphelins, les couches de build inutilisées de plus de 30 minutes et les images pendantes, sans purger les volumes ni les images nommées des autres projets.
|
||||
- [ ] Vérifier en exécution les secrets Docker Hub déclarés au niveau de l'organisation, puis un push des images serveur `eltruncho/heimdall` et agent `eltruncho/heimdall-agent` après merge sur `main`, avec tags `latest` et `sha-<commit>`. Namespace `eltruncho` confirmé par le propriétaire le 24 octobre 2026 ; la liste des secrets d'organisation n'est pas lisible avec le jeton actuel.
|
||||
- [ ] Provisionner `RELEASE_SERVER_URL` comme variable Gitea, puis vérifier la publication signée et le registre sélectionné par `docker/server-image.json` et `docker/agent-image.json`. La PR #61 rend les noms d'images et l'origine des images configurables ; aucun push de release n'a été réalisé.
|
||||
- [ ] Réparer l'accès des conteneurs de job au serveur de cache/artefacts des runners (`cache.host`/réseau/port). Le run #442 a passé compilation, 1 965 tests, archives, images et sécurité, puis a échoué à `CreateArtifact: EHOSTUNREACH`. Restaurer les TRX et rapports comme artefacts lorsque l'endpoint est accessible.
|
||||
- [ ] Vérifier que le secret d'organisation `RENOVATE_TOKEN` est disponible au workflow, qu'il appartient à un compte bot Gitea et que la tâche planifiée crée des PR de dépendances avec lockfiles NuGet actualisés.
|
||||
- [ ] Vérifier la protection de `main` : contrôles obligatoires, merge d'une PR rouge refusé, aucun secret de publication exposé aux PR.
|
||||
@@ -19,7 +20,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant
|
||||
## P1 — parcours caméra, agent et données
|
||||
|
||||
- [ ] **PIPE-09** Valider sur caméra réelle capture automatique/manuelle, corrélation, miniatures, lecture autorisée, reprise d'upload et absence de références cassées.
|
||||
- [ ] **PIPE-01/02** Décider si une analyse à la demande distribuée est requise. Si oui, construire une file PostgreSQL/outbox durable, bail atomique, routage ciblé via Agent, accusé, résultat idempotent et dead letter. Ne pas réintroduire RabbitMQ sans verticale complète démontrée.
|
||||
- [ ] **PIPE-01/02** La PR #61 implémente une première verticale PostgreSQL : dispatch vers l'agent assigné, claim atomique, tentative protégée, capture/analyse `ObjectDetection` CPU et résultat JSON persisté. CI et parcours avec deux agents, timeout/réessai et résultats tardifs restent à valider ; les autres types d'analyse ne sont pas pris en charge.
|
||||
- [ ] **PIPE-10 / FEAT-05** Vérifier une coupure réseau et reprise sans perte ni doublon ; ajouter outbox transactionnelle serveur, état de livraison et limitation par destinataire/canal. Tester SMTP/ntfy réels et échappement HTML.
|
||||
- [ ] **OPS-02** Généraliser la destination d'objet enregistrée aux médias futurs, traiter destinations perdues et lignes historiques sans inventer d'emplacement, supprimer les objets avant leurs références SQL. Vérifier réconciliation staging/finale et changement de provider.
|
||||
- [ ] **OPS-05 / AGENT-06** Installer clés de signature CI et clés publiques indépendantes de Central côté Agent ; tester release réelle, digest/signature, mise à jour native et Docker, arrêt propre et rollback.
|
||||
|
||||
Reference in new issue
Block a user