Repository navigation
fix(logs)!: end the agent-log commands with terminating errors - #89
Conversation
Get-IntuneAgentLog, Get-IntuneAgentTimeline and Export-IntuneAgentDiagnostic, and the two private functions that parse the logs, ended on a failure with throw. A throw is suppressed by a caller's -ErrorAction SilentlyContinue, after which the function carries on as if it had succeeded, and it carries no error ID. They now end with $PSCmdlet.ThrowTerminatingError() and a record that has an ID and a category of its own (ERR-10, ERR-11, ERR-14). That change is not safe by itself. ThrowTerminatingError ends only the function that calls it: the module function that made the call goes on at its next statement, with nothing where the result should be, unless the call is inside a try that has a catch. So each of the five functions also guards its calls that way: the read of the logs in Get-IntuneAgentLog and Get-IntuneAgentTimeline, the file access in ConvertFrom-IslCmTraceLog, and the whole transaction of Export-IntuneAgentDiagnostic, which had a try with only a finally. New, for this area and the ones that follow (#64): - New-IslErrorRecord builds the record. It does not fail for any input, because it is called in the argument of ThrowTerminatingError and an error there would end only that statement. - Tests/Unit/Module.ErrorFlow.Tests.ps1 checks the rule on the syntax trees: no call to a function that ends with ThrowTerminatingError outside a try with a catch. It lists the 46 calls that still rely on a throw, and the list has to match the code. Behaviour does not show a missing guard reliably: with the guard of Get-IntuneAgentTimeline removed, its tests still passed, and this test failed and named the call. - Invoke-CallerScript, a test helper, runs statements from a script in a new process that has no try, for what such a caller sees. BREAKING CHANGE: a script that calls Get-IntuneAgentLog, Get-IntuneAgentTimeline or Export-IntuneAgentDiagnostic without try and without $ErrorActionPreference = 'Stop' now goes on at its next statement after the command fails, where it used to end. Set the preference at the top of the script, or make the call inside try. Refs #64
fadwen
left a comment
There was a problem hiding this comment.
Notes on the lines whose reason the diff does not show.
| # statement, and the timelines would be built from nothing | ||
| try { | ||
| $entries = @(Get-IntuneAgentLog @logSplat) | ||
| } catch { |
There was a problem hiding this comment.
This guard changes nothing a test of behaviour can see. Without it the command goes on with no entries and returns no timelines, which is also what it returns when it stops here; the 11 tests of this command passed with the guard removed. It is here because the rule has to hold everywhere to hold where it matters, and Module.ErrorFlow.Tests.ps1 is what fails when it is missing.
| } | ||
| $entryCount = Compress-Staging -Folder $staging -Destination $zip | ||
| } | ||
| catch { |
There was a problem hiding this comment.
The try had only a finally. A terminating error raised by a function called inside it, such as the read of a log with a bad timestamp for the timeline, ended that one statement, and the command went on to write the manifest and the zip. With the catch the command ends, and the finally still removes the staging folder. Measured from a script without try: no zip is written, and an existing one is left as it was.
| $kept = @(ConvertFrom-IslCmTraceLog -Path $file @parseSplat) | ||
| try { | ||
| $kept = @(ConvertFrom-IslCmTraceLog -Path $file @parseSplat) | ||
| } catch { |
There was a problem hiding this comment.
A log that cannot be parsed still ends the whole command, as the throw in the parser did. ERR-13 would report the file with WriteError and go on with the other logs. That would be a change of behaviour of its own, so it is left as a question in the description.
| $exception = $ExceptionType::new($Message, $InnerException) -as [System.Exception] | ||
| } catch { | ||
| # The type has no such constructor. The record is still built: see the description | ||
| Write-Debug "No $($ExceptionType.FullName) could be built for error $ErrorId." |
There was a problem hiding this comment.
An earlier form of this function validated the ID with a pattern and ended with an error for a type it could not build. Both made it possible for the function to fail in the argument of ThrowTerminatingError, which ends that statement only: the caller would have gone on past the failure it had just detected. So it accepts anything and falls back to InvalidOperationException. The typo that validation would have caught is caught by the tests that assert each ID.
| # The caller would carry on with nothing where the result should be. The one exception is | ||
| # the cleanup after a timeout: measured, a failure of it leaves the run with its TimedOut | ||
| # result and without its output. It goes with the runtime harness, the next area of #64 | ||
| $known = @( |
There was a problem hiding this comment.
The one known exception, from #87. Stop-IslProcessTree ends with ThrowTerminatingError when taskkill.exe cannot be started, and Invoke-IslProcess calls it outside a try with a catch. Measured, the run then returns its TimedOut result without its output. Guarding it means deciding what a timed-out run returns when its cleanup fails, which belongs with the rest of Invoke-IslProcess in the next area.
| Wait = $true | ||
| PassThru = $true | ||
| } | ||
| $process = Start-Process @startParameters |
There was a problem hiding this comment.
Start-Process with the streams redirected to files, not the call operator: the script is expected to write errors, and Windows PowerShell 5.1 turns what a native command writes to a redirected error stream into error records, which end the test under the error preference of a CI step. That is the mechanism of #86.
Get-IntuneAgentLog ended at the first path that did not exist and at the first log it could not read or parse. Each path and each log is one item of its input, and the others can still be read, so such an item is now reported with WriteError and the command goes on (ERR-13). A caller that wants the command to end there passes -ErrorAction Stop. A path that cannot be resolved no longer draws the warning about a folder without logs as well: the error has said why nothing came back. Get-IntuneAgentTimeline and Export-IntuneAgentDiagnostic read the logs through this command. The timelines are built from the logs that could be read, and the package is still written, with every log in it, which is what a ticket needs most when one log is damaged. Refs #64
|
ERR-13 is now applied in bd4cf8a, as decided: |
fadwen
left a comment
There was a problem hiding this comment.
Verdict: approve. No blockers or should-fixes, one nit.
Reviewed against ai-powershell-standards (ERR-10, ERR-11, ERR-13, ERR-14). Checked in a Linux sandbox with pwsh 7.6.0 and Pester 6.2.0.
Verified
- No regressions (differential run): full unit suites on #87 and on this branch, same seed.
- Passes went from 871 to 886.
- The 5 new failures on Linux are all platform-related:
Start-Process -WindowStylein the newInvoke-CallerScripthelper is not supported on Linux, and Windows paths giveDriveNotFound. None of them is a logic failure. - No test that passed on #87 fails here.
Module.ErrorFlow.Tests.ps1catches a missing guard, as claimed: I removed thetry/catcharoundGet-IntuneAgentLoginGet-IntuneAgentTimeline. The test then failed and namedGet-IntuneAgentTimeline -> Get-IntuneAgentLog. With the guard back it passes 3/3.New-IslErrorRecord.Tests.ps1: 8/8. The fallback toInvalidOperationExceptionmeans building a record can't itself fail inside the argument ofThrowTerminatingError.- The four
throwstatements: each is replaced with an ID and a category. The IDs match the description. - The
!and the CHANGELOG: both mark the behaviour change for callers. - ERR-13 in
Get-IntuneAgentLog: a path that can't be resolved and a log that can't be parsed are each reported withWriteError, and the command goes on with the rest.- The warning about a folder without logs is now skipped only when every path failed, which is right.
- Under
-ErrorAction Stopgiven toGet-IntuneAgentTimeline, the innerWriteErrorbecomes terminating and reaches the outercatch, so the timeline ends as documented.
Unverified (needs Windows or CI): the caller-script runs on 5.1 and 7.6, and CI runs 45268336847 and 45273313845. This PR has no checks because its base isn't main.
Nit: Tests/TestHelpers/TestHelpers.ps1, Invoke-CallerScript. It uses Start-Process -WindowStyle, which exists only on Windows. That's fine for a suite that is Windows-only, but splatting WindowStyle only when $IsWindows is true (or on 5.1) would let the error-flow tests run on the Linux help job too, if you ever want that.
Invoke-CallerScript started its child process with -WindowStyle Hidden. Start-Process has that parameter on Windows only, so the helper failed on Linux before it ran anything. The suites are Windows-only, but the Linux job imports the module and could run the tests of the error flow one day. The parameter is now added to the call on Windows alone. Refs #64
|
The nit is addressed in 07f7f5f.
|
Summary
The first area of #64: the commands that read the agent's logs.
Get-IntuneAgentLog,Get-IntuneAgentTimeline,Export-IntuneAgentDiagnosticand the two private functions that parse the logs ended on a failure withthrow. A caller's-ErrorAction SilentlyContinuesuppresses athrowand lets the function carry on, and athrowof a string has no error ID. They now end with$PSCmdlet.ThrowTerminatingError()and a record that has an ID and a category (ERR-10, ERR-11, ERR-14). Refs #64, which stays open for the other three areas.Replacing the
throwstatements alone would have made the module worse.ThrowTerminatingErrorends only the function that calls it: the module function that made the call goes on at its next statement with nothing where the result should be, unless the call is inside atrythat has acatch. The measurements are in a comment on #64. So this change also guards the calls, and adds a test that holds the rule for the whole module.This pull request is stacked on #87 (
fix/process-tree-cleanup) and merges after it.This changes what a caller sees. A script that calls one of the three commands without
tryand without$ErrorActionPreference = 'Stop'now goes on at its next statement after the command fails, where it used to end. That is the behaviour of a compiled cmdlet and the one ERR-10 chooses.Changes
throwstatements of the area are replaced, inGet-IntuneAgentLog,Export-IntuneAgentDiagnostic,ConvertFrom-IslCmTraceLogandConvertTo-IslCmTraceTime. The IDs areUnknownAgentLogEvent(Get-IntuneAgentLog -EventName),CmTraceTimestampInvalid(both parsers) andDiagnosticPackageExists(Export-IntuneAgentDiagnosticwithout-Force).trywith acatchthat ends the function: the path resolution and the parse inGet-IntuneAgentLog, the read inGet-IntuneAgentTimeline, the file access inConvertFrom-IslCmTraceLog, and the whole transaction ofExport-IntuneAgentDiagnostic, whosetryhad only afinally.Get-IntuneAgentLogreports a path that does not exist, and a log it cannot read or parse, withWriteErrorand goes on with the other paths and logs (ERR-13); the first such item used to end the command.-ErrorAction Stopends it there.Get-IntuneAgentTimelineandExport-IntuneAgentDiagnosticread the logs through it, so the timelines are built from the logs that could be read and the package is still written, with every log in it. A path that cannot be resolved no longer draws the warning about a folder without logs as well.New-IslErrorRecordbuilds the record: message, ID, category, target, exception type and inner exception. It does not fail for any input, because it is called in the argument ofThrowTerminatingError, where an error would end only that statement and the function would go on as if it had detected nothing.Tests/Unit/Module.ErrorFlow.Tests.ps1checks the rule on the syntax trees ofPublic,PrivateandPrivate/Rules, nested functions included: no call to a function that ends withThrowTerminatingErroroutside atrywith acatch. It also lists the 46 calls that still rely on athrowin the function they call, and that list has to match the code exactly, so it shrinks with each area and a new unguarded call fails the test.Invoke-CallerScriptruns statements as a script in a new process that has notryand the default error preference, and returns what the script wrote and the IDs of the errors the session recorded.Should-Throw -FullyQualifiedErrorId, and each has a test throughInvoke-CallerScript.README.mdhas a troubleshooting row for a script that goes on after one of these commands failed,CHANGELOG.mdhas the entry under Changed with the consequence for callers, andCLAUDE.mdrecords the invariant.Verification
try, in a new process, on PowerShell 7.6.10 and Windows PowerShell 5.1, six failure cases (a missing folder, an unknown event, a log with a bad timestamp, an existing zip, and the last two through the timeline and the export). Before this change each ended the script with no output. After it, a bad argument and an existing package end the command with the one error of that failure, and the script goes on. A missing path and a log with a bad timestamp are reported once for that item, and the command returns what the other logs hold.Get-IntuneAgentTimelineremoved, the 11 tests of that command still passed, because going on with no entries also returns no timelines, andModule.ErrorFlow.Tests.ps1failed and namedGet-IntuneAgentTimeline -> Get-IntuneAgentLog../Tests/Invoke-Tests.ps1 -CodeCoverageon PowerShell 7.6.10: 1,086 passed, 3 failed, 7 skipped, coverage 95.22 percent../Tests/Invoke-Tests.ps1on Windows PowerShell 5.1: 1,050 passed, 3 failed, 43 skipped. The three failures are the ones that fail on that computer without this change and pass in CI (Repair-IntuneScript corrupts an ANSI script on a host with a UTF-8 system code page #75 twice, In-box module table does not list UOPProviders, present on Windows 11 26H2 #76).Invoke-ScriptAnalyzerat Error and Warning on the 13 changed script files: no findings.Test-StandardsCompliance.ps1of ai-powershell-standards 2.0.0: no finding in the three new files, and no ERR-11 finding left in the five converted ones../Build/Publish-Module.ps1 -WhatIf: the staged module imports, exports the declared commands and serves its help.quality-gates.yml, dispatched on this branch because it triggers only for pull requests intomain, run 45268336847: all five jobs passed. After the commit for ERR-13, run 45273313845: all five jobs passed.Notes
ThrowTerminatingErroris listed in the test as a known exception:Invoke-IslProcess -> Stop-IslProcessTree, the cleanup after a timeout. Measured, a failure of it leaves the run with itsTimedOutresult and without its output. It is fixed with the runtime harness, the next area.Export-IntuneAgentDiagnosticreads the logs twice, for the events and for the timelines, so it reports a log that cannot be parsed twice.throwstatements in nested and plain functions are untouched; they stay allowed until Nested helper functions have no CmdletBinding, help or parameter types (FUN-01, DOC-01, FUN-20, MOD-01) #65 makes those functions advanced.