Add authenticated Gateway system updates with rollback
This commit is contained in:
1 parent
198b1d7b78
commit
4e35a3a557
9 files changed
+423
-1
No files matched your search
@@ -0,0 +1,53 @@
|
||||
using System.Net.Sockets;
|
||||
using System.Text.Json;
|
||||
using Gateway.Api.Options;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
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);
|
||||
|
||||
public sealed class SystemUpdateService(IOptions<GatewayOptions> options)
|
||||
{
|
||||
private static readonly JsonSerializerOptions StatusJson = new(JsonSerializerDefaults.Web);
|
||||
|
||||
public bool Enabled => OperatingSystem.IsLinux()
|
||||
&& !string.IsNullOrWhiteSpace(options.Value.UpdateSocketPath)
|
||||
&& !string.IsNullOrWhiteSpace(options.Value.UpdateStatusPath);
|
||||
|
||||
public SystemUpdateStatus GetStatus()
|
||||
{
|
||||
if (!Enabled) return new("disabled", "Der lokale Systemupdate-Dienst ist für dieses Gateway nicht eingerichtet.");
|
||||
try
|
||||
{
|
||||
var status = JsonSerializer.Deserialize<SystemUpdateStatus>(File.ReadAllText(options.Value.UpdateStatusPath!), StatusJson);
|
||||
if (status is not null) return status;
|
||||
}
|
||||
catch (FileNotFoundException) { return new("ready", "Bereit für ein Update aus Git."); }
|
||||
catch (DirectoryNotFoundException) { return new("ready", "Bereit für ein Update aus Git."); }
|
||||
catch (IOException) { }
|
||||
catch (UnauthorizedAccessException) { }
|
||||
catch (JsonException) { }
|
||||
return new("unavailable", "Der Update-Status konnte nicht gelesen werden.");
|
||||
}
|
||||
|
||||
public async Task<bool> StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (!Enabled) return false;
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(5));
|
||||
using var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
|
||||
try
|
||||
{
|
||||
await socket.ConnectAsync(new UnixDomainSocketEndPoint(options.Value.UpdateSocketPath!), timeout.Token);
|
||||
using var stream = new NetworkStream(socket);
|
||||
using var response = new StreamReader(stream);
|
||||
return string.Equals(await response.ReadLineAsync(timeout.Token), "accepted", StringComparison.Ordinal);
|
||||
}
|
||||
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { return false; }
|
||||
catch (SocketException) { return false; }
|
||||
catch (IOException) { return false; }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user