@* Pangolin-style installer command generator for a single Heimdall site. *@ @using MudBlazor @inject Heimdall.Web.Services.UiText Text @Text["SiteInstallPanel_Title"] @Text["SiteInstallPanel_Description"] @Text["SiteInstallPanel_OperatingSystem"] @foreach (var os in OperatingSystems) { @os.Icon @Text[os.Label] } @Text["SiteInstallPanel_Method"] @foreach (var method in AvailableMethods) { var selectedMethod = method.Id; @Text[method.Label] } @if (_method == "docker-compose" && CanGenerateDocker) { @Text["SiteInstallPanel_Configuration"] @Text["SiteInstallPanel_DockerUpdateNote"] @Text["SiteInstallPanel_Install"]
@ComposeYaml
@Text["SiteInstallPanel_CopyCompose"] } else if (_method == "docker-compose" && !CanGenerateDocker) { @Text["SiteInstallPanel_ImageUnavailable"] } @Text["SiteInstallPanel_Commands"] @foreach (var command in Commands) { @Text[command.Label]
@command.Value
@Text["SiteInstallPanel_CopyCommand"] } @if (_method == "windows-run") { @Text["SiteInstallPanel_WindowsConsoleNote"] } else if (_method == "windows-service") { @Text["SiteInstallPanel_WindowsServiceAdminNote"] } @code { [Parameter, EditorRequired] public string SiteName { get; set; } = ""; [Parameter, EditorRequired] public string SiteToken { get; set; } = ""; [Parameter, EditorRequired] public string CentralUrl { get; set; } = ""; [Inject] private ISnackbar Snackbar { get; set; } = default!; [Inject] private HeimdallApiClient Api { get; set; } = default!; [Inject] private IJSRuntime JsRuntime { get; set; } = default!; private static readonly (string Id, string Label, string Icon)[] OperatingSystems = [ ("linux", "SiteInstallPanel_Linux", "🐧"), ("windows", "SiteInstallPanel_Windows", "⊞"), ("docker", "SiteInstallPanel_Docker", "🐳") ]; private string _operatingSystem = "linux"; private string _method = "linux-systemd"; private string? _agentImageReference; private string? _updatePublicKeyPem; private bool CanGenerateDocker => !string.IsNullOrWhiteSpace(_agentImageReference) && !string.IsNullOrWhiteSpace(_updatePublicKeyPem); private IReadOnlyList<(string Id, string Label)> AvailableMethods => _operatingSystem switch { "linux" => [("linux-run", "SiteInstallPanel_Run"), ("linux-systemd", "SiteInstallPanel_SystemdService")], "windows" => [("windows-run", "SiteInstallPanel_PowerShellRun"), ("windows-service", "SiteInstallPanel_WindowsService")], _ => [("docker-compose", "SiteInstallPanel_DockerCompose"), ("docker-run", "SiteInstallPanel_DockerRun")] }; private IReadOnlyList<(string Label, string Value)> Commands { get { if (_method == "linux-systemd") return [ ("SiteInstallPanel_Install", LinuxInstallCommand(service: true)), ("SiteInstallPanel_Run", "sudo systemctl start heimdall-agent"), ("SiteInstallPanel_Check", "sudo systemctl status heimdall-agent --no-pager && curl -fsS http://127.0.0.1:8081/api/version") ]; if (_method == "linux-run") return [ ("SiteInstallPanel_InstallAndRun", LinuxInstallCommand(service: false)), ("SiteInstallPanel_Check", "curl -fsS http://127.0.0.1:8081/api/version") ]; if (_method == "windows-run") return [ ("SiteInstallPanel_Install", WindowsInstallCommand(service: false, installOnly: true)), ("SiteInstallPanel_Run", WindowsConsoleRunCommand), ("SiteInstallPanel_Check", "Invoke-RestMethod http://127.0.0.1:8081/api/version") ]; if (_method == "windows-service") { var serviceName = WindowsServiceName; return [ ("SiteInstallPanel_Install", WindowsInstallCommand(service: true, installOnly: true)), ("SiteInstallPanel_Run", $"Start-Service -Name {PowerShellQuote(serviceName)}"), ("SiteInstallPanel_Check", $"Get-Service -Name {PowerShellQuote(serviceName)}; Invoke-RestMethod http://127.0.0.1:8081/api/version") ]; } if (_method == "docker-compose") return [ ("SiteInstallPanel_Run", "docker compose up -d"), ("SiteInstallPanel_Check", $"docker compose ps heimdall-agent-{Slugify(SiteName)} && docker compose logs --tail 50 heimdall-agent-{Slugify(SiteName)}") ]; if (_method == "docker-run") return [ ("SiteInstallPanel_Install", DockerRunInstallCommand), ("SiteInstallPanel_Run", DockerRunCommand), ("SiteInstallPanel_Check", $"docker inspect --format '{{{{.State.Status}}}}' heimdall-agent-{Slugify(SiteName)} && docker logs --tail 50 heimdall-agent-{Slugify(SiteName)}") ]; return []; } } protected override async Task OnInitializedAsync() { try { var release = await Api.GetLatestUpdateAsync(); if (!string.IsNullOrWhiteSpace(release?.ContainerImage) && !string.IsNullOrWhiteSpace(release.ContainerImageDigest)) _agentImageReference = $"{release.ContainerImage}@{release.ContainerImageDigest}"; _updatePublicKeyPem = release?.UpdatePublicKeyPem; } catch { // Native installers fetch signed release metadata directly; Docker needs a verified image reference and key. } } private string ComposeYaml { get { var safeName = Slugify(SiteName); var pem = EscapeYamlString(_updatePublicKeyPem ?? ""); return $$""" services: heimdall-agent: image: {{_agentImageReference}} container_name: heimdall-agent-{{safeName}} restart: unless-stopped user: "1654:1654" network_mode: host environment: Agent__CentralUrl: {{YamlScalar(CentralUrl)}} Agent__SiteToken: {{YamlScalar(SiteToken)}} Agent__AgentName: {{YamlScalar(SiteName)}} Agent__HeartbeatIntervalSeconds: "30" Agent__StateDirectory: /var/lib/heimdall Agent__UpdatePublicKeyPem: "{{pem}}" volumes: - agent_state_{{safeName}}:/var/lib/heimdall depends_on: agent-state-init: condition: service_completed_successfully healthcheck: test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/healthz"] interval: 30s timeout: 5s retries: 3 start_period: 15s agent-state-init: image: {{_agentImageReference}} user: "0:0" entrypoint: ["chown", "-R", "1654:1654", "/state"] volumes: - agent_state_{{safeName}}:/state restart: "no" volumes: agent_state_{{safeName}}: """; } } private string DockerRunInstallCommand { get { var volume = "heimdall-agent-state-" + Slugify(SiteName); return $"docker pull {_agentImageReference} && docker volume create {volume} && " + $"docker run --rm --user 0:0 --entrypoint chown -v {volume}:/state {_agentImageReference} -R 1654:1654 /state"; } } private string DockerRunCommand { get { var name = "heimdall-agent-" + Slugify(SiteName); var volume = "heimdall-agent-state-" + Slugify(SiteName); return $"docker run -d --name {name} --restart unless-stopped --network host --user 1654:1654 " + $"-e Agent__CentralUrl={ShellQuote(CentralUrl)} -e Agent__SiteToken={ShellQuote(SiteToken)} " + $"-e Agent__AgentName={ShellQuote(SiteName)} -e Agent__StateDirectory=/var/lib/heimdall " + $"-e Agent__UpdatePublicKeyPem={ShellQuote(_updatePublicKeyPem ?? "")} " + $"-v {volume}:/var/lib/heimdall {_agentImageReference}"; } } private string LinuxInstallCommand(bool service) { var baseUrl = CentralUrl.TrimEnd('/'); var scriptUrl = ShellQuote(baseUrl + "/install/install-agent.sh"); var supervisorUrl = ShellQuote(baseUrl + "/install/agent-supervisor.py"); var args = $"--central-url {ShellQuote(CentralUrl)} --site-token {ShellQuote(SiteToken)} --agent-name {ShellQuote(SiteName)}"; args += service ? " --install-only" : " --run"; return "tmp=$(mktemp -d) && " + $"curl -fsSL {scriptUrl} -o \"$tmp/install-agent.sh\" && " + $"curl -fsSL {supervisorUrl} -o \"$tmp/agent-supervisor.py\" && " + $"sudo bash \"$tmp/install-agent.sh\" {args}; rc=$?; rm -rf \"$tmp\"; exit $rc"; } private string WindowsServiceName => "HeimdallAgent-" + Slugify(SiteName)[..Math.Min(60, Slugify(SiteName).Length)]; private string WindowsConsoleRunCommand { get { var root = "$env:LOCALAPPDATA + '\\Heimdall\\Agent'"; return $"$root = {root}; $env:PATH = (Join-Path $root 'runtime') + ';' + $env:PATH; " + $"$env:ASPNETCORE_URLS = 'http://127.0.0.1:8081'; " + $"$env:Agent__CentralUrl = {PowerShellQuote(CentralUrl)}; " + $"$env:Agent__SiteToken = {PowerShellQuote(SiteToken)}; " + $"$env:Agent__AgentName = {PowerShellQuote(SiteName)}; " + "$env:Agent__StateDirectory = Join-Path $root 'state'; " + $"$env:Agent__UpdatePublicKeyPem = {PowerShellQuote(_updatePublicKeyPem ?? "")}; " + "$env:Agent__UpdateInstallRoot = $root; " + "$env:Agent__UpdateSupervisorPath = Join-Path $root 'agent-update-supervisor.ps1'; " + "$current = Join-Path $root 'current'; " + "Start-Process -FilePath 'dotnet' -ArgumentList 'Heimdall.Agent.dll' -WorkingDirectory $current " + "-RedirectStandardOutput (Join-Path $root 'agent.log') -RedirectStandardError (Join-Path $root 'agent-error.log') " + "-WindowStyle Hidden -PassThru"; } } private string WindowsInstallCommand(bool service, bool installOnly) { var scriptUrl = PowerShellQuote(CentralUrl.TrimEnd('/') + "/install/install-agent.ps1"); var args = $"-CentralUrl {PowerShellQuote(CentralUrl)} -SiteToken {PowerShellQuote(SiteToken)} " + $"-AgentName {PowerShellQuote(SiteName)}"; if (service) args += $" -InstallAsService -ServiceName {PowerShellQuote(WindowsServiceName)}"; if (installOnly) args += " -InstallOnly"; return "$script = Join-Path $env:TEMP 'heimdall-install-agent.ps1'; " + $"Invoke-WebRequest -UseBasicParsing -Uri {scriptUrl} -OutFile $script; Unblock-File $script; " + "Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force; " + $"try {{ & $script {args} }} finally {{ Remove-Item $script -Force -ErrorAction SilentlyContinue }}"; } private void SelectOperatingSystem(string value) { _operatingSystem = value; _method = value switch { "linux" => "linux-systemd", "windows" => "windows-run", _ => "docker-compose" }; } private async Task CopyCode(string code) { await JsRuntime.InvokeVoidAsync("navigator.clipboard.writeText", code); Snackbar.Add(Text["SiteInstallPanel_Copied"], Severity.Success); } private static string Slugify(string value) { var sb = new System.Text.StringBuilder(); foreach (var ch in value.ToLowerInvariant()) sb.Append(char.IsAsciiLetterOrDigit(ch) ? ch : '-'); var slug = sb.ToString().Trim('-'); return string.IsNullOrWhiteSpace(slug) ? "site" : slug; } private static string ShellQuote(string value) => "'" + value.Replace("'", "'\\''", StringComparison.Ordinal) + "'"; private static string PowerShellQuote(string value) => "'" + value.Replace("'", "''", StringComparison.Ordinal) + "'"; private static string YamlScalar(string value) => "\"" + value.Replace("\\", "\\\\", StringComparison.Ordinal) .Replace("\"", "\\\"", StringComparison.Ordinal) .Replace("\r", "", StringComparison.Ordinal) .Replace("\n", "\\n", StringComparison.Ordinal) + "\""; private static string EscapeYamlString(string value) => value.Replace("\\", "\\\\", StringComparison.Ordinal) .Replace("\"", "\\\"", StringComparison.Ordinal) .Replace("\r", "", StringComparison.Ordinal) .Replace("\n", "\\n", StringComparison.Ordinal); }