Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
489 lines
23 KiB
PowerShell
489 lines
23 KiB
PowerShell
<#
|
|
.SYNOPSIS
|
|
READ-ONLY state and precondition reader for the Windows laptop (STRA-319, S3.10 of STRA-245).
|
|
|
|
.DESCRIPTION
|
|
Prints ONE JSON document on stdout and changes nothing. It never changes a power, display, lock, sleep,
|
|
execution-policy or any other system setting; the owner-run SETTER is scripts\dev\laptop-turbo.ps1 and is
|
|
not used or cited here as a reader. The commands used are query-only:
|
|
powercfg (the active-scheme query and the settings-dump query for one scheme and subgroup)
|
|
nvidia-smi --query-gpu=... / --query-compute-apps=... (query only, no GPU load)
|
|
Get-CimInstance (Win32_Battery, Win32_OperatingSystem), Get-Process, Get-WinEvent (System log, read only)
|
|
Windows PowerShell 5.1, standard library only, no WSL launcher and no other shell is started.
|
|
|
|
Usage (from the repository root):
|
|
powershell -NoProfile -ExecutionPolicy Bypass -File scripts\laptop\win\state.ps1
|
|
powershell -NoProfile -ExecutionPolicy Bypass -File scripts\laptop\win\state.ps1 -ReferenceTime 2026-10-28T08:00:00Z
|
|
powershell -NoProfile -ExecutionPolicy Bypass -File scripts\laptop\win\state.ps1 -PostAbort
|
|
... -OutFile C:\Users\pavel\work\leleka\artifacts\runs\<series>\state-before.json (also writes the JSON there;
|
|
the artifacts\ directory is ignored by Git, keep outputs there and never commit them)
|
|
|
|
Parameters
|
|
-PostAbort also run the post-abort check: no leleka-* / strata-* process is left and the nvidia-smi
|
|
compute-app list is empty. Note: on a WDDM (Windows display driver) GPU the compute-app
|
|
list can be empty even while a process uses the GPU, so the process-name check is the
|
|
primary evidence and the compute-app list is a second, weaker one.
|
|
-ReferenceTime instant (ISO 8601, give 'Z' or an offset; without one UTC is assumed) from which
|
|
Kernel-Power 41 and BugCheck (System log event 1001) events are listed. Default: the last
|
|
boot time (a crash is logged by the boot that follows it), reference_time_source says which.
|
|
-OutFile optional path; the same JSON is also written there (UTF-8 without BOM).
|
|
|
|
Output (stable `settings` object first, then the volatile fields; compare two reads by `settings` alone):
|
|
settings.power_scheme_guid / power_scheme_name, settings.timeouts_s (sleep, hibernate, display_off,
|
|
console_lock_display_off; each {ac, dc} in seconds, 0 = never), settings.ac_status,
|
|
settings.enforced_power_limit (W; the field is enforced.power.limit because power.limit is N/A on this GPU),
|
|
settings.power_max_limit_w (W, from power.max_limit), settings.owner_attestation (items with NO read-only
|
|
command, printed as required, never guessed: unlocked_screen, sign_in_requirement, oem_turbo).
|
|
gpu (name, clocks, pstate, throttle reasons, temperature), boot_time_utc, crash_evidence (Kernel-Power 41 and
|
|
BugCheck since the reference time), wsl_docker, top_processes (CPU over a 1 s window), post_abort (with -PostAbort),
|
|
unreadable_fields, exit_code.
|
|
|
|
Exit codes
|
|
0 read done; 4 = fail closed: enforced_power_limit or power_max_limit_w is empty, N/A, unparsable, or the
|
|
nvidia-smi sample is missing (each nvidia-smi / powercfg call is abandoned after 5 s and counts as a
|
|
missing sample); 5 = -PostAbort found something left over (or could not prove nothing is left);
|
|
3 = unexpected error. Any other field that could not be read is the string 'unreadable' and is listed in
|
|
`unreadable_fields`; a consumer must check that list.
|
|
|
|
Test hook: when the environment variable LELEKA_STATE_FIXTURE_DIR names a directory, the cmdlet-based sources
|
|
(battery.json, os.json, events.json, processes.json in that directory) are read from those data files instead of
|
|
the live system; the JSON then carries "source": "fixture". powercfg and nvidia-smi are always resolved through the
|
|
process PATH, so the tests put shims of them first on the CHILD process PATH only (scripts\laptop\win\test_state.ps1).
|
|
#>
|
|
[CmdletBinding()]
|
|
param(
|
|
[switch]$PostAbort,
|
|
[string]$ReferenceTime,
|
|
[string]$OutFile
|
|
)
|
|
|
|
Set-StrictMode -Version 2.0
|
|
$ErrorActionPreference = 'Stop'
|
|
|
|
$Unreadable = 'unreadable'
|
|
$ToolTimeoutSec = 5
|
|
$Inv = [System.Globalization.CultureInfo]::InvariantCulture
|
|
$FixtureDir = $env:LELEKA_STATE_FIXTURE_DIR
|
|
$UseFixture = $false
|
|
if ($FixtureDir -and (Test-Path -LiteralPath $FixtureDir -PathType Container)) { $UseFixture = $true }
|
|
|
|
$UnreadableFields = New-Object System.Collections.Generic.List[string]
|
|
function Add-Unreadable([string]$Name) { if (-not $UnreadableFields.Contains($Name)) { $UnreadableFields.Add($Name) } }
|
|
|
|
# ---------------------------------------------------------------- tool runner (5 s per call, kills only its own child)
|
|
function Invoke-QueryTool {
|
|
param([string]$Name, [string[]]$ToolArgs, [int]$TimeoutSec = $ToolTimeoutSec)
|
|
$res = [ordered]@{ status = 'ok'; exit_code = $null; text = '' }
|
|
$cmd = Get-Command -Name $Name -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
|
|
if (-not $cmd) { $res.status = 'missing'; return $res }
|
|
$p = $null
|
|
try {
|
|
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
|
$psi.FileName = $cmd.Source
|
|
$psi.Arguments = ($ToolArgs -join ' ')
|
|
$psi.UseShellExecute = $false
|
|
$psi.RedirectStandardOutput = $true
|
|
$psi.RedirectStandardError = $true
|
|
$psi.CreateNoWindow = $true
|
|
try {
|
|
$oem = [System.Globalization.CultureInfo]::CurrentCulture.TextInfo.OEMCodePage
|
|
$psi.StandardOutputEncoding = [System.Text.Encoding]::GetEncoding($oem)
|
|
} catch { }
|
|
$p = [System.Diagnostics.Process]::Start($psi)
|
|
$outTask = $p.StandardOutput.ReadToEndAsync()
|
|
$errTask = $p.StandardError.ReadToEndAsync()
|
|
if (-not $p.WaitForExit($TimeoutSec * 1000)) {
|
|
# abandon the call: kill the tool this script started (and its children), nothing else
|
|
& taskkill.exe /PID $p.Id /T /F 2>&1 | Out-Null
|
|
try { [void]$p.WaitForExit(2000) } catch { }
|
|
$res.status = 'timeout'
|
|
return $res
|
|
}
|
|
$p.WaitForExit()
|
|
$res.exit_code = $p.ExitCode
|
|
$res.text = [string]$outTask.Result
|
|
if ($p.ExitCode -ne 0) { $res.status = 'error' }
|
|
} catch {
|
|
$res.status = 'error'
|
|
$res.text = $_.Exception.Message
|
|
} finally {
|
|
if ($p) { $p.Dispose() }
|
|
}
|
|
return $res
|
|
}
|
|
|
|
function Test-Unreadable($Value) { return (($Value -is [string]) -and ($Value -ceq 'unreadable')) }
|
|
|
|
function ConvertTo-PositiveNumber([string]$Text) {
|
|
# '138.94 W', '140.00', ' 1545 MHz ' -> double; '[N/A]', '', 'x', '0', '-1' -> $null
|
|
if ($null -eq $Text) { return $null }
|
|
$m = [regex]::Match($Text, '^\s*([0-9]+(\.[0-9]+)?)\s*[A-Za-z%]*\s*$')
|
|
if (-not $m.Success) { return $null }
|
|
$v = [double]::Parse($m.Groups[1].Value, $Inv)
|
|
if ($v -le 0) { return $null }
|
|
return $v
|
|
}
|
|
|
|
function ConvertTo-NonNegativeNumber([string]$Text) {
|
|
if ($null -eq $Text) { return $null }
|
|
$m = [regex]::Match($Text, '^\s*([0-9]+(\.[0-9]+)?)\s*[A-Za-z%]*\s*$')
|
|
if (-not $m.Success) { return $null }
|
|
return [double]::Parse($m.Groups[1].Value, $Inv)
|
|
}
|
|
|
|
function Read-FixtureJson([string]$File) {
|
|
$path = Join-Path $FixtureDir $File
|
|
if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { return $null }
|
|
$raw = Get-Content -LiteralPath $path -Raw -ErrorAction Stop
|
|
if ([string]::IsNullOrWhiteSpace($raw)) { return $null }
|
|
return ($raw | ConvertFrom-Json)
|
|
}
|
|
|
|
function ConvertTo-UtcDate($Value) {
|
|
if ($null -eq $Value) { return $null }
|
|
if ($Value -is [datetime]) { return $Value.ToUniversalTime() }
|
|
$dto = [DateTimeOffset]::MinValue
|
|
$styles = [System.Globalization.DateTimeStyles]::AssumeUniversal
|
|
if ([DateTimeOffset]::TryParse([string]$Value, $Inv, $styles, [ref]$dto)) { return $dto.UtcDateTime }
|
|
return $null
|
|
}
|
|
|
|
function Format-Utc($Value) {
|
|
if ($null -eq $Value) { return $null }
|
|
return $Value.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffZ', $Inv)
|
|
}
|
|
|
|
# ---------------------------------------------------------------- power scheme and timeouts (powercfg, query forms only)
|
|
$SettingGuids = [ordered]@{
|
|
sleep = '29f6c1db-86da-48c5-9fdb-f2b67b1f44da' # STANDBYIDLE, subgroup SUB_SLEEP
|
|
hibernate = '9d7815a6-7ee4-497e-8888-515a05f02364' # HIBERNATEIDLE, subgroup SUB_SLEEP
|
|
display_off = '3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e' # VIDEOIDLE, subgroup SUB_VIDEO
|
|
console_lock_display_off = '8ec4b3a5-6868-48c2-be75-4f3044be88a7' # VIDEOCONLOCK, subgroup SUB_VIDEO
|
|
}
|
|
|
|
function Get-SettingIndexes([string]$Dump, [string]$SettingGuid) {
|
|
# Parse by the setting GUID (not by the localized name): the first two 'Power Setting Index: 0x..' lines after
|
|
# the setting GUID that are not 'Possible' are AC then DC.
|
|
$lines = $Dump -split "`r?`n"
|
|
$found = $false
|
|
$vals = @()
|
|
foreach ($line in $lines) {
|
|
if (-not $found) {
|
|
if ($line -match 'Power Setting GUID:\s*([0-9a-fA-F-]{36})' -and $Matches[1].ToLowerInvariant() -eq $SettingGuid) { $found = $true }
|
|
continue
|
|
}
|
|
if ($line -match 'Power Setting GUID:') { break }
|
|
if ($line -match '^\s*Current\b.*Power Setting Index:\s*0x([0-9a-fA-F]+)') {
|
|
$vals += [Convert]::ToInt64($Matches[1], 16)
|
|
}
|
|
if ($vals.Count -ge 2) { break }
|
|
}
|
|
if ($vals.Count -lt 2) { return $null }
|
|
return [ordered]@{ ac = $vals[0]; dc = $vals[1] }
|
|
}
|
|
|
|
$schemeGuid = $Unreadable
|
|
$schemeName = $Unreadable
|
|
$timeouts = [ordered]@{}
|
|
foreach ($k in $SettingGuids.Keys) { $timeouts[$k] = $Unreadable }
|
|
|
|
$active = Invoke-QueryTool -Name 'powercfg' -ToolArgs @('/getactivescheme')
|
|
if ($active.status -eq 'ok') {
|
|
$m = [regex]::Match($active.text, '([0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12})\s*(\(([^)]*)\))?')
|
|
if ($m.Success) {
|
|
$schemeGuid = $m.Groups[1].Value.ToLowerInvariant()
|
|
if ($m.Groups[4].Success) { $schemeName = $m.Groups[4].Value.Trim() }
|
|
}
|
|
}
|
|
if ($schemeGuid -eq $Unreadable) { Add-Unreadable 'power_scheme_guid' }
|
|
if ($schemeName -eq $Unreadable) { Add-Unreadable 'power_scheme_name' }
|
|
|
|
if ($schemeGuid -ne $Unreadable) {
|
|
$dumps = @{}
|
|
foreach ($sub in 'SUB_SLEEP', 'SUB_VIDEO') {
|
|
$r = Invoke-QueryTool -Name 'powercfg' -ToolArgs @('/q', $schemeGuid, $sub)
|
|
$dumps[$sub] = if ($r.status -eq 'ok') { $r.text } else { '' }
|
|
}
|
|
$map = @{ sleep = 'SUB_SLEEP'; hibernate = 'SUB_SLEEP'; display_off = 'SUB_VIDEO'; console_lock_display_off = 'SUB_VIDEO' }
|
|
foreach ($k in $SettingGuids.Keys) {
|
|
$idx = Get-SettingIndexes $dumps[$map[$k]] $SettingGuids[$k]
|
|
if (-not $idx -and $k -eq 'console_lock_display_off') {
|
|
# this setting is a hidden one on some builds: the dump that includes hidden settings is also a query
|
|
$r2 = Invoke-QueryTool -Name 'powercfg' -ToolArgs @('/qh', $schemeGuid, 'SUB_VIDEO')
|
|
if ($r2.status -eq 'ok') { $idx = Get-SettingIndexes $r2.text $SettingGuids[$k] }
|
|
}
|
|
if ($idx) { $timeouts[$k] = $idx } else { Add-Unreadable ("timeouts_s." + $k) }
|
|
}
|
|
} else {
|
|
foreach ($k in $SettingGuids.Keys) { Add-Unreadable ("timeouts_s." + $k) }
|
|
}
|
|
|
|
# ---------------------------------------------------------------- AC / charger status
|
|
$acStatus = [ordered]@{ battery_status_code = $null; state = $Unreadable }
|
|
try {
|
|
$bat = $null
|
|
if ($UseFixture) { $bat = Read-FixtureJson 'battery.json' }
|
|
else { $bat = Get-CimInstance -ClassName Win32_Battery -ErrorAction Stop | Select-Object -First 1 }
|
|
if ($null -eq $bat) {
|
|
$acStatus.state = 'no_battery_instance' # owner attestation only (P3)
|
|
} else {
|
|
$code = [int]$bat.BatteryStatus
|
|
$acStatus.battery_status_code = $code
|
|
if (@(2, 3, 6, 7, 8, 9) -contains $code) { $acStatus.state = 'on_ac' }
|
|
elseif (@(1, 4, 5) -contains $code) { $acStatus.state = 'on_battery' }
|
|
else { $acStatus.state = 'unknown' }
|
|
}
|
|
} catch { Add-Unreadable 'ac_status' }
|
|
|
|
# ---------------------------------------------------------------- GPU line (nvidia-smi --query-gpu, 5 s timeout)
|
|
$gpuFields = 'name,enforced.power.limit,power.max_limit,clocks.sm,clocks.mem,pstate,clocks_throttle_reasons.active,temperature.gpu'
|
|
$enforced = $Unreadable
|
|
$maxLimit = $Unreadable
|
|
$gpu = [ordered]@{
|
|
sample_status = 'missing'; name = $Unreadable; clocks_sm_mhz = $Unreadable; clocks_mem_mhz = $Unreadable
|
|
pstate = $Unreadable; throttle_reasons_active = $Unreadable; throttle_reason_names = @(); temperature_c = $Unreadable
|
|
}
|
|
$g = Invoke-QueryTool -Name 'nvidia-smi' -ToolArgs @("--query-gpu=$gpuFields", '--format=csv,noheader')
|
|
$gpu.sample_status = $g.status
|
|
if ($g.status -eq 'ok') {
|
|
$line = ($g.text -split "`r?`n" | Where-Object { $_.Trim() } | Select-Object -First 1)
|
|
$parts = @()
|
|
if ($line) { $parts = @($line -split ',' | ForEach-Object { $_.Trim() }) }
|
|
if ($parts.Count -eq 8) {
|
|
if ($parts[0] -and $parts[0] -notmatch '^\[') { $gpu.name = $parts[0] }
|
|
$v = ConvertTo-PositiveNumber $parts[1]; if ($null -ne $v) { $enforced = $v }
|
|
$v = ConvertTo-PositiveNumber $parts[2]; if ($null -ne $v) { $maxLimit = $v }
|
|
$v = ConvertTo-NonNegativeNumber $parts[3]; if ($null -ne $v) { $gpu.clocks_sm_mhz = $v }
|
|
$v = ConvertTo-NonNegativeNumber $parts[4]; if ($null -ne $v) { $gpu.clocks_mem_mhz = $v }
|
|
if ($parts[5] -match '^P\d+$') { $gpu.pstate = $parts[5] }
|
|
if ($parts[6] -match '^0[xX]([0-9a-fA-F]+)$') {
|
|
$mask = [Convert]::ToUInt64($Matches[1], 16)
|
|
$gpu.throttle_reasons_active = ('0x{0:X16}' -f $mask)
|
|
$names = @()
|
|
$bits = @(
|
|
@(1, 'gpu_idle'), @(2, 'applications_clocks_setting'), @(4, 'sw_power_cap'), @(8, 'hw_slowdown'), @(16, 'sync_boost'),
|
|
@(32, 'sw_thermal_slowdown'), @(64, 'hw_thermal_slowdown'), @(128, 'hw_power_brake_slowdown'), @(256, 'display_clock_setting')
|
|
)
|
|
foreach ($b in $bits) { if (($mask -band [uint64]$b[0]) -ne 0) { $names += $b[1] } }
|
|
$gpu.throttle_reason_names = $names
|
|
}
|
|
$v = ConvertTo-NonNegativeNumber $parts[7]; if ($null -ne $v) { $gpu.temperature_c = $v }
|
|
}
|
|
}
|
|
foreach ($f in 'name', 'clocks_sm_mhz', 'clocks_mem_mhz', 'pstate', 'throttle_reasons_active', 'temperature_c') {
|
|
if ((Test-Unreadable $gpu[$f])) { Add-Unreadable ("gpu." + $f) }
|
|
}
|
|
if (Test-Unreadable $enforced) { Add-Unreadable 'enforced_power_limit' }
|
|
if (Test-Unreadable $maxLimit) { Add-Unreadable 'power_max_limit_w' }
|
|
|
|
# ---------------------------------------------------------------- process list (CPU over a 1 s window) and WSL / Docker presence
|
|
function Get-ProcessSnapshot {
|
|
$out = [ordered]@{ status = 'ok'; processes = @() }
|
|
try {
|
|
if ($UseFixture) {
|
|
$fx = Read-FixtureJson 'processes.json'
|
|
$list = @()
|
|
foreach ($p in @($fx)) {
|
|
if ($null -eq $p) { continue }
|
|
$list += [pscustomobject]@{ name = [string]$p.Name; id = [int]$p.Id; cpu_percent = [double]$p.CpuPercent }
|
|
}
|
|
$out.processes = $list
|
|
return $out
|
|
}
|
|
$first = @{}
|
|
foreach ($p in (Get-Process -ErrorAction SilentlyContinue)) {
|
|
$cpu = $null
|
|
try { $cpu = $p.CPU } catch { }
|
|
$first[$p.Id] = @{ name = $p.Name; cpu = $cpu }
|
|
}
|
|
$sw = [System.Diagnostics.Stopwatch]::StartNew()
|
|
Start-Sleep -Milliseconds 1000
|
|
$list = @()
|
|
foreach ($p in (Get-Process -ErrorAction SilentlyContinue)) {
|
|
$cpu = $null
|
|
try { $cpu = $p.CPU } catch { }
|
|
$pct = 0.0
|
|
if ($null -ne $cpu -and $first.ContainsKey($p.Id) -and $null -ne $first[$p.Id].cpu -and $first[$p.Id].name -eq $p.Name) {
|
|
$pct = [math]::Round((($cpu - $first[$p.Id].cpu) / ($sw.Elapsed.TotalSeconds)) * 100.0, 1)
|
|
if ($pct -lt 0) { $pct = 0.0 }
|
|
}
|
|
$list += [pscustomobject]@{ name = $p.Name; id = $p.Id; cpu_percent = $pct }
|
|
}
|
|
$out.processes = $list
|
|
} catch {
|
|
$out.status = $Unreadable
|
|
}
|
|
return $out
|
|
}
|
|
|
|
$snap = Get-ProcessSnapshot
|
|
$procs = @($snap.processes)
|
|
if ($snap.status -ne 'ok') { Add-Unreadable 'top_processes'; Add-Unreadable 'wsl_docker' }
|
|
|
|
$wslDockerNames = @('vmmemWSL', 'vmmem', 'wslhost', 'Docker Desktop', 'com.docker.backend', 'dockerd')
|
|
$wslFound = @($procs | Where-Object { $wslDockerNames -contains $_.name } | ForEach-Object { [ordered]@{ name = $_.name; id = $_.id } })
|
|
$wslDocker = [ordered]@{
|
|
status = $snap.status
|
|
vmmemWSL_present = [bool](@($procs | Where-Object { $_.name -ieq 'vmmemWSL' }).Count -gt 0)
|
|
docker_present = [bool](@($procs | Where-Object { $_.name -match '^(Docker Desktop|com\.docker\.backend|dockerd)$' }).Count -gt 0)
|
|
found = $wslFound
|
|
}
|
|
$top = @($procs | Where-Object { $_.name -ne 'Idle' -and $_.name -ne '_Total' } | Sort-Object cpu_percent -Descending |
|
|
Select-Object -First 5 | ForEach-Object { [ordered]@{ name = $_.name; id = $_.id; cpu_percent = $_.cpu_percent } })
|
|
|
|
# ---------------------------------------------------------------- boot time and crash evidence (Get-WinEvent, read only)
|
|
$bootUtc = $null
|
|
try {
|
|
if ($UseFixture) {
|
|
$os = Read-FixtureJson 'os.json'
|
|
if ($os) { $bootUtc = ConvertTo-UtcDate $os.LastBootUpTime }
|
|
} else {
|
|
$bootUtc = ConvertTo-UtcDate (Get-CimInstance -ClassName Win32_OperatingSystem -ErrorAction Stop).LastBootUpTime
|
|
}
|
|
} catch { }
|
|
if ($null -eq $bootUtc) { Add-Unreadable 'boot_time_utc' }
|
|
|
|
$refUtc = $null
|
|
$refSource = 'boot_time'
|
|
if ($ReferenceTime) {
|
|
$refUtc = ConvertTo-UtcDate $ReferenceTime
|
|
if ($null -eq $refUtc) { [Console]::Error.WriteLine("state.ps1: -ReferenceTime is not a valid ISO 8601 instant: $ReferenceTime"); exit 3 }
|
|
$refSource = 'parameter'
|
|
} elseif ($null -ne $bootUtc) {
|
|
$refUtc = $bootUtc
|
|
} else {
|
|
$refUtc = (Get-Date).ToUniversalTime().AddHours(-24)
|
|
$refSource = 'last_24h_fallback'
|
|
}
|
|
|
|
function Get-RawEvents([datetime]$SinceUtc) {
|
|
# returns @{ status; events = list of @{id; provider; time (UTC); message} }
|
|
$res = @{ status = 'ok'; events = @() }
|
|
try {
|
|
if ($UseFixture) {
|
|
$fx = Read-FixtureJson 'events.json'
|
|
foreach ($e in @($fx)) {
|
|
if ($null -eq $e) { continue }
|
|
$res.events += @{ id = [int]$e.Id; provider = [string]$e.ProviderName; time = (ConvertTo-UtcDate $e.TimeCreated); message = [string]$e.Message }
|
|
}
|
|
return $res
|
|
}
|
|
$since = $SinceUtc.ToLocalTime()
|
|
$queries = @(
|
|
@{ LogName = 'System'; ProviderName = 'Microsoft-Windows-Kernel-Power'; Id = 41; StartTime = $since },
|
|
@{ LogName = 'System'; ProviderName = 'Microsoft-Windows-WER-SystemErrorReporting'; Id = 1001; StartTime = $since }
|
|
)
|
|
foreach ($q in $queries) {
|
|
try {
|
|
foreach ($e in @(Get-WinEvent -FilterHashtable $q -ErrorAction Stop)) {
|
|
$res.events += @{ id = [int]$e.Id; provider = [string]$e.ProviderName; time = $e.TimeCreated.ToUniversalTime(); message = [string]$e.Message }
|
|
}
|
|
} catch {
|
|
if ($_.FullyQualifiedErrorId -notlike '*NoMatchingEventsFound*') { throw }
|
|
}
|
|
}
|
|
} catch {
|
|
$res.status = $Unreadable
|
|
}
|
|
return $res
|
|
}
|
|
|
|
function ConvertTo-EventRecord($E) {
|
|
$first = ($E.message -split "`r?`n" | Select-Object -First 1)
|
|
if ($null -eq $first) { $first = '' }
|
|
if ($first.Length -gt 300) { $first = $first.Substring(0, 300) }
|
|
return [ordered]@{ id = $E.id; provider = $E.provider; time_utc = (Format-Utc $E.time); message_first_line = $first }
|
|
}
|
|
|
|
$raw = Get-RawEvents $refUtc
|
|
$kp = @(); $bc = @()
|
|
if ($raw.status -eq 'ok') {
|
|
$after = @($raw.events | Where-Object { $null -ne $_.time -and $_.time -ge $refUtc } | Sort-Object { $_.time })
|
|
$kp = @($after | Where-Object { $_.id -eq 41 -and $_.provider -eq 'Microsoft-Windows-Kernel-Power' } | ForEach-Object { ConvertTo-EventRecord $_ })
|
|
$bc = @($after | Where-Object { $_.id -eq 1001 -and $_.provider -match 'WER-SystemErrorReporting|BugCheck' } | ForEach-Object { ConvertTo-EventRecord $_ })
|
|
} else {
|
|
Add-Unreadable 'crash_evidence'
|
|
}
|
|
$crash = [ordered]@{
|
|
query_status = $raw.status
|
|
reference_time_utc = (Format-Utc $refUtc)
|
|
reference_time_source = $refSource
|
|
kernel_power_41 = $kp
|
|
bugcheck = $bc
|
|
count = ($kp.Count + $bc.Count)
|
|
}
|
|
|
|
# ---------------------------------------------------------------- post-abort check
|
|
$paDoc = $null
|
|
$postAbortClean = $true
|
|
if ($PostAbort) {
|
|
$reasons = @()
|
|
$left = @($procs | Where-Object { $_.name -like 'leleka-*' -or $_.name -like 'strata-*' } | ForEach-Object { [ordered]@{ name = $_.name; id = $_.id } })
|
|
if ($snap.status -ne 'ok') { $reasons += 'process_list_unreadable' }
|
|
if ($left.Count -gt 0) { $reasons += ('leftover_process:' + (($left | ForEach-Object { $_.name }) -join ',')) }
|
|
|
|
$apps = @()
|
|
$ca = Invoke-QueryTool -Name 'nvidia-smi' -ToolArgs @('--query-compute-apps=pid,process_name,used_memory', '--format=csv,noheader')
|
|
if ($ca.status -eq 'ok') {
|
|
foreach ($l in ($ca.text -split "`r?`n")) {
|
|
if (-not $l.Trim()) { continue }
|
|
$f = @($l -split ',' | ForEach-Object { $_.Trim() })
|
|
$apps += [ordered]@{ pid = $f[0]; process_name = $(if ($f.Count -gt 1) { $f[1] } else { '' }); used_memory = $(if ($f.Count -gt 2) { $f[2] } else { '' }) }
|
|
}
|
|
if ($apps.Count -gt 0) { $reasons += ('compute_app:' + (($apps | ForEach-Object { $_.process_name + '(pid ' + $_.pid + ')' }) -join ',')) }
|
|
} else {
|
|
$reasons += 'compute_apps_unreadable'
|
|
Add-Unreadable 'post_abort.compute_apps'
|
|
}
|
|
$postAbortClean = ($reasons.Count -eq 0)
|
|
$paDoc = [ordered]@{
|
|
clean = $postAbortClean
|
|
leftover_processes = $left
|
|
compute_apps_status = $ca.status
|
|
compute_apps = $apps
|
|
reasons = $reasons
|
|
}
|
|
}
|
|
|
|
# ---------------------------------------------------------------- assemble and print
|
|
$exitCode = 0
|
|
if ((Test-Unreadable $enforced) -or (Test-Unreadable $maxLimit)) { $exitCode = 4 }
|
|
elseif ($PostAbort -and -not $postAbortClean) { $exitCode = 5 }
|
|
|
|
$doc = [ordered]@{
|
|
schema_version = 1
|
|
tool = 'scripts/laptop/win/state.ps1'
|
|
read_only = $true
|
|
source = $(if ($UseFixture) { 'fixture' } else { 'live' })
|
|
mode = $(if ($PostAbort) { 'post_abort' } else { 'state' })
|
|
settings = [ordered]@{
|
|
power_scheme_guid = $schemeGuid
|
|
power_scheme_name = $schemeName
|
|
timeouts_s = $timeouts
|
|
ac_status = $acStatus
|
|
enforced_power_limit = $enforced
|
|
power_limit_unit = 'W'
|
|
power_max_limit_w = $maxLimit
|
|
owner_attestation = @('unlocked_screen', 'sign_in_requirement', 'oem_turbo')
|
|
owner_attestation_status = 'required'
|
|
}
|
|
gpu = $gpu
|
|
boot_time_utc = (Format-Utc $bootUtc)
|
|
crash_evidence = $crash
|
|
wsl_docker = $wslDocker
|
|
top_processes = $top
|
|
time_utc = (Format-Utc ((Get-Date).ToUniversalTime()))
|
|
unreadable_fields = @($UnreadableFields)
|
|
exit_code = $exitCode
|
|
}
|
|
if ($PostAbort) { $doc['post_abort'] = $paDoc }
|
|
|
|
$json = ConvertTo-Json -InputObject $doc -Depth 8
|
|
Write-Output $json
|
|
if ($OutFile) {
|
|
$dir = Split-Path -Parent $OutFile
|
|
if ($dir -and -not (Test-Path -LiteralPath $dir)) { [void][System.IO.Directory]::CreateDirectory($dir) }
|
|
[System.IO.File]::WriteAllText($OutFile, $json + "`r`n", (New-Object System.Text.UTF8Encoding($false)))
|
|
}
|
|
exit $exitCode
|