Show running Gateway commit and available updates

This commit is contained in:
jhartworks committed 2026-11-24 14:05:38 +01:00
1 parent 32b240469c
commit 36b2057991
12 files changed
+188 -21

No files matched your search

@@ -3,8 +3,11 @@ namespace Gateway.Api.Options;
public sealed class GatewayOptions
{
public string DataDirectory { get; init; } = "data";
public string? RunningCommit { get; init; }
public string? UpdateSocketPath { get; init; }
public string? UpdateStatusPath { get; init; }
public string? UpdateAvailabilityCommand { get; init; }
public string UpdateBranch { get; init; } = "main";
public BacnetBootstrapOptions Bacnet { get; init; } = new();
+11 -1
View File
@@ -105,7 +105,17 @@ app.MapGet("/api/system/update", (HttpRequest request, HttpResponse response, Se
if (user is null) return Results.Unauthorized();
if (user.Role != "admin") return Results.StatusCode(StatusCodes.Status403Forbidden);
response.Headers.CacheControl = "no-store";
return Results.Ok(updates.GetStatus());
return Results.Ok(updates.GetStatus() with { RunningCommit = updates.RunningCommit });
});
app.MapGet("/api/system/update/availability", async (bool? refresh, HttpRequest request, HttpResponse response, SessionService sessions,
SystemUpdateService updates, CancellationToken cancellationToken) =>
{
var user = sessions.GetUser(request.Headers.Authorization)?.User;
if (user is null) return Results.Unauthorized();
if (user.Role != "admin") return Results.StatusCode(StatusCodes.Status403Forbidden);
response.Headers.CacheControl = "no-store";
return Results.Ok(await updates.CheckAvailabilityAsync(refresh == true, cancellationToken));
});
app.MapPost("/api/system/update", async (SystemUpdateRequest request, HttpRequest http, SessionService sessions,
@@ -1,3 +1,5 @@
using System.ComponentModel;
using System.Diagnostics;
using System.Net.Sockets;
using System.Text.Json;
using Gateway.Api.Options;
@@ -7,16 +9,22 @@ namespace Gateway.Api.Services;
public sealed record SystemUpdateRequest(string Password);
public sealed record SystemUpdateStatus(string Phase, string Message, string? Commit = null, string? Target = null,
DateTimeOffset? UpdatedAt = null, string? RunId = null);
DateTimeOffset? UpdatedAt = null, string? RunId = null, string? RunningCommit = null);
public sealed record SystemUpdateAvailability(string State, string Branch, string? RemoteCommit = null);
public sealed class SystemUpdateService(IOptions<GatewayOptions> options)
public sealed class SystemUpdateService(IOptions<GatewayOptions> options) : IDisposable
{
private static readonly JsonSerializerOptions StatusJson = new(JsonSerializerDefaults.Web);
private readonly SemaphoreSlim _availabilityLock = new(1, 1);
private SystemUpdateAvailability? _availability;
private DateTimeOffset _checkedAt;
public bool Enabled => OperatingSystem.IsLinux()
&& !string.IsNullOrWhiteSpace(options.Value.UpdateSocketPath)
&& !string.IsNullOrWhiteSpace(options.Value.UpdateStatusPath);
public string? RunningCommit => IsCommit(options.Value.RunningCommit) ? options.Value.RunningCommit!.ToLowerInvariant() : null;
public SystemUpdateStatus GetStatus()
{
if (!Enabled) return new("disabled", "Der lokale Systemupdate-Dienst ist für dieses Gateway nicht eingerichtet.");
@@ -33,6 +41,64 @@ public sealed class SystemUpdateService(IOptions<GatewayOptions> options)
return new("unavailable", "Der Update-Status konnte nicht gelesen werden.");
}
public async Task<SystemUpdateAvailability> CheckAvailabilityAsync(bool refresh, CancellationToken cancellationToken)
{
var branch = options.Value.UpdateBranch;
if (!Enabled || string.IsNullOrWhiteSpace(options.Value.UpdateAvailabilityCommand)) return new("disabled", branch);
if (RunningCommit is not { } running) return new("unknown", branch);
await _availabilityLock.WaitAsync(cancellationToken);
try
{
if (!refresh && _availability is not null && DateTimeOffset.UtcNow - _checkedAt < TimeSpan.FromSeconds(15))
return _availability;
_availability = await ProbeAsync(running, branch, cancellationToken);
_checkedAt = DateTimeOffset.UtcNow;
return _availability;
}
finally { _availabilityLock.Release(); }
}
private async Task<SystemUpdateAvailability> ProbeAsync(string running, string branch, CancellationToken cancellationToken)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(TimeSpan.FromSeconds(32));
var start = new ProcessStartInfo(options.Value.UpdateAvailabilityCommand!)
{
UseShellExecute = false,
RedirectStandardOutput = true
};
start.ArgumentList.Add(running);
try
{
using var process = Process.Start(start);
if (process is null) return new("unavailable", branch);
try
{
var output = await process.StandardOutput.ReadToEndAsync(timeout.Token);
await process.WaitForExitAsync(timeout.Token);
var parts = output.Trim().Split(' ');
if (process.ExitCode == 0 && parts is ["current" or "available" or "incompatible", var tip] && IsCommit(tip))
return new(parts[0], branch, tip);
}
catch (OperationCanceledException)
{
try { if (!process.HasExited) process.Kill(entireProcessTree: true); }
catch (InvalidOperationException) { }
catch (Win32Exception) { }
cancellationToken.ThrowIfCancellationRequested();
}
}
catch (Win32Exception) { }
catch (IOException) { }
return new("unavailable", branch);
}
private static bool IsCommit(string? value) => value is { Length: 40 } && value.All(Uri.IsHexDigit);
public void Dispose() => _availabilityLock.Dispose();
public async Task<bool> StartAsync(CancellationToken cancellationToken)
{
if (!Enabled) return false;
+1 -1
View File
@@ -24,7 +24,7 @@
<script src="/mqtt-topic-browser.js?v=20261119-mqtt-browser-1" defer></script>
<script src="/vendor/markdown-it-15.0.3.min.js" defer></script>
<script src="/documentation.js?v=20261119-docs-1" defer></script>
<script src="/system-update.js?v=20261124-update-1" defer></script>
<script src="/system-update.js?v=20261124-update-availability-1" defer></script>
<script src="/app.js?v=20261124-update-1" defer></script>
</body>
</html>
+59 -12
View File
@@ -4,9 +4,10 @@ function bindSystemUpdate() {
const content = document.querySelector('#content');
content.querySelector('.grid').insertAdjacentHTML('beforeend', `
<article class="card" id="system-update-card">
<div class="card-head"><h2>Gateway-Update</h2></div>
<div class="card-head"><h2>Gateway-Update</h2><button class="btn" type="button" data-check-update hidden>Verfügbarkeit prüfen</button></div>
<p class="note">Laufender Commit <code data-running-commit>–</code></p>
<p class="note" data-update-availability role="status"></p>
<p class="note" data-update-status role="status">Status wird geladen …</p>
<p class="note" data-update-versions></p>
<form class="form" hidden>
<label>Administrator-Passwort<input name="password" type="password" autocomplete="current-password" maxlength="512" required></label>
<div class="buttons"><button class="btn primary">Update starten</button></div>
@@ -16,15 +17,55 @@ function bindSystemUpdate() {
const card = content.querySelector('#system-update-card');
const form = card.querySelector('form');
const fields = form.querySelectorAll('input, button');
const checkButton = card.querySelector('[data-check-update]');
const message = card.querySelector('[data-update-status]');
const versions = card.querySelector('[data-update-versions]');
const runningCommit = card.querySelector('[data-running-commit]');
const availability = card.querySelector('[data-update-availability]');
const error = card.querySelector('[data-update-error]');
const activePhases = new Set(['checking', 'fetching', 'building', 'activating', 'rollingBack']);
const informationalPhases = new Set(['ready', 'current', 'unpublished']);
let lastRun = '';
let queuedUntil = 0;
let busy = false;
let checking = false;
let checked = false;
let updateAvailable = false;
function setBusy(busy) {
function updateControls() {
form.hidden = !updateAvailable;
fields.forEach(field => { field.disabled = busy; });
checkButton.disabled = busy || checking;
}
async function checkAvailability(force = false) {
if (busy || checking) return;
checking = true;
updateAvailable = false;
availability.textContent = 'Update-Verfügbarkeit wird geprüft …';
updateControls();
try {
const result = await api(force ? '/api/system/update/availability?refresh=true' : '/api/system/update/availability');
if (!card.isConnected) return;
const branch = result.branch;
const version = result.remoteCommit?.slice(0, 8);
const details = {
current: `Auf ${branch} ist kein Update verfügbar.`,
available: `Update auf ${branch} verfügbar · ${version}`,
incompatible: `Der Stand auf ${branch} ist älter oder hat einen abweichenden Verlauf · ${version}`,
unknown: 'Die Update-Verfügbarkeit kann ohne Build-Commit nicht ermittelt werden.',
disabled: 'Die Verfügbarkeitsprüfung ist nicht eingerichtet.'
};
availability.textContent = details[result.state] || `Der Stand auf ${branch} konnte nicht geprüft werden.`;
availability.title = result.remoteCommit || '';
updateAvailable = result.state === 'available';
} catch (failure) {
availability.textContent = failure.message;
availability.title = '';
} finally {
checking = false;
checked = true;
updateControls();
}
}
async function refresh() {
@@ -37,18 +78,20 @@ function bindSystemUpdate() {
return;
}
queuedUntil = 0;
const checkNeeded = !checked || busy || (status.runId || '') !== lastRun;
lastRun = status.runId || '';
message.textContent = status.message;
versions.textContent = [status.commit && `Installiert ${status.commit.slice(0, 8)}`,
status.target && status.target !== status.commit && `Ziel ${status.target.slice(0, 8)}`].filter(Boolean).join(' · ');
form.hidden = status.phase === 'disabled';
const busy = activePhases.has(status.phase);
setBusy(busy);
runningCommit.textContent = status.runningCommit?.slice(0, 8) || 'Unbekannt';
runningCommit.title = status.runningCommit || '';
message.textContent = informationalPhases.has(status.phase) ? '' : status.message;
checkButton.hidden = status.phase === 'disabled';
busy = activePhases.has(status.phase);
updateControls();
if (busy) {
sessionStorage.setItem(updateReturnKey, '1');
setTimeout(refresh, 1500);
} else {
sessionStorage.removeItem(updateReturnKey);
if (!checkButton.hidden && checkNeeded) await checkAvailability();
}
} catch (failure) {
if (!card.isConnected) return;
@@ -61,12 +104,15 @@ function bindSystemUpdate() {
}
}
checkButton.addEventListener('click', () => checkAvailability(true));
form.addEventListener('submit', async event => {
event.preventDefault();
if (!updateAvailable || busy) return;
const body = JSON.stringify({ password: form.elements.password.value });
form.reset();
error.textContent = '';
setBusy(true);
busy = true;
updateControls();
try {
const status = await api('/api/system/update', { method: 'POST', body });
sessionStorage.setItem(updateReturnKey, '1');
@@ -75,7 +121,8 @@ function bindSystemUpdate() {
setTimeout(refresh, 750);
} catch (failure) {
error.textContent = failure.message;
setBusy(false);
busy = false;
updateControls();
}
});