Files
Heimdall/src/Heimdall.Web/Components/SiteInstallPanel.razor
T

340 lines
15 KiB
Plaintext
Raw Normal View History

@* Pangolin-style installer command generator for a single Heimdall site. *@
@using MudBlazor
@inject Heimdall.Web.Services.UiText Text
<MudText Typo="Typo.h6" Class="mb-1">
<MudIcon Icon="@Icons.Material.Filled.Download" Size="Size.Small" Class="mr-1" />
@Text["SiteInstallPanel_Title"]
</MudText>
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-4">
@Text["SiteInstallPanel_Description"]
</MudText>
<MudText Typo="Typo.subtitle1" Class="mb-2">@Text["SiteInstallPanel_OperatingSystem"]</MudText>
<MudGrid Class="mb-3">
@foreach (var os in OperatingSystems)
{
<MudItem xs="12" sm="4" @key="os.Id">
<MudButton FullWidth="true" Variant="@(_operatingSystem == os.Id ? Variant.Filled : Variant.Outlined)"
Color="@(_operatingSystem == os.Id ? Color.Primary : Color.Default)"
OnClick="@(() => SelectOperatingSystem(os.Id))">@os.Icon @Text[os.Label]</MudButton>
</MudItem>
}
</MudGrid>
<MudText Typo="Typo.subtitle1" Class="mb-2">@Text["SiteInstallPanel_Method"]</MudText>
<MudGrid Class="mb-4">
@foreach (var method in AvailableMethods)
{
var selectedMethod = method.Id;
<MudItem xs="12" sm="6" @key="method.Id">
<MudButton FullWidth="true" Variant="@(_method == method.Id ? Variant.Filled : Variant.Outlined)"
Color="@(_method == method.Id ? Color.Primary : Color.Default)"
OnClick="@(() => _method = selectedMethod)">@Text[method.Label]</MudButton>
</MudItem>
}
</MudGrid>
@if (_method == "docker-compose" && CanGenerateDocker)
{
<MudText Typo="Typo.subtitle1" Class="mb-2">@Text["SiteInstallPanel_Configuration"]</MudText>
<MudAlert Severity="Severity.Info" Class="mb-3">@Text["SiteInstallPanel_DockerUpdateNote"]</MudAlert>
<MudText Typo="Typo.subtitle2" Class="mb-2">@Text["SiteInstallPanel_Install"]</MudText>
<MudPaper Class="pa-3" Style="border-radius:8px;background:#0d1117;overflow-x:auto;">
<pre class="mb-0" style="color:#c9d1d9;font-size:.85rem;"><code>@ComposeYaml</code></pre>
</MudPaper>
<MudButton Variant="Variant.Filled" Color="Color.Primary" Class="mt-3"
OnClick="@(() => CopyCode(ComposeYaml))" StartIcon="@Icons.Material.Filled.ContentCopy">
@Text["SiteInstallPanel_CopyCompose"]
</MudButton>
}
else if (_method == "docker-compose" && !CanGenerateDocker)
{
<MudAlert Severity="Severity.Warning">@Text["SiteInstallPanel_ImageUnavailable"]</MudAlert>
}
<MudText Typo="Typo.subtitle1" Class="mb-2 mt-4">@Text["SiteInstallPanel_Commands"]</MudText>
@foreach (var command in Commands)
{
<MudText Typo="Typo.subtitle2" Class="mb-2 mt-3">@Text[command.Label]</MudText>
<MudPaper Class="pa-3" Style="border-radius:8px;background:#0d1117;overflow-x:auto;">
<pre class="mb-0" style="color:#c9d1d9;font-size:.85rem;"><code>@command.Value</code></pre>
</MudPaper>
<MudButton Variant="Variant.Text" Color="Color.Primary" Class="mt-2"
OnClick="@(() => CopyCode(command.Value))" StartIcon="@Icons.Material.Filled.ContentCopy">
@Text["SiteInstallPanel_CopyCommand"]
</MudButton>
}
@if (_method == "windows-run")
{
<MudAlert Severity="Severity.Info" Class="mt-3">@Text["SiteInstallPanel_WindowsConsoleNote"]</MudAlert>
}
else if (_method == "windows-service")
{
<MudAlert Severity="Severity.Info" Class="mt-3">@Text["SiteInstallPanel_WindowsServiceAdminNote"]</MudAlert>
}
@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
2026-10-22 07:00:12 +02:00
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
2026-10-22 07:00:12 +02:00
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
2026-10-22 07:00:12 +02:00
agent-state-init:
image: {{_agentImageReference}}
2026-10-22 07:00:12 +02:00
user: "0:0"
entrypoint: ["chown", "-R", "1654:1654", "/state"]
volumes:
- agent_state_{{safeName}}:/state
2026-10-22 07:00:12 +02:00
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; " +
$"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);
}