diff --git a/README.md b/README.md index 8ce4f47..0be5eb9 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ systemctl status seiugw Die Weboberfläche ist auf `http://: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. diff --git a/flake.nix b/flake.nix index 40b2809..fd3a924 100644 --- a/flake.nix +++ b/flake.nix @@ -14,7 +14,7 @@ pkgs = import nixpkgs { inherit system; }; in { - default = pkgs.callPackage ./nix/package.nix { }; + default = pkgs.callPackage ./nix/package.nix { sourceRevision = self.rev or ""; }; seiugw = self.packages.${system}.default; bacnet = pkgs.callPackage ./nix/bacnet.nix { }; }); diff --git a/nix/host-hyperv.nix b/nix/host-hyperv.nix index 2183755..79e4195 100644 --- a/nix/host-hyperv.nix +++ b/nix/host-hyperv.nix @@ -2,7 +2,7 @@ { imports = [ - (builtins.getFlake "path:/etc/nixos/seiugw").nixosModules.default + (builtins.getFlake "git+file:///etc/nixos/seiugw").nixosModules.default ]; services.seiugw = { diff --git a/nix/host-snippet.nix b/nix/host-snippet.nix index 1a42a3c..90d7215 100644 --- a/nix/host-snippet.nix +++ b/nix/host-snippet.nix @@ -2,7 +2,7 @@ { imports = [ - (builtins.getFlake "path:/etc/nixos/seiugw").nixosModules.default + (builtins.getFlake "git+file:///etc/nixos/seiugw").nixosModules.default ]; services.seiugw = { diff --git a/nix/module.nix b/nix/module.nix index 5c31242..426e3f3 100644 --- a/nix/module.nix +++ b/nix/module.nix @@ -13,6 +13,12 @@ let dhcpcdBase = builtins.head (builtins.match ".* --config ([^ ]+).*" config.systemd.services.dhcpcd.serviceConfig.ExecStart); networkHelper = "${pkgs.python3}/bin/python3 ${./host-network.py}"; 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" '' 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}"} @@ -310,9 +316,12 @@ in Gateway__Bacnet__DeviceInstance = toString cfg.bacnet.deviceInstance; Gateway__Bacnet__IpPort = toString cfg.bacnet.ipPort; Gateway__OpcUa__Port = toString cfg.opcUa.port; + Gateway__RunningCommit = cfg.package.sourceRevision or ""; } // lib.optionalAttrs cfg.updates.enable { Gateway__UpdateSocketPath = updateSocket; Gateway__UpdateStatusPath = "/var/lib/seiugw-updater/status.json"; + Gateway__UpdateAvailabilityCommand = updateAvailability; + Gateway__UpdateBranch = cfg.updates.branch; }; serviceConfig = { diff --git a/nix/package.nix b/nix/package.nix index 60eccd4..27a2f33 100644 --- a/nix/package.nix +++ b/nix/package.nix @@ -1,4 +1,4 @@ -{ lib, buildDotnetModule, dotnetCorePackages }: +{ lib, buildDotnetModule, dotnetCorePackages, sourceRevision ? "" }: buildDotnetModule { pname = "seiugw"; @@ -12,6 +12,8 @@ buildDotnetModule { dotnet-runtime = dotnetCorePackages.aspnetcore_8_0; executables = [ "Gateway.Api" ]; + passthru = { inherit sourceRevision; }; + meta = { description = "Industrial protocol gateway for BACnet/IP, OPC UA, Modbus TCP and MQTT"; platforms = lib.platforms.linux; diff --git a/nix/system-update-availability.sh b/nix/system-update-availability.sh new file mode 100644 index 0000000..2f8ae0a --- /dev/null +++ b/nix/system-update-availability.sh @@ -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 diff --git a/src/Gateway.Api/Options/GatewayOptions.cs b/src/Gateway.Api/Options/GatewayOptions.cs index d47a77a..4f31e9e 100644 --- a/src/Gateway.Api/Options/GatewayOptions.cs +++ b/src/Gateway.Api/Options/GatewayOptions.cs @@ -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(); diff --git a/src/Gateway.Api/Program.cs b/src/Gateway.Api/Program.cs index 628d584..3de5bff 100644 --- a/src/Gateway.Api/Program.cs +++ b/src/Gateway.Api/Program.cs @@ -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, diff --git a/src/Gateway.Api/Services/SystemUpdateService.cs b/src/Gateway.Api/Services/SystemUpdateService.cs index 5e14823..1b31cee 100644 --- a/src/Gateway.Api/Services/SystemUpdateService.cs +++ b/src/Gateway.Api/Services/SystemUpdateService.cs @@ -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 options) +public sealed class SystemUpdateService(IOptions 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 options) return new("unavailable", "Der Update-Status konnte nicht gelesen werden."); } + public async Task 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 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 StartAsync(CancellationToken cancellationToken) { if (!Enabled) return false; diff --git a/src/Gateway.Api/wwwroot/index.html b/src/Gateway.Api/wwwroot/index.html index 901afd5..95af058 100644 --- a/src/Gateway.Api/wwwroot/index.html +++ b/src/Gateway.Api/wwwroot/index.html @@ -24,7 +24,7 @@ - + diff --git a/src/Gateway.Api/wwwroot/system-update.js b/src/Gateway.Api/wwwroot/system-update.js index 0b9e951..b5badef 100644 --- a/src/Gateway.Api/wwwroot/system-update.js +++ b/src/Gateway.Api/wwwroot/system-update.js @@ -4,9 +4,10 @@ function bindSystemUpdate() { const content = document.querySelector('#content'); content.querySelector('.grid').insertAdjacentHTML('beforeend', `
-

Gateway-Update

+

Gateway-Update

+

Laufender Commit –

+

Status wird geladen …

-