Repository navigation
Memory 1/4: write the inventory per collector and release its data - #41
Conversation
ProcessResourceResult serialised the whole inventory with one ConvertTo-Json call and piped the string to Out-File. On a large estate that string, built on top of the collector objects already in memory, can run out of memory. - Add Write-InventoryJson, which writes the inventory object one property (collector) at a time through a single StreamWriter, and call it from ProcessResourceResult instead of the pipeline. - The output is unchanged: the file is byte-for-byte what the previous pipeline wrote (UTF-8 without BOM, a one-element collector still written as an array, Version last, trailing newline, same depth limit). - The whole inventory is no longer built as one JSON string; the largest string is now one collector's JSON. - The file is written to a temporary file in the same folder and moved into place only when complete, so a failed write leaves no cut-off inventory; the temporary file is removed and the error re-thrown. - Add Tests/InventoryWrite.Tests.ps1: byte equality with the previous output, array and encoding details, no whole-document ConvertTo-Json call, relative path, replacing an existing file, and that a failed write throws and leaves neither the inventory nor the temporary file.
On a large estate the HTML report step ran out of memory while the collector output ($Global:SmaResources) and the raw discovery rows ($Global:Resources) were still held, although nothing reads either once the inventory is written. - Release both after ProcessResourceResult and run a full collection. - Keep the discovered resource count in $Global:ResourceCount. It is reset with $Global:Resources at the start of each run and set when discovery finishes, so an early exit never reports the previous subscription's count. - Run-AllSubscriptions.ps1 and Run-AllSubscriptions.Stream.ps1 read the per-subscription count from $Global:ResourceCount instead of counting $Global:Resources. - Tests: the count after a normal run, after an early exit and after a run that stopped once discovery had finished; the data is released before the report step; each wrapper call site records the count.
…elease its data
|
$GapInventory | ConvertTo-Json -Depth 100 -Compress | Out-File -FilePath $OutInventoryFileA merged inventory is at least as large as the gap run's inventory. Recovering a large estate can therefore hit the same out-of-memory failure and 0-byte file that this PR fixes for the main run. The comment above that line also says the output matches the serialization in Calling |
… the data Setting $Global:SmaResources and $Global:Resources to $null did not free the data on a live run with virtual machines or scale sets. Az cmdlets leave their stream handlers in the shared Azure session when they return. The VM size lookup pipes its output into Where-Object, so its handlers kept the collector, and the rows it was given, referenced until the next Az cmdlet ran. With billing on, the billing step's sign-in check freed them a few seconds later; with -SkipConsumption nothing did before the report step. - Right after the release, and before it collects, read the Azure context once ($null = Get-AzContext -ErrorAction SilentlyContinue). That call replaces the handlers from a scope that holds no rows. - The read sits in a try block. If it fails, the run goes on and one line goes to the debug log. - Output is unchanged. No Azure resource is called. - Tests in Tests/InventoryWrite.Tests.ps1: the read comes after the release and before its first collect and the billing step; there is exactly one; and, in a separate offline pwsh process, the shipped block frees rows that a collector-shaped scope kept through a piped Az call, where a plain statement does not (three rounds). The last test is skipped when Az.Accounts is not installed. The run harness now stubs Get-AzContext, and a test checks it never loads Az.Accounts.
|
Thanks, good catch. Agreed on all three points: Merge-RecoveryData still writes the merged inventory with the whole-document pipeline, a merged inventory is at least as large as the gap run's, and the comment above it is out of date. To keep #41 to the main run, the fix is in #70, which is built on this branch:
|
The read after the release used -ErrorAction SilentlyContinue, so a non-terminating error from Get-AzContext never reached the catch and no debug-log line was written. The comment also named only the VM size lookup, while the scale set collector makes the same piped call later. - Read with -ErrorAction Stop inside the existing try, so every failure is logged to the debug log and the run goes on. With no Azure context the read returns nothing and raises no error. - The comment names the VM or scale set size lookup. - Tests: a non-terminating error, a terminating error and a missing cmdlet are each logged once to the debug log only, and the code after the block runs. The memory test is skipped on Windows, where the child process cannot be kept away from the user's Azure profile. Its comment says why it pipes Get-AzContext rather than the size lookup.
…he release The Azure context read after the release does not always free the collector data. The VM or scale set size lookup also adds a provider-registration handler to the shared Azure client factory, and that handler keeps the lookup cmdlet, and through it the rows the collector was given, referenced. On some live runs the read left that handler in place, so with -SkipConsumption the rows were still held when the report step started. - In the same try block, right after the read, remove that handler by type. The next resource-manager cmdlet adds its own again, so later Azure calls work as before. If the removal fails, the catch writes one line to the debug log and the run goes on. - Output is unchanged. No Azure resource is called. - Tests in Tests/InventoryWrite.Tests.ps1: the removal follows the read in the guarded block; and, in a separate offline pwsh process, the shipped block frees rows that a provider-registration handler kept while the read did nothing, where a plain statement does not, and leaves no such handler in the client factory (three rounds). The last test is skipped where the other memory test is.
…ing zip Write-InventoryJson removes its temporary file and throws when the write fails. ResourceInventory.ps1 runs with ErrorActionPreference 'silentlycontinue', and a direct run has no caller that catches the throw, so the error was never shown: the report step then failed with 'Inventory JSON not found' and the run still printed 'Reporting Data File' for a zip that was never made. ProcessResourceResult now logs the real cause as an error (console, error log and debug log), naming the inventory file and the exception, and then throws it on, so a wrapper run still stops with that cause. The last line of the run names the zip only when it exists, and otherwise says that no report zip was written. Exit codes are unchanged.
Also word the last-line comment and the no-zip check so they hold when a direct run's exit-code check comes first.
… was written The zip step's catch used Write-Error, which the script's 'silentlycontinue' preference hides, so a failed Compress-Archive left no message on the console or in the error log. It now uses Write-Log with the exception. When the HTML report step fails, the run no longer says the inventory, metrics and consumption files were still written: after a failed inventory write that is not true. It says the files the run did write are still in the output folder.
- A zip the failed zip step left behind is removed, so the last line cannot name a cut-off file; a zip that was already there is left alone. - Under -Obfuscate, 'The ZIP file is safe to share' is printed after the zip step and only when the zip exists. - The no-zip line uses the same words as the exit-code check for a direct run that wrote no report: 'No report was written: ...'.
A file at the zip path is not proof that this run wrote it: Compress-Archive refuses to overwrite a zip that was already there, and a zip cut off part-way may not be removable. The zip step now keeps a flag, cleared in its catch, and the 'Reporting Data File' and 'safe to share' lines need it. - A failed removal of the unfinished zip is logged with advice. - 'Please zip the output files manually' is shown only when the inventory and the HTML report are there; otherwise the run says there is no report to zip. - The run times are shown as Info, not Success, when no zip was written.
After a failed inventory write the run no longer prints 'Compressing Resources Output', and 'Reporting Time' says it was not measured instead of printing an empty value. The zip-step comment says the partial-zip removal is a backstop: Compress-Archive removes its own unfinished zip.
…hout a file Under 'silentlycontinue' an input Compress-Archive cannot read was only a hidden error: the zip was made without it and named as the report. The call now uses -ErrorAction Stop, so that zip goes to the catch and is removed, and the run says no report was written. - The 'transcript log excluded from zip' line is printed only when the zip was written. - The zip is this run's report only when the step finished and the file is there; the 'safe to share' and 'Reporting Data File' lines use the same check. - The raw error record dump next to the error line is gone.
…led write - A failed inventory write now frees the collector output and the discovery rows before it throws on: the throw skips the release, so the report step, and under the wrappers the next subscription, kept them. - The report step is not run without the inventory: the run says 'No HTML report: the inventory ... was not written' instead of failing with 'Inventory JSON not found' as if it were a second fault. - The zip step is not tried without the inventory and the HTML report, so a zip can never be made without the inventory. - The manual-zip advice names the files, and under -Obfuscate says to add only those: the dictionary, the transcript and the logs hold real names. - The context-read tests find the release from the ProcessResourceResult call, so the new failure-path release is not taken for it.
Without the inventory the report step now stops before its 'Creating Summary Report' lines, and without the inventory and the HTML report the zip step is not called, so the run prints no 'Error Compressing Output File' for a call it did not make; it says once that there is no report to zip.
…er a failed write - The zip step needs the report step to have finished, not only an HTML file at the path: a report step that failed after writing part of its file no longer has that file zipped and named as the report. - After a failed inventory write the run also reads the Azure context and removes the provider-registration handler, as the release does, so the Azure session lets go of the rows too.
$Global:ReportingRunTime is reset before the processing step, so a run in the same session whose processing step stops says the time was not measured instead of printing the previous run's time.
…r the call The flag that keeps a failed report step's HTML file out of the zip is now set in the catch, so the Summary.ps1 call line is left as it was and open PRs that change that call merge without a conflict there.
The catch frees the collector output and the discovery rows first, so the error line has the memory it needs. A test checks that a failing Azure session read after the failed write does not replace the write error the wrapper sees.
In a reused output folder the zip's '*.json' input also matches earlier runs' files, which may hold real names. The advice now lists only files with this run's stamp.
Write-InventoryJson wrote to '<final path>.<32 hex>.tmp' and then moved it into place. That name is 37 characters longer than the final one, so a final file name of more than 218 characters, which the file system takes, failed with "the path is too long" before anything was written. The temporary file is now 'rda-write-<32 hex>.tmp' beside the final one: a new GUID for each write, 46 ASCII characters, never ending in .json. It is opened for this writer only and counts as this call's from the moment it exists, so a failure while building the writer still closes and removes it. On a failed write only that file is removed, and a warning says when it cannot be. No change to what the inventory holds. Tests: InventoryWrite writes a 255-character name and a 255-byte non-ASCII name (skipped on a file system that refuses one), checks the temporary name's shape, warns when removal fails and not on success, and leaves an earlier leftover and other files alone, and leaves nothing when the move into place fails (the first four fail without this).
…nto recovery-merge-stream awslabs#41's last commit edits Write-InventoryJson in Functions/ResourceInventory.Functions.ps1. This branch moved that function to Functions/InventoryJson.Functions.ps1, which already holds the same change plus this branch's own checks, so the conflict keeps this branch's side: the function stays out of ResourceInventory.Functions.ps1. awslabs#41 is merged into awslabs main, so this also clears the conflict with main.
awslabs#41 is now in main, and both PRs add a function at the end of Functions/ResourceInventory.Functions.ps1 and touch the same zip call, so awslabs#44 no longer merged cleanly. - Functions: keep both, Write-InventoryJson (awslabs#41) then Compress-RdaReportArchive (awslabs#44). - Zip step: keep every awslabs#41 rule (zip only when the inventory and the HTML report were written, -ErrorAction Stop, no zip named or shared that this call did not finish, remove a cut-off one) and call Compress-RdaReportArchive instead of Compress-Archive. The comments now name the function that runs.
After the merge with awslabs#41 the run zips with Compress-RdaReportArchive, so awslabs#41's zip-step tests stubbed a function the run no longer calls and 7 of them failed. They now stub Compress-RdaReportArchive; the stand-ins that take parameters are advanced functions, so they accept the call's -ErrorAction Stop as the real one does. The packaging test now expects the call with -ErrorAction Stop.
Part 1 of 4 of the memory series, tracked in #45.
Merge order: first. #42 needs it. Conflicts with other open PRs, and how to resolve them:
Functions/ResourceInventory.Functions.ps1and renames the zip call; it will berebased once this one is merged. On the zip call keep this PR's line and use Memory 4/4: stream the report zip instead of using Compress-Archive #44's name:
if ($ReportInputsReady) { Compress-RdaReportArchive @CompressionOutput -ErrorAction Stop } else { $ZipWritten = $false }. Thetests in
Tests/InventoryWrite.Tests.ps1that stand in forCompress-Archivemust then stand in forCompress-RdaReportArchive.ResourceInventory.ps1: inRunInventorySetupkeep Check read access and usage values up front for every subscription #38's$script:AccessSkippedfilter block first, thenthis PR's
$Global:ResourceCountline; at the end of the script keep this PR's last if/else, then Check read access and usage values up front for every subscription #38'sWrite-NoUsageSummaryandWrite-SkippedSubscriptionSummarycalls.ResourceInventory.ps1, where each adds an exit-code check next to the lastReporting Data Fileline, which this PR now prints only when the zip was written. Keep this PR's last if/else. Put Exit 2 from a direct run that wrote no report #52's exit-2 block just before
it, with the condition
-not $RunAllSubs.IsPresent -and -not $ZipWritten, and Report: name failed collectors, count consolidated subscriptions #51's exit-4 block after it, with$ZipWrittenin place of itsTest-Pathon the zip. Exit 2 from a direct run that wrote no report #52's testRun under -RunAllSubs stopped by the collector circuit breaker keeps its exit code 0 and its last line; the wrapper checks the zip(Tests/NoReportExitCode.Tests.ps1) then failson two lines, because this PR's last line under
-RunAllSubsis nowNo report was writtenwhen there is no zip: expect thatline instead of
Reporting Data File:, drop the check thatNo report was writtenis absent, and keep its exit code 0 checks.Write-InventoryJsonout ofFunctions/ResourceInventory.Functions.ps1intoFunctions/InventoryJson.Functions.ps1,and this PR's last commit changes that function's body, so the two conflict in
Functions/ResourceInventory.Functions.ps1: takeMemory 1b/4: write the merged recovery inventory with Write-InventoryJson #70's side (the function removed there, its pointer comment kept). Memory 1b/4: write the merged recovery inventory with Write-InventoryJson #70 carries the same change in its own copy.
Tests/InventoryWrite.Tests.ps1merges on its own.Write-NoUsageSummaryandWrite-SkippedSubscriptionSummarycalls, then Report: name failed collectors, count consolidated subscriptions #51's exit-4 block (so a run that exits 4 still printsCheck read access and usage values up front for every subscription #38's summaries).
Problem
On a large estate with limited memory, a run can finish with exit code 0 and an empty inventory, or with an inventory but no HTML
report and no zip. The README lists Azure Cloud Shell's RAM as "~3.5 GB total, ~2.7 GB usable at idle".
ProcessResourceResultserialises the whole inventory with oneConvertTo-Jsoncall and pipes the string toOut-File. When thatstring does not fit next to the collector objects already in memory, the inventory file is left at 0 bytes, the zip contains it,
the HTML report says nothing was found and the Diagnostics log shows "Collector failures: 0". The
OutOfMemoryExceptionis writtenonly to the local transcript, which is not in the zip.
$Global:SmaResources) and the discovery rows ($Global:Resources) stay inmemory although nothing reads them any more. The HTML report step that follows can then run out of memory: no HTML, no zip.
$ErrorActionPreference = 'silentlycontinue', so on a direct run a failed step's error was not shown. Afailed inventory write, a failed zip step (
Write-Erroris hidden by that preference) or an inputCompress-Archivecould not readended with
Reporting Data File: <zip>for a zip that was not there, or that was made without one of its files.Change
Write-InventoryJsoninFunctions/ResourceInventory.Functions.ps1writes the inventory one property (collector) at a timethrough a single
StreamWriter, so the largest string is one collector's JSON.ProcessResourceResultcalls it instead of thepipeline. The file is byte-for-byte what the pipeline wrote: UTF-8 without BOM, a one-element collector still an array,
Versionlast, trailing newline, same depth limit.
file is removed and the error is thrown on, so no cut-off inventory is left behind. The temporary name is short and of its own,
rda-write-<32 hex>.tmp(a new GUID per write, never ending in.json), so a long final file name (up to the file system's255) still works; a name built on the final one was 37 characters longer and failed above 218. Only the file this call created
is removed, and a warning says when it cannot be.
ProcessResourceResultcatches that error, frees the collector output and the discovery rows (the throw skips the releasebelow), writes
Inventory write FAILED: <inventory file> was not written: <error>to the console, the error log and thedebug log, reads the Azure context and removes the provider-registration handler as the release does, and throws it on. Under the
wrappers it still stops that subscription with the real cause, and the next subscription does not start with the failed
one's data held by those globals. (A test checks that this path runs the same read and removal as the release; the freeing
itself was measured for the release, not separately for this path.) On a direct run the script's
silentlycontinuepreference does not stopon the throw: the rest of the processing step is skipped, the report step is not run (
No HTML report: the inventory <file> was not written, instead ofInventory JSON not foundas a second fault) and the zip step is not tried (There is no report to zip).inventory, or with an HTML file a failed report step left. It
calls
Compress-Archive -ErrorAction Stopand logs its error withWrite-Log, so a file it cannot read stops the zip instead ofbeing left out without a word. It removes a zip it left unfinished (Compress-Archive normally does that itself; this is a
backstop), and leaves alone one that was there before it ran.
Please zip the output files manually:then names this run's files, andunder
-Obfuscatesays to add only those (the dictionary, the transcript and the logs hold real names).Reporting Data File), says it is safe to share under-Obfuscate, and says the transcript was left out ofit, only when its zip step finished and the file is there. Otherwise its last line is
No report was written: <zip> was not created. See the errors above, fix the cause and re-run., the same words as Exit 2 from a direct run that wrote no report #52, and the run times are shown as Info(
Reporting Time: not measured, ...when the processing step stopped, never an earlier run's time). Exit codesare unchanged: a direct run that wrote no report still exits 0; Exit 2 from a direct run that wrote no report #52 makes it exit 2.
ExecuteInventoryProcessingreleases$Global:SmaResourcesand$Global:Resourcesright afterProcessResourceResultand runs afull garbage collection.
ExecuteInventoryProcessingreads the Azure context once(
$null = Get-AzContext -ErrorAction Stop, in a try block that writes one debug-log line if it fails and lets the run go on).Az cmdlets keep their stream handlers in the shared Azure session after they return, so the VM or scale set size lookup, whose
output is piped on to a filter,
stayed referenced with the rows the collector was given until the next Az cmdlet. The read replaces those handlers, so the release
frees them. Without it, on a live run with VMs or scale sets, the data was freed only at the cost step's sign-in check, and with
-SkipConsumptionnot before the report step.factory is removed by type (
ClientFactory.RemoveHandler([...RPRegistrationDelegatingHandler])). That handler also keeps thelookup's cmdlet, and with it the rows, and the read does not always remove it: on live runs the read alone freed the rows in 3 of
7 runs, the read and the removal in 3 of 3. The next resource-manager cmdlet adds its own handler again.
$Global:ResourceCount, reset at the start of each run and set when discoveryfinishes, so an early exit never reports the previous subscription's count.
Run-AllSubscriptions.ps1(sequential and parallelpaths) and
Run-AllSubscriptions.Stream.ps1read it instead of counting$Global:Resources. Those three reads were the only uses ofeither variable after the inventory is written.
Testing
Linux, PowerShell 7.6, Pester 5.7.1.
Tests/InventoryWrite.Tests.ps1, 55 tests: byte equality with the previous output, array and encoding details, no whole-documentConvertTo-Jsoncall, relative path, replacing an existing file, a failed write leaving neither the inventory nor the temporaryfile, the count after a normal run, an early exit and a run that stopped after discovery, the data released before the report
step, and each wrapper call site. Twenty-one tests run the script's end as a direct run (
pwsh -File, no caller catching errors)or as the wrappers call it: with the inventory write failing (a collector
ConvertTo-Jsonrejects, and out of memory) the realcause is logged once, the report step is not run, no
Reporting Data Fileline, no inventory, temporary file or zip is left, thecollector data is freed, and a wrapper run stops with that cause, even when the Azure session read after it fails too; the next two runs in the same process are normal; an HTML file
with no inventory next to it, or one a failed report step left, is never zipped; a zip step that throws, leaves a cut-off zip, cannot remove it, meets a
zip already at the path, or reports a file it cannot read only as a non-terminating error never names a zip, and its manual-zip
advice names only this run's files;
safe to shareandthe run times follow the zip and never show an earlier run's time; a normal direct run names its zip and exits 0. Three tests cover the provider-registration handler
removal, one of them on the failed-write path. Six tests cover the Azure context read: it comes after the release and before its first
collection and the cost step; there is exactly one; a non-terminating error, a terminating error and a missing cmdlet are each
written once to the debug log only and the run goes on; and, in a separate pwsh process with no Azure sign-in and no network,
the shipped block frees rows that a collector-shaped scope kept through a piped Az call, where a plain statement does not (three
rounds). That test and the one for a provider-registration handler the read leaves in place are skipped where Az.Accounts is
not installed, and on Windows, where the separate process cannot be kept
away from the user's Azure profile. The run harness stubs
Get-AzContext, and a test checks itnever loads Az.Accounts. On awslabs main 52 of the 55 fail (run with Az.Accounts installed; the 3 that pass check a normal run's
last lines); on this branch all pass. On this branch
without the read, the new tests fail with
Expected $true, because the release frees nothing until an Az cmdlet replaces the stream handlers the last collector left in the Azure session, but got $false.,Expected 1, but got 0., and (read removed or replaced bya plain statement)
Expected $false, because round 1: the session read after the release frees them, but got $true.With-ErrorAction SilentlyContinueon the read, the non-terminating case fails withExpected 1, because one debug-log line per failed read, but got 0.Az.Accounts 5.5.3 and 5.5.4: in a standalone check with the collector's shape (2,000 rows), the rows stay held after the release
without the read and are freed with it, with the size lookup succeeding or failing, on both versions.
Full suite: no failure added, compared test by test with the previous head of this PR (8afde1e): the same failing and skipped
tests, plus the new ones, which pass.
PSScriptAnalyzer per file with the repository settings reports nothing on the changed files, before or after.
The memory figures below for generated estates were measured on an earlier head of this branch, before the Azure context read
was added, with disk records replayed in place of the Resource Graph query (no VMs, so no size lookup and nothing for the read to
free). Live figures for the Azure context read are further down.
Generated disks-only estates (disk records copied from a test subscription and replayed in place of the Resource Graph query by a
test-only change), memory limit set with a cgroup. Every one of these runs skipped the cost step (
-SkipConsumption). With metricson, the metrics step was stopped once it had built its request list (test-only change; generated resources have no metrics), so no
Azure Monitor calls were made. No run was killed by the system; each failure below is an
OutOfMemoryExceptioninside PowerShell.With memory limited to 2.7 GB (2,600 MiB), about the usable memory the README gives for Cloud Shell:
Managed heap at the start of the report step at 60,000 disks (read without forcing a collection): 1,117 to 1,329 MB on main,
61 MB with this PR.
Each commit alone was also measured, which is why they come as one PR: the writer alone completed 0 of 3 runs at 60,000 disks (the
inventory was written, then the HTML step ran out of memory), and the release alone still left a 0-byte inventory at 80,000 disks
with metrics off.
With memory limited to 3.4 GB (3,242 MiB), 80,000 disks, metrics on: main wrote the inventory, then the HTML step ran out of memory (no zip, exit 0);
this PR completed (inventory, HTML, zip, exit 0), peak about 2,585 MB. Wherever both sides completed, the inventory content was
identical record for record.
Live, on a test subscription, before the Azure context read was added (earlier head of this branch against main), all defaults
including the cost step and real Azure Monitor calls, as a single run and through
Run-AllSubscriptions.ps1(sequential and-ParallelStreams 2): inventory identical record for record, every metric recordidentical in every field (metrics time window pinned to the same moment for both runs), the same consumption rows, the zip with
the same entries and sizes, and the same exit code as main. With
-Obfuscate(replayed rows): identical apart from the obfuscatedfields, which are random per run by design.
Live, Azure context read: Az.Accounts 5.5.4, a test subscription of about 11,000 resources (3 VMs, 132 scale sets, 454 inventory records), the
discovery query as on main (network rows included), managed heap after a full collection, three alternating runs of each
side. These runs used this branch merged on Run with Az PowerShell only: drop the Azure CLI #66 (PowerShell-only sign-in), with and without the read, because the test
host has no Azure CLI, which this branch's base needs; the diff between the two trees was only the read and its tests.
-SkipConsumptionRun-AllSubscriptions.ps1, two runs in one sessionRun-AllSubscriptions.ps1, two runs in one sessionRun-AllSubscriptions.ps1 -ParallelStreams 2With the cost step on, the cost step's sign-in check already freed the data before the report step; the read moves that to
the release, so the cost step and the report step both start without it, and with
-SkipConsumptionthe report step nowdoes too. No consistent whole-run slowdown in three alternating runs. Compared with and without the read in every pair:
lines with times, durations or memory; the HTML text was the same apart from phase durations; the zip held the same entry
names (sizes and metric files not compared);
were the same, apart from a few metric records with a different number of points with data (the newest point can arrive
between runs; values are not compared), and one pair that ran either side of midnight UTC, whose cost rows and the run summary's cost record count differ because each day asks for a different 31 days. Both
sides exit 4 on this subscription through the wrapper, from the scale set collector date error that Fix VMSS collector failing on Flexible scale sets #39 fixes.
How to test
1. Quick check, no Azure needed (PowerShell 7, Pester 5, from the repository root; your own checkout is not touched):
On awslabs main 52 of the 55 fail (run with Az.Accounts installed). The key messages:
Expected function 'Write-InventoryJson' to be defined by <repo>/Functions/ResourceInventory.Functions.ps1, but it was not.,Expected ConvertTo-Json to be called 0 times exactly, because the inventory is written one collector at a time, but was called 1 times,Expected 1, but got 0.andExpected $true, because the report step must not have to share memory with the discovery rows, but got $false.On this branch all 55 pass. (Run on Linux, PowerShell 7.6,Pester 5.7.1.)
2. Live check of the release on a test subscription (read-only):
set size lookup, so a subscription with neither shows no difference.
az login, thenConnect-AzAccount, same tenant (main and this PR still use theAzure CLI).
-ParallelStreams 1it runsResourceInventory.ps1in the same window, so one MEMCHECK line prints persubscription:
The wrapper runs every subscription in the tenant. For a big tenant, the faster choice is a direct run on one subscription:
pwsh -NoProfile -File ../rdfa-<main|pr41>/ResourceInventory.ps1 -TenantID <tenant-id> -SubscriptionID <subscription-id> -SkipConsumption.-SkipConsumption: with the cost step on, the cost step's own Azure context check frees the rows a few seconds later, sothe report step looks the same on both. To see the gap with the cost step on, put the same line at the start of
function GetResorceConsumptioninstead ($lines.IndexOf(' function GetResorceConsumption()'), then the same insert);measured at that point: 557-560 MB without the read vs 129-130 MB with it (three runs each).
11,000 resources (454 inventory records), three runs each: report start with
-SkipConsumption556-560 MB without the readvs 128-129 MB with it; through the wrapper (two runs in one session), heap at the cost step start for that subscription
567-589 vs 140-158 MB, and in a
-ParallelStreams 2worker 563-564 vs 135-136 MB. These were measured with this PR merged on Run with Az PowerShell only: drop the Azure CLI #66 (PowerShell-only sign-in),because the test host has no Azure CLI. The figure depends on the subscription's size. Inventory records are the same in
both runs.
bug Fix VMSS collector failing on Flexible scale sets #39 fixes, not this PR.
3. Reproduce the memory problem (Linux with a systemd user session; not run exactly as written: the runs above fed generated
disk records in place of the Resource Graph query). Against a subscription with tens of thousands of managed disks, on awslabs main
and then on this branch:
Leave out
-SkipMetricsfor the HTML-step failure (seen at 60,000 disks); at 80,000 disks that run fails earlier, see#42.
4. What to look for, in
~/InventoryReports/ResourcesReport<timestamp>/:Inventory_ResourcesReport_<timestamp>.jsonis 0 bytes, the HTML report shows no resources, andDiagnostics_ResourcesReport_<timestamp>.logsaysCollector failures: 0; theOutOfMemoryExceptionis only inTranscript_Log_ResourcesReport_<timestamp>.txt; exit code 0. Or, when the inventory fits: the console showsHTML report generation FAILED: ... OutOfMemoryException ...and there is no HTML file and noResourcesReport_<timestamp>.zip.Limitations
built. Memory 2/4: build metric request definitions as a compact class #42 addresses that step.
then the HTML step runs out of memory: no HTML, no zip, exit 0. Not addressed by this series.
with exit 0 (related to Collector errors are silently swallowed by global SilentlyContinue + missing try/catch #22); Exit 2 from a direct run that wrote no report #52 makes a direct run that wrote no report exit 2. When the inventory write fails in a direct
run, the rest of the processing step is skipped (the release and the cost step; the failure path frees the collector data and
does the Azure context read and handler removal itself); the run prints the cause, writes no HTML report and no zip, and ends
with
No report was written. The wrappers record that subscription as failed.-RunAllSubs, a subscription whose zip step fails returns normally, soRun-AllSubscriptions.ps1records it as completedand a later
-Resumeskips it, as on main. Carry earlier reports into the -Resume bundle #48 fixes that (a run that left no zip is not completed).-OutputDirectory, the zip's*.jsoninput still takes earlier runs' JSON files too, as on main (under-Obfuscatethat can include an earlier plain run's inventory, with real names). Zip only this run's files when -OutputDirectory is reused #57 fixes that by taking only this run'sfiles; until it is merged, do not share a zip from a reused folder. The manual-zip advice added here names only this run's
files.
FinalizeOutputsrun after the transcript has stopped, as on main, so the report and zip errors are on the console andin the error log, not in the transcript; the
Inventory write FAILEDline is in all three.the read does not cover that case, and it was not measured here.
<inventory>.<id>.tmpfile can be left next to it.step at these sizes, Windows, macOS, and Cloud Shell itself.