Files
opengenesislinkserver/addons/OSWebInterface/LiveUpdateBridge.cs
T

100 lines
4.4 KiB
C#

// SPDX-License-Identifier: MPL-2.0
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
namespace OpenGenesisLINK.Addons.OSWebInterface;
/// <summary>
/// Optional integration with the separately installed and independently
/// authenticated OGL G1 live-update systemd service. This DLL NEVER runs
/// a shell and NEVER receives script paths/commands from the browser.
/// </summary>
internal sealed class LiveUpdateBridge : IDisposable
{
private readonly bool _enabled;
private readonly string _nodeId;
private readonly string _token;
private readonly HttpClient _http;
public LiveUpdateBridge(bool requested, string nodeId, string serviceUrl, string token)
{
_nodeId = nodeId;
_token = token;
bool goodId = nodeId.Length is >= 1 and <= 64 &&
char.IsLetterOrDigit(nodeId[0]) &&
nodeId.All(c => char.IsLetterOrDigit(c) || c is '.' or '_' or '-');
bool local = Uri.TryCreate(serviceUrl, UriKind.Absolute, out Uri? u) &&
u.Scheme == "http" && u.Host == "127.0.0.1" &&
u.Port is >= 1025 and <= 65535 &&
u.AbsolutePath == "/" && u.Query.Length == 0 && u.Fragment.Length == 0;
_enabled = requested && goodId && local && Encoding.UTF8.GetByteCount(token) >= 32 &&
!OperatingSystem.IsWindows();
_http = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false })
{
BaseAddress = _enabled ? new Uri(serviceUrl.TrimEnd('/') + "/") :
new Uri("http://127.0.0.1:19090/"),
Timeout = TimeSpan.FromSeconds(6)
};
}
private HttpRequestMessage Request(HttpMethod method, string relative, object? body = null)
{
var req = new HttpRequestMessage(method, relative);
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _token);
if (body is not null)
{
req.Content = new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json");
}
return req;
}
public async Task<object> StatusAsync(CancellationToken stop)
{
if (!_enabled) return new { enabled = false, reachable = false, message = "Live-Updates sind nicht aktiviert oder der externe Updater ist nicht sicher konfiguriert." };
try
{
using var request = Request(HttpMethod.Get, "v1/status");
using var response = await _http.SendAsync(request, stop);
if (!response.IsSuccessStatusCode)
return new { enabled = true, reachable = false, message = "Update-Dienst verweigert Statusabfrage: " + (int)response.StatusCode };
using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync(stop));
return new { enabled = true, reachable = true, update = document.RootElement.Clone() };
}
catch (Exception)
{
return new { enabled = true, reachable = false, message = "Updater auf 127.0.0.1 nicht erreichbar" };
}
}
public async Task<object> StartAsync(CancellationToken stop)
{
if (!_enabled) throw new AdminOperations.OperationException(403, "Live-Update-Dienst ist nicht aktiviert.");
using var request = Request(HttpMethod.Post, "v1/updates", new
{
node_id = _nodeId,
operation_id = Guid.NewGuid().ToString()
});
try
{
using var response = await _http.SendAsync(request, stop);
if (!response.IsSuccessStatusCode)
throw new AdminOperations.OperationException((int)response.StatusCode, "Update-Dienst hat den Auftrag abgelehnt (" + (int)response.StatusCode + ").");
using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync(stop));
return new
{
accepted = true,
update = document.RootElement.Clone(),
note = "Updater führt Backup, Git-Aktualisierung und .NET-10-Build eigenständig aus. Anschließend Simulator manuell neu starten."
};
}
catch (AdminOperations.OperationException) { throw; }
catch (Exception e)
{
throw new AdminOperations.OperationException(503, "Lokaler Update-Dienst nicht erreichbar: " + e.GetType().Name);
}
}
public void Dispose() => _http.Dispose();
}