@* Pangolin-style installer command generator for a single Heimdall site. *@ @using MudBlazor @inject Heimdall.Web.Services.UiText Text @Text["SiteInstallPanel_Title"] @Text["SiteInstallPanel_Description"] @if (_releaseLoading) { } else if (_releaseReady) { @string.Format(Text["SiteInstallPanel_ReleaseReady"], _releaseVersion) } else { @Text["SiteInstallPanel_ReleaseUnavailable"] } @Text["SiteInstallPanel_OperatingSystem"] @foreach (var os in OperatingSystems) { @Text[os.Label] } @Text["SiteInstallPanel_Method"] @foreach (var method in AvailableMethods) { var selectedMethod = method.Id; @Text[method.Label] } @if ((_method == "docker-compose" || _method == "docker-run") && CanGenerateDocker && !string.IsNullOrWhiteSpace(_agentGpuImageReference)) { @Text["SiteInstallPanel_Configuration"] @Text["SiteInstallPanel_NvidiaInference"] @Text["SiteInstallPanel_NvidiaDescription"] @if (_useGpuImage) { @Text["SiteInstallPanel_NvidiaRequirement"] } } @if (_method == "docker-compose" && CanGenerateDocker) { @Text["SiteInstallPanel_DockerUpdateNote"] } else if (_method == "docker-compose" && !CanGenerateDocker) { @Text["SiteInstallPanel_ImageUnavailable"] } else if (_method == "docker-run" && CanGenerateDocker) { @Text["SiteInstallPanel_DockerUpdateNote"] } else if (_method == "docker-run") { @Text["SiteInstallPanel_ImageUnavailable"] } @if (CanGenerateSelectedMethod) { @Text["SiteInstallPanel_Commands"] @if (_method == "docker-compose") { @Text["SiteInstallPanel_Configuration"]
@ComposeYaml
} @foreach (var command in Commands) { @Text[command.Label]
@command.Value
} } @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", Icons.Material.Filled.Terminal), ("windows", "SiteInstallPanel_Windows", Icons.Material.Filled.Window), ("docker", "SiteInstallPanel_Docker", Icons.Material.Filled.ViewInAr) ]; private string _operatingSystem = "linux"; private string _method = "linux-systemd"; private string? _agentImageReference; private string? _agentGpuImageReference; private string? _updatePublicKeyPem; private string? _releaseVersion; private bool _releaseLoading = true; private bool _releaseReady; private bool _useGpuImage; private string? _copiedCode; private string CopyIconFor(string code) => _copiedCode == code ? Icons.Material.Filled.Check : Icons.Material.Filled.ContentCopy; private static string OptionClass(bool selected) => selected ? "installer-option installer-option-selected" : "installer-option"; private bool CanGenerateDocker => !string.IsNullOrWhiteSpace(_agentImageReference) && !string.IsNullOrWhiteSpace(_updatePublicKeyPem) && _releaseReady; private bool CanGenerateSelectedMethod => _method switch { "docker-compose" or "docker-run" => CanGenerateDocker, _ => _releaseReady }; 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)}"), ("SiteInstallPanel_InstallPowerShell", DockerRunPowerShellInstallCommand), ("SiteInstallPanel_RunPowerShell", DockerRunPowerShellCommand), ("SiteInstallPanel_CheckPowerShell", DockerRunPowerShellCheckCommand) ]; return []; } } protected override async Task OnInitializedAsync() { try { var release = await Api.GetLatestUpdateAsync(); _releaseVersion = release?.Version; _releaseReady = !string.IsNullOrWhiteSpace(release?.UpdatePublicKeyPem) && !string.IsNullOrWhiteSpace(release?.SignedManifest) && !string.IsNullOrWhiteSpace(release?.ManifestSignature) && release?.Assets.Count > 0; if (!string.IsNullOrWhiteSpace(release?.ContainerImage) && !string.IsNullOrWhiteSpace(release.ContainerImageDigest)) _agentImageReference = $"{release.ContainerImage}@{release.ContainerImageDigest}"; if (!string.IsNullOrWhiteSpace(release?.ContainerImageGpu) && !string.IsNullOrWhiteSpace(release.ContainerImageGpuDigest)) _agentGpuImageReference = $"{release.ContainerImageGpu}@{release.ContainerImageGpuDigest}"; _updatePublicKeyPem = release?.UpdatePublicKeyPem; } catch { // Native installers fetch signed release metadata directly; Docker needs a verified image reference and key. } finally { _releaseLoading = false; } } private string ComposeYaml { get { var safeName = Slugify(SiteName); var pem = EscapeYamlString(_updatePublicKeyPem ?? ""); var image = _useGpuImage ? _agentGpuImageReference : _agentImageReference; var provider = _useGpuImage ? "CUDA" : "CPU"; var gpuReservation = _useGpuImage ? "deploy:\n resources:\n reservations:\n devices:\n - driver: nvidia\n count: all\n capabilities: [gpu]\n" : string.Empty; return $$""" services: heimdall-agent: image: {{image}} container_name: heimdall-agent-{{safeName}} restart: unless-stopped user: "1654:1654" group_add: - "${DOCKER_GID:-0}" 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__InferenceExecutionProvider: {{provider}} Agent__UpdatePublicKeyPem: "{{pem}}" volumes: - agent_state_{{safeName}}:/var/lib/heimdall - /var/run/docker.sock:/var/run/docker.sock 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 __NVIDIA_RESERVATION__ agent-state-init: image: {{image}} user: "0:0" entrypoint: ["chown", "-R", "1654:1654", "/state"] volumes: - agent_state_{{safeName}}:/state restart: "no" volumes: agent_state_{{safeName}}: """.Replace("__NVIDIA_RESERVATION__", gpuReservation, StringComparison.Ordinal); } } private string DockerRunInstallCommand { get { var volume = "heimdall-agent-state-" + Slugify(SiteName); var image = _useGpuImage ? _agentGpuImageReference : _agentImageReference; return $"docker pull {image} && docker volume create {volume} && " + $"docker run --rm --user 0:0 --entrypoint chown -v {volume}:/state {image} -R 1654:1654 /state"; } } private string DockerRunCommand { get { var name = "heimdall-agent-" + Slugify(SiteName); var volume = "heimdall-agent-state-" + Slugify(SiteName); var image = _useGpuImage ? _agentGpuImageReference : _agentImageReference; return $"docker run -d --name {name} --restart unless-stopped --network host --user 1654:1654 " + (_useGpuImage ? "--gpus all " : "") + "--group-add \"$(stat -c '%g' /var/run/docker.sock)\" " + "-v /var/run/docker.sock:/var/run/docker.sock " + $"-e Agent__CentralUrl={ShellQuote(CentralUrl)} -e Agent__SiteToken={ShellQuote(SiteToken)} " + $"-e Agent__AgentName={ShellQuote(SiteName)} -e Agent__StateDirectory=/var/lib/heimdall " + $"-e Agent__InferenceExecutionProvider={(_useGpuImage ? "CUDA" : "CPU")} " + $"-e Agent__UpdatePublicKeyPem={ShellQuote(_updatePublicKeyPem ?? "")} " + $"-v {volume}:/var/lib/heimdall {image}"; } } private string DockerRunPowerShellInstallCommand { get { var volume = "heimdall-agent-state-" + Slugify(SiteName); var image = _useGpuImage ? _agentGpuImageReference : _agentImageReference; return "$ErrorActionPreference = 'Stop'; " + "docker pull " + PowerShellQuote(image ?? "") + "; if ($LASTEXITCODE -ne 0) { throw 'docker pull failed' }; " + "docker volume create " + PowerShellQuote(volume) + "; if ($LASTEXITCODE -ne 0) { throw 'docker volume create failed' }; " + "docker run --rm --user 0:0 --entrypoint chown -v " + PowerShellQuote(volume + ":/state") + " " + PowerShellQuote(image ?? "") + " -R 1654:1654 /state; if ($LASTEXITCODE -ne 0) { throw 'state volume initialization failed' }"; } } private string DockerRunPowerShellCommand { get { var name = "heimdall-agent-" + Slugify(SiteName); var volume = "heimdall-agent-state-" + Slugify(SiteName); var image = _useGpuImage ? _agentGpuImageReference : _agentImageReference; var args = new List { "run", "-d", "--name", name, "--restart", "unless-stopped", "--user", "1654:1654", "--publish", "127.0.0.1:8081:8080", "--group-add", "0", "-v", "/var/run/docker.sock:/var/run/docker.sock" }; if (_useGpuImage) args.AddRange(["--gpus", "all"]); args.AddRange([ "-e", "Agent__CentralUrl=" + CentralUrl, "-e", "Agent__SiteToken=" + SiteToken, "-e", "Agent__AgentName=" + SiteName, "-e", "Agent__StateDirectory=/var/lib/heimdall", "-e", "ASPNETCORE_URLS=http://+:8080", "-e", "Agent__InferenceExecutionProvider=" + (_useGpuImage ? "CUDA" : "CPU"), "-e", "Agent__UpdatePublicKeyPem=" + (_updatePublicKeyPem ?? ""), "-v", volume + ":/var/lib/heimdall", image ?? "" ]); return "$dockerArgs = @(" + string.Join(",", args.Select(PowerShellQuote)) + "); & docker @dockerArgs; if ($LASTEXITCODE -ne 0) { throw 'docker run failed' }"; } } private string DockerRunPowerShellCheckCommand { get { var name = "heimdall-agent-" + Slugify(SiteName); return "$status = docker inspect --format '{{.State.Status}}' " + PowerShellQuote(name) + "; " + "if ($LASTEXITCODE -ne 0) { throw 'container inspect failed' }; $status; " + "docker logs --tail 50 " + PowerShellQuote(name) + "; if ($LASTEXITCODE -ne 0) { throw 'container logs failed' }"; } } 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); _copiedCode = code; StateHasChanged(); Snackbar.Add(Text["SiteInstallPanel_Copied"], Severity.Success); await Task.Delay(TimeSpan.FromSeconds(2)); if (_copiedCode == code) _copiedCode = null; await InvokeAsync(StateHasChanged); } 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); }