Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 31 additions & 1 deletion Extension/Summary.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,13 @@ param(
# -SkipConsumption was used; the check is silently skipped in that case.
$ConsumptionFile,

# Collector failures for this run: objects with a Module property naming
# the resource type whose collector threw. A failed type serialises as an
# empty array and its section is dropped from the report, which reads the
# same as a subscription that has none of that type, so the report names
# these types in a banner. Optional; omitted on standalone invocations.
$CollectorFailures = @(),

# Minimum running-VM-vs-billed shortfall (count) required before the VM
# billing-coverage banner is shown. Default 0 means any shortfall is
# surfaced; raise it to suppress small billing-lag noise.
Expand Down Expand Up @@ -670,6 +677,7 @@ footer {
color: #856404;
}
.coverage-banner b { font-weight: 600; }
.incomplete-note { font-weight: 600; color: #7d2019; }
.coverage-icon { font-size: 16px; }
@media print {
body { background: white; font-size: 11px; }
Expand Down Expand Up @@ -819,6 +827,21 @@ else
$PrivacyBanner = '<div class="privacy-banner identifiable"><span class="privacy-icon">&#9888;</span><div><b>Identifiable report.</b> Contains real subscription, resource group, and resource names. Treat as confidential and avoid sharing outside intended recipients. Re-run with <code>-Obfuscate</code> to produce a sharable report.</div></div>'
}

# Collector-failure banner. A resource type whose collector threw is absent
# from the tables, which reads the same as a subscription that has none of that
# type; this banner is the only place the report tells the two apart. The guard
# counts every non-null record, so a record without a Module name still shows
# the banner (as '(unnamed collector)') instead of hiding it.
$CollectorBanner = ''
$CollectorNames = @()
$CollectorFailureList = @(@($CollectorFailures) | Where-Object { $null -ne $_ })
if ($CollectorFailureList.Count -gt 0)
{
$CollectorNames = @($CollectorFailureList | ForEach-Object { if ([string]::IsNullOrWhiteSpace([string]$_.Module)) { '(unnamed collector)' } else { [string]$_.Module } } | Sort-Object -Unique)
$CollectorNameList = (($CollectorNames | ForEach-Object { '<code>' + (ConvertTo-HtmlSafe $_) + '</code>' }) -join ', ')
$CollectorBanner = ('<div class="coverage-banner"><span class="coverage-icon">&#9888;</span><div><b>Incomplete collection:</b> {0} resource type(s) could not be collected and are MISSING from this report - not empty because there are none, but because the collector errored: {1}. See the Diagnostics log in this bundle for the underlying error, then re-run.</div></div>' -f $CollectorNames.Count, $CollectorNameList)
}

# VM billing-coverage banner. Rendered only when the inventory shows materially
# more running VMs than the consumption data billed for (see the $VmBilling
# detection above). Frames the inventory as authoritative and points at
Expand Down Expand Up @@ -866,12 +889,14 @@ $ReportBlock
$RenderBlock
$PlatBlock
<div><b>Total Resources:</b> $TotalResources</div>
<div><b>Service Types:</b> $($ServiceSummary.Count)</div>
<div><b>Service Types:</b> $($ServiceSummary.Count)$(if ($CollectorBanner) { ' <span class="incomplete-note">(collection incomplete, see below)</span>' })</div>
</div>
</header>

$PrivacyBanner

$CollectorBanner

$CoverageBanner

<div class="charts">
Expand Down Expand Up @@ -914,3 +939,8 @@ else
{
Write-Host " Privacy posture: identifiable (contains real names; treat as confidential)" -ForegroundColor Yellow
}
# Last, so the summary block cannot end on a clean line over an incomplete report.
if ($CollectorBanner)
{
Write-Host (" Collection INCOMPLETE: {0} resource type(s) missing because the collector errored: {1}" -f $CollectorNames.Count, ($CollectorNames -join ', ')) -ForegroundColor Yellow
}
13 changes: 10 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -619,11 +619,18 @@ A direct run of `ResourceInventory.ps1` (without `-RunAllSubs`) exits `1` and wr

Codes `3`–`5` still mean the report was produced — they flag that it is **incomplete** in a specific, diagnosable way, rather than silently looking like a clean/empty result.

### Exit Codes 1 and 2 (ResourceInventory.ps1, direct run)
### Exit Codes (ResourceInventory.ps1, direct run)

A direct `ResourceInventory.ps1` run (without `-RunAllSubs`) that ends without writing its report zip exits `2`, and its last console line says `No report was written`. This happens, for example, when 5 collectors failed in a row and collection stopped, or when the HTML report or the zip could not be written; the errors printed before that line give the cause. Under `-RunAllSubs` the script's exit code is unchanged and the wrapper's codes above apply.
A direct `ResourceInventory.ps1` run (without `-RunAllSubs`) also sets an exit code:

A run that stops during setup, before it collects anything, exits `1`, and the red error line printed before it gives the cause: for example the output folder cannot be written, the Azure CLI is not installed, a service principal sign-in has no `-Secret`, or `-ResourceGroup` is given without `-SubscriptionID`. Under `-RunAllSubs` the wrapper counts that subscription as failed.
| Code | Meaning |
|---|---|
| `0` | Completed: the report and zip were written and no collector failed. |
| `1` | The run stopped during setup or a pre-flight check, before it collected anything; the red error line printed before it gives the cause. For example the output folder cannot be written, the Azure CLI is not installed, a service principal sign-in has no `-Secret`, `-ResourceGroup` is given without `-SubscriptionID`, `-Service` matched no collector, or the `-ObfuscationDictionary` file is missing or not valid JSON. |
| `2` | The run ended without writing its report zip, and its last console line says `No report was written`. This happens, for example, when 5 collectors failed in a row and collection stopped, or when the HTML report or the zip could not be written; the errors printed before that line give the cause. |
| `4` | Completed and the report and zip were written, but one or more `Services/*/*.ps1` collectors failed. Those resource types are missing (not empty) from the report; its "Incomplete collection" banner names them. |

Under `-RunAllSubs`, which is how `Run-AllSubscriptions.ps1` calls it, the script does not exit `2` or `4`: the wrapper checks each subscription's zip itself and reports a failed collector with its own code `4` above. A run that stops during setup (`1`) is counted by the wrapper as a failed subscription.

### Important Notes

Expand Down
39 changes: 37 additions & 2 deletions ResourceInventory.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -1568,11 +1568,15 @@ function ExecuteInventoryProcessing()
Write-Log -Message ("FAIL ({0}/{1}) {2}: {3}" -f $ModuleIndex, $ModuleTotal, $ModName, $_.Exception.Message) -NoConsole -ToDebugLog

if ($null -eq $Global:CollectorFailures) { $Global:CollectorFailures = @() }
$Global:CollectorFailures += [pscustomobject]@{
$CollectorFailure = [pscustomobject]@{
Id = $SubscriptionID
Module = $ModName
Message = $_.Exception.Message
}
$Global:CollectorFailures += $CollectorFailure
# $Global:CollectorFailures is a running total across every subscription a wrapper run
# processes; this list holds only this run's failures, for this run's HTML report.
$script:CollectorFailuresThisRun += $CollectorFailure

Write-Log -Message ("Collector FAILED: {0}: {1}" -f $ModName, $_.Exception.Message) -Severity 'Error'
Write-Log -Message ("The rest of the inventory will continue, but the '{0}' resource type is MISSING from this report - not empty because there are none, but because the collector errored. Re-run to retry, or investigate the error above if it repeats." -f $ModName) -Severity 'Error'
Expand Down Expand Up @@ -1985,6 +1989,7 @@ function ExecuteInventoryProcessing()
InitializeInventoryProcessing

$script:PhaseTimings = [ordered]@{}
$script:CollectorFailuresThisRun = @()

$MetricsPhaseTimer = [System.Diagnostics.Stopwatch]::StartNew()
CreateMetricsJob
Expand Down Expand Up @@ -2066,11 +2071,33 @@ function FinalizeOutputs
}

$ReportTenantId = if ($Obfuscate.IsPresent) { $null } else { $TenantID }
# The header's subscription, for a run of one subscription: a subscription
# with no resources has no record for Summary.ps1 to take the name from.
# A run without -SubscriptionID over several subscriptions says how many
# it covers (a count, so nothing to mask under -Obfuscate); naming the
# first record's subscription would label the whole report with one.
# Otherwise, under -Obfuscate, Summary.ps1 keeps taking it from the
# first record (the masked name).
# The count is of the subscriptions such a run inventories: the list
# 'az account list' gives (outside Cloud Shell, LoginSession narrows it
# to -TenantID when one is given), with the same filter az applies by
# default (state exactly 'Enabled'), so a Disabled or Warned entry is
# never counted as covered.
$ReportSubscriptionName = $null
$RunSubscriptionCount = @(@($Global:Subscriptions) | Where-Object { $null -ne $_ -and [string]$_.state -ceq 'Enabled' }).Count
if ([string]::IsNullOrEmpty($SubscriptionID) -and $RunSubscriptionCount -gt 1)
{
$ReportSubscriptionName = '{0} subscriptions (consolidated)' -f $RunSubscriptionCount
}
elseif (-not $Obfuscate.IsPresent -and -not [string]::IsNullOrEmpty($SubscriptionID))
{
$ReportSubscriptionName = [string](@($Global:Subscriptions) | Where-Object { $null -ne $_ -and [string]$_.id -eq $SubscriptionID } | Select-Object -First 1).name
}
$ReportTitle = ('Azure Resource Inventory - {0}' -f $Global:ReportName)

try
{
$null = & $SummaryPath -JsonFile $Global:JsonFile -HtmlFile $Global:HtmlFile -Title $ReportTitle -TenantId $ReportTenantId -Version $Global:Version -ExtractionRunTime $Runtime -ReportingRunTime $ReportingRunTime -PhaseTimings $script:PhaseTimings -PlatOS $PlatformOS -ConsumptionFile $Global:ConsumptionFileCsv
$null = & $SummaryPath -JsonFile $Global:JsonFile -HtmlFile $Global:HtmlFile -Title $ReportTitle -SubscriptionName $ReportSubscriptionName -TenantId $ReportTenantId -Version $Global:Version -ExtractionRunTime $Runtime -ReportingRunTime $ReportingRunTime -PhaseTimings $script:PhaseTimings -PlatOS $PlatformOS -ConsumptionFile $Global:ConsumptionFileCsv -CollectorFailures $script:CollectorFailuresThisRun
}
catch
{
Expand Down Expand Up @@ -2469,3 +2496,11 @@ else
# subscription and checks each subscription's zip itself.
if (-not $RunAllSubs.IsPresent) { exit 2 }
}

# A direct run that lost a collector still writes the report and zip, then exits 4.
# Under -RunAllSubs the wrapper treats any non-zero exit as a failed subscription and
# reports collector failures through its own exit code, so this is skipped there.
# The zip check keeps 4 to runs that produced their report: Compress-Archive writes no
# zip when the HTML report is missing.
$CollectorFailureCount = @(@($script:CollectorFailuresThisRun) | Where-Object { $null -ne $_ }).Count
if (-not $RunAllSubs.IsPresent -and $CollectorFailureCount -gt 0 -and (Test-Path -LiteralPath $Global:ZipOutputFile)) { exit 4 }
141 changes: 141 additions & 0 deletions Tests/CollectorFailureBanner.Tests.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
# Collector-failure banner tests
# Run with: Invoke-Pester ./Tests/CollectorFailureBanner.Tests.ps1 -Output Detailed
#
# WHY THIS TEST EXISTS
# --------------------
# When a Services/*/*.ps1 collector throws, ResourceInventory.ps1 logs the
# error and carries on. The failed type serialises as an empty array, so its
# section is dropped from the HTML report, which then reads the same as a
# subscription that has none of that type. Summary.ps1 takes this run's
# collector failures (-CollectorFailures) and names the missing types in a
# banner at the top of the report and in a console line at the end of its
# output.
#
# This test is SELF-CONTAINED: it builds a tiny Inventory JSON in a temp dir,
# invokes the REAL Extension/Summary.ps1, and asserts on the written HTML and
# the console output. No live Azure, no output zip. Generic names only.

BeforeAll {
$script:SummaryScript = Join-Path -Path $PSScriptRoot -ChildPath '..' -AdditionalChildPath 'Extension', 'Summary.ps1' | Resolve-Path | Select-Object -ExpandProperty Path
$script:WorkDir = Join-Path ([System.IO.Path]::GetTempPath()) ("CollectorFailureBanner_" + [guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory -Path $script:WorkDir -Force | Out-Null

# Two populated service types, so the report renders normally around the
# banner. The VMSS key is an empty array, which is how a failed collector's
# type reaches the Inventory JSON.
$script:Inventory = [pscustomobject]@{
StorageAcc = @(
[pscustomobject]@{ Name = 'storage-demo-01'; Subscription = 'sub-demo'; Location = 'eastus'; ResourceGroup = 'rg-demo' },
[pscustomobject]@{ Name = 'storage-demo-02'; Subscription = 'sub-demo'; Location = 'eastus'; ResourceGroup = 'rg-demo' }
)
KeyVault = @(
[pscustomobject]@{ Name = 'kv-demo-01'; Subscription = 'sub-demo'; Location = 'eastus'; ResourceGroup = 'rg-demo' }
)
VMSS = @()
}

function New-Failure
{
param($Module, [string]$Message = 'collector error')
[pscustomobject]@{ Id = '12345678-1234-1234-1234-123456789012'; Module = $Module; Message = $Message }
}

# Runs Summary.ps1 and returns the HTML plus the console lines it wrote.
# -CollectorFailures is passed only when the caller supplies it, so the
# omitted case is the standalone invocation.
function Invoke-Summary
{
param($CollectorFailures)

$JsonPath = Join-Path $script:WorkDir ('inv_{0}.json' -f [guid]::NewGuid().ToString('N'))
$HtmlPath = Join-Path $script:WorkDir ('rpt_{0}.html' -f [guid]::NewGuid().ToString('N'))
$script:Inventory | ConvertTo-Json -Depth 8 | Out-File -FilePath $JsonPath -Encoding utf8

$Params = @{ JsonFile = $JsonPath; HtmlFile = $HtmlPath }
if ($PSBoundParameters.ContainsKey('CollectorFailures')) { $Params['CollectorFailures'] = $CollectorFailures }

$Console = @(& $script:SummaryScript @Params 6>&1 | ForEach-Object { [string]$_ })
return [pscustomobject]@{
Html = (Get-Content -Path $HtmlPath -Raw)
Console = $Console
}
}
}

AfterAll {
if ($script:WorkDir -and (Test-Path $script:WorkDir))
{
Remove-Item -Path $script:WorkDir -Recurse -Force -ErrorAction SilentlyContinue
}
}

Describe 'Collector-failure banner in the HTML report' {

It 'names the failed resource type when one collector failed' {
$R = Invoke-Summary -CollectorFailures @(New-Failure -Module 'VMSS')

# Assert on the rendered banner text, not the CSS class name
# ('.coverage-banner' is always present in the <style> block).
$R.Html | Should -Match '<b>Incomplete collection:</b> 1 resource type\(s\) could not be collected and are MISSING from this report'
$R.Html | Should -Match 'the collector errored: <code>VMSS</code>\.'
$R.Html | Should -Match '<b>Service Types:</b> 2 <span class="incomplete-note">\(collection incomplete, see below\)</span>'
}

It 'lists each failed type once, sorted, when several failed' {
$Failures = @(
(New-Failure -Module 'VMSS'),
(New-Failure -Module 'AKS'),
(New-Failure -Module 'VMSS')
)
$R = Invoke-Summary -CollectorFailures $Failures

$R.Html | Should -Match '<b>Incomplete collection:</b> 2 resource type\(s\)'
$R.Html | Should -Match 'the collector errored: <code>AKS</code>, <code>VMSS</code>\.'
}

It 'still shows the banner for a failure record with no collector name' {
$R = Invoke-Summary -CollectorFailures @(New-Failure -Module ' ')

$R.Html | Should -Match '<b>Incomplete collection:</b> 1 resource type\(s\)'
$R.Html | Should -Match '<code>\(unnamed collector\)</code>'
}

It 'HTML-escapes the collector name' {
$R = Invoke-Summary -CollectorFailures @(New-Failure -Module '<b>x</b>')

$R.Html | Should -Match '<code>&lt;b&gt;x&lt;/b&gt;</code>'
}

It 'renders no banner when -CollectorFailures is omitted' {
$R = Invoke-Summary

$R.Html | Should -Not -Match 'Incomplete collection'
$R.Html | Should -Not -Match '<span class="incomplete-note">'
}

It 'renders no banner when the failure list is empty or holds only nulls' {
$Empty = Invoke-Summary -CollectorFailures @()
$Empty.Html | Should -Not -Match 'Incomplete collection'
$Empty.Html | Should -Not -Match '<span class="incomplete-note">'

$NullOnly = Invoke-Summary -CollectorFailures @($null)
$NullOnly.Html | Should -Not -Match 'Incomplete collection'
$NullOnly.Html | Should -Not -Match '<span class="incomplete-note">'
}
}

Describe 'Collector-failure line in the console output' {

It 'ends the summary output with a line naming the failed types' {
$R = Invoke-Summary -CollectorFailures @((New-Failure -Module 'VMSS'), (New-Failure -Module 'AKS'))

$R.Console[-1] | Should -Be ' Collection INCOMPLETE: 2 resource type(s) missing because the collector errored: AKS, VMSS'
($R.Console | Where-Object { $_ -match '^ Total resources:' }) | Should -Not -BeNullOrEmpty
}

It 'writes no such line when nothing failed' {
$R = Invoke-Summary -CollectorFailures @()

($R.Console | Where-Object { $_ -match 'Collection INCOMPLETE' }) | Should -BeNullOrEmpty
}
}
Loading