@@ -26,12 +26,20 @@ function Start-DurableCleanup {
2626
2727 $CleanupCount = 0
2828 $QueueCount = 0
29+ $ClearQueues = $false
30+
31+ $FunctionsWithLongRunningOrchestrators = [System.Collections.Generic.List [object ]]::new()
2932 foreach ($Table in $InstancesTables ) {
33+ $RunningOrchestratorCount = 0
3034 $Table = Get-CippTable - TableName $Table
31- $ClearQueues = $false
3235 $FunctionName = $Table.TableName -replace ' Instances' , ' '
3336 $Orchestrators = Get-CIPPAzDataTableEntity @Table - Filter " RuntimeStatus eq 'Running'" | Select-Object * - ExcludeProperty Input
37+ $Queues = Get-AzStorageQueue - Context $StorageContext - Name (' {0}*' -f $FunctionName ) | Select-Object - Property Name, ApproximateMessageCount, QueueClient
38+ $RunningOrchestratorCount = $Orchestrators.Count
3439 $LongRunningOrchestrators = $Orchestrators | Where-Object { $_.CreatedTime.DateTime -lt $TargetTime }
40+ if ($LongRunningOrchestrators.Count -gt 0 ) {
41+ $FunctionsWithLongRunningOrchestrators.Add (@ {' FunctionName' = $FunctionName })
42+ }
3543 foreach ($Orchestrator in $LongRunningOrchestrators ) {
3644 $CreatedTime = [DateTime ]::SpecifyKind($Orchestrator.CreatedTime.DateTime , [DateTimeKind ]::Utc)
3745 $TimeSpan = New-TimeSpan - Start $CreatedTime - End (Get-Date ).ToUniversalTime()
@@ -45,9 +53,7 @@ function Start-DurableCleanup {
4553 $CleanupCount ++
4654 }
4755 }
48-
49- if ($ClearQueues ) {
50- $Queues = Get-AzStorageQueue - Context $StorageContext - Name (' {0}*' -f $FunctionName ) | Select-Object - Property Name, ApproximateMessageCount, QueueClient
56+ if ($ClearQueues -or ($RunningOrchestratorCount -eq 0 -and $Queues.ApproximateMessageCount -gt 0 )) {
5157 $RunningQueues = $Queues | Where-Object { $_.ApproximateMessageCount -gt 0 }
5258 foreach ($Queue in $RunningQueues ) {
5359 Write-Information " - Removing queue: $ ( $Queue.Name ) , message count: $ ( $Queue.ApproximateMessageCount ) "
@@ -58,5 +64,10 @@ function Start-DurableCleanup {
5864 }
5965 }
6066 }
61- Write-Information " Cleanup complete. $CleanupCount orchestrators were terminated. $QueueCount queues were cleared."
67+
68+ if ($CleanupCount -gt 0 -or $QueueCount -gt 0 ) {
69+ Write-LogMessage - api ' Durable Cleanup' - message " $CleanupCount orchestrators were terminated. $QueueCount queues were cleared." - sev ' Info' - LogData $FunctionsWithLongRunningOrchestrators
70+ }
71+
72+ Write-Information " Durable cleanup complete. $CleanupCount orchestrators were terminated. $QueueCount queues were cleared."
6273}
0 commit comments