Implement US-16 independent Linux service installation
This commit is contained in:
1 parent
b6342afdad
commit
950f67d8b7
10 files changed
+837
No files matched your search
@@ -0,0 +1,180 @@
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Security.Cryptography;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Npgsql;
|
||||
using Xunit;
|
||||
|
||||
namespace Deployment.AcceptanceTests;
|
||||
|
||||
public sealed class DeploymentFixture : IAsyncLifetime
|
||||
{
|
||||
public static readonly string[] Services = ["api-gateway", "patient-profile", "observation", "insights", "health-overview"];
|
||||
public static string Assembly(string service) => service switch
|
||||
{
|
||||
"api-gateway" => "ApiGateway", "patient-profile" => "PatientProfileService",
|
||||
"observation" => "ObservationService", "insights" => "InsightsService", _ => "HealthOverviewService"
|
||||
};
|
||||
public static string Repository
|
||||
{
|
||||
get
|
||||
{
|
||||
var directory = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "HealthApp.slnx"))) directory = directory.Parent;
|
||||
return directory?.FullName ?? throw new InvalidOperationException("Repository root not found.");
|
||||
}
|
||||
}
|
||||
public string Dotnet { get; } = Environment.GetEnvironmentVariable("HEALTHAPP_DOTNET") ??
|
||||
Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet";
|
||||
public string Temporary { get; } = Path.Combine(Path.GetTempPath(), "healthapp-us16-" + Guid.NewGuid().ToString("N"));
|
||||
public string Bundle => Path.Combine(Temporary, "release");
|
||||
public string Configuration => Path.Combine(Temporary, "configuration");
|
||||
public string Root => Path.Combine(Temporary, "installed");
|
||||
public Dictionary<string, string> Urls { get; } = new();
|
||||
public Dictionary<string, Dictionary<string, string>> Settings { get; } = new();
|
||||
public Dictionary<string, Process> Processes { get; } = new();
|
||||
private readonly List<string> databases = [];
|
||||
public string Admin { get; private set; } = "";
|
||||
public const string Password = "synthetic-deployment-password";
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
Directory.CreateDirectory(Temporary);
|
||||
Directory.CreateDirectory(Configuration);
|
||||
Admin = Environment.GetEnvironmentVariable("TEST_POSTGRES_CONNECTION") ?? throw new InvalidOperationException("TEST_POSTGRES_CONNECTION is required.");
|
||||
var release = await Run("bash", [Path.Combine(Repository, "deploy/build-release.sh"), "--output", Bundle],
|
||||
new() { ["HEALTHAPP_DOTNET"] = Dotnet });
|
||||
Assert.True(release.Code == 0, "Release publishing failed; no secret configuration was used.");
|
||||
foreach (var service in Services)
|
||||
{
|
||||
using var listener = new TcpListener(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
Urls[service] = $"http://127.0.0.1:{((IPEndPoint)listener.LocalEndpoint).Port}/";
|
||||
Settings[service] = new()
|
||||
{
|
||||
["ASPNETCORE_ENVIRONMENT"] = "Development", ["ASPNETCORE_URLS"] = Urls[service],
|
||||
["InternalAccess__GatewayKey"] = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)),
|
||||
["Logging__LogLevel__Default"] = "Warning", ["Logging__LogLevel__Microsoft.AspNetCore"] = "Warning"
|
||||
};
|
||||
}
|
||||
foreach (var service in new[] { "patient-profile", "observation" })
|
||||
{
|
||||
var database = "us16_" + Guid.NewGuid().ToString("N");
|
||||
await using var connection = new NpgsqlConnection(Admin);
|
||||
await connection.OpenAsync();
|
||||
await using var create = new NpgsqlCommand("CREATE DATABASE " + database, connection);
|
||||
await create.ExecuteNonQueryAsync();
|
||||
databases.Add(database);
|
||||
Settings[service][service == "patient-profile" ? "ConnectionStrings__PatientDatabase" : "ConnectionStrings__ObservationDatabase"] =
|
||||
new NpgsqlConnectionStringBuilder(Admin) { Database = database }.ConnectionString;
|
||||
}
|
||||
var names = new Dictionary<string, string> { ["patient-profile"] = "PatientProfile", ["observation"] = "Observation",
|
||||
["insights"] = "Insights", ["health-overview"] = "HealthOverview" };
|
||||
foreach (var (service, name) in names)
|
||||
{
|
||||
Settings["api-gateway"][$"Services__{name}__BaseUrl"] = Urls[service];
|
||||
Settings["api-gateway"][$"Services__{name}__Key"] = Settings[service]["InternalAccess__GatewayKey"];
|
||||
if (service == "patient-profile") continue;
|
||||
var key = Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
|
||||
Settings["api-gateway"][$"InternalAccess__{name}__Key"] = key;
|
||||
Settings[service]["Services__ApiGateway__Key"] = key;
|
||||
Settings[service]["Services__ApiGateway__BaseUrl"] = Urls["api-gateway"];
|
||||
}
|
||||
var gateway = Settings["api-gateway"];
|
||||
gateway["Authentication__KeyDirectory"] = Path.Combine(Temporary, "keys");
|
||||
gateway["Authentication__Accounts__0__AccountId"] = "deployment-patient";
|
||||
gateway["Authentication__Accounts__0__Role"] = "Patient";
|
||||
gateway["Authentication__Accounts__0__PasswordHash"] = new PasswordHasher<string>().HashPassword("deployment-patient", Password);
|
||||
foreach (var service in Services)
|
||||
await File.WriteAllLinesAsync(Path.Combine(Configuration, service + ".env"), Settings[service]
|
||||
.Select(p => $"{p.Key}=\"{p.Value.Replace("\\", "\\\\").Replace("\"", "\\\"")}\""));
|
||||
var installation = await Install(Root, "all");
|
||||
Assert.Equal(0, installation.Code);
|
||||
foreach (var service in new[] { "patient-profile", "observation" })
|
||||
{
|
||||
var migrated = await Run(Dotnet, [InstalledAssembly(service), "--migrate"], Settings[service]);
|
||||
Assert.True(migrated.Code == 0, "Deployment database migration failed.");
|
||||
}
|
||||
}
|
||||
|
||||
public string InstalledAssembly(string service) => Path.Combine(Root, "opt/healthapp", service, Assembly(service) + ".dll");
|
||||
public Task<(int Code, string Output)> Install(string root, string services) => Run("bash",
|
||||
[Path.Combine(Bundle, "install.sh"), "--services", services, "--config-dir", Configuration, "--root", root]);
|
||||
|
||||
public async Task Start(string service, string? root = null)
|
||||
{
|
||||
var start = new ProcessStartInfo(Dotnet) { WorkingDirectory = Path.Combine(root ?? Root, "opt/healthapp", service),
|
||||
RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false };
|
||||
start.ArgumentList.Add(Path.Combine(root ?? Root, "opt/healthapp", service, Assembly(service) + ".dll"));
|
||||
foreach (var (key, value) in Settings[service]) start.Environment[key] = value;
|
||||
var process = Process.Start(start)!;
|
||||
// Do not emit application logs containing potentially sensitive deployment information.
|
||||
process.OutputDataReceived += (_, _) => { };
|
||||
process.ErrorDataReceived += (_, _) => { };
|
||||
process.BeginOutputReadLine(); process.BeginErrorReadLine();
|
||||
Processes[service] = process;
|
||||
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(1) };
|
||||
for (var attempt = 0; attempt < 100; attempt++)
|
||||
{
|
||||
Assert.False(process.HasExited, $"{service} exited during startup.");
|
||||
try { using var response = await client.GetAsync(Urls[service]); return; }
|
||||
catch (HttpRequestException) { }
|
||||
catch (TaskCanceledException) { }
|
||||
await Task.Delay(100);
|
||||
}
|
||||
throw new TimeoutException($"{service} did not accept configured network traffic.");
|
||||
}
|
||||
|
||||
public async Task Stop(string service)
|
||||
{
|
||||
if (!Processes.Remove(service, out var process)) return;
|
||||
try
|
||||
{
|
||||
if (!process.HasExited)
|
||||
{
|
||||
// SIGINT is also the committed systemd unit's graceful stop signal.
|
||||
var sent = await Run("kill", ["-INT", process.Id.ToString()]);
|
||||
Assert.Equal(0, sent.Code);
|
||||
using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));
|
||||
try { await process.WaitForExitAsync(deadline.Token); }
|
||||
catch (OperationCanceledException) { process.Kill(true); await process.WaitForExitAsync(); throw; }
|
||||
Assert.Equal(0, process.ExitCode);
|
||||
}
|
||||
}
|
||||
finally { process.Dispose(); }
|
||||
}
|
||||
|
||||
public static async Task<(int Code, string Output)> Run(string executable, string[] arguments,
|
||||
Dictionary<string, string>? environment = null, string? workingDirectory = null)
|
||||
{
|
||||
var start = new ProcessStartInfo(executable) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true };
|
||||
if (workingDirectory is not null) start.WorkingDirectory = workingDirectory;
|
||||
foreach (var argument in arguments) start.ArgumentList.Add(argument);
|
||||
if (environment is not null) foreach (var (key, value) in environment) start.Environment[key] = value;
|
||||
using var process = Process.Start(start)!;
|
||||
var stdout = process.StandardOutput.ReadToEndAsync();
|
||||
var stderr = process.StandardError.ReadToEndAsync();
|
||||
using var deadline = new CancellationTokenSource(TimeSpan.FromMinutes(3));
|
||||
try { await process.WaitForExitAsync(deadline.Token); }
|
||||
catch (OperationCanceledException) { process.Kill(true); await process.WaitForExitAsync(); throw; }
|
||||
return (process.ExitCode, await stdout + await stderr);
|
||||
}
|
||||
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
foreach (var service in Processes.Keys.ToArray()) await Stop(service);
|
||||
NpgsqlConnection.ClearAllPools();
|
||||
if (!string.IsNullOrEmpty(Admin))
|
||||
{
|
||||
await using var connection = new NpgsqlConnection(Admin);
|
||||
await connection.OpenAsync();
|
||||
foreach (var database in databases)
|
||||
{
|
||||
await using var drop = new NpgsqlCommand("DROP DATABASE IF EXISTS " + database + " WITH (FORCE)", connection);
|
||||
await drop.ExecuteNonQueryAsync();
|
||||
}
|
||||
}
|
||||
if (Directory.Exists(Temporary)) Directory.Delete(Temporary, true);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user