fix(agent): retry transient release metadata failures (#271)
Heimdall Gitea / Detect CI scope (push) Successful in 14s
Heimdall Gitea / Build and tests (push) Successful in 28m18s
Heimdall Gitea / Publish versioned release (push) Skipped
Heimdall Gitea / Build and scan server image (push) Successful in 7m48s
Heimdall Gitea / Build and scan agent image (push) Successful in 9m41s
Heimdall Gitea / Publish Docker Hub latest tags (push) Failing after 1m6s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 30m59s
Heimdall Gitea / CI policy (push) Failing after 2s

## Problème et résultat

Central peut répondre 502 lorsque Forgejo ne fournit temporairement pas les métadonnées de release. L’installateur Linux réessaie maintenant au plus trois fois les erreurs réseau temporaires et réponses HTTP 408/425/429/5xx, avec attente de 2 puis 4 secondes. Les 4xx permanents échouent immédiatement. Central applique également une reprise bornée à sa requête Forgejo. La signature de release et le digest d’archive restent vérifiés avant installation.

Refs #171

## Vérification

- [x] Simulation locale : 502 puis succès, 502 persistant (3 requêtes, 6 secondes), 404 sans reprise; aucun token synthétique dans la sortie.
- [x] Test de rollback existant passé.
- [x] Recette Compose source exécutée : projet `heimdall-171-1793969417-26321`, tag `heimdall:heimdall-171-1793969417-26321-central`; `/healthz` 200 et assets installateur identiques aux sources. Conteneurs, volumes, réseau et tag exact supprimés et vérifiés absents.
- [x] `bash -n install/install-agent.sh`, `git diff --check`.
- [ ] Tests .NET ciblés : bloqués par les caches `obj/` appartenant à root dans le checkout. Le build du contrôleur dans la recette Compose a réussi.
- [ ] Confirmation de l’instance Central publique après déploiement et analyse de la cause racine terrain du 502 restent à faire.
- [x] Aucun secret réel dans les logs/artefacts ou cette PR.

## Livraison

- [ ] CI Gitea à consulter après ouverture.
- [ ] Pas de publication ni déploiement inclus dans cette PR.

Skill de validation : `skills/agent-update-acceptance/SKILL.md`.

Reviewed-on: #271
This commit was merged in pull request #271.
This commit is contained in:
arnaud.dartois committed 2026-11-06 16:02:48 +01:00
1 parent d12e16c6e5
commit af67a1757a
4 files changed
+84 -3

No files matched your search

+21 -1
View File
@@ -41,7 +41,27 @@ fi
"$DOTNET_BIN" --list-runtimes | grep -q '^Microsoft.AspNetCore.App 10\.' || {
echo 'A compatible ASP.NET Core 10 runtime is required' >&2; exit 1;
}
curl -fsS "$CENTRAL_URL/api/updates/latest" -o "$TMP_DIR/release.json" || { echo "Failed to fetch release" >&2; exit 1; }
RELEASE_METADATA_URL="$CENTRAL_URL/api/updates/latest"
for attempt in 1 2 3; do
CURL_PROTOCOL=https
[[ "$CENTRAL_URL" == https://* ]] || CURL_PROTOCOL=http
HTTP_STATUS=$(curl -sS --proto "$CURL_PROTOCOL" \
--connect-timeout 10 --max-time 30 \
-w '%{http_code}' "$RELEASE_METADATA_URL" -o "$TMP_DIR/release.json") && CURL_STATUS=0 || CURL_STATUS=$?
if [[ "$CURL_STATUS" -eq 0 && "$HTTP_STATUS" =~ ^2[0-9][0-9]$ ]]; then
break
fi
if [[ "$CURL_STATUS" -ne 0 && "$HTTP_STATUS" == 000 ]] || [[ "$HTTP_STATUS" =~ ^(408|425|429|5[0-9][0-9])$ ]]; then
if [[ "$attempt" -lt 3 ]]; then
delay=$((attempt * 2))
echo "Release metadata request failed temporarily (attempt $attempt/3); retrying in ${delay}s." >&2
sleep "$delay"
continue
fi
fi
echo "Failed to fetch release metadata from Central (HTTP ${HTTP_STATUS:-000}; curl exit ${CURL_STATUS})." >&2
exit 1
done
if [[ -z "$UPDATE_PUBLIC_KEY" ]]; then
jq -er '.updatePublicKeyPem | select(type == "string" and length > 0 and length <= 4096)' "$TMP_DIR/release.json" > "$TMP_DIR/update-public-key.pem" || {
echo 'Central release metadata has no valid publisher public key' >&2; exit 1;
+1
View File
@@ -20,6 +20,7 @@ Use this skill when changing `install/install-agent.sh`, `install/install-agent.
- For updates, exercise both successful and rejected signatures before installation. Preserve the previous release until the candidate has reported the expected version and stayed healthy for the configured stability interval.
- Use a temporary install root and fake runtime for local failure/rollback tests. Never point these tests at `/usr/local`, a real systemd service, production credentials, or an installed Agent state directory.
- Report Linux and Windows real-host install/update/rollback as open until each OS has been exercised with a real service and the expected signing configuration.
- The Linux installer retries the release metadata request at most three times for transport failures, HTTP 408/425/429, and HTTP 5xx, with 2s then 4s waits. Other HTTP statuses fail immediately. Acceptance should verify transient-then-success, persistent-5xx bounded failure, permanent-4xx no-retry behavior, and that release signature and archive digest checks remain required.
## Central installer asset delivery
@@ -119,8 +119,9 @@ public class UpdatesController : ControllerBase
{
using var client = _httpClientFactory.CreateClient("Central");
client.Timeout = TimeSpan.FromSeconds(15);
var response = await client.GetAsync(sourceUri, ct);
if (!response.IsSuccessStatusCode) { _logger.LogWarning("Forgejo returned {Code}", response.StatusCode); return null; }
using var response = await GetReleaseResponseWithRetryAsync(client, sourceUri, ct);
if (response is null || !response.IsSuccessStatusCode)
return null;
var release = await response.Content.ReadFromJsonAsync<ForgejoRelease>(Json, ct);
if (release is null) return null;
var assets = new Dictionary<string, PlatformAsset>();
@@ -167,6 +168,39 @@ public class UpdatesController : ControllerBase
catch (Exception ex) { _logger.LogError(ex, "Failed to fetch release"); return null; }
}
private async Task<HttpResponseMessage?> GetReleaseResponseWithRetryAsync(HttpClient client, Uri sourceUri,
CancellationToken ct)
{
for (var attempt = 1; attempt <= 3; attempt++)
{
HttpResponseMessage response;
try
{
response = await client.GetAsync(sourceUri, ct);
}
catch (HttpRequestException ex) when (attempt < 3)
{
_logger.LogWarning(ex, "Forgejo release request failed temporarily on attempt {Attempt}/3", attempt);
await Task.Delay(TimeSpan.FromSeconds(attempt * 2), ct);
continue;
}
if (response.IsSuccessStatusCode || !IsTransientStatusCode(response.StatusCode) || attempt == 3)
return response;
_logger.LogWarning("Forgejo returned transient HTTP {Code} on attempt {Attempt}/3", response.StatusCode, attempt);
response.Dispose();
await Task.Delay(TimeSpan.FromSeconds(attempt * 2), ct);
}
return null;
}
private static bool IsTransientStatusCode(System.Net.HttpStatusCode statusCode) =>
statusCode is System.Net.HttpStatusCode.RequestTimeout or System.Net.HttpStatusCode.TooManyRequests ||
(int)statusCode >= 500;
private static async Task<AgentImageManifest?> FetchAgentImageManifestAsync(List<ForgejoAsset>? assets,
string assetName, HttpClient client, CancellationToken ct)
{
@@ -0,0 +1,26 @@
using System.Net;
using System.Net.Http;
using System.Reflection;
using Heimdall.Api.Controllers;
using Xunit;
namespace Heimdall.Web.Tests.Controllers;
public sealed class UpdatesControllerRetryTests
{
[Theory]
[InlineData(HttpStatusCode.RequestTimeout, true)]
[InlineData(HttpStatusCode.TooManyRequests, true)]
[InlineData(HttpStatusCode.BadGateway, true)]
[InlineData(HttpStatusCode.ServiceUnavailable, true)]
[InlineData(HttpStatusCode.NotFound, false)]
[InlineData(HttpStatusCode.BadRequest, false)]
public void IsTransientStatusCode_classifies_only_retryable_http_responses(HttpStatusCode code, bool expected)
{
var method = typeof(UpdatesController).GetMethod("IsTransientStatusCode",
BindingFlags.NonPublic | BindingFlags.Static);
Assert.NotNull(method);
Assert.Equal(expected, method.Invoke(null, [code]));
}
}