using System.Diagnostics; using System.Text.Json; using System.Text.RegularExpressions; namespace HealthApp.Provisioning; public static class Distribution { public static async Task Deploy(string bundle, string directory, string user, string[] selected) { if (!Regex.IsMatch(user, "^[a-zA-Z_][a-zA-Z0-9_-]*$")) throw new InvalidOperationException("SSH user is invalid."); var deployment = Deployment.Load(directory); async Task Run(string command, params string[] args) { var start = new ProcessStartInfo(command) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; foreach (var argument in args) start.ArgumentList.Add(argument); using var process = Process.Start(start) ?? throw new InvalidOperationException("Could not run deployment transport."); var stdout = process.StandardOutput.ReadToEndAsync(); var stderr = process.StandardError.ReadToEndAsync(); using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(20)); try { await process.WaitForExitAsync(timeout.Token); } catch (OperationCanceledException) { process.Kill(true); throw; } await stdout; var errors = await stderr; if (process.ExitCode != 0) { var reportedStep = errors.Split('\n').LastOrDefault(line => line.StartsWith("Installation failed at ", StringComparison.Ordinal)); throw new InvalidOperationException(reportedStep ?? "SSH deployment transport failed; check administrative SSH access and node installation logs."); } } var temporary = Path.Combine(Path.GetTempPath(), "healthapp-distribution-" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(temporary); if (OperatingSystem.IsLinux()) File.SetUnixFileMode(temporary, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); try { foreach (var group in selected.GroupBy(n => deployment.Services[n].Host, StringComparer.OrdinalIgnoreCase)) { var names = group.ToArray(); var node = Path.Combine(temporary, "node-" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(node); var material = Path.Combine(node, "deployment"); Directory.CreateDirectory(material); foreach (var script in Directory.GetFiles(bundle).Where(p => p.EndsWith(".sh") || p.EndsWith(".ps1"))) File.Copy(script, Path.Combine(node, Path.GetFileName(script))); CopyDirectory(Path.Combine(bundle, "provisioner"), Path.Combine(node, "provisioner")); Directory.CreateDirectory(Path.Combine(node, "services")); Directory.CreateDirectory(Path.Combine(node, "systemd")); foreach (var name in names) { CopyDirectory(Path.Combine(bundle, "services", name), Path.Combine(node, "services", name)); CopyDirectory(Path.Combine(directory, name), Path.Combine(material, name)); File.Copy(Path.Combine(bundle, "systemd", "healthapp-" + name + ".service"), Path.Combine(node, "systemd", "healthapp-" + name + ".service")); } // Retain remote origins, but do not give a node unrelated service/database/private-key credentials. var scoped = deployment with { Services = deployment.Services.ToDictionary(p => p.Key, p => names.Contains(p.Key) ? p.Value : p.Value with { IncomingKey = "", OutgoingKey = null, CertificatePassword = "", Database = null, Environment = new() }), Accounts = names.Contains("api-gateway") ? deployment.Accounts : [] }; File.WriteAllText(Path.Combine(material, "deployment.json"), JsonSerializer.Serialize(scoped, Deployment.Json)); if (names.Contains("api-gateway")) File.Copy(Path.Combine(directory, "accounts.json"), Path.Combine(material, "accounts.json")); File.Copy(Path.Combine(directory, "healthapp-ca.crt"), Path.Combine(material, "healthapp-ca.crt")); var target = user + "@" + group.Key; var windows = names.All(n => deployment.Services[n].Platform == "windows"); if (names.Any(n => deployment.Services[n].Platform == "windows") && !windows) throw new InvalidOperationException("One host cannot use two native service managers."); var remote = windows ? "C:/ProgramData/healthapp-install-" + deployment.Id : "/var/tmp/healthapp-install-" + deployment.Id; Console.WriteLine("Install selected node: " + group.Key); if (windows) await Run("ssh", target, "powershell", "-NoProfile", "-NonInteractive", "-Command", "New-Item -ItemType Directory -Path '" + remote + "' | Out-Null"); else await Run("ssh", target, "mkdir", "-m", "0700", remote); var scpHost = group.Key.Contains(':') ? user + "@[" + group.Key + "]" : target; await Run("scp", "-r", node + "/.", scpHost + ":" + remote + "/"); if (windows) await Run("ssh", target, "powershell", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", remote + "/install.ps1", "-Services", string.Join(',', names), "-Deployment", remote + "/deployment", "-DeferTopologyCheck"); else await Run("ssh", target, "sudo", "-n", "bash", remote + "/install.sh", "--services", string.Join(',', names), "--deployment", remote + "/deployment", "--defer-topology-check"); } // Services communicate through the actual HTTPS origins on their installed hosts. await InstallationVerification.Verify(directory, selected, selected.Length == Deployment.Names.Length); Console.WriteLine("Distributed topology verification passed."); } finally { Directory.Delete(temporary, true); } } private static void CopyDirectory(string source, string destination) { Directory.CreateDirectory(destination); foreach (var file in Directory.GetFiles(source)) File.Copy(file, Path.Combine(destination, Path.GetFileName(file))); foreach (var child in Directory.GetDirectories(source)) CopyDirectory(child, Path.Combine(destination, Path.GetFileName(child))); } }