Private/Checks/VCenter/Test-VcfVcenterCheckDatastoreSpace.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-VcfVcenterCheckDatastoreSpace {

    <#
        .SYNOPSIS
        Reports free space on every datastore visible to every vCenter attached to SDDC Manager,
        warning on datastores that are inaccessible or exceed utilization thresholds.

        .DESCRIPTION
        Queries datastore inventory across all vCenters associated with SDDC Manager and reports
        capacity, free space, and accessibility status per domain.

        Datastores shared across clusters are deduplicated by MoRef ID (falling back to Name if ID is
        unavailable). The 'Storage Type' column normalizes underlying datastore types (e.g., VMFS, NFS, VSAN).

        Evaluates status per datastore:
        - Warning: Inaccessible datastores or datastores exceeding utilization thresholds:
            - vSAN datastores: Warns when utilization exceeds 80% (Free % < 20) to maintain required slack space.
            - Non-vSAN datastores: Warns when utilization exceeds 90% (Free % < 10).
        - Pass: Datastores that are accessible and within capacity thresholds.

        Datastores actively in maintenance mode (MaintenanceMode = 'inMaintenance') are exempt from
        utilization and accessibility warnings.

        .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 = ''
    )

    $vsanFreeThresholdPercent = 20
    $defaultFreeThresholdPercent = 10
    $vsanCapacityKbUrl = 'https://knowledge.broadcom.com/external/article/372112/resolving-storage-capacity-issues-in-a-v.html'
    $inaccessibleKbUrl = 'https://knowledge.broadcom.com/external/article/313878/datastore-shows-inaccessible-state-in-vc.html'

    return Invoke-VcfCheckPerVCenterCheck -Context $Context -CheckId 'vcenter_check_datastore_space' -Area vCenter -DisplayName $DisplayName -Body {
        param($Context, $VCenterFqdn)
        $datastores = @(Get-VcfCheckDatastoreInventory -Server $VCenterFqdn)

        if ($datastores.Count -eq 0) {
            return [PSCustomObject]@{ Status = 'Pass'; Detail = $null; Rows = @() }
        }

        $uniqueDatastores = @($datastores | Group-Object -Property { if ($_.Id) { $_.Id } else { $_.Name } } | ForEach-Object { $_.Group[0] })

        $warningNotes = @()
        $rows = @($uniqueDatastores | ForEach-Object {
            $isVsan = $_.Type -match 'vsan'
            $storageType = if ($isVsan) { 'VSAN' } elseif ($_.Type -match 'nfs') { 'NFS' } elseif ($_.Type -match 'vmfs') { 'VMFS' } else { $_.Type }
            $freeThresholdPercent = if ($isVsan) { $vsanFreeThresholdPercent } else { $defaultFreeThresholdPercent }
            $freePercent = if ($_.CapacityGB -gt 0) { [Math]::Round(($_.FreeSpaceGB / $_.CapacityGB) * 100, 2) } else { $null }
            $isAccessible = if ($null -eq $_.ExtensionData.Summary.Accessible) { $true } else { [Bool]$_.ExtensionData.Summary.Accessible }
            $inMaintenance = $_.ExtensionData.Summary.MaintenanceMode -eq 'inMaintenance'

            $notes = @()
            if ($inMaintenance) {
                $notes += 'Maintenance mode'
            } else {
                if (-not $isAccessible) { $notes += "Inaccessible - see $inaccessibleKbUrl" }
                if ($null -ne $freePercent -and $freePercent -lt $freeThresholdPercent) {
                    $notes += if ($isVsan) {
                        "$freePercent% free (over 80% full) - vSAN needs slack space for standard operations, see $vsanCapacityKbUrl to avoid VMs freezing"
                    } else {
                        "$freePercent% free (over 90% full) - Storage DRS will not be available to remedy this during the vCenter portion of the VCF 9 upgrade if VM-provisioned VMs expand to occupy the entire datastore; rebalance VMs onto other datastores or increase storage capacity before upgrading vCenter"
                    }
                }
            }
            $rowStatus = if ($notes.Count -gt 0 -and -not $inMaintenance) { 'Warning' } else { 'Pass' }
            if ($rowStatus -eq 'Warning') { $warningNotes += "$($_.Name) ($($notes -join ', '))" }

            [PSCustomObject]@{
                Datastore      = $_.Name
                'Storage Type' = $storageType
                'Free (GB)'    = [Math]::Round($_.FreeSpaceGB, 2)
                'Total (GB)'   = [Math]::Round($_.CapacityGB, 2)
                'Free %'       = $freePercent
                Status         = $rowStatus
            }
        } | Sort-Object -Property Datastore)

        if ($warningNotes.Count -gt 0) {
            return [PSCustomObject]@{ Status = 'Warning'; Detail = "Datastore(s) requiring attention: $($warningNotes -join '; ')."; Rows = $rows }
        }
        return [PSCustomObject]@{ Status = 'Pass'; Detail = $null; Rows = $rows }
    }
}