AzStackHciStandaloneObservability/package/bin/ObsAgent/lib/Scripts/InvokeLogCollection.psm1

<##############################################################
 # #
 # Copyright (C) Microsoft Corporation. All rights reserved. #
 # #
 ##############################################################>


#
# Get logs from various roles of AzureStack.
#

# Do not change the order of imports
Import-Module $PSScriptRoot\LogCollectionHelper.psm1 -Force -Verbose:$false
Import-Module $PSScriptRoot\GenericHelper.psm1 -Force -Verbose:$false

function GetFileOrFolderSize
{
    Param
    (
        [Parameter(Mandatory=$true)]
        [string]
        $RootPath
    )
    $size = [long] (Get-ChildItem -Recurse $RootPaTh -ErrorAction SilentlyContinue -force | Where-Object { -not $_.PSIsContainer }  | Measure-Object -Sum Length ).Sum
    return $size
}
function Convert-UtctoLocal
{ 
    param( 
            [parameter(Mandatory=$true)] 
            [DateTime] $UtcdateTime 
        )
        
        if ($UtcdateTime.Kind -eq [DateTimeKind]::Utc) {
            return [System.TimeZoneInfo]::ConvertTimeFromUtc($UtcdateTime, (Get-TimeZone))
        }

        # Override
        # Using (Get-Date) will get the local time, so assuming user adjusted the time to UTC
        # need to convert it into string to remove the kind property which is local if we use get-date
        return [System.TimeZoneInfo]::ConvertTimeFromUtc($UtcdateTime.tostring(), (Get-TimeZone))
}
function Invoke-GarbageCollector
{
    $functionName = $($MyInvocation.MyCommand.Name)

    if(((Get-Date) - $Global:LastGarbageCollectedTime).TotalSeconds -gt 60 ) {
        Trace-Progress -Message "$functionName : Invoking Garbage Collector"
        [System.GC]::Collect()
        $Global:LastGarbageCollectedTime = Get-Date
    } else {
        Trace-Progress -Message "$functionName : Skipping Garbage Collector invocation"
    }
}

function Write-RoleTime
{
    param (
        [string]$RoleName,
        [int]$Empty,
        [int]$Filled,
        [float]$Duration
    )
    #no role name is > 32 charaters currently
    $roleFiller = (32 - $RoleName.Length)
    $RoleName = ' '*$roleFiller + $RoleName

    <# This will print double line
    switch($Filled)
    {
        1 {$line = '║'}
        default {$line = '╠'+'═'*($Filled-2)+'╣'}
    }
    #>

    switch($Filled)
    {
        1 {$line = '║'}
        default {$line = '├'+'─'*($Filled-2)+'┤'}
    }

    $d ="{0:00.0}" -f $Duration
    [String]$printLine = "[$RoleName][$d]" + ' '*$Empty + $line
    Write-Host $printLine
}


function Show-RoleTime
{
    param(
        [string]$roleTimesCsvFilePath
    )

    $functionName = $($MyInvocation.MyCommand.Name)

    try{
        $fileContent = Get-Content -Path $roleTimesCsvFilePath
        $expectedFirstLine = "RoleName, StartTime, EndTime, Minutes"

        if (($fileContent.GetType().Name -eq "String") -and ($fileContent -eq $expectedFirstLine))
        {
            Trace-Progress "$functionName : There is no role time data. Cannot show role timeline." 
            return
        }

        $f = @()
        if($fileContent[0] -ne $expectedFirstLine)
        {
            $f += $expectedFirstLine
            $f += $fileContent
            $fileContent = $f
        }

        $rawData = $fileContent| ConvertFrom-Csv
        $SortedData = $rawData | Sort-Object StartTime

        [System.Globalization.CultureInfo]$provider = [System.Globalization.CultureInfo]::InvariantCulture
        $format = 'MM/dd/yyyy HH:mm:ss'
        [ref]$parsedDate = get-date
        foreach ($obj in $SortedData)
        {
            $IsDateStartTime = [DateTime]::TryParseExact($obj.StartTime, $format,$provider,[System.Globalization.DateTimeStyles]::None,$parseddate)
            $IsDateEndTime = [DateTime]::TryParseExact($obj.EndTime, $format,$provider,[System.Globalization.DateTimeStyles]::None,$parseddate)
            $RoleNullOrEmpty =  [string]::IsNullOrEmpty($obj.RoleName)
            $IsMinutesFloat = $obj.Minutes -match "^[\d\.]+$"

            $errorMessage = [System.Text.StringBuilder]::new()
            if (!$IsDateStartTime)
            {
                [void]$errorMessage.Append("Start Time of $($obj.StartTime) is not a valid date. ")
            }
            if (!$IsDateEndTime)
            {
                [void]$errorMessage.Append("End Time of $($obj.EndTime) is not a valid date. ")
            }
            if ($RoleNullOrEmpty)
            {
                [void]$errorMessage.Append("Role Name is null or empty. ")
            }
            if (!$IsMinutesFloat)
            {
                [void]$errorMessage.Append("Minutes of $($obj.Minutes) is not a valid float. ")
            }
            if ($errorMessage.Length -ne 0)
            {
                $errorMessageStart = "Role Time Information for role $($obj.RoleName) is invalid : "
                $errorMessageEnd = " Cannot show role timeline."
                $fullErrorMessage = $errorMessageStart + $errorMessage.ToString() + $errorMessageEnd
                Trace-Progress "$functionName : $fullErrorMessage" -error
                return
            }
        }

        $allData = @()
        $allData += $SortedData | ForEach-Object {     $element = @{
                                    RoleName  = $_.RoleName
                                    StartTime = Get-Date -Date $_.StartTime
                                    EndTime   = Get-Date -Date $_.EndTime
                                    Duration  = [float]$_.Minutes
                                }
                            return $element }

        $data = $allData

        $minStartime    = ($data.StartTime | Measure-Object -Minimum).Minimum
        $maxEndtime     = ($data.EndTime | Measure-Object -Maximum).Maximum
        $TotalDuration  = ($maxEndtime - $minStartime).TotalMinutes

        #Lets assume screen has 160 + 32 + few characters for printing name and timetime
        $multiplier = (160/$TotalDuration)

        Write-Host '**********************Get AzureStackLog Role Timeline**********************'
        foreach($role in $data)
        {
            $empty = [math]::Ceiling((($role.StartTime - $minStartime).TotalMinutes)*$multiplier)
            $fill = [math]::Ceiling(($role.Duration)*$multiplier)
            Write-RoleTime -RoleName $role.RoleName -Empty $empty -Filled $fill -Duration $role.Duration
        }
        Write-Host $printLine
        Write-Host '***************************************************************************'
    }
    catch {
        Trace-Progress -Message "$functionName : Failed to graph times for each role exception : $_" 
    }
}

function TerminateJobAndCopyTempFilesToOutputPath
{
    param
    (
    [Parameter(Mandatory=$true)]
    [System.Management.Automation.Job]$JobToTerminate,

    [Parameter(Mandatory=$true)]
    [string] $TempFolderPath,

    [Parameter(Mandatory=$true)]
    [string] $OutputPath,

    [string]
    $SharePath,

    [string]
    $SasUri

    )
    $functionName = $($MyInvocation.MyCommand.Name)
    #we do not want to copy all role* folders bcoz, we have few roles with same prefix as
    # ACS, ACSFabric,ACSWac etc..
    # Which could be all running parallel, we need to copy only folders with pattern "$role", "$role-"
    Trace-Progress -Message "$functionName_$($JobToTerminate.Name) : Forcibly stopping the job "
    $JobToTerminate | Stop-Job  # Force the job to Terminate
    Trace-Progress -Message "$functionName_$($JobToTerminate.Name) : Stopped, current state = [$($JobToTerminate.State)] ...."
    Start-Sleep 60 # Give few seconds for child processes to terminate, this can be upto 60 seconds
    $JobToTerminate | Receive-Job
    <#
    #copy files from temp and destination to outputpath for current role only.
    $RoleFoldersInTemp1 = $TempFolderPath + "\" + $JobToTerminate.Name + "*" # this will capture Storage, Storage-part2, Storage-Uncompressed, Storage-Uncompressed-Part2
 
    $roleFoldersOnly = Get-ChildItem -Path $RoleFoldersInTemp1 -Directory
    Trace-Progress -message "$functionName_$($JobToTerminate.Name) : [$($roleFoldersOnly.count)] exist at the time job was terminated. `n folder list = [$roleFoldersOnly]"
    #note this will get the files and folders if they are non empty.
 
    if($roleFoldersOnly.count)
    {
        foreach( $folderPath in $roleFoldersOnly.FullName)
        {
            $tempFiles = Get-ChildItem -Path $folderPath -Recurse -ErrorAction SilentlyContinue -Verbose
            Trace-Progress -message "$functionName_$($JobToTerminate.Name) : $($tempFiles.count) files/folders to copy"
            #Copy-Item -Path $RoleFoldersInTemp1 -Destination "$OutputPath\FilesCopiedOnTermination\$($JobToTerminate.Name)\" -Recurse -Force -ErrorAction SilentlyContinue -Verbose
            #Remove-Item -Path $RoleFoldersInTemp1 -Recurse -ErrorAction SilentlyContinue -verbose
            if($tempFiles)
            {
                #$folderPath
                if((split-path $folderPath -leaf) -match 'UnCompressed')
                {
                    $CompressionLevel = [System.IO.Compression.CompressionLevel]::NoCompression
                } else {
                    $CompressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
                }
 
                $output = Get-FolderAsZip -SourceFolder $folderPath -DestinationFolder "$OutputPath\FilesCopiedOnTermination\$($JobToTerminate.Name)\" -RoleName $JobToTerminate.Name -CompressionLevel $CompressionLevel -SharePath $SharePath -SasUri $SasUri
                Trace-Progress -message "$functionName_$($JobToTerminate.Name) : created and copied zip [($output.Path)] - [$($output.success)]"
             } else {
                Trace-Progress -message "$functionName_$($JobToTerminate.Name) : [$folderPath] is empty, skipping copy"
             }
         }
     }else {
        Trace-Progress -message "$functionName_$($JobToTerminate.Name) : [$RoleFoldersInTemp1] is empty, nothing to copy upon termination"
     }
     #>

}

function Invoke-AzureStackLogCollection
{
    [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingComputerNameHardcoded','')]

    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$false)]
        [string[]]
        $FilterByRole,

        [Parameter(Mandatory=$false)]
        [string[]]
        $FilterByNode,

        [Parameter(Mandatory=$false)]
        [ValidateSet('File','CSV','WindowsEvent','ContainerState')]
        [String[]]
        $FilterByLogType,

        [Parameter(Mandatory=$false)]
        [ValidateNotNullOrEmpty()]
        [string]
        $CustomerConfigurationFilePath,

        # This will get the logs starting from last hour
        [Parameter(Mandatory=$false)]
        [DateTime]
        $FromDate = ([DateTime]::UtcNow).AddHours(-1),

        # This will get the logs until the current date
        [Parameter(Mandatory=$false)]
        [DateTime]
        $ToDate = ([DateTime]::UtcNow),

        # Whether the log collection is autonomous
        [Parameter(Mandatory=$false)]
        [bool]
        $IsAutonomous = $false,

        # Log Collection Job type
        [Parameter(Mandatory=$false)]
        [string]
        $LogCollectionJobType = "OnDemand",

        # Log Collection output path
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string]
        $OutputPath,

        # Whether to only collect logs from the localhost
        [Parameter(Mandatory=$false)]
        [bool]
        $LocalMode = $false,

        # Whether we are pushing logs to an SMBShare
        [Parameter(Mandatory=$false)]
        [bool]
        $ToSMBShare = $false
    )
    Trace-EnteringMethod

    # Let start time be the first garbage collection time.
    $Global:LastGarbageCollectedTime = Get-Date
    $logCollectionStartDate = Get-Date
    $logCollectionPerfResult = @{}
    $Error.Clear()

    $functionName = $($MyInvocation.MyCommand.Name)

    $azsLogFolderPrefix = "ASZLogs-" + ((Get-Date).ToString('yyyyMMddHHmmss'))
    # Adding this OutputFolderName variable to have azsLogFolderPrefix and env name together.
    $OutputFolderName = "$azsLogFolderPrefix-$env:ComputerName"

    #User has provided the outputpath, lets add AzureStackLog-yyyyMMddHHmmss to the path.
    $OutputPath = Join-Path -Path $OutputPath -ChildPath "$OutputFolderName"

    $transcriptPath = "$OutputPath\Get-AzureStackLog_Output.log"
    Start-Transcript -Path $transcriptPath -Verbose

    Trace-Progress -Message "$functionName : Outputpath = [$OutputPath]"
    Trace-Progress -Message "$functionName : transcriptPath = [$transcriptPath]"

    $collectionDetails = @{}
    $collectionDetails.Reason = "User Initiated"

    $maxJobTimeInSec = 15600 # 260min = 15600sec
    $maxJobLimit = 6

    Trace-Progress -Message "$functionName : Running on Machine = [$($env:COMPUTERNAME)] with max parallel jobs =[$maxJobLimit]"
    #$filterOnlyRoles = $FilterByRole -and -not $FilterByResourceProvider
    #$filterOnlyRps = $FilterByResourceProvider -and -not $FilterByRole

    # Prepare and send telemetry event
    $telActivityId = New-Guid
    if ($null -eq $FilterByRole)
    {
        $telRoles = ""
    }
    else
    {
        $telRoles = [string]$FilterByRole
    }

    $telParameters = $MyInvocation.BoundParameters.Keys
    $telParameters = $telParameters -join ','

    $message = ("$functionName : Started new InvokeLogCollection instance with activity ID '{0}'" -f $telActivityId)
    Trace-Progress -Message $message

    # Convert UTC times to local time
    $ToDate = Convert-UtctoLocal -UtcdateTime $ToDate
    $FromDate = Convert-UtctoLocal -UtcdateTime $FromDate

    if ($ToDate -gt (Get-Date).addMinutes(5))
    {   
        $OldToDate = $ToDate
        $ToDate = (Get-Date)
        $warningMessage = "$functionName : Log Collection To Date cannot be greater than current datetime. Changed Log Collection ToDate from $OldToDate to $ToDate"
        Trace-Progress -Message $warningMessage -Warning
    }

    if ($FromDate -gt (Get-Date))
    {
        $errorMessage = "$functionName : Log Collection From Date cannot be greater than current datetime. Aborting log collection."
        Trace-Progress -Message $errorMessage -Error
        Stop-Transcript
        return
    }

    if ($ToDate -le $FromDate)
    {
        $errorMessage = "$functionName : ToDate cannot be less than or equal to FromDate. Aborting log collection."
        Trace-Progress -Message $errorMessage -Error
        Stop-Transcript
        return
    }

    $telDate = Get-Date
    # Send-InstanceStartEvent -ActivityId $telActivityId -Timestamp $telDate -Roles $telRoles -OutputParameters $telParameters -FromRange $FromDate -ToRange $ToDate -AlertBased $AlertBased

    $collectionDetails.computerName = $env:COMPUTERNAME
    $collectionDetails.computerOS = [environment]::OSVersion.VersionString
    $collectionDetails.activityId = $telActivityId
    $collectionDetails.telParams = $telParameters
    $collectionDetails.fromDate = $FromDate
    $collectionDetails.toDate = $ToDate
    $collectionDetails.rolesSelected = $telRoles
    $collectionDetails.outputFolderName = $OutputFolderName
    $collectionDetails.invokeTime = $telDate
    $collectionDetails.filterOnlyRoles = $filterOnlyRoles
    $collectionDetails.filterOnlyRps = $filterOnlyRps

    if (-not (Test-IsElevated))
    {
        $errorMessage = "$functionName : Collecting logs requires elevation. Aborting."
        Trace-Progress -Message $errorMessage -Error
        #Send-InstanceFinishEvent -ActivityId $telActivityId -Timestamp (Get-Date) -TerminalError $errorMessage
        return
    }

    #Input object pipeline for parameters
    $argumentsObject = [PSCustomObject]@{}

    $isArcAEnv = $false

    # Get domain information
    $domain = $env:USERDNSDomain
    if ($null -eq $domain -and $env:COMPUTERNAME -like "IRVM*") {
        $isArcAEnv = $true
        $localMode = $true
    }

    Trace-Progress -Message "$functionName : Domain name fetched from environment variable = $domain"
    Add-Member -InputObject $argumentsObject -MemberType NoteProperty -Name "domain" -Value $domain

    Add-Member -InputObject $argumentsObject -MemberType NoteProperty -Name "functionName" -Value $functionName
    Add-Member -InputObject $argumentsObject -MemberType NoteProperty -Name "OutputPath" -Value $OutputPath

    Add-Member -InputObject $argumentsObject -MemberType NoteProperty -Name "FromDate" -Value $FromDate
    Add-Member -InputObject $argumentsObject -MemberType NoteProperty -Name "ToDate" -Value $ToDate

    Add-Member -InputObject $argumentsObject -MemberType NoteProperty -Name "localMode" -Value $LocalMode
    Add-Member -InputObject $argumentsObject -MemberType NoteProperty -Name "isArcAEnv" -Value $isArcAEnv
    Add-Member -InputObject $argumentsObject -MemberType NoteProperty -Name "toSMBShare" -Value $ToSMBShare

    try
    {
        $FromDateG = $FromDate.ToString("G")
        $ToDateG = $ToDate.ToString("G")
        Trace-Progress -Message "$functionName : Collecting logs from $FromDateG to $ToDateG"
        Trace-Progress -Message "$functionName : Local time zone is $(([TimeZoneInfo]::Local).DisplayName)"

        Add-Member -InputObject $argumentsObject -MemberType NoteProperty -Name "FromDateG" -Value $FromDateG
        Add-Member -InputObject $argumentsObject -MemberType NoteProperty -Name "ToDateG" -Value $ToDateG

        if(-not $CustomerConfigurationFilePath) {
            if ($isArcAEnv) {
                $CustomerConfigurationFilePath = "$PSScriptRoot\ArcADiagnosticLogRoleConfiguration.json"
            }
            else {
                $CustomerConfigurationFilePath = "$PSScriptRoot\DiagnosticLogRoleConfiguration.json"
            }
        }

        $roles = Get-RoleInfoFromJsonConfig -RoleJsonFile $CustomerConfigurationFilePath 

        Add-Member -InputObject $argumentsObject -MemberType NoteProperty -Name "roles" -Value $roles

        $roleNames = Get-FilteredRoleName -Roles $roles -FilterByRole $FilterByRole -LogCollectionJobType $LogCollectionJobType
        $nodeNames = Get-NodeNamesFromClusterOrDefaultLocalHostName
        $vmRoleNames = Get-InfraVMNames -InfraHostNames $nodeNames

        # TODOTODO suppress node filtering for now.
        <# $nodeNames = Get-FilteredNodeName -Roles $roles -RoleNames $roleNames -FilterByNode $FilterByNode
 
         $roleNamesAfterNodeFilter = $roleNames | Where-Object { ($roles[$_].PublicConfiguration.Nodes.Node.Name | Where-Object { $nodeNames -contains $_}).Count -gt 0 }
         Trace-Progress "$functionName : Role names after applying node filter: $($roleNamesAfterNodeFilter -join ', ')"
         $collectionDetails.nodeFilteredRoles = $roleNamesAfterNodeFilter
 
        if ($FilterByRole -and $FilterByNode)
        {
            if (($null -eq $roleNamesAfterNodeFilter) -or ($null -ne (Compare-Object $roleNames $roleNamesAfterNodeFilter)))
            {
                $message = "Invalid role / node filters, please check the input and try again."
                Trace-Progress "$functionName : $message" -Error
                throw $message
            }
        }
 
        $roleNames = $roleNamesAfterNodeFilter
        Add-Member -InputObject $argumentsObject -MemberType NoteProperty -Name "nodeNames" -Value $nodeNames
        #>


        # nodenames = list of baremetal nodes
        # if LocalMode, ensure we are only collecting logs on the local node.
        if ($LocalMode)
        {
            Trace-progress -Message "$functionName : In LocalMode. LocalMode will override filterByNode parameter to make sure it is the local node only."
            $filterByNode = @($env:COMPUTERNAME)
        }
        Add-Member -InputObject $argumentsObject -MemberType NoteProperty -Name "filterByNode" -Value $FilterByNode
        Add-Member -InputObject $argumentsObject -MemberType NoteProperty -Name "nodeNames" -Value $nodeNames
        Add-Member -InputObject $argumentsObject -MemberType NoteProperty -Name "roleNames" -Value $roleNames
        Add-Member -InputObject $argumentsObject -MemberType NoteProperty -Name "vmRoleNames" -Value $vmRoleNames

        if (-not $FilterByLogType)
        {
            Trace-Progress "$functionName : No log type filters specified, getting all log types."
            $FilterByLogType = @('File','CSV','WindowsEvent')

            if ($isArcAEnv)
            {
                $FilterByLogType += 'ContainerState'
            }
        }

        Trace-Progress -Message "$functionName : Collecting $($FilterByLogType -join ', ') logs"
        Add-Member -InputObject $argumentsObject -MemberType NoteProperty -Name "FilterByLogType" -Value $FilterByLogType

        <# Get cluster information (including multiple clusters) clusternames, fileservername, ismanagementcluster, diagnosticshare full path
        $allClusterInfo = Get-StorageClusterInformation -AllRoles $roles
        Add-Member -InputObject $argumentsObject -MemberType NoteProperty -Name "allClusterInfo" -Value $allClusterInfo
        #>


        # Job array to track background jobs created
        $jobArray = New-Object -TypeName System.Collections.ArrayList

        <#
            Creating scriptblock this way expands $psscriptroot,
            using powershell way of defining scriptblock delays expansion of $psscriptroot and fails if used inside a job init block
        #>

        Trace-Progress "$functionName : INITBLOCK - $PSScriptRoot"

        $initblock = [ScriptBlock]::Create("Import-Module -Name '$PSScriptRoot\LogCollectionHelper.psm1' -Force; Import-Module -Name '$PSScriptRoot\GenericHelper.psm1' -Force")

        # TimeTracker for each job
        $roleTimeLog = "$OutputPath\RoleTime_Output.csv"
        Trace-Progress -Message "Adding header to file [$roleTimeLog]"
        #Add header for csv file, makes it easier to open the file in excel
        Add-Content -Path $roleTimeLog -Value "RoleName, StartTime, EndTime, Minutes"

        ##TODO - try ?? or remove {}
        try {
            $logCollectionPerfResult.Add("SetupTime", ((Get-Date) - $logCollectionStartDate).TotalMinutes)

            # role count info
            $roleCount = $roleNames.Count
            Trace-Progress -Message "$functionName : Total number of roles $roleCount"

            foreach ($role in $roleNames)
            {
                $alljobs = Get-Job
                foreach($j in $alljobs)
                {
                    $jobToBeRemoved = $null
                    if($j.State -in @('Completed')) # let the failed, Suspended and Disconnected jobs be in the list
                    {
                        $j | Receive-Job
                        $j |Stop-Job
                        $jobToBeRemoved = $true
                    }
                    elseif (($jobTime = ((Get-date) - $j.PSBeginTime).Totalseconds) -gt $maxJobTimeInSec ) {
                        #Time to terminate the job
                        Trace-Progress -Message "$functionName : job [$($j.Name)] exceeded maximum time for individual job [$jobTime] seconds - Terminating Job forcefully...." -Error
                        $jobToBeRemoved = $true
                        # TerminateJobAndCopyTempFilesToOutputPath -JobToTerminate $j -TempFolderPath $destPath -OutputPath $OutputPath -SharePath $DestinationSharePath -SasUri $OutputSasUri
                    }
                    if ($jobToBeRemoved)
                    {
                        Trace-Progress -Message "$functionName : job $($j.Name) completed with state = $($j.State)"
                        if ($j.State -ne 'Completed') {
                            $errorMessage = $j.ChildJobs.JobStateInfo.Reason.Message
                            if($errorMessage) {
                                Trace-Progress -message "$functionName : child job- $($j.Name) errors = $errorMessage"
                            }
                        }

                        $j |ForEach-Object {Add-Content -Path $roleTimeLog -Value "$($_.Name), $($_.PSBeginTime), $($_.PSEndTime), $(($_.PSEndTime - $_.PSBeginTime).TotalMinutes)"}
                        $logCollectionPerfResult.Add($j.Name, ($j.PSEndTime - $j.PSBeginTime).TotalMinutes)
                        
                        $j | Remove-Job
                        Invoke-GarbageCollector
                        if ($j -in $jobArray)
                        {
                            Trace-Progress -Message "$functionName : Removing job [$($j.Name)] from job array"
                            $jobArray.Remove($j)
                        }
                    }
                }

                while(@(Get-Job -State Running).Count -ge $maxJobLimit) {
                    Trace-Progress -Message "$functionName : Running $maxJobLimit jobs already, waiting before starting next job"
                    Start-Sleep 10
                }

                # Background job that collects logs for each role
                $jobStatic = Start-Job -Scriptblock {
                    param($argumentsObject)
                    Trace-Progress -Message "$using:functionName : invoking script variables - using:PSScriptRoot = [$using:PSScriptRoot]"
                    Set-Location $using:PSScriptRoot
                    Trace-Progress -Message "$using:functionName : after set pwd, job pwd = [$pwd]"
                    $transcriptPath = "$using:OutputPath\RoleOutput\Get-Roles_Output_$using:role.log"
                    Start-Transcript -Path $transcriptPath -Verbose
                    Get-RoleLogs -argumentsObject $argumentsObject -role $using:role
                    Stop-Transcript
                } -Name $role -ArgumentList $argumentsObject `
                -InitializationScript $initblock

                $jobArray.Add($jobStatic)
                Trace-Progress -Message "$functionName : Started Get-RoleLogs for role $role"

            } #foreach ($role in $roleNames)
        }
        catch {
            Trace-Progress -Message "$functionName : Failed to kick off jobs"
        }
        Trace-Progress -Message "$functionName : Background jobs for all roles and resource providers kicked off in parallel"

        while($jobArray.Count -gt 0)
        {
            $completedJob = $jobArray | Wait-Job -Any -Timeout 30
            $jobToBeRemoved = $null
            if ($null -ne $completedJob)
            {
                # $completedJob will have exactly one job that completed.
                $jobToBeRemoved = $completedJob
            } else {
                # No job finished Continue to wait
                Trace-Progress -Message "$functionName : Waiting for $($jobArray.Count) jobs to finish.."

                # Check any job exceeded time
                foreach($j in $jobArray)
                {
                    #Check if any of the job has exceeded the timeout
                    if (($jobTime = ((Get-date) - $j.PSBeginTime).Totalseconds) -gt $maxJobTimeInSec )
                    {
                        #Time to terminate the job
                        Trace-Progress -Message "$functionName : job [$($j.Name)] exceeded maximum time for individual job [$jobTime] seconds - Terminating Job forcefully...." -Error
                        #TerminateJobAndCopyTempFilesToOutputPath -JobToTerminate $j -TempFolderPath $destPath -OutputPath $OutputPath -SharePath $DestinationSharePath -SasUri $OutputSasUri
                        $jobToBeRemoved = $j
                        break;
                    }
                }
            }

            if ($jobToBeRemoved)
            {
                $jobToBeRemoved | Stop-Job
                $jobToBeRemoved | Receive-Job
                Trace-Progress -Message "$functionName : job $($jobToBeRemoved.Name) completed with state = $($jobToBeRemoved.State)"
                if ($jobToBeRemoved.State -ne 'Completed') {
                    $errorMessage = $jobToBeRemoved.ChildJobs.JobStateInfo.Reason.Message
                    if($errorMessage) {
                        Trace-Progress -message "$functionName : child job errors = $errorMessage"
                    }
                }

                # Trace the time took by each job
                $jobToBeRemoved |ForEach-Object {Add-Content -Path $roleTimeLog -Value "$($_.Name), $($_.PSBeginTime), $($_.PSEndTime), $(($_.PSEndTime - $_.PSBeginTime).TotalMinutes)"}
                $logCollectionPerfResult.Add($jobToBeRemoved.Name, ($jobToBeRemoved.PSEndTime - $jobToBeRemoved.PSBeginTime).TotalMinutes)
                
                $jobToBeRemoved | Remove-Job
                Invoke-GarbageCollector
                if ($jobToBeRemoved -in $jobArray)
                {
                    Trace-Progress -Message "$functionName : Removing job [$($jobToBeRemoved.Name)] from job array"
                    $jobArray.Remove($jobToBeRemoved)           
                }
            }
        } #while($jobArray.Count -gt 0)

        Write-Output "`r"
        Trace-Progress -Message "$functionName : Logs placed at : $OutputPath on $env:ComputerName"
    }
    finally
    {
        $logCollectionCleanUpStartDate = Get-Date

        if($jobArray.Count -gt 0) {
            Trace-Progress -Message "$functionName : Termination event triggered - job array has $($jobArray.Count) jobs in progress"
            $jobArray | Stop-job 
            foreach($j in $jobArray) {
                Trace-Progress -Message "$functionName : processing $($j.Id) , $($j.Name) , $($j.State)"
            }
            Trace-Progress -Message "$functionName : terminated all jobs"
            Trace-Progress -Message "$functionName : Copying in progress files if any..."
        }

        $logCollectionPerfResult.Add("CleanUpTime", ((Get-Date) - $logCollectionCleanUpStartDate).TotalMinutes)
        $logCollectionPerfSortedResult = $logCollectionPerfResult.GetEnumerator() | Select-Object -Property Key,Value | Sort-Object -Property value -Descending
        $logCollectionPerfSortedResult | ConvertTo-Json | Set-Content "$OutputPath\Get-AzureStackLog_Performance.json"

        $LogCollectionUploadNumberOfFiles = ($telInventory | Measure-Object).Count
        $LogCollectionUploadFileSizeInMb = $telOutputSizeMb

        # dump current process metrics, we can compare at the end
        # Trace-InvokingProcessStats -Role "Main_End"
        if ($roleTimeLog -ne $null)
        {
            Show-RoleTime -roleTimesCsvFilePath $roleTimeLog
        }
        else
        {
            Trace-Progress "RoleTime CSV FilePath is null. Cannot show graph of time to collect logs for each role." 
        }
        
        Write-ErrorsIfExist -Role "MainLogCollection"        
        $logCollectionDuration = ($ToDate - $FromDate).Totalhours.ToString("0.0##")
        $logCollectionTime = ((Get-Date) - $logCollectionStartDate).TotalMinutes.ToString("0.0##")

        # Mandatory trace statements as output file is parsed by StampTools.psm1 in SupportBridge repo
        Trace-Progress -Message "$functionName : LogCollectionUploadFileSizeInMb : $LogCollectionUploadFileSizeInMb"
        Trace-Progress -Message "$functionName : LogCollectionUploadNumberOfFiles : $LogCollectionUploadNumberOfFiles"
        Trace-Progress -Message "$functionName : LogCollectionUploadDirectory : $OutputFolderName"
        Trace-Progress -Message "$functionName : logCollectionTime : $logCollectionTime"
        Trace-Progress -Message "$functionName : logCollectionDuration : $logCollectionDuration"

        $collectionDetails.logCollectionUploadFileSizeInMb = $LogCollectionUploadFileSizeInMb
        $collectionDetails.logCollectionUploadNumberOfFiles = $LogCollectionUploadNumberOfFiles
        $collectionDetails.outputFolderName = $OutputFolderName
        $collectionDetails.logCollectionTime = $logCollectionTime
        $collectionDetails.logCollectionDuration = $logCollectionDuration

        # This has to be the last line before the transcipt ends, other wise LogCollection BVT validation would fail.
        Trace-Progress "$functionName : Completed collecting information for all roles - Get-AzureStackLog_Output for [$logCollectionDuration] hours took [$logCollectionTime] minutes, followed up by copying out to assigned destination."

        # Transcript needs tobe stopped as move-item would fail moving get-azurestacklog.
        Stop-Transcript
        $totalTime = ((Get-Date) - $logCollectionStartDate).TotalMinutes.ToString("0.0##")
        Trace-Progress "$functionName : Log collection completed duration [$totalTime] minutes"
    }
}

Export-ModuleMember -Function Invoke-AzureStackLogCollection
# SIG # Begin signature block
# MIInpAYJKoZIhvcNAQcCoIInlTCCJ5ECAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCDX3U++05rIxIAx
# Kjjv7NY64BaNDZUsjm5PSwtxJ7HLf6CCDYUwggYDMIID66ADAgECAhMzAAADTU6R
# phoosHiPAAAAAANNMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNVBAYTAlVTMRMwEQYD
# VQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNy
# b3NvZnQgQ29ycG9yYXRpb24xKDAmBgNVBAMTH01pY3Jvc29mdCBDb2RlIFNpZ25p
# bmcgUENBIDIwMTEwHhcNMjMwMzE2MTg0MzI4WhcNMjQwMzE0MTg0MzI4WjB0MQsw
# CQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9u
# ZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMR4wHAYDVQQDExVNaWNy
# b3NvZnQgQ29ycG9yYXRpb24wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB
# AQDUKPcKGVa6cboGQU03ONbUKyl4WpH6Q2Xo9cP3RhXTOa6C6THltd2RfnjlUQG+
# Mwoy93iGmGKEMF/jyO2XdiwMP427j90C/PMY/d5vY31sx+udtbif7GCJ7jJ1vLzd
# j28zV4r0FGG6yEv+tUNelTIsFmmSb0FUiJtU4r5sfCThvg8dI/F9Hh6xMZoVti+k
# bVla+hlG8bf4s00VTw4uAZhjGTFCYFRytKJ3/mteg2qnwvHDOgV7QSdV5dWdd0+x
# zcuG0qgd3oCCAjH8Z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