Private/Checks/VCenter/Test-VcfVcenterCheckHostsMemoryUsage.ps1

# Copyright (c) 2026 Broadcom. All Rights Reserved.
# Broadcom Confidential. The term "Broadcom" refers to Broadcom Inc.
# and/or its subsidiaries.
#
# =============================================================================
#
# SOFTWARE LICENSE AGREEMENT
#
# Copyright (c) CA, Inc. All rights reserved.
#
# You are hereby granted a non-exclusive, worldwide, royalty-free license
# under CA, Inc.'s copyrights to use, copy, modify, and distribute this
# software in source code or binary form for use in connection with CA, Inc.
# products.
#
# This copyright notice shall be included in all copies or substantial
# portions of the software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
# =============================================================================
function Test-VcfVcenterCheckHostsMemoryUsage {

    <#
        .SYNOPSIS
        Checks ESX host memory utilization against RED/YELLOW/GREEN thresholds.

        .DESCRIPTION
        Queries host memory utilization across all vCenter domains attached to SDDC Manager using
        Get-VcfCheckVMHostInventory.

        Evaluates memory utilization thresholds for each host:
        - Memory Usage >= 95%: Evaluated as RED (Fail).
        - 80% <= Memory Usage < 95%: Evaluated as YELLOW (Warning).
        - Memory Usage < 80%: Evaluated as GREEN (Pass).

        Any host evaluated as RED or YELLOW causes the domain check to return a Warning status.
        Populates HostDetails (ClusterName, HostName, UsedPercent, FreeMemoryGB, Status) grouped
        and rendered per-cluster with an expandable per-host breakdown.

        Iterates across all vCenter domains using Invoke-VcfCheckPerVCenterCheck.

        .PARAMETER Context
        The VcfCheck.Context object. Must already be connected to SDDC Manager.

        .PARAMETER DisplayName
        Optional friendly display name for the check result.

        .OUTPUTS
        [PSObject[]] Per-vCenter check results generated by Invoke-VcfCheckPerVCenterCheck.
    #>


    [CmdletBinding()]
    [OutputType([PSObject])]
    Param (
        [Parameter(Mandatory = $true)] [PSObject]$Context,
        [Parameter(Mandatory = $false)] [String]$DisplayName = ''
    )

    return Invoke-VcfCheckPerVCenterCheck -Context $Context -CheckId 'vcenter_check_hosts_memory_usage' -Area vCenter -DisplayName $DisplayName -Body {
        param($Context, $VCenterFqdn)
        $hosts = @(Get-VcfCheckVMHostInventory -Server $VCenterFqdn)

        $hostDetails = [System.Collections.Generic.List[PSCustomObject]]::new()
        $flagged = [System.Collections.Generic.List[String]]::new()
        foreach ($vmhost in $hosts) {
            if ($vmhost.MemoryTotalGB -le 0) { continue }
            $percentage = [Math]::Round(($vmhost.MemoryUsageGB / $vmhost.MemoryTotalGB) * 100, 2)
            $freeMemoryGB = [Math]::Round($vmhost.MemoryTotalGB - $vmhost.MemoryUsageGB, 1)
            $level = if ($percentage -ge 95) { 'RED' } elseif ($percentage -ge 80) { 'YELLOW' } else { 'GREEN' }
            $status = if ($level -eq 'RED') { 'Fail' } elseif ($level -eq 'YELLOW') { 'Warning' } else { 'Pass' }
            $hostDetails.Add([PSCustomObject]@{
                    ClusterName  = $vmhost.Parent.Name
                    HostName     = $vmhost.Name
                    UsedPercent  = $percentage
                    FreeMemoryGB = $freeMemoryGB
                    Status       = $status
                })
            if ($level -ne 'GREEN') {
                $flagged.Add("$($vmhost.Name): $percentage% ($level)")
            }
        }
        $hostDetails = @($hostDetails | Sort-Object -Property ClusterName, HostName)

        if ($flagged.Count -gt 0) {
            return [PSCustomObject]@{ Status = 'Warning'; Detail = "Host(s) above the memory utilization threshold: $($flagged -join '; ')"; HostDetails = $hostDetails }
        }
        return [PSCustomObject]@{ Status = 'Pass'; Detail = "Checked $($hosts.Count) host(s); all are below 80% memory utilization."; HostDetails = $hostDetails }
    }
}