Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
896 lines
46 KiB
PowerShell
896 lines
46 KiB
PowerShell
# guard.ps1 - process containment, dead-man and STOP file for the RTX 3080 laptop GPU child (STRA-320, S3.8b of STRA-245).
|
|
#
|
|
# A laptop GPU child must never outlive its watchdog. This is the containment layer split from watchdog.ps1 (STRA-291). It is
|
|
# Windows PowerShell 5.1, stdlib only, and it never changes a power, display, lock, sleep, execution-policy or registry setting.
|
|
# It kills ONLY the process tree it created (the job it made, or the wrapper it started and that wrapper's descendants), never by
|
|
# image name.
|
|
#
|
|
# USAGE (owner / runner)
|
|
# powershell -NoProfile -ExecutionPolicy Bypass -File scripts\laptop\win\guard.ps1 `
|
|
# -ChildCommand <exe> -ChildArguments "<one argument string>" [-RunId <id>] [-Leaf <name>] [-TimeoutSeconds <s>]
|
|
# Other parameters: -ArtifactsRoot <dir> (default artifacts\ of the MAIN checkout, never inside .git\wt), -RunRoot <dir>
|
|
# (default <artifacts>\runs\<RunId>), -StopFile <path> (default <artifacts>\runs\STOP), -StateScript <path> (default state.ps1
|
|
# beside this file), -HeartbeatFile <path> (default <RunRoot>\heartbeat), -DeadmanSeconds <s> (default 30), -NoJobObject (force
|
|
# the dead-man fallback), -TimeScale <x> (clock speed-up for the dry tests: every second below is a CLOCK second), -Library
|
|
# (dot-source: define the functions, run nothing; used by the tests and by watchdog.ps1 when it adopts the containment).
|
|
# Laptop precondition at real use (owner actions, never agent actions): OEM Turbo scheme, enforced power limit above 100 W,
|
|
# charger connected, screen unlocked, recorded confirmation of the BSOD 0x19C history.
|
|
#
|
|
# CONTAINMENT, PRIMARY: WINDOWS JOB OBJECT
|
|
# The child is created SUSPENDED (kernel32 CreateProcessW), assigned to a job created with JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
|
# (CreateJobObjectW, SetInformationJobObject with JobObjectExtendedLimitInformation = 9, AssignProcessToJobObject) and only then
|
|
# resumed, so no grandchild can start before the assignment. The job handle is non-inheritable and lives only in the process that
|
|
# created the job (guard.ps1, or the watchdog that dot-sources this file): when that process dies for any reason the kernel
|
|
# closes the handle and terminates every process in the job, immediately. TerminateJobObject is the explicit kill; it reaches
|
|
# exactly the processes of the job (a Windows 10+ nested job is fine). All of it is Add-Type P/Invoke of kernel32 (C# 5, the
|
|
# compiler of Windows PowerShell 5.1); see LelekaGuardNative below.
|
|
# CONTAINMENT, FALLBACK: DEAD-MAN
|
|
# Used when the Job Object cannot be created (Add-Type fails, CreateJobObject / SetInformationJobObject / Assign fails) or with
|
|
# -NoJobObject. The child is started by a WRAPPER (this file with -Wrapper, started as a normal process). The wrapper polls the
|
|
# heartbeat file written by the owner of the watchdog (Send-GuardHeartbeat, every second) and, when the file is older than
|
|
# -DeadmanSeconds (30 s), kills the child's process tree (Stop-Process -Id of the PIDs of its own child tree) and exits 90. The
|
|
# kill delay is up to 30 s plus one poll. MEASURED (test_guard.ps1, Windows PowerShell 5.1.26100.9711, the watchdog host killed
|
|
# while its child tree cmd.exe + ping.exe ran): Job Object route 0.2 s; dead-man fallback 30.6 s. The Job Object route IS feasible
|
|
# in PS 5.1 (Add-Type compiles the C# 5 wrapper in about 1 s), so the fallback is only used when it fails or with -NoJobObject.
|
|
#
|
|
# WHAT IT DOES (CLI)
|
|
# 1. Refuses to start (exit 5) while a STOP file exists. The file is never created again, changed or deleted by this script when
|
|
# it exists; only the orchestrator's recorded owner inspection removes it (SC3). The STOP file is one file at the root of the
|
|
# runs directory (<artifacts>\runs\STOP by default), so it gates every later run, not only one run's directory.
|
|
# 2. Machine lock (SC13, one GPU job at a time): artifacts\locks\LAPTOP_GPU.lock with the contents of the protocol (leaf, run_id,
|
|
# pid, utc, boot_time, created_by). ONE OWNER: the runner (STRA-316) creates it for a run. guard.ps1 creates it only when it is
|
|
# started standalone and no lock exists (CreateNew + FileShare.None). With -RunId equal to the run id of an existing lock it
|
|
# verifies that lock and creates no second one; with another run id, or with a held lock and no -RunId, it refuses (exit 3).
|
|
# A lock is never stolen. In every path the lock's boot time and creation time feed the crash check, and the lock is released
|
|
# after the cool-down (also the verified runner lock, as the leaf demands).
|
|
# 3. Crash check (state.ps1, read-only), before the child starts and after it ends: STOP file written and exit 9 when the boot
|
|
# time of the machine differs from the lock's, when state.ps1 lists a Kernel-Power 41 / BugCheck event since the lock was
|
|
# created, or when the evidence cannot be read (fail closed).
|
|
# 4. Starts the child contained (job, else dead-man) and supervises: STALL (a file STALL in the run root written by the watchdog,
|
|
# or child exit code 7) -> kill, STOP file, exit 7; child exit code 5 or 6 (the watchdog's own abort / timeout) -> abort,
|
|
# exit 6; -TimeoutSeconds reached -> kill, abort, exit 6; dead-man fired -> abort, exit 6; child exit 0 / non-zero -> exit
|
|
# 0 / 1.
|
|
# 5. After every abort: state.ps1 -PostAbort once (no leftover leleka-/strata- process, empty compute-app list). Not clean ->
|
|
# STOP file and the lock is KEPT. Clean -> the cool-down stamp (artifacts\locks\last_gpu_run.json, the format watchdog.ps1
|
|
# reads) is written, the 600 s cool-down is enforced on the clock, and then the lock is released.
|
|
# Output: <RunRoot>\guard_summary.json, child.stdout.txt, child.stderr.txt, heartbeat.
|
|
#
|
|
# EXIT CODES: 0 child ok; 1 child failed; 2 usage; 3 lock refused (held / run id mismatch / unreadable); 5 STOP file present at
|
|
# start; 6 aborted (timeout, watchdog abort, dead-man, child not startable); 7 STALL (STOP file written); 8 internal error;
|
|
# 9 crash evidence (STOP file written); 10 post-abort verification not clean (STOP file written, lock kept).
|
|
[CmdletBinding()]
|
|
param(
|
|
[string]$ChildCommand,
|
|
[string]$ChildArguments = '',
|
|
[string]$RunId,
|
|
[string]$Leaf = 'standalone',
|
|
[double]$TimeoutSeconds = 0,
|
|
[string]$ArtifactsRoot,
|
|
[string]$RunRoot,
|
|
[string]$StopFile,
|
|
[string]$StateScript,
|
|
[string]$HeartbeatFile,
|
|
[double]$DeadmanSeconds = 30,
|
|
[double]$TimeScale = 1.0,
|
|
[switch]$NoJobObject,
|
|
[switch]$Wrapper,
|
|
[switch]$Library
|
|
)
|
|
|
|
$script:GuardDir = $PSScriptRoot
|
|
$script:LockName = 'LAPTOP_GPU.lock'
|
|
$script:StampName = 'last_gpu_run.json'
|
|
$script:CooldownAbortS = 600.0
|
|
$script:StateCalls = 0
|
|
$script:PostAbortCalls = 0
|
|
$script:NativeReady = $null
|
|
$script:NativeWhy = ''
|
|
|
|
# ------------------------------------------------------------------------------------------------ clock (injectable)
|
|
function New-GuardClock {
|
|
param([double]$Scale = 1.0, [switch]$Virtual)
|
|
$c = [hashtable]::Synchronized(@{})
|
|
$c.Virtual = [bool]$Virtual
|
|
$c.Scale = $Scale
|
|
$c.T = 0.0
|
|
$c.Sw = [Diagnostics.Stopwatch]::StartNew()
|
|
return $c
|
|
}
|
|
|
|
function Get-GuardNow {
|
|
param($Clock)
|
|
if ($Clock.Virtual) { return [double]$Clock.T }
|
|
return $Clock.Sw.Elapsed.TotalSeconds * $Clock.Scale
|
|
}
|
|
|
|
function Invoke-GuardSleep {
|
|
param($Clock, [double]$Seconds)
|
|
if ($Seconds -le 0) { return }
|
|
if ($Clock.Virtual) { $Clock.T = $Clock.T + $Seconds; return }
|
|
Start-Sleep -Milliseconds ([int][math]::Max(1, [math]::Ceiling($Seconds / $Clock.Scale * 1000)))
|
|
}
|
|
|
|
# ------------------------------------------------------------------------------------------------ process tree (own PIDs only)
|
|
function Get-GuardPidTree {
|
|
param([int]$RootPid)
|
|
$all = @(Get-CimInstance -ClassName Win32_Process -Property ProcessId, ParentProcessId, CreationDate -ErrorAction Stop)
|
|
$byPid = @{}
|
|
$byParent = @{}
|
|
foreach ($p in $all) {
|
|
$byPid[[int]$p.ProcessId] = $p
|
|
$k = [int]$p.ParentProcessId
|
|
if (-not $byParent.ContainsKey($k)) { $byParent[$k] = New-Object System.Collections.ArrayList }
|
|
[void]$byParent[$k].Add($p)
|
|
}
|
|
if (-not $byPid.ContainsKey($RootPid)) { return @() }
|
|
$out = New-Object System.Collections.ArrayList
|
|
$seen = @{}
|
|
$queue = New-Object System.Collections.Queue
|
|
$queue.Enqueue($byPid[$RootPid])
|
|
while ($queue.Count -gt 0) {
|
|
$n = $queue.Dequeue()
|
|
$id = [int]$n.ProcessId
|
|
if ($seen.ContainsKey($id)) { continue }
|
|
$seen[$id] = $true
|
|
[void]$out.Add($id)
|
|
if ($byParent.ContainsKey($id)) {
|
|
foreach ($c in $byParent[$id]) {
|
|
# a child was created after its parent: guards against a reused parent PID
|
|
if ($null -ne $c.CreationDate -and $null -ne $n.CreationDate -and $c.CreationDate -ge $n.CreationDate) { $queue.Enqueue($c) }
|
|
}
|
|
}
|
|
}
|
|
return @($out)
|
|
}
|
|
|
|
# Kills the tree rooted at a PID this script started. Never by image name. Returns the PIDs it stopped.
|
|
function Stop-GuardPidTree {
|
|
param([int]$RootPid)
|
|
$killed = New-Object System.Collections.ArrayList
|
|
for ($pass = 0; $pass -lt 3; $pass++) {
|
|
$tree = @()
|
|
try { $tree = @(Get-GuardPidTree -RootPid $RootPid) } catch { $tree = @() }
|
|
if ($tree.Count -eq 0) { break }
|
|
[array]::Reverse($tree)
|
|
foreach ($id in $tree) {
|
|
try { Stop-Process -Id $id -Force -ErrorAction Stop; [void]$killed.Add($id) } catch { }
|
|
}
|
|
Start-Sleep -Milliseconds 100
|
|
}
|
|
return @($killed)
|
|
}
|
|
|
|
# ------------------------------------------------------------------------------------------------ Job Object (P/Invoke of kernel32)
|
|
$script:NativeSource = @'
|
|
using System;
|
|
using System.ComponentModel;
|
|
using System.Runtime.InteropServices;
|
|
using System.Text;
|
|
|
|
public static class LelekaGuardNative
|
|
{
|
|
const uint JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000;
|
|
const int JobObjectExtendedLimitInformation = 9;
|
|
const uint CREATE_SUSPENDED = 0x4;
|
|
const uint CREATE_NO_WINDOW = 0x08000000;
|
|
const uint STARTF_USESTDHANDLES = 0x100;
|
|
const uint GENERIC_READ = 0x80000000;
|
|
const uint GENERIC_WRITE = 0x40000000;
|
|
const uint FILE_SHARE_RW = 3;
|
|
const uint CREATE_ALWAYS = 2;
|
|
const uint OPEN_EXISTING = 3;
|
|
const uint FILE_ATTRIBUTE_NORMAL = 0x80;
|
|
|
|
[StructLayout(LayoutKind.Sequential)]
|
|
struct JOBOBJECT_BASIC_LIMIT_INFORMATION
|
|
{
|
|
public long PerProcessUserTimeLimit;
|
|
public long PerJobUserTimeLimit;
|
|
public uint LimitFlags;
|
|
public UIntPtr MinimumWorkingSetSize;
|
|
public UIntPtr MaximumWorkingSetSize;
|
|
public uint ActiveProcessLimit;
|
|
public UIntPtr Affinity;
|
|
public uint PriorityClass;
|
|
public uint SchedulingClass;
|
|
}
|
|
|
|
[StructLayout(LayoutKind.Sequential)]
|
|
struct IO_COUNTERS
|
|
{
|
|
public ulong ReadOperationCount;
|
|
public ulong WriteOperationCount;
|
|
public ulong OtherOperationCount;
|
|
public ulong ReadTransferCount;
|
|
public ulong WriteTransferCount;
|
|
public ulong OtherTransferCount;
|
|
}
|
|
|
|
[StructLayout(LayoutKind.Sequential)]
|
|
struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION
|
|
{
|
|
public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;
|
|
public IO_COUNTERS IoInfo;
|
|
public UIntPtr ProcessMemoryLimit;
|
|
public UIntPtr JobMemoryLimit;
|
|
public UIntPtr PeakProcessMemoryUsed;
|
|
public UIntPtr PeakJobMemoryUsed;
|
|
}
|
|
|
|
[StructLayout(LayoutKind.Sequential)]
|
|
struct SECURITY_ATTRIBUTES
|
|
{
|
|
public int nLength;
|
|
public IntPtr lpSecurityDescriptor;
|
|
[MarshalAs(UnmanagedType.Bool)] public bool bInheritHandle;
|
|
}
|
|
|
|
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
|
struct STARTUPINFO
|
|
{
|
|
public int cb;
|
|
public string lpReserved;
|
|
public string lpDesktop;
|
|
public string lpTitle;
|
|
public int dwX;
|
|
public int dwY;
|
|
public int dwXSize;
|
|
public int dwYSize;
|
|
public int dwXCountChars;
|
|
public int dwYCountChars;
|
|
public int dwFillAttribute;
|
|
public uint dwFlags;
|
|
public short wShowWindow;
|
|
public short cbReserved2;
|
|
public IntPtr lpReserved2;
|
|
public IntPtr hStdInput;
|
|
public IntPtr hStdOutput;
|
|
public IntPtr hStdError;
|
|
}
|
|
|
|
[StructLayout(LayoutKind.Sequential)]
|
|
struct PROCESS_INFORMATION
|
|
{
|
|
public IntPtr hProcess;
|
|
public IntPtr hThread;
|
|
public int dwProcessId;
|
|
public int dwThreadId;
|
|
}
|
|
|
|
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
|
static extern IntPtr CreateJobObjectW(IntPtr lpJobAttributes, string lpName);
|
|
|
|
[DllImport("kernel32.dll", SetLastError = true)]
|
|
static extern bool SetInformationJobObject(IntPtr hJob, int infoClass, IntPtr lpInfo, uint cbInfo);
|
|
|
|
[DllImport("kernel32.dll", SetLastError = true)]
|
|
static extern bool AssignProcessToJobObject(IntPtr hJob, IntPtr hProcess);
|
|
|
|
[DllImport("kernel32.dll", SetLastError = true)]
|
|
static extern bool TerminateJobObject(IntPtr hJob, uint exitCode);
|
|
|
|
[DllImport("kernel32.dll", SetLastError = true)]
|
|
static extern bool TerminateProcess(IntPtr hProcess, uint exitCode);
|
|
|
|
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
|
static extern bool CreateProcessW(string lpApplicationName, StringBuilder lpCommandLine, IntPtr lpProcessAttributes,
|
|
IntPtr lpThreadAttributes, bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory,
|
|
ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
|
|
|
|
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
|
static extern IntPtr CreateFileW(string lpFileName, uint dwDesiredAccess, uint dwShareMode, ref SECURITY_ATTRIBUTES lpSecurityAttributes,
|
|
uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile);
|
|
|
|
[DllImport("kernel32.dll", SetLastError = true)]
|
|
static extern uint ResumeThread(IntPtr hThread);
|
|
|
|
[DllImport("kernel32.dll", SetLastError = true)]
|
|
static extern uint WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds);
|
|
|
|
[DllImport("kernel32.dll", SetLastError = true)]
|
|
static extern bool GetExitCodeProcess(IntPtr hProcess, out uint lpExitCode);
|
|
|
|
[DllImport("kernel32.dll", SetLastError = true)]
|
|
static extern bool CloseHandle(IntPtr hObject);
|
|
|
|
// A job whose handle, when the last copy closes (the creating process died), terminates every process in the job.
|
|
// The handle is created WITHOUT inheritance so no child can hold a copy and keep the job alive.
|
|
public static IntPtr CreateKillOnCloseJob()
|
|
{
|
|
IntPtr job = CreateJobObjectW(IntPtr.Zero, null);
|
|
if (job == IntPtr.Zero) { throw new Win32Exception(Marshal.GetLastWin32Error(), "CreateJobObjectW"); }
|
|
JOBOBJECT_EXTENDED_LIMIT_INFORMATION info = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION();
|
|
info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
|
|
int size = Marshal.SizeOf(typeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
|
|
IntPtr p = Marshal.AllocHGlobal(size);
|
|
try
|
|
{
|
|
Marshal.StructureToPtr(info, p, false);
|
|
if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, p, (uint)size))
|
|
{
|
|
int err = Marshal.GetLastWin32Error();
|
|
CloseHandle(job);
|
|
throw new Win32Exception(err, "SetInformationJobObject");
|
|
}
|
|
}
|
|
finally { Marshal.FreeHGlobal(p); }
|
|
return job;
|
|
}
|
|
|
|
static IntPtr OpenStd(string path, bool write)
|
|
{
|
|
SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
|
|
sa.nLength = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES));
|
|
sa.bInheritHandle = true;
|
|
string name = string.IsNullOrEmpty(path) ? "NUL" : path;
|
|
uint access = write ? GENERIC_WRITE : GENERIC_READ;
|
|
uint disp = (write && !string.IsNullOrEmpty(path)) ? CREATE_ALWAYS : OPEN_EXISTING;
|
|
IntPtr h = CreateFileW(name, access, FILE_SHARE_RW, ref sa, disp, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero);
|
|
if (h == new IntPtr(-1)) { throw new Win32Exception(Marshal.GetLastWin32Error(), "CreateFileW " + name); }
|
|
return h;
|
|
}
|
|
|
|
// Creates the process SUSPENDED, puts it in the job, then resumes it: no descendant can exist outside the job.
|
|
public static int StartInJob(IntPtr job, string commandLine, string stdoutPath, string stderrPath, out IntPtr hProcess)
|
|
{
|
|
hProcess = IntPtr.Zero;
|
|
IntPtr hIn = IntPtr.Zero, hOut = IntPtr.Zero, hErr = IntPtr.Zero;
|
|
PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
|
|
try
|
|
{
|
|
hIn = OpenStd(null, false);
|
|
hOut = OpenStd(stdoutPath, true);
|
|
hErr = OpenStd(stderrPath, true);
|
|
STARTUPINFO si = new STARTUPINFO();
|
|
si.cb = Marshal.SizeOf(typeof(STARTUPINFO));
|
|
si.dwFlags = STARTF_USESTDHANDLES;
|
|
si.hStdInput = hIn;
|
|
si.hStdOutput = hOut;
|
|
si.hStdError = hErr;
|
|
StringBuilder cl = new StringBuilder(commandLine);
|
|
if (!CreateProcessW(null, cl, IntPtr.Zero, IntPtr.Zero, true, CREATE_SUSPENDED | CREATE_NO_WINDOW, IntPtr.Zero, null, ref si, out pi))
|
|
{
|
|
throw new Win32Exception(Marshal.GetLastWin32Error(), "CreateProcessW");
|
|
}
|
|
if (!AssignProcessToJobObject(job, pi.hProcess))
|
|
{
|
|
int err = Marshal.GetLastWin32Error();
|
|
TerminateProcess(pi.hProcess, 1);
|
|
CloseHandle(pi.hThread);
|
|
CloseHandle(pi.hProcess);
|
|
throw new Win32Exception(err, "AssignProcessToJobObject");
|
|
}
|
|
ResumeThread(pi.hThread);
|
|
CloseHandle(pi.hThread);
|
|
hProcess = pi.hProcess;
|
|
return pi.dwProcessId;
|
|
}
|
|
finally
|
|
{
|
|
if (hIn != IntPtr.Zero) { CloseHandle(hIn); }
|
|
if (hOut != IntPtr.Zero) { CloseHandle(hOut); }
|
|
if (hErr != IntPtr.Zero) { CloseHandle(hErr); }
|
|
}
|
|
}
|
|
|
|
public static bool IsRunning(IntPtr hProcess) { return WaitForSingleObject(hProcess, 0) == 258; }
|
|
|
|
public static int ExitCode(IntPtr hProcess)
|
|
{
|
|
uint code;
|
|
if (!GetExitCodeProcess(hProcess, out code)) { throw new Win32Exception(Marshal.GetLastWin32Error(), "GetExitCodeProcess"); }
|
|
return unchecked((int)code);
|
|
}
|
|
|
|
public static void KillJob(IntPtr job) { TerminateJobObject(job, 1); }
|
|
public static void Close(IntPtr h) { if (h != IntPtr.Zero) { CloseHandle(h); } }
|
|
}
|
|
'@
|
|
|
|
# $true when the kernel32 wrapper compiled; the reason is kept in $script:NativeWhy.
|
|
function Initialize-GuardNative {
|
|
if ($null -ne $script:NativeReady) { return $script:NativeReady }
|
|
try {
|
|
if (-not ('LelekaGuardNative' -as [type])) { Add-Type -TypeDefinition $script:NativeSource -Language CSharp -ErrorAction Stop }
|
|
$script:NativeReady = $true
|
|
} catch {
|
|
$script:NativeReady = $false
|
|
$script:NativeWhy = 'Add-Type failed: ' + $_.Exception.Message
|
|
}
|
|
return $script:NativeReady
|
|
}
|
|
|
|
function Send-GuardHeartbeat {
|
|
param([string]$Path)
|
|
$dir = Split-Path -Parent $Path
|
|
if ($dir -and -not (Test-Path -LiteralPath $dir)) { [void](New-Item -ItemType Directory -Path $dir -Force) }
|
|
[IO.File]::WriteAllText($Path, [DateTime]::UtcNow.ToString('o'), (New-Object Text.UTF8Encoding $false))
|
|
}
|
|
|
|
function ConvertTo-QuotedArg {
|
|
param([string]$S)
|
|
if ($S -match '[\s"]') { return '"' + ($S -replace '"', '\"') + '"' }
|
|
return $S
|
|
}
|
|
|
|
# Starts a child that dies with the owner of this call. Returns a hashtable:
|
|
# Mode = job | deadman, Pid (child, or the wrapper in dead-man mode), Job, Process (handle or Process object), Why (why not a job).
|
|
# In dead-man mode the CALLER keeps the heartbeat file fresh (Send-GuardHeartbeat at least every few seconds).
|
|
function Start-Contained {
|
|
param([string]$FilePath, [string]$Arguments = '', [string]$StdoutPath, [string]$StderrPath, [string]$HeartbeatFile,
|
|
[double]$DeadmanSeconds = 30, [switch]$ForceFallback)
|
|
$exe = $FilePath
|
|
$cmd = Get-Command -Name $FilePath -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
|
|
if ($null -ne $cmd) { $exe = $cmd.Source }
|
|
$why = ''
|
|
if ($ForceFallback) { $why = 'forced (-NoJobObject)' }
|
|
elseif (-not (Initialize-GuardNative)) { $why = $script:NativeWhy }
|
|
else {
|
|
$job = [IntPtr]::Zero
|
|
try {
|
|
$job = [LelekaGuardNative]::CreateKillOnCloseJob()
|
|
$cl = (ConvertTo-QuotedArg $exe)
|
|
if (-not [string]::IsNullOrWhiteSpace($Arguments)) { $cl = $cl + ' ' + $Arguments }
|
|
$h = [IntPtr]::Zero
|
|
$childPid = [LelekaGuardNative]::StartInJob($job, $cl, $StdoutPath, $StderrPath, [ref]$h)
|
|
return @{ Mode = 'job'; Pid = $childPid; Job = $job; Process = $h; Why = ''; Wrapper = $null }
|
|
} catch {
|
|
if ($job -ne [IntPtr]::Zero) { [LelekaGuardNative]::Close($job) }
|
|
$why = 'Job Object route failed: ' + $_.Exception.Message
|
|
}
|
|
}
|
|
# dead-man fallback
|
|
if ([string]::IsNullOrWhiteSpace($HeartbeatFile)) { throw 'dead-man fallback needs -HeartbeatFile' }
|
|
Send-GuardHeartbeat $HeartbeatFile
|
|
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
|
$psi.FileName = (Get-Command powershell.exe -CommandType Application).Source
|
|
$psi.Arguments = '-NoProfile -ExecutionPolicy Bypass -File ' + (ConvertTo-QuotedArg $script:GuardDir) + '\guard.ps1 -Wrapper -HeartbeatFile ' + (ConvertTo-QuotedArg $HeartbeatFile) +
|
|
' -DeadmanSeconds ' + $DeadmanSeconds.ToString([Globalization.CultureInfo]::InvariantCulture)
|
|
$psi.UseShellExecute = $false
|
|
$psi.CreateNoWindow = $true
|
|
$psi.EnvironmentVariables['LELEKA_GUARD_CHILD'] = $exe
|
|
$psi.EnvironmentVariables['LELEKA_GUARD_ARGS'] = $Arguments
|
|
$psi.EnvironmentVariables['LELEKA_GUARD_OUT'] = [string]$StdoutPath
|
|
$psi.EnvironmentVariables['LELEKA_GUARD_ERR'] = [string]$StderrPath
|
|
$wp = [System.Diagnostics.Process]::Start($psi)
|
|
$null = $wp.Handle
|
|
return @{ Mode = 'deadman'; Pid = $wp.Id; Job = [IntPtr]::Zero; Process = $wp; Why = $why; Wrapper = $wp }
|
|
}
|
|
|
|
function Test-ContainedAlive {
|
|
param($C)
|
|
if ($C.Mode -eq 'job') { return [LelekaGuardNative]::IsRunning($C.Process) }
|
|
return (-not $C.Process.HasExited)
|
|
}
|
|
|
|
# Exit code of a finished child (dead-man mode: the wrapper's, which is the child's, or 90 when the dead-man fired).
|
|
function Get-ContainedExitCode {
|
|
param($C)
|
|
if ($C.Mode -eq 'job') { return [LelekaGuardNative]::ExitCode($C.Process) }
|
|
$C.Process.WaitForExit()
|
|
return $C.Process.ExitCode
|
|
}
|
|
|
|
# The kill: the job, or the wrapper's own tree. Returns the PIDs stopped (dead-man mode) or @() (job: the kernel does it).
|
|
function Stop-Contained {
|
|
param($C)
|
|
if ($C.Mode -eq 'job') { [LelekaGuardNative]::KillJob($C.Job); return @() }
|
|
if ($C.Process.HasExited) { return @() }
|
|
return @(Stop-GuardPidTree -RootPid $C.Process.Id)
|
|
}
|
|
|
|
# Releases the handles. Closing the job handle also kills anything still in the job (KILL_ON_JOB_CLOSE).
|
|
function Close-Contained {
|
|
param($C)
|
|
if ($C.Mode -eq 'job') {
|
|
[LelekaGuardNative]::Close($C.Process)
|
|
[LelekaGuardNative]::Close($C.Job)
|
|
} else {
|
|
try { $C.Process.Dispose() } catch { }
|
|
}
|
|
}
|
|
|
|
# The dead-man wrapper process (-Wrapper). Environment: LELEKA_GUARD_CHILD / _ARGS / _OUT / _ERR.
|
|
function Invoke-Wrapper {
|
|
$exe = $env:LELEKA_GUARD_CHILD
|
|
if ([string]::IsNullOrWhiteSpace($exe) -or [string]::IsNullOrWhiteSpace($HeartbeatFile)) { return 2 }
|
|
$sp = @{ FilePath = $exe; PassThru = $true; NoNewWindow = $true }
|
|
if (-not [string]::IsNullOrWhiteSpace($env:LELEKA_GUARD_ARGS)) { $sp.ArgumentList = $env:LELEKA_GUARD_ARGS }
|
|
if (-not [string]::IsNullOrWhiteSpace($env:LELEKA_GUARD_OUT)) { $sp.RedirectStandardOutput = $env:LELEKA_GUARD_OUT }
|
|
if (-not [string]::IsNullOrWhiteSpace($env:LELEKA_GUARD_ERR)) { $sp.RedirectStandardError = $env:LELEKA_GUARD_ERR }
|
|
$startedAt = [DateTime]::UtcNow
|
|
$p = Start-Process @sp
|
|
$null = $p.Handle
|
|
while (-not $p.HasExited) {
|
|
$age = ([DateTime]::UtcNow - $startedAt).TotalSeconds
|
|
if (Test-Path -LiteralPath $HeartbeatFile) {
|
|
$age = ([DateTime]::UtcNow - (Get-Item -LiteralPath $HeartbeatFile -Force).LastWriteTimeUtc).TotalSeconds
|
|
}
|
|
if ($age -gt $DeadmanSeconds) {
|
|
[void](Stop-GuardPidTree -RootPid $p.Id)
|
|
return 90
|
|
}
|
|
Start-Sleep -Milliseconds 500
|
|
}
|
|
$p.WaitForExit()
|
|
return $p.ExitCode
|
|
}
|
|
|
|
# ------------------------------------------------------------------------------------------------ machine lock (SC13)
|
|
function Get-GuardBootTimeUtc {
|
|
return (Get-CimInstance -ClassName Win32_OperatingSystem -Property LastBootUpTime).LastBootUpTime.ToUniversalTime().ToString('o')
|
|
}
|
|
|
|
# Returns @{ Mode = created | verified | refused; Kind (refused only: held | mismatch | unreadable | reparse); Stream; Path; Reason; Holder }
|
|
function Enter-GuardLock {
|
|
param([string]$LockDir, [string]$RunId, [string]$Leaf, [bool]$RunIdGiven)
|
|
if (-not (Test-Path -LiteralPath $LockDir)) { [void](New-Item -ItemType Directory -Path $LockDir -Force) }
|
|
$di = Get-Item -LiteralPath $LockDir -Force
|
|
if (($di.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) {
|
|
return @{ Mode = 'refused'; Kind = 'reparse'; Reason = ('lock directory ' + $LockDir + ' is a reparse point'); Stream = $null; Path = $null; Holder = $null }
|
|
}
|
|
$path = Join-Path $LockDir $script:LockName
|
|
$content = [ordered]@{ leaf = $Leaf; run_id = $RunId; pid = $PID; utc = [DateTime]::UtcNow.ToString('o'); boot_time = (Get-GuardBootTimeUtc); created_by = 'guard.ps1' }
|
|
$bytes = (New-Object Text.UTF8Encoding $false).GetBytes(($content | ConvertTo-Json))
|
|
try {
|
|
$fs = [IO.FileStream]::new($path, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None)
|
|
$fs.Write($bytes, 0, $bytes.Length)
|
|
$fs.Flush()
|
|
return @{ Mode = 'created'; Kind = ''; Stream = $fs; Path = $path; Reason = ''; Holder = ([pscustomobject]$content) }
|
|
} catch [IO.IOException] {
|
|
if (-not (Test-Path -LiteralPath $path)) { throw }
|
|
}
|
|
$holder = $null
|
|
try {
|
|
$rf = [IO.FileStream]::new($path, [IO.FileMode]::Open, [IO.FileAccess]::Read, ([IO.FileShare]::ReadWrite -bor [IO.FileShare]::Delete))
|
|
try { $sr = New-Object IO.StreamReader($rf); $holder = $sr.ReadToEnd() | ConvertFrom-Json } finally { $rf.Dispose() }
|
|
} catch {
|
|
# held open with FileShare.None by its owner, or not parseable: either way it is somebody's lock
|
|
return @{ Mode = 'refused'; Kind = 'held'; Reason = ('a lock file exists at ' + $path + ' and cannot be read (' + $_.Exception.Message + '); never stolen'); Stream = $null; Path = $path; Holder = $null }
|
|
}
|
|
if ($null -eq $holder) {
|
|
return @{ Mode = 'refused'; Kind = 'unreadable'; Reason = ('the lock file ' + $path + ' is empty or not JSON; never stolen, needs inspection'); Stream = $null; Path = $path; Holder = $null }
|
|
}
|
|
$who = 'run ' + $holder.run_id + ' leaf ' + $holder.leaf + ' pid ' + $holder.pid + ' since ' + $holder.utc
|
|
if (-not $RunIdGiven) {
|
|
return @{ Mode = 'refused'; Kind = 'held'; Reason = ('the machine lock is held by ' + $who + ' and no -RunId was given; never stolen'); Stream = $null; Path = $path; Holder = $holder }
|
|
}
|
|
if ([string]$holder.run_id -ne $RunId -or [string]::IsNullOrEmpty([string]$holder.run_id)) {
|
|
return @{ Mode = 'refused'; Kind = 'mismatch'; Reason = ('the machine lock is held by ' + $who + ', not by run ' + $RunId + '; never stolen'); Stream = $null; Path = $path; Holder = $holder }
|
|
}
|
|
return @{ Mode = 'verified'; Kind = ''; Stream = $null; Path = $path; Reason = ''; Holder = $holder }
|
|
}
|
|
|
|
# Releases the lock (a created one is held open: dispose first). A lock that is not there is not an error.
|
|
function Remove-GuardLock {
|
|
param($Lock)
|
|
if ($null -eq $Lock -or $Lock.Mode -eq 'refused') { return }
|
|
if ($null -ne $Lock.Stream) { try { $Lock.Stream.Dispose() } catch { } }
|
|
Remove-Item -LiteralPath $Lock.Path -Force -ErrorAction SilentlyContinue
|
|
}
|
|
|
|
# ------------------------------------------------------------------------------------------------ state.ps1 (read-only evidence)
|
|
function Convert-GuardInstant {
|
|
param($Value)
|
|
if ($null -eq $Value) { return $null }
|
|
if ($Value -is [DateTime]) { return ([DateTime]$Value).ToUniversalTime() }
|
|
$dto = [DateTimeOffset]::MinValue
|
|
$styles = [Globalization.DateTimeStyles]::AssumeUniversal -bor [Globalization.DateTimeStyles]::AdjustToUniversal
|
|
if ([DateTimeOffset]::TryParse([string]$Value, [Globalization.CultureInfo]::InvariantCulture, $styles, [ref]$dto)) { return $dto.UtcDateTime }
|
|
return $null
|
|
}
|
|
|
|
# Runs state.ps1 as its own process (per-process ExecutionPolicy, SC16), timeout 90 s, returns @{ Ok; Doc; Why; ExitCode }.
|
|
# Exit 5 of -PostAbort (not clean) still carries a document.
|
|
function Invoke-GuardState {
|
|
param([string]$Script, [switch]$PostAbort, [string]$ReferenceTime, [double]$TimeoutS = 90)
|
|
$script:StateCalls++
|
|
if ($PostAbort) { $script:PostAbortCalls++ }
|
|
$a = '-NoProfile -ExecutionPolicy Bypass -File ' + (ConvertTo-QuotedArg $Script)
|
|
if ($PostAbort) { $a += ' -PostAbort' }
|
|
if (-not [string]::IsNullOrWhiteSpace($ReferenceTime)) { $a += ' -ReferenceTime ' + (ConvertTo-QuotedArg $ReferenceTime) }
|
|
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
|
$psi.FileName = (Get-Command powershell.exe -CommandType Application).Source
|
|
$psi.Arguments = $a
|
|
$psi.UseShellExecute = $false
|
|
$psi.RedirectStandardOutput = $true
|
|
$psi.RedirectStandardError = $true
|
|
$psi.CreateNoWindow = $true
|
|
try { $p = [System.Diagnostics.Process]::Start($psi) } catch { return @{ Ok = $false; Doc = $null; Why = ('cannot start the state script: ' + $_.Exception.Message); ExitCode = -1 } }
|
|
try {
|
|
$o = $p.StandardOutput.ReadToEndAsync()
|
|
$e = $p.StandardError.ReadToEndAsync()
|
|
if (-not $p.WaitForExit([int]($TimeoutS * 1000))) {
|
|
[void](Stop-GuardPidTree -RootPid $p.Id)
|
|
return @{ Ok = $false; Doc = $null; Why = ('state script timeout after ' + $TimeoutS + ' s'); ExitCode = -1 }
|
|
}
|
|
$p.WaitForExit()
|
|
[void]$o.Wait(5000)
|
|
$text = ''
|
|
if ($o.IsCompleted) { $text = $o.Result }
|
|
$doc = $null
|
|
try { $doc = $text | ConvertFrom-Json } catch { }
|
|
if ($null -eq $doc) { return @{ Ok = $false; Doc = $null; Why = ('state script output is not JSON (exit ' + $p.ExitCode + ')'); ExitCode = $p.ExitCode } }
|
|
return @{ Ok = $true; Doc = $doc; Why = ''; ExitCode = $p.ExitCode }
|
|
} finally { $p.Dispose() }
|
|
}
|
|
|
|
# Crash evidence: boot time differs from the lock's, a Kernel-Power 41 / BugCheck event since the lock was created, or the evidence
|
|
# is unreadable (fail closed). Returns the list of reasons (empty = none).
|
|
function Get-CrashEvidence {
|
|
param($State, $Holder)
|
|
$r = New-Object System.Collections.ArrayList
|
|
if (-not $State.Ok) { [void]$r.Add('crash evidence unreadable (' + $State.Why + '): fail closed'); return @($r) }
|
|
$d = $State.Doc
|
|
if ($null -eq $d.crash_evidence -or $d.crash_evidence.query_status -ne 'ok') { [void]$r.Add('crash evidence unreadable (event log query status ' + $d.crash_evidence.query_status + '): fail closed') }
|
|
elseif ([int]$d.crash_evidence.count -gt 0) {
|
|
$n41 = @($d.crash_evidence.kernel_power_41).Count
|
|
$nbc = @($d.crash_evidence.bugcheck).Count
|
|
[void]$r.Add('crash evidence: ' + $n41 + ' Kernel-Power 41 and ' + $nbc + ' BugCheck event(s) since the lock was created')
|
|
}
|
|
$cur = Convert-GuardInstant $d.boot_time_utc
|
|
$lockBoot = $null
|
|
if ($null -ne $Holder) { $lockBoot = Convert-GuardInstant $Holder.boot_time }
|
|
if ($null -eq $cur) { [void]$r.Add('boot time of the machine unreadable: fail closed') }
|
|
elseif ($null -ne $lockBoot -and [math]::Abs(($cur - $lockBoot).TotalSeconds) -gt 5) {
|
|
[void]$r.Add('boot time ' + $cur.ToString('o') + ' differs from the lock''s ' + $lockBoot.ToString('o') + ': the machine restarted')
|
|
}
|
|
return @($r)
|
|
}
|
|
|
|
# ------------------------------------------------------------------------------------------------ STOP file (SC3)
|
|
# Creates the STOP file when none exists (CreateNew: an existing one is never overwritten or removed). Returns 'created' | 'exists'.
|
|
function Write-StopFile {
|
|
param([string]$Path, [string]$Kind, [string]$Reason, [string]$RunId)
|
|
$dir = Split-Path -Parent $Path
|
|
if ($dir -and -not (Test-Path -LiteralPath $dir)) { [void](New-Item -ItemType Directory -Path $dir -Force) }
|
|
$obj = [ordered]@{ kind = $Kind; reason = $Reason; run_id = $RunId; utc = [DateTime]::UtcNow.ToString('o')
|
|
remove = 'Only after the owner has inspected the machine and the orchestrator has recorded that inspection (SC3). An agent does not delete this file.' }
|
|
$bytes = (New-Object Text.UTF8Encoding $false).GetBytes(($obj | ConvertTo-Json))
|
|
try {
|
|
$fs = [IO.FileStream]::new($Path, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::Read)
|
|
try { $fs.Write($bytes, 0, $bytes.Length) } finally { $fs.Dispose() }
|
|
return 'created'
|
|
} catch [IO.IOException] {
|
|
if (Test-Path -LiteralPath $Path) { return 'exists' }
|
|
throw
|
|
}
|
|
}
|
|
|
|
# ------------------------------------------------------------------------------------------------ abort completion
|
|
function Write-GuardStamp {
|
|
param([string]$LockDir, [bool]$Aborted, [string]$RunId, [string]$Reason)
|
|
if (-not (Test-Path -LiteralPath $LockDir)) { [void](New-Item -ItemType Directory -Path $LockDir -Force) }
|
|
$p = Join-Path $LockDir $script:StampName
|
|
$obj = [ordered]@{ end_epoch = ([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() / 1000.0); aborted = $Aborted; run_id = $RunId; reason = $Reason }
|
|
$tmp = $p + '.tmp'
|
|
[IO.File]::WriteAllText($tmp, ($obj | ConvertTo-Json), (New-Object Text.UTF8Encoding $false))
|
|
Move-Item -LiteralPath $tmp -Destination $p -Force
|
|
}
|
|
|
|
# Holds the lock for the cool-down on the (injectable) clock. $OnTick is called once per clock second with the elapsed seconds.
|
|
function Wait-GuardCooldown {
|
|
param($Clock, [double]$Seconds, [scriptblock]$OnTick)
|
|
$t0 = Get-GuardNow $Clock
|
|
while ($true) {
|
|
$el = (Get-GuardNow $Clock) - $t0
|
|
if ($null -ne $OnTick) { & $OnTick $el }
|
|
if ($el -ge $Seconds) { break }
|
|
Invoke-GuardSleep $Clock ([math]::Min(1.0, $Seconds - $el))
|
|
}
|
|
}
|
|
|
|
# After an abort: state.ps1 -PostAbort once, the cool-down stamp, the cool-down on the clock, then the lock release.
|
|
# Not clean -> STOP file, lock kept. Returns @{ Clean; Released; ReleasedAt; Reasons }.
|
|
function Complete-GuardAbort {
|
|
param($Lock, $Clock, [string]$StateScript, [string]$LockDir, [string]$StopFile, [string]$RunId, [string]$Reason, [scriptblock]$OnTick, [string]$ReferenceTime)
|
|
$pa = Invoke-GuardState -Script $StateScript -PostAbort -ReferenceTime $ReferenceTime
|
|
$clean = $false
|
|
$reasons = @()
|
|
if (-not $pa.Ok) { $reasons = @('post-abort verification unreadable (' + $pa.Why + ')') }
|
|
elseif ($null -eq $pa.Doc.post_abort) { $reasons = @('post-abort verification missing from the state document') }
|
|
elseif ($pa.Doc.post_abort.clean -eq $true) { $clean = $true }
|
|
else { $reasons = @($pa.Doc.post_abort.reasons) }
|
|
if (-not $clean) {
|
|
$s = Write-StopFile -Path $StopFile -Kind 'POST_ABORT_NOT_CLEAN' -Reason ('post-abort verification not clean: ' + ($reasons -join '; ')) -RunId $RunId
|
|
return @{ Clean = $false; Released = $false; ReleasedAt = $null; Reasons = $reasons; Stop = $s }
|
|
}
|
|
Write-GuardStamp -LockDir $LockDir -Aborted $true -RunId $RunId -Reason $Reason
|
|
$t0 = Get-GuardNow $Clock
|
|
Wait-GuardCooldown -Clock $Clock -Seconds $script:CooldownAbortS -OnTick $OnTick
|
|
$at = [math]::Round((Get-GuardNow $Clock) - $t0, 3)
|
|
Remove-GuardLock $Lock
|
|
return @{ Clean = $true; Released = $true; ReleasedAt = $at; Reasons = @(); Stop = '' }
|
|
}
|
|
|
|
# ------------------------------------------------------------------------------------------------ paths
|
|
function Resolve-GuardTreeRoot {
|
|
$d = $script:GuardDir
|
|
while ($d) {
|
|
if (Test-Path -LiteralPath (Join-Path $d '.git')) { return $d }
|
|
$parent = Split-Path -Parent $d
|
|
if ($parent -eq $d) { break }
|
|
$d = $parent
|
|
}
|
|
return (Resolve-Path (Join-Path $script:GuardDir '..\..\..')).Path
|
|
}
|
|
|
|
# artifacts\ lives in the MAIN checkout, never inside .git\wt\<leaf> (worktree cleanup deletes ignored files)
|
|
function Resolve-GuardMainCheckout {
|
|
$d = $script:GuardDir
|
|
$marker = [IO.Path]::DirectorySeparatorChar + '.git' + [IO.Path]::DirectorySeparatorChar + 'wt' + [IO.Path]::DirectorySeparatorChar
|
|
$i = $d.IndexOf($marker, [StringComparison]::OrdinalIgnoreCase)
|
|
if ($i -ge 0) { return $d.Substring(0, $i) }
|
|
return Resolve-GuardTreeRoot
|
|
}
|
|
|
|
function Write-GuardLog {
|
|
param([string]$Msg)
|
|
Write-Host ('GUARD ' + $Msg)
|
|
}
|
|
|
|
function Write-GuardText {
|
|
param([string]$Path, [string]$Text)
|
|
[IO.File]::WriteAllText($Path, $Text, (New-Object Text.UTF8Encoding $false))
|
|
}
|
|
|
|
# ------------------------------------------------------------------------------------------------ main
|
|
function Invoke-GuardMain {
|
|
$summary = [ordered]@{ run_id = $null; leaf = $Leaf; outcome = 'NOT_STARTED'; guard_exit_code = $null; reason = ''; containment = $null; containment_why = ''
|
|
child_pid = $null; child_exit_code = $null; lock_mode = $null; stop_file = $null; stop_file_state = $null; crash_evidence = @(); post_abort_calls = 0
|
|
post_abort_clean = $null; lock_released = $null; cooldown_released_at_s = $null; timeout_seconds = $TimeoutSeconds; time_scale = $TimeScale
|
|
started_utc = [DateTime]::UtcNow.ToString('o'); ended_utc = $null; run_root = $null }
|
|
if ([string]::IsNullOrWhiteSpace($ChildCommand)) { Write-GuardLog 'ERROR -ChildCommand is required'; return 2 }
|
|
if ($TimeScale -le 0 -or $TimeoutSeconds -lt 0 -or $DeadmanSeconds -le 0) { Write-GuardLog 'ERROR -TimeScale and -DeadmanSeconds must be positive, -TimeoutSeconds not negative'; return 2 }
|
|
$runIdGiven = -not [string]::IsNullOrWhiteSpace($RunId)
|
|
if (-not $runIdGiven) { $RunId = 'guard-' + [DateTime]::UtcNow.ToString('yyyyMMddTHHmmssfff') + '-' + $PID }
|
|
$summary.run_id = $RunId
|
|
|
|
$artifacts = $ArtifactsRoot
|
|
if ([string]::IsNullOrWhiteSpace($artifacts)) { $artifacts = Join-Path (Resolve-GuardMainCheckout) 'artifacts' }
|
|
$lockDir = Join-Path $artifacts 'locks'
|
|
$runsDir = Join-Path $artifacts 'runs'
|
|
$runRoot = $RunRoot
|
|
if ([string]::IsNullOrWhiteSpace($runRoot)) { $runRoot = Join-Path $runsDir $RunId }
|
|
$stop = $StopFile
|
|
if ([string]::IsNullOrWhiteSpace($stop)) { $stop = Join-Path $runsDir 'STOP' }
|
|
$state = $StateScript
|
|
if ([string]::IsNullOrWhiteSpace($state)) { $state = Join-Path $script:GuardDir 'state.ps1' }
|
|
$hb = $HeartbeatFile
|
|
if ([string]::IsNullOrWhiteSpace($hb)) { $hb = Join-Path $runRoot 'heartbeat' }
|
|
$summary.run_root = $runRoot
|
|
$summary.stop_file = $stop
|
|
|
|
# 1. STOP file: refuse before anything else is touched
|
|
if (Test-Path -LiteralPath $stop) {
|
|
Write-GuardLog ('STOP FILE PRESENT: ' + $stop + ' - refusing to start; only the orchestrator''s recorded owner inspection removes it')
|
|
return 5
|
|
}
|
|
|
|
# 2. lock
|
|
try { $lock = Enter-GuardLock -LockDir $lockDir -RunId $RunId -Leaf $Leaf -RunIdGiven $runIdGiven } catch { Write-GuardLog ('ERROR lock: ' + $_.Exception.Message); return 8 }
|
|
$summary.lock_mode = $lock.Mode
|
|
if ($lock.Mode -eq 'refused') { Write-GuardLog ('LOCK REFUSED (' + $lock.Kind + '): ' + $lock.Reason); return 3 }
|
|
Write-GuardLog ('lock ' + $lock.Mode + ': ' + $lock.Path)
|
|
|
|
$code = 8
|
|
$abortKind = $null # null = normal end; else STALL | ABORT | CRASH
|
|
$abortReason = ''
|
|
$contained = $null
|
|
$clock = New-GuardClock -Scale $TimeScale
|
|
$refTime = [string]$lock.Holder.utc
|
|
try {
|
|
[void](New-Item -ItemType Directory -Path $runRoot -Force)
|
|
|
|
# 3. crash check before the start
|
|
$st = Invoke-GuardState -Script $state -ReferenceTime $refTime
|
|
$ev = @(Get-CrashEvidence -State $st -Holder $lock.Holder)
|
|
if ($ev.Count -gt 0) {
|
|
$summary.crash_evidence = $ev
|
|
$abortKind = 'CRASH'; $abortReason = ($ev -join '; ')
|
|
$summary.outcome = 'CRASH_EVIDENCE'; $code = 9
|
|
}
|
|
|
|
# 4. start and supervise
|
|
if ($null -eq $abortKind) {
|
|
$outF = Join-Path $runRoot 'child.stdout.txt'
|
|
$errF = Join-Path $runRoot 'child.stderr.txt'
|
|
try {
|
|
$contained = Start-Contained -FilePath $ChildCommand -Arguments $ChildArguments -StdoutPath $outF -StderrPath $errF -HeartbeatFile $hb -DeadmanSeconds $DeadmanSeconds -ForceFallback:$NoJobObject
|
|
} catch {
|
|
Write-GuardLog ('ERROR cannot start the child: ' + $_.Exception.Message)
|
|
$abortKind = 'ABORT'; $abortReason = 'cannot start the child: ' + $_.Exception.Message
|
|
$summary.outcome = 'CHILD_NOT_STARTED'; $code = 6
|
|
}
|
|
}
|
|
if ($null -eq $abortKind) {
|
|
$summary.containment = $contained.Mode; $summary.containment_why = $contained.Why; $summary.child_pid = $contained.Pid
|
|
Write-GuardLog ('child started: pid ' + $contained.Pid + ' containment ' + $contained.Mode + $(if ($contained.Why) { ' (' + $contained.Why + ')' } else { '' }))
|
|
$stallFile = Join-Path $runRoot 'STALL'
|
|
$t0 = Get-GuardNow $clock
|
|
$exitCode = $null
|
|
while ($true) {
|
|
if ($contained.Mode -eq 'deadman') { Send-GuardHeartbeat $hb }
|
|
if (Test-Path -LiteralPath $stallFile) { $abortKind = 'STALL'; $abortReason = 'STALL file ' + $stallFile + ' written by the watchdog'; break }
|
|
if (-not (Test-ContainedAlive $contained)) { $exitCode = Get-ContainedExitCode $contained; break }
|
|
if ($TimeoutSeconds -gt 0 -and ((Get-GuardNow $clock) - $t0) -ge $TimeoutSeconds) { $abortKind = 'ABORT'; $abortReason = 'run timeout of ' + $TimeoutSeconds + ' s reached'; break }
|
|
Invoke-GuardSleep $clock ([math]::Max(0.25, 0.05 * $TimeScale)) # about 0.25 s real; 50 ms real when -TimeScale speeds the clock up
|
|
}
|
|
$killed = @(Stop-Contained $contained) # always: nothing of this job outlives the run (leftover grandchildren included)
|
|
if ($null -ne $exitCode) {
|
|
$summary.child_exit_code = $exitCode
|
|
if ($exitCode -eq 7) { $abortKind = 'STALL'; $abortReason = 'the child (watchdog) exited with 7 = STALL' }
|
|
elseif ($exitCode -eq 90 -and $contained.Mode -eq 'deadman') { $abortKind = 'ABORT'; $abortReason = 'dead-man: the heartbeat was older than ' + $DeadmanSeconds + ' s' }
|
|
elseif ($exitCode -eq 5 -or $exitCode -eq 6) { $abortKind = 'ABORT'; $abortReason = 'the child (watchdog) aborted with exit code ' + $exitCode }
|
|
elseif ($exitCode -eq 0) { $summary.outcome = 'COMPLETED'; $code = 0 }
|
|
else { $summary.outcome = 'CHILD_FAILED'; $code = 1 }
|
|
}
|
|
if ($abortKind -eq 'STALL') { $summary.outcome = 'STALL'; $code = 7 }
|
|
elseif ($abortKind -eq 'ABORT') { $summary.outcome = 'ABORTED'; $code = 6 }
|
|
Write-GuardLog ($summary.outcome + $(if ($abortReason) { ': ' + $abortReason } else { '' }) + ' (killed pids: ' + ($killed -join ',') + ')')
|
|
|
|
# 5. crash check after the end (a crash during the run shows as a different boot time or a Kernel-Power 41 event)
|
|
if ($abortKind -ne 'STALL') {
|
|
$st2 = Invoke-GuardState -Script $state -ReferenceTime $refTime
|
|
$ev2 = @(Get-CrashEvidence -State $st2 -Holder $lock.Holder)
|
|
if ($ev2.Count -gt 0) {
|
|
$summary.crash_evidence = $ev2
|
|
$abortKind = 'CRASH'; $abortReason = ($ev2 -join '; ')
|
|
$summary.outcome = 'CRASH_EVIDENCE'; $code = 9
|
|
}
|
|
}
|
|
}
|
|
|
|
# STOP file on STALL or crash evidence (never overwritten, never removed here)
|
|
if ($abortKind -eq 'STALL' -or $abortKind -eq 'CRASH') {
|
|
$kind = $abortKind
|
|
if ($kind -eq 'CRASH') { $kind = 'CRASH_EVIDENCE' }
|
|
$summary.stop_file_state = Write-StopFile -Path $stop -Kind $kind -Reason $abortReason -RunId $RunId
|
|
Write-GuardLog ('stop file: ' + $summary.stop_file_state + ' ' + $stop)
|
|
}
|
|
|
|
# 6. after every abort: post-abort verification, cool-down, lock release
|
|
if ($null -ne $abortKind) {
|
|
$fin = Complete-GuardAbort -Lock $lock -Clock $clock -StateScript $state -LockDir $lockDir -StopFile $stop -RunId $RunId -Reason $summary.outcome -ReferenceTime $refTime
|
|
$summary.post_abort_clean = $fin.Clean
|
|
$summary.lock_released = $fin.Released
|
|
$summary.cooldown_released_at_s = $fin.ReleasedAt
|
|
if (-not $fin.Clean) {
|
|
$summary.reason = 'post-abort verification not clean: ' + ($fin.Reasons -join '; ')
|
|
Write-GuardLog ('POST ABORT NOT CLEAN: ' + ($fin.Reasons -join '; ') + ' - STOP file ' + $fin.Stop + ', the lock is kept')
|
|
if ($code -eq 6) { $code = 10 }
|
|
} else {
|
|
Write-GuardLog ('lock released after the cool-down at ' + $fin.ReleasedAt + ' clock s')
|
|
}
|
|
} else {
|
|
Write-GuardStamp -LockDir $lockDir -Aborted $false -RunId $RunId -Reason $summary.outcome
|
|
Remove-GuardLock $lock
|
|
$summary.lock_released = $true
|
|
}
|
|
if ($summary.reason -eq '') { $summary.reason = $abortReason }
|
|
return $code
|
|
} catch {
|
|
Write-GuardLog ('ERROR internal: ' + $_.Exception.Message)
|
|
$summary.outcome = 'ERROR'; $summary.reason = $_.Exception.Message
|
|
if ($null -ne $contained) { try { [void](Stop-Contained $contained) } catch { } }
|
|
$code = 8
|
|
return $code
|
|
} finally {
|
|
if ($null -ne $contained) { Close-Contained $contained }
|
|
$summary.post_abort_calls = $script:PostAbortCalls
|
|
$summary.guard_exit_code = $code
|
|
$summary.ended_utc = [DateTime]::UtcNow.ToString('o')
|
|
try { Write-GuardText (Join-Path $runRoot 'guard_summary.json') ($summary | ConvertTo-Json -Depth 4) } catch { Write-GuardLog ('WARNING cannot write the summary: ' + $_.Exception.Message) }
|
|
}
|
|
}
|
|
|
|
if ($Library) { return }
|
|
|
|
if ($Wrapper) {
|
|
$wrapperCode = @(Invoke-Wrapper)
|
|
exit ([int]$wrapperCode[$wrapperCode.Count - 1])
|
|
}
|
|
|
|
$exitCode = @(Invoke-GuardMain)
|
|
exit ([int]$exitCode[$exitCode.Count - 1])
|