Files
Heimdall/src/Heimdall.Web/Components/SiteInstallPanel.razor
T
arnaud.dartois d4b4ae8233
Heimdall Gitea / Detect CI scope (pull_request) Successful in 5s
Heimdall Gitea / Build and tests (pull_request) Successful in 21m57s
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (pull_request) Skipped
Heimdall Gitea / Build and scan server image (pull_request) Successful in 4m41s
Heimdall Gitea / Publish versioned installer release (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Successful in 2s
ci(release): publish versioned installer bundles
Refs #314
2026-11-09 15:38:50 +01:00

502 lines
24 KiB
Plaintext

@* Pangolin-style installer command generator for a single Heimdall site. *@
@using MudBlazor
@inject Heimdall.Web.Services.UiText Text
<style>
.installer-option { min-height: 3.25rem; justify-content: center; gap: .6rem; text-transform: none; }
.installer-option-selected { background: color-mix(in srgb, var(--mud-palette-primary) 10%, transparent); }
.installer-copy-box { position: relative; border: 1px solid var(--mud-palette-lines-default); border-radius: 6px; background: var(--mud-palette-surface); overflow: hidden; }
.installer-copy-box pre { margin: 0; padding: 1rem 3.5rem 1rem 1rem; overflow-x: auto; white-space: pre; font-size: .875rem; }
.installer-copy-button { position: absolute; top: .25rem; right: .25rem; background: var(--mud-palette-surface); }
</style>
<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>
@if (_releaseLoading)
{
<MudProgressLinear Indeterminate="true" Color="Color.Primary" Class="mb-3" />
}
else if (_releaseReady)
{
<MudAlert Severity="Severity.Info" Class="mb-3">
@string.Format(Text["SiteInstallPanel_ReleaseReady"], _releaseVersion)
</MudAlert>
}
else
{
<MudAlert Severity="Severity.Error" Class="mb-3">
@Text["SiteInstallPanel_ReleaseUnavailable"]
</MudAlert>
}
<MudText Typo="Typo.subtitle1" Class="mb-3">@Text["SiteInstallPanel_OperatingSystem"]</MudText>
<MudGrid Class="mb-4">
@foreach (var os in OperatingSystems)
{
<MudItem xs="12" sm="4" @key="os.Id">
<MudButton FullWidth="true" Variant="Variant.Outlined"
Color="@(_operatingSystem == os.Id ? Color.Primary : Color.Default)"
Class="@OptionClass(_operatingSystem == os.Id)"
OnClick="@(() => SelectOperatingSystem(os.Id))">
<MudIcon Icon="@os.Icon" Size="Size.Small" />
<span>@Text[os.Label]</span>
</MudButton>
</MudItem>
}
</MudGrid>
<MudText Typo="Typo.subtitle1" Class="mb-3">@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="Variant.Outlined"
Color="@(_method == method.Id ? Color.Primary : Color.Default)"
Class="@OptionClass(_method == method.Id)"
OnClick="@(() => _method = selectedMethod)">
@Text[method.Label]
</MudButton>
</MudItem>
}
</MudGrid>
@if ((_method == "docker-compose" || _method == "docker-run") && CanGenerateDocker &&
!string.IsNullOrWhiteSpace(_agentGpuImageReference))
{
<MudText Typo="Typo.subtitle1" Class="mb-2">@Text["SiteInstallPanel_Configuration"]</MudText>
<MudCheckBox @bind-Value="_useGpuImage" Color="Color.Primary" Class="mb-1">
@Text["SiteInstallPanel_NvidiaInference"]
</MudCheckBox>
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-3">@Text["SiteInstallPanel_NvidiaDescription"]</MudText>
@if (_useGpuImage)
{
<MudAlert Severity="Severity.Warning" Class="mb-3">@Text["SiteInstallPanel_NvidiaRequirement"]</MudAlert>
}
}
@if (_method == "docker-compose" && CanGenerateDocker)
{
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-3">@Text["SiteInstallPanel_DockerUpdateNote"]</MudText>
}
else if (_method == "docker-compose" && !CanGenerateDocker)
{
<MudAlert Severity="Severity.Warning">@Text["SiteInstallPanel_ImageUnavailable"]</MudAlert>
}
else if (_method == "docker-run" && CanGenerateDocker)
{
<MudAlert Severity="Severity.Info" Class="mb-3">@Text["SiteInstallPanel_DockerUpdateNote"]</MudAlert>
}
else if (_method == "docker-run")
{
<MudAlert Severity="Severity.Warning">@Text["SiteInstallPanel_ImageUnavailable"]</MudAlert>
}
@if (CanGenerateSelectedMethod)
{
<MudText Typo="Typo.subtitle1" Class="mb-3 mt-5">@Text["SiteInstallPanel_Commands"]</MudText>
@if (_method == "docker-compose")
{
<MudText Typo="Typo.subtitle2" Class="mb-2 mt-3">@Text["SiteInstallPanel_Configuration"]</MudText>
<MudPaper Class="installer-copy-box mb-3">
<pre><code>@ComposeYaml</code></pre>
<MudTooltip Text="@Text["SiteInstallPanel_CopyCommand"]">
<MudIconButton Icon="@CopyIconFor(ComposeYaml)" Color="Color.Default" Size="Size.Small"
Class="installer-copy-button" AriaLabel="@Text["SiteInstallPanel_CopyCommand"]"
OnClick="@(() => CopyCode(ComposeYaml))" />
</MudTooltip>
</MudPaper>
}
@foreach (var command in Commands)
{
<MudText Typo="Typo.subtitle2" Class="mb-2 mt-3">@Text[command.Label]</MudText>
<MudPaper Class="installer-copy-box">
<pre><code>@command.Value</code></pre>
<MudTooltip Text="@Text["SiteInstallPanel_CopyCommand"]">
<MudIconButton Icon="@CopyIconFor(command.Value)" Color="Color.Default" Size="Size.Small"
Class="installer-copy-button" AriaLabel="@Text["SiteInstallPanel_CopyCommand"]"
OnClick="@(() => CopyCode(command.Value))" />
</MudTooltip>
</MudPaper>
}
}
@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", 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<string> { "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);
}