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

+1 -1
View File
@@ -45,7 +45,7 @@ systemctl status seiugw
Die Weboberfläche ist auf `http://<gateway-ip>:8088` verfügbar. Beim ersten Aufruf werden das Passwort für `admin`, die Projektnummer und die ISP-Nummer festgelegt. Für Updates reichen `git -C /etc/nixos/seiugw pull --ff-only` und anschließend `sudo nixos-rebuild switch`. Die Weboberfläche ist auf `http://<gateway-ip>:8088` verfügbar. Beim ersten Aufruf werden das Passwort für `admin`, die Projektnummer und die ISP-Nummer festgelegt. Für Updates reichen `git -C /etc/nixos/seiugw pull --ff-only` und anschließend `sudo nixos-rebuild switch`.
**Einstellungen → Gateway-Update** ist für Administratoren verfügbar, wenn `services.seiugw.updates` in der NixOS-Hostkonfiguration aktiviert ist und `remote` auf das vertrauenswürdige HTTPS-Repository verweist. Nach erneuter Passworteingabe baut das Gateway den neueren Git-Stand und prüft Web und BACnet vor der dauerhaften Aktivierung. Bei einem Fehler stellt es den vorherigen Checkout und bei Bedarf die vorherige NixOS-Generation und den SQLite-Stand wieder her. Nach einem Dienstneustart kann eine erneute Anmeldung erforderlich sein. **Einstellungen → Gateway-Update** ist für Administratoren verfügbar, wenn `services.seiugw.updates` in der NixOS-Hostkonfiguration aktiviert ist und `remote` auf das vertrauenswürdige HTTPS-Repository verweist. Die Seite zeigt den Commit der laufenden Version und prüft beim Öffnen den konfigurierten Branch. Nach erneuter Passworteingabe baut das Gateway den neueren Git-Stand und prüft Web und BACnet vor der dauerhaften Aktivierung. Bei einem Fehler stellt es den vorherigen Checkout und bei Bedarf die vorherige NixOS-Generation und den SQLite-Stand wieder her. Nach einem Dienstneustart kann eine erneute Anmeldung erforderlich sein.
Die Flake sperrt Nixpkgs und sämtliche NuGet-Archive. Die Paketaktualisierung erfolgt bewusst, indem `flake.lock`, `nix/deps.json` und die Projekt-Abhängigkeiten zusammen geändert und getestet werden. Die Flake sperrt Nixpkgs und sämtliche NuGet-Archive. Die Paketaktualisierung erfolgt bewusst, indem `flake.lock`, `nix/deps.json` und die Projekt-Abhängigkeiten zusammen geändert und getestet werden.
+1 -1
View File
@@ -14,7 +14,7 @@
pkgs = import nixpkgs { inherit system; }; pkgs = import nixpkgs { inherit system; };
in in
{ {
default = pkgs.callPackage ./nix/package.nix { }; default = pkgs.callPackage ./nix/package.nix { sourceRevision = self.rev or ""; };
seiugw = self.packages.${system}.default; seiugw = self.packages.${system}.default;
bacnet = pkgs.callPackage ./nix/bacnet.nix { }; bacnet = pkgs.callPackage ./nix/bacnet.nix { };
}); });
+1 -1
View File
@@ -2,7 +2,7 @@
{ {
imports = [ imports = [
(builtins.getFlake "path:/etc/nixos/seiugw").nixosModules.default (builtins.getFlake "git+file:///etc/nixos/seiugw").nixosModules.default
]; ];
services.seiugw = { services.seiugw = {
+1 -1
View File
@@ -2,7 +2,7 @@
{ {
imports = [ imports = [
(builtins.getFlake "path:/etc/nixos/seiugw").nixosModules.default (builtins.getFlake "git+file:///etc/nixos/seiugw").nixosModules.default
]; ];
services.seiugw = { services.seiugw = {
+9
View File
@@ -13,6 +13,12 @@ let
dhcpcdBase = builtins.head (builtins.match ".* --config ([^ ]+).*" config.systemd.services.dhcpcd.serviceConfig.ExecStart); dhcpcdBase = builtins.head (builtins.match ".* --config ([^ ]+).*" config.systemd.services.dhcpcd.serviceConfig.ExecStart);
networkHelper = "${pkgs.python3}/bin/python3 ${./host-network.py}"; networkHelper = "${pkgs.python3}/bin/python3 ${./host-network.py}";
updateSocket = "/run/seiugw-update/request.sock"; updateSocket = "/run/seiugw-update/request.sock";
updateAvailability = pkgs.writeShellScript "seiugw-update-availability" ''
export PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.git ]}
export SEIUGW_UPDATE_REMOTE=${escapeShellArg cfg.updates.remote}
export SEIUGW_UPDATE_BRANCH=${escapeShellArg cfg.updates.branch}
${builtins.readFile ./system-update-availability.sh}
'';
updateWorker = pkgs.writeShellScript "seiugw-system-update" '' updateWorker = pkgs.writeShellScript "seiugw-system-update" ''
export PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.git pkgs.util-linux pkgs.systemd pkgs.curl pkgs.jq pkgs.sqlite pkgs.nix ]}:/run/current-system/sw/bin export PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.git pkgs.util-linux pkgs.systemd pkgs.curl pkgs.jq pkgs.sqlite pkgs.nix ]}:/run/current-system/sw/bin
export NIX_PATH=${escapeShellArg "nixos-config=/etc/nixos/configuration.nix:nixpkgs=${pkgs.path}"} export NIX_PATH=${escapeShellArg "nixos-config=/etc/nixos/configuration.nix:nixpkgs=${pkgs.path}"}
@@ -310,9 +316,12 @@ in
Gateway__Bacnet__DeviceInstance = toString cfg.bacnet.deviceInstance; Gateway__Bacnet__DeviceInstance = toString cfg.bacnet.deviceInstance;
Gateway__Bacnet__IpPort = toString cfg.bacnet.ipPort; Gateway__Bacnet__IpPort = toString cfg.bacnet.ipPort;
Gateway__OpcUa__Port = toString cfg.opcUa.port; Gateway__OpcUa__Port = toString cfg.opcUa.port;
Gateway__RunningCommit = cfg.package.sourceRevision or "";
} // lib.optionalAttrs cfg.updates.enable { } // lib.optionalAttrs cfg.updates.enable {
Gateway__UpdateSocketPath = updateSocket; Gateway__UpdateSocketPath = updateSocket;
Gateway__UpdateStatusPath = "/var/lib/seiugw-updater/status.json"; Gateway__UpdateStatusPath = "/var/lib/seiugw-updater/status.json";
Gateway__UpdateAvailabilityCommand = updateAvailability;
Gateway__UpdateBranch = cfg.updates.branch;
}; };
serviceConfig = { serviceConfig = {
+3 -1
View File
@@ -1,4 +1,4 @@
{ lib, buildDotnetModule, dotnetCorePackages }: { lib, buildDotnetModule, dotnetCorePackages, sourceRevision ? "" }:
buildDotnetModule { buildDotnetModule {
pname = "seiugw"; pname = "seiugw";
@@ -12,6 +12,8 @@ buildDotnetModule {
dotnet-runtime = dotnetCorePackages.aspnetcore_8_0; dotnet-runtime = dotnetCorePackages.aspnetcore_8_0;
executables = [ "Gateway.Api" ]; executables = [ "Gateway.Api" ];
passthru = { inherit sourceRevision; };
meta = { meta = {
description = "Industrial protocol gateway for BACnet/IP, OPC UA, Modbus TCP and MQTT"; description = "Industrial protocol gateway for BACnet/IP, OPC UA, Modbus TCP and MQTT";
platforms = lib.platforms.linux; platforms = lib.platforms.linux;
+30
View File
@@ -0,0 +1,30 @@
set -euo pipefail
umask 077
export GIT_TERMINAL_PROMPT=0 GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1
running=$1
[[ $running =~ ^[0-9a-f]{40}$ ]]
ref="refs/heads/$SEIUGW_UPDATE_BRANCH"
remote="$SEIUGW_UPDATE_REMOTE"
tip=$(timeout --kill-after=1s 8s git ls-remote --exit-code --refs -- "$remote" "$ref")
tip=${tip%%$'\t'*}
[[ $tip =~ ^[0-9a-f]{40}$ ]]
if [[ $tip == "$running" ]]; then
printf 'current %s\n' "$tip"
exit 0
fi
# Check ancestry in a temporary repository. The update worker owns the live checkout.
probe=$(mktemp -d)
trap 'rm -rf -- "$probe"' EXIT
git init --quiet --bare "$probe"
timeout --kill-after=1s 18s git -C "$probe" fetch --quiet --no-tags -- "$remote" "$ref"
tip=$(git -C "$probe" rev-parse FETCH_HEAD)
if [[ $tip == "$running" ]]; then
printf 'current %s\n' "$tip"
elif git -C "$probe" cat-file -e "$running^{commit}" 2>/dev/null &&
git -C "$probe" merge-base --is-ancestor "$running" "$tip"; then
printf 'available %s\n' "$tip"
else
printf 'incompatible %s\n' "$tip"
fi
@@ -3,8 +3,11 @@ namespace Gateway.Api.Options;
public sealed class GatewayOptions public sealed class GatewayOptions
{ {
public string DataDirectory { get; init; } = "data"; public string DataDirectory { get; init; } = "data";
public string? RunningCommit { get; init; }
public string? UpdateSocketPath { get; init; } public string? UpdateSocketPath { get; init; }
public string? UpdateStatusPath { get; init; } public string? UpdateStatusPath { get; init; }
public string? UpdateAvailabilityCommand { get; init; }
public string UpdateBranch { get; init; } = "main";
public BacnetBootstrapOptions Bacnet { get; init; } = new(); 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 is null) return Results.Unauthorized();
if (user.Role != "admin") return Results.StatusCode(StatusCodes.Status403Forbidden); if (user.Role != "admin") return Results.StatusCode(StatusCodes.Status403Forbidden);
response.Headers.CacheControl = "no-store"; 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, 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.Net.Sockets;
using System.Text.Json; using System.Text.Json;
using Gateway.Api.Options; using Gateway.Api.Options;
@@ -7,16 +9,22 @@ namespace Gateway.Api.Services;
public sealed record SystemUpdateRequest(string Password); public sealed record SystemUpdateRequest(string Password);
public sealed record SystemUpdateStatus(string Phase, string Message, string? Commit = null, string? Target = null, 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 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() public bool Enabled => OperatingSystem.IsLinux()
&& !string.IsNullOrWhiteSpace(options.Value.UpdateSocketPath) && !string.IsNullOrWhiteSpace(options.Value.UpdateSocketPath)
&& !string.IsNullOrWhiteSpace(options.Value.UpdateStatusPath); && !string.IsNullOrWhiteSpace(options.Value.UpdateStatusPath);
public string? RunningCommit => IsCommit(options.Value.RunningCommit) ? options.Value.RunningCommit!.ToLowerInvariant() : null;
public SystemUpdateStatus GetStatus() public SystemUpdateStatus GetStatus()
{ {
if (!Enabled) return new("disabled", "Der lokale Systemupdate-Dienst ist für dieses Gateway nicht eingerichtet."); 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."); 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) public async Task<bool> StartAsync(CancellationToken cancellationToken)
{ {
if (!Enabled) return false; 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="/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="/vendor/markdown-it-15.0.3.min.js" defer></script>
<script src="/documentation.js?v=20261119-docs-1" 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> <script src="/app.js?v=20261124-update-1" defer></script>
</body> </body>
</html> </html>
+59 -12
View File
@@ -4,9 +4,10 @@ function bindSystemUpdate() {
const content = document.querySelector('#content'); const content = document.querySelector('#content');
content.querySelector('.grid').insertAdjacentHTML('beforeend', ` content.querySelector('.grid').insertAdjacentHTML('beforeend', `
<article class="card" id="system-update-card"> <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-status role="status">Status wird geladen …</p>
<p class="note" data-update-versions></p>
<form class="form" hidden> <form class="form" hidden>
<label>Administrator-Passwort<input name="password" type="password" autocomplete="current-password" maxlength="512" required></label> <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> <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 card = content.querySelector('#system-update-card');
const form = card.querySelector('form'); const form = card.querySelector('form');
const fields = form.querySelectorAll('input, button'); const fields = form.querySelectorAll('input, button');
const checkButton = card.querySelector('[data-check-update]');
const message = card.querySelector('[data-update-status]'); 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 error = card.querySelector('[data-update-error]');
const activePhases = new Set(['checking', 'fetching', 'building', 'activating', 'rollingBack']); const activePhases = new Set(['checking', 'fetching', 'building', 'activating', 'rollingBack']);
const informationalPhases = new Set(['ready', 'current', 'unpublished']);
let lastRun = ''; let lastRun = '';
let queuedUntil = 0; 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; }); 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() { async function refresh() {
@@ -37,18 +78,20 @@ function bindSystemUpdate() {
return; return;
} }
queuedUntil = 0; queuedUntil = 0;
const checkNeeded = !checked || busy || (status.runId || '') !== lastRun;
lastRun = status.runId || ''; lastRun = status.runId || '';
message.textContent = status.message; runningCommit.textContent = status.runningCommit?.slice(0, 8) || 'Unbekannt';
versions.textContent = [status.commit && `Installiert ${status.commit.slice(0, 8)}`, runningCommit.title = status.runningCommit || '';
status.target && status.target !== status.commit && `Ziel ${status.target.slice(0, 8)}`].filter(Boolean).join(' · '); message.textContent = informationalPhases.has(status.phase) ? '' : status.message;
form.hidden = status.phase === 'disabled'; checkButton.hidden = status.phase === 'disabled';
const busy = activePhases.has(status.phase); busy = activePhases.has(status.phase);
setBusy(busy); updateControls();
if (busy) { if (busy) {
sessionStorage.setItem(updateReturnKey, '1'); sessionStorage.setItem(updateReturnKey, '1');
setTimeout(refresh, 1500); setTimeout(refresh, 1500);
} else { } else {
sessionStorage.removeItem(updateReturnKey); sessionStorage.removeItem(updateReturnKey);
if (!checkButton.hidden && checkNeeded) await checkAvailability();
} }
} catch (failure) { } catch (failure) {
if (!card.isConnected) return; if (!card.isConnected) return;
@@ -61,12 +104,15 @@ function bindSystemUpdate() {
} }
} }
checkButton.addEventListener('click', () => checkAvailability(true));
form.addEventListener('submit', async event => { form.addEventListener('submit', async event => {
event.preventDefault(); event.preventDefault();
if (!updateAvailable || busy) return;
const body = JSON.stringify({ password: form.elements.password.value }); const body = JSON.stringify({ password: form.elements.password.value });
form.reset(); form.reset();
error.textContent = ''; error.textContent = '';
setBusy(true); busy = true;
updateControls();
try { try {
const status = await api('/api/system/update', { method: 'POST', body }); const status = await api('/api/system/update', { method: 'POST', body });
sessionStorage.setItem(updateReturnKey, '1'); sessionStorage.setItem(updateReturnKey, '1');
@@ -75,7 +121,8 @@ function bindSystemUpdate() {
setTimeout(refresh, 750); setTimeout(refresh, 750);
} catch (failure) { } catch (failure) {
error.textContent = failure.message; error.textContent = failure.message;
setBusy(false); busy = false;
updateControls();
} }
}); });