[CmdletBinding()] param( [Parameter(Mandatory = $true)][ValidateRange(1, 2147483647)][int] $AgentPid, [Parameter(Mandatory = $true)][string] $InstallRoot, [Parameter(Mandatory = $true)][string] $ArchivePath, [Parameter(Mandatory = $true)][string] $Version, [Parameter(Mandatory = $true)][ValidatePattern('^[A-Fa-f0-9]{64}$')][string] $ExpectedSha256, [Parameter(Mandatory = $true)][string] $DotnetPath, [string] $ServiceName, [string] $HealthUrl = 'http://127.0.0.1:8081/api/version' ) $ErrorActionPreference = 'Stop' $ProgressPreference = 'SilentlyContinue' $StartupTimeout = [TimeSpan]::FromSeconds(180) $StablePeriod = [TimeSpan]::FromSeconds(60) function Get-Sha256([string] $Path) { return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant() } function Assert-SafeArchive([string] $Path) { if ((Get-Item -LiteralPath $Path).Length -gt 2GB) { throw 'Update archive exceeds 2 GiB.' } $entries = & tar.exe -tzf $Path if ($LASTEXITCODE -ne 0 -or $entries.Count -gt 20000) { throw 'Update archive cannot be inspected or has too many entries.' } foreach ($entry in $entries) { $name = ([string]$entry).Replace('\', '/') if ([string]::IsNullOrWhiteSpace($name) -or $name.StartsWith('/') -or $name -match '^[A-Za-z]:' -or ($name -split '/') -contains '..') { throw 'Update archive contains an unsafe path.' } } } function Start-Agent([string] $Directory, [string] $RuntimePath) { $assembly = Join-Path $Directory 'Heimdall.Agent.dll' if (-not (Test-Path -LiteralPath $assembly -PathType Leaf)) { throw 'Release directory has no Agent assembly.' } $quotedAssembly = '"' + $assembly.Replace('"', '\"') + '"' return Start-Process -FilePath $RuntimePath -ArgumentList $quotedAssembly -WorkingDirectory $Directory -WindowStyle Hidden -PassThru } function Stop-AgentProcess($Process) { if ($null -ne $Process -and -not $Process.HasExited) { Stop-Process -Id $Process.Id -Force -ErrorAction SilentlyContinue try { $Process.WaitForExit(10000) } catch { } } } function Wait-ForHealthyVersion($Process, [string] $ExpectedVersion) { $deadline = [DateTime]::UtcNow + $StartupTimeout $healthySince = $null while ([DateTime]::UtcNow -lt $deadline) { if ($Process.HasExited) { return $false } try { $health = Invoke-RestMethod -Method Get -Uri $HealthUrl -TimeoutSec 3 $actual = ([string]$health.version).Split('+')[0].TrimStart('v', 'V') $wanted = $ExpectedVersion.Split('+')[0].TrimStart('v', 'V') if ($actual -eq $wanted) { if ($null -eq $healthySince) { $healthySince = [DateTime]::UtcNow } if ([DateTime]::UtcNow - $healthySince -ge $StablePeriod) { return $true } } else { $healthySince = $null } } catch { $healthySince = $null } Start-Sleep -Seconds 2 } return $false } function Wait-ForHealthyService([string] $Name, [string] $ExpectedVersion) { $deadline = [DateTime]::UtcNow + $StartupTimeout $healthySince = $null while ([DateTime]::UtcNow -lt $deadline) { $service = Get-Service -Name $Name -ErrorAction SilentlyContinue if ($null -eq $service -or $service.Status.ToString() -ne 'Running') { $healthySince = $null Start-Sleep -Seconds 2 continue } try { $health = Invoke-RestMethod -Method Get -Uri $HealthUrl -TimeoutSec 3 $actual = ([string]$health.version).Split('+')[0].TrimStart('v', 'V') $wanted = if ($ExpectedVersion) { $ExpectedVersion.Split('+')[0].TrimStart('v', 'V') } else { $null } if (-not $wanted -or $actual -eq $wanted) { if ($null -eq $healthySince) { $healthySince = [DateTime]::UtcNow } if ([DateTime]::UtcNow - $healthySince -ge $StablePeriod) { return $true } } else { $healthySince = $null } } catch { $healthySince = $null } Start-Sleep -Seconds 2 } return $false } $root = [IO.Path]::GetFullPath($InstallRoot).TrimEnd('\') $releases = Join-Path $root 'releases' $current = Join-Path $root 'current' $sourceArchive = [IO.Path]::GetFullPath($ArchivePath) $versionLeaf = $Version.TrimStart('v', 'V') if ($versionLeaf -notmatch '^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$') { throw 'Invalid update version.' } if (-not (Test-Path -LiteralPath $current -PathType Container)) { throw 'Managed current Agent directory is missing.' } if ((Get-Item -LiteralPath $current -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'The current Agent directory cannot be a reparse point.' } if ([IO.Path]::IsPathRooted($DotnetPath) -and -not (Test-Path -LiteralPath $DotnetPath -PathType Leaf)) { throw 'The configured .NET host was not found.' } New-Item -ItemType Directory -Path $releases -Force | Out-Null if (-not (Test-Path -LiteralPath $sourceArchive -PathType Leaf)) { throw 'Update archive is missing.' } $archive = Join-Path $releases ('.update-' + [Guid]::NewGuid().ToString('N') + '.tar.gz') Copy-Item -LiteralPath $sourceArchive -Destination $archive if ((Get-Sha256 $archive) -ine $ExpectedSha256) { Remove-Item -LiteralPath $archive -Force throw 'Update archive SHA-256 verification failed.' } try { Assert-SafeArchive $archive } catch { Remove-Item -LiteralPath $archive -Force -ErrorAction SilentlyContinue throw } # Wait until the old Agent has completely left its working directory before replacing files. try { $old = Get-Process -Id $AgentPid -ErrorAction Stop $old.WaitForExit(180000) | Out-Null if (-not $old.HasExited) { throw 'Previous Agent process did not stop within 180 seconds.' } } catch [Microsoft.PowerShell.Commands.ProcessCommandException] { # The process may have exited between the helper launch and this lookup. } catch { Remove-Item -LiteralPath $archive -Force -ErrorAction SilentlyContinue throw } if ($ServiceName) { $serviceDeadline = [DateTime]::UtcNow.AddSeconds(30) do { $service = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue if ($null -eq $service -or $service.Status.ToString() -eq 'Stopped') { break } Start-Sleep -Seconds 1 } while ([DateTime]::UtcNow -lt $serviceDeadline) if ($service -and $service.Status.ToString() -ne 'Stopped') { Remove-Item -LiteralPath $archive -Force -ErrorAction SilentlyContinue throw "Windows Service '$ServiceName' did not stop after its Agent process exited." } } $stage = Join-Path $releases ('.staging-' + [Guid]::NewGuid().ToString('N')) $previous = Join-Path $releases ('.previous-' + [Guid]::NewGuid().ToString('N')) $failed = Join-Path $releases ('.failed-' + [Guid]::NewGuid().ToString('N')) $versionRoot = Join-Path $releases $versionLeaf New-Item -ItemType Directory -Path $stage | Out-Null $newProcess = $null $swapped = $false try { & tar.exe -xzf $archive -C $stage if ($LASTEXITCODE -ne 0 -or -not (Test-Path -LiteralPath (Join-Path $stage 'Heimdall.Agent.dll') -PathType Leaf)) { throw 'Update archive extraction failed.' } if (Test-Path -LiteralPath $versionRoot) { throw "Release $versionLeaf is already present." } Move-Item -LiteralPath $stage -Destination $versionRoot # Directory moves stay on the same volume. Keep the old tree until the new process passes its startup probe. Move-Item -LiteralPath $current -Destination $previous try { Copy-Item -LiteralPath $versionRoot -Destination $current -Recurse $swapped = $true } catch { if (Test-Path -LiteralPath $current -PathType Container) { Remove-Item -LiteralPath $current -Recurse -Force -ErrorAction SilentlyContinue } Move-Item -LiteralPath $previous -Destination $current throw } if ($ServiceName) { Start-Service -Name $ServiceName if (-not (Wait-ForHealthyService $ServiceName $Version)) { throw 'Updated Windows Service failed its startup and 60-second stability checks.' } } else { $newProcess = Start-Agent $current $DotnetPath if (-not (Wait-ForHealthyVersion $newProcess $Version)) { throw 'Updated Agent failed its startup and 60-second stability checks.' } } Remove-Item -LiteralPath $previous -Recurse -Force Write-Output "Agent update to $Version passed startup verification." if (-not $ServiceName) { # Keep this supervisor alive with the launched console Agent. $newProcess.WaitForExit() } } catch { $failure = $_ if ($ServiceName) { Stop-Service -Name $ServiceName -Force -ErrorAction SilentlyContinue } else { Stop-AgentProcess $newProcess } if ($swapped -and (Test-Path -LiteralPath $current -PathType Container)) { Move-Item -LiteralPath $current -Destination $failed } if (Test-Path -LiteralPath $previous -PathType Container) { Move-Item -LiteralPath $previous -Destination $current try { if ($ServiceName) { Start-Service -Name $ServiceName if (-not (Wait-ForHealthyService $ServiceName $null)) { throw 'Restored service did not pass its health check.' } } else { $rollbackProcess = Start-Agent $current $DotnetPath $rollbackProcess.WaitForExit() } Write-Warning 'The previous Agent release was restored and restarted.' } catch { Write-Error "Rollback restart failed: $($_.Exception.Message)" } } if (Test-Path -LiteralPath $versionRoot -PathType Container) { Remove-Item -LiteralPath $versionRoot -Recurse -Force -ErrorAction SilentlyContinue } throw $failure } finally { if (Test-Path -LiteralPath $stage -PathType Container) { Remove-Item -LiteralPath $stage -Recurse -Force -ErrorAction SilentlyContinue } if (Test-Path -LiteralPath $failed -PathType Container) { Remove-Item -LiteralPath $failed -Recurse -Force -ErrorAction SilentlyContinue } if (Test-Path -LiteralPath $archive -PathType Leaf) { Remove-Item -LiteralPath $archive -Force -ErrorAction SilentlyContinue } }