Migration/hyper_v/HyperV.psm1

using module '../../Common/Result'
Import-Module -Name @(Join-Path $PSScriptRoot .. | Join-Path -ChildPath .. | Join-Path -ChildPath MigrationProfile | Join-Path -ChildPath HyperVMigrationProfile)
Import-Module -Name @(Join-Path $PSScriptRoot .. | Join-Path -ChildPath .. | Join-Path -ChildPath CloudAccount | Join-Path -ChildPath CloudAccount)
Import-Module -Name @(Join-Path $PSScriptRoot .. | Join-Path -ChildPath .. | Join-Path -ChildPath Preflight | Join-Path -ChildPath Preflight)
Import-Module -Name @(Join-Path $PSScriptRoot .. | Join-Path -ChildPath .. | Join-Path -ChildPath Util | Join-Path -ChildPath Util)
Import-Module -Name @(Join-Path $PSScriptRoot .. | Join-Path -ChildPath .. | Join-Path -ChildPath Common | Join-Path -ChildPath Common)
Import-Module -Name @(Join-Path $PSScriptRoot .. | Join-Path -ChildPath .. | Join-Path -ChildPath RiverMeadow.Development.Source | Join-Path -ChildPath SourceUtil | Join-Path -ChildPath SourceUtil)
Import-Module -Name @(Join-Path $PSScriptRoot .. | Join-Path -ChildPath .. | Join-Path -ChildPath Common | Join-Path -ChildPath Wrappers | Join-Path -ChildPath Wrappers)

function Start-RMHyperVOSBasedNonInteractiveMigration {
    param (
        [string] $TargetCloud,
        [string] $SourceIP,
        [string] $ScheduledAt,
        [string] $TargetVMName,
        [System.Object[]] $MountPoint,
        [string] $DiskType,
        [string] $Cluster,
        [string] $HostName,
        [string] $VMLocation,
        [string] $DiskLocation,
        [int] $RAM,
        [int] $CPU,
        [System.Object[]] $DestinationNICConfig,
        [string] $DefaultGateway,
        [string] $PrimaryDNS,
        [string] $SecondaryDNS,
        [string[]] $ResizeMountPoint,
        [string] $NetBIOSName,
        [bool] $Sysprep,
        [string] $ConvertFileSystem,
        [string] $MigrationExtension,
        [string] $MigrationExtensionOSM,
        [string] $UpgradeOSVersion,
        [bool] $EnableOSHardening,
        [string] $OSHardeningProfile,
        [bool] $Level1Server,
        [bool] $Level2Server,
        [bool] $Level1Computer,
        [bool] $Level2Computer,
        [bool] $Level1User,
        [bool] $Level2User,
        [string] $AdministratorName,
        [string] $GuestName,
        [string] $LegalNoticeCaption,
        [string] $LegalNoticeText,
        [bool] $InstallAzureARC,
        [bool] $ConnectARCAgent,
        [bool] $RemoveRMSAgent,
        [bool] $IgnoreValidationError,
        [bool] $InstallAWSSSMAgent,
        [bool] $InstallAWSCloudWatchAgent,
        [bool] $DisableTargetDNSRegistration,
        [bool] $ShutdownSource,
        [bool] $ShutdownTarget,
        [string[]] $MigrationInstruction,
        [bool] $EnableCloudFilesMigration,
        [bool] $OverrideExistingMigration
    )

    $UserInput = @{}
    $CloudAccount = $null
    $CloudAccountErrors = $null
    $Source = $null
    $Entitlement = Get-RMEntitlement

    $Errors = @()
    $Warnings = @()
    $IsSourceAndTargetCloudPresent = $true
    $IsRequiredParametersPresentAndValid = $true

    try {
        if (![string]::IsNullOrEmpty($TargetCloud)) {
            $CloudAccount, $ErrorString = Get-RMCloudAccountByName -CloudAccountName $TargetCloud -AccountType "hyperv"
            if (![string]::IsNullOrEmpty($ErrorString)) {
                $CloudAccountErrors += $ErrorString
                $IsSourceAndTargetCloudPresent = $false
            } else {
                $TargetInventory = Get-RMTargetInventory -CloudAccount $CloudAccount
            }
        }
    } catch [System.Management.Automation.ItemNotFoundException] {
        $CloudAccountErrors += $PSItem.Exception.Message
        $IsSourceAndTargetCloudPresent = $false
    }

    if ($null -ne $CloudAccountErrors) {
        $Errors += $CloudAccountErrors
        $IsSourceAndTargetCloudPresent = $false
    }

    $ShouldExit = $false
    try {
        if (![string]::IsNullOrEmpty($SourceIP)) {
            $Source = Get-RMSourceByIP -IPAddress $SourceIP
        }
    } catch [System.Management.Automation.ItemNotFoundException] {
        $Errors += $PSItem.Exception.Message
        $IsSourceAndTargetCloudPresent = $false
    }

    if ($null -ne $CloudAccount) {
        $ProjectSettingsResponse = Invoke-RMProjectSettings -OrganizationId $CloudAccount.organization_id
    }

    $ParameterErrors, $ParameterWarnings, $IsSourceAndTargetCloudPresent, $IsRequiredParametersPresentAndValid = `
        Confirm-RMHyperVFullMigrationParameter $PSBoundParameters `
            -TargetInventory $TargetInventory -ProjectSettingsResponse $ProjectSettingsResponse
    $Errors += $ParameterErrors
    $Warnings += $ParameterWarnings

    [RMMigrationReturn] $RMMigrationReturn = [RMMigrationReturn]::new()
    if (!$IsSourceAndTargetCloudPresent -or !$IsRequiredParametersPresentAndValid) {
        Add-RMErrorAndWarning -RMReturnObject $RMMigrationReturn -ErrorMessage $Errors -WarningMessage $Warnings
        Out-RMUserParameterResult -ErrorMessage $Errors -WarningMessage $Warnings
        return $RMMigrationReturn
    }

    try {
        $Source, $ShouldExit, $OverrideExistingMigrationWarning, $OverrideExistingMigrationError = `
            Get-RMSourceWithAttribute -Source $Source -CloudAccount $CloudAccount `
                -IgnoreValidationErrors $IgnoreValidationError -AccountType "hyperv" `
                -RMMigrationReturn $RMMigrationReturn
    }
    catch [System.InvalidOperationException], [System.Management.Automation.RuntimeException] {
        $Errors += $PSItem.Exception.Message
        $IsRequiredParametersPresentAndValid = $false
    }

    $MigrationExtensionResponse = Get-RMMigrationExtension -OrganizationId $CloudAccount.organization_id
    $MigrationExtensionArray, $MigrationExtensionOSMArray = Get-RMMigrationExtensionFromStep -MigrationExtensionArray $MigrationExtensionResponse.content

    $OSHardening = Get-RMOSHardening -OrganizationId $CloudAccount.organization_id

    if ($null -ne $Source) {
        $SourceErrors = Confirm-RMHyperVFullMigrationParameterWithSource -UserParameter $PSBoundParameters -Source $Source `
            -MigrationExtension $MigrationExtensionArray -MigrationExtensionOSM $MigrationExtensionOSMArray -OSHardeningProfile $OSHardening.content
        $Errors += $SourceErrors
    }

    if ([string]::IsNullOrEmpty($TargetVMName)) {
        $TargetVMName = $Source.hostname
    }

    $SelectedMountPoints = $null
    $SourceMountPoints = Get-MountPoint -Source $Source
    if ($MountPoint.Count -gt 0) {
        $SelectedMountPoints = Get-RMSelectedMount -MountPoints $SourceMountPoints -DifferenceList $MountPoint -IncludeEqual $true
    } else {
        $SelectedMountPoints = $SourceMountPoints
    }

    $MountsResize = @{}
    if ($null -ne $ResizeMountPoint -and $ResizeMountPoint.Count -gt 0) {
        $MountsResize, $MountsResizeErrors = Get-RMResizeMountsPoint -ResizeMountPoints $ResizeMountPoint -SelectedMountPoints $SelectedMountPoints -Source $Source

        if (![string]::IsNullOrEmpty($MountsResizeErrors)) {
            $Errors += $MountsResizeErrors
        }

        if ("" -ne $TransferMethod -and "block-based" -eq $TransferMethod) {
            $Errors += "TransferMethod needs to be 'file-based' if you want to resize the mount points."
        }
        $TransferMethod = "file-based"
    } else {
        $TransferMethod, $SelectedMountPointArray, $ErrorString = Get-RMTransferMethod -Source $Source -SelectedMountPoints $SelectedMountPoints `
            -TransferMethod $TransferMethod
        if (![string]::IsNullOrEmpty($ErrorString)) {
            $Errors += $ErrorString
        }

        if ($SelectedMountPointArray -and $SelectedMountPointArray.Count -gt 0) {
            $SelectedMountPoints = $SelectedMountPointArray
        }
    }

    $UserInput.Add("SelectedMount", $SelectedMountPoints)

    $InstallAzureARCParameter = $null
    if ($InstallAzureARC) {
        $InstallAzureARCParameter = $ProjectSettingsResponse.hyperv.arc_settings
    }

    if ([string]::IsNullOrEmpty($NetBIOSName)) {
        $NetBIOSName = $Source.hostname
    }

    $MigrationInstructionsAsHashTable = $null
    try {
        if (($IgnoreValidationError -and $OverrideExistingMigration) -or (!$IgnoreValidationError -and $OverrideExistingMigration) -or $OverrideExistingMigrationWarning) {
            $MigrationInstruction += "override_source_migration=true"
        }
        $MigrationInstructionsAsHashTable = Get-RMStringArrayAsHashtable -InputItems $MigrationInstruction -ParameterName "MigrationInstruction"
    } catch {
        $Errors += $PSItem.Exception.Message
    }

    Add-RMOSUpgrade -UserParameter $PSBoundParameters -UpdatedParameter $UserInput -Source $Source

    Add-RMConvertFileSystem -Source $Source -UpdatedUserInput $UserInput -ConvertFileSystem $ConvertFileSystem

    Add-RMMigrationExtension -UpdatedParameter $UserInput -MigrationExtension $MigrationExtension `
        -MigrationExtensionOSM $MigrationExtensionOSM -MigrationExtensionResponse $MigrationExtensionResponse

    if (![string]::IsNullOrEmpty($ScheduledAt)) {
        $ScheduledAt = Convert-RMDateTimeToUTC -InputDateTime $ScheduledAt
    }

    $ErrorsOSHardening = Add-RMOSHardening -Source $Source -UpdatedParameter $UserInput -UserParameter $PSBoundParameters -OSHardeningProfile $OSHardening.content
    if ($null -ne $ErrorsOSHardening) {
        $Errors += $ErrorsOSHardening
    }

    Out-RMUserParameterResult -ErrorMessage $Errors -WarningMessage $Warnings
    if ($Errors.Count -gt 0 -or $ShouldExit) {
        Add-RMErrorAndWarning -RMReturnObject $RMMigrationReturn -ErrorMessage $Errors -WarningMessage $Warnings
        return $RMMigrationReturn
    }

    $HashArguments = @{
        CloudAccount              = $CloudAccount
        Entitlement               = $Entitlement
        Source                    = $Source
        ScheduledAt               = $ScheduledAt
        TransferMethod            = $TransferMethod
        TargetVMName              = $TargetVMName
        DiskType                  = $DiskType
        Cluster                   = $Cluster
        HostName                  = $HostName
        CPU                       = $CPU
        RAM                       = $RAM
        DestinationNICConfig      = $DestinationNICConfig
        DefaultGateway            = $DefaultGateway
        PrimaryDNS                = $PrimaryDNS
        SecondaryDNS              = $SecondaryDNS
        ResizeMountPoint          = $MountsResize
        NetBIOSName               = $NetBIOSName
        Sysprep                   = $Sysprep
        InstallAzureARC           = $InstallAzureARC
        ConnectARCAgent           = $ConnectARCAgent
        InstallAzureARCParameter  = $InstallAzureARCParameter
        RemoveRMSAgent            = $RemoveRMSAgent
        IgnoreValidationError     = $IgnoreValidationError
        InstallAWSSSMAgent        = $InstallAWSSSMAgent
        InstallAWSCloudWatchAgent = $InstallAWSCloudWatchAgent
        DisableTargetDNSRegistration = $DisableTargetDNSRegistration
        ShutdownSource            = $ShutdownSource
        ShutdownTarget            = $ShutdownTarget
        MigrationInstruction      = $MigrationInstructionsAsHashTable
        EnableCloudFilesMigration = $EnableCloudFilesMigration
        TargetInventory           = $TargetInventory
    }

    $HashArguments += $UserInput

    $Response = New-RMHyperVMigrationProfile @HashArguments
    if ($ShouldExit) {
        return $RMMigrationReturn
    }
    $IsScheduled = ![string]::IsNullOrWhiteSpace($ScheduledAt)
    $MigrationResponse = Invoke-RMMigrationPost -MigrationProfileResponse $Response
    return Update-RMMigrationReturnAsSuccess -MigrationResponse $MigrationResponse `
        -RMMigrationReturn $RMMigrationReturn -IsScheduledMigration $IsScheduled `
        -ReturnMessage "Migration started successfully, migration ID"
}

function Confirm-RMHyperVFullMigrationParameter {
    param (
        [hashtable] $UserParameter,
        [System.Object] $TargetInventory,
        [System.Object] $ProjectSettingsResponse
    )

    $Errors, $Warnings, $IsSourceAndTargetCloudPresent = Confirm-RMCommonParameter -UserParameter $UserParameter
    $hyperVErrors, $IsRequiredParametersPresentAndValid = Confirm-RMHyperVParameter -UserParameter $UserParameter `
        -TargetInventory $TargetInventory -ProjectSettingsResponse $ProjectSettingsResponse
    $Errors += $hyperVErrors
    return $Errors, $Warnings, $IsSourceAndTargetCloudPresent, $IsRequiredParametersPresentAndValid
}

function Confirm-RMHyperVFullMigrationParameterWithSource {
    param (
        [hashtable] $UserParameter,
        [System.Object] $Source,
        [System.Array] $MigrationExtension,
        [System.Array] $MigrationExtensionOSM,
        [System.Object] $OSHardeningProfile
    )

    $Errors = @()
    $ConfirmErrors = Confirm-RMCommonParameterWithSource -UserParameter $UserParameter -Source $Source `
        -MigrationExtension $MigrationExtension -MigrationExtensionOSM $MigrationExtensionOSM -OSHardeningProfile $OSHardeningProfile
    $Errors += $ConfirmErrors

    if ($Source.os_type -ne 'windows' -and $UserParameter["DisableTargetDNSRegistration"]) {
        $Errors += "DisableTargetDNSRegistration can only be 'true', if the source type is 'windows'."
    }

    return $Errors
}

function Confirm-RMHyperVCommonParameter {
    param (
        [hashtable] $UserParameter,
        [System.Object] $TargetInventory
    )

    $Errors = @()
    $IsRequiredParametersPresentAndValid = $true

    $SelectedCluster = $null

    if (!$UserParameter.ContainsKey("DiskType") -or [string]::IsNullOrWhiteSpace($UserParameter["DiskType"])) {
        $Errors += "DiskType is required."
        $IsRequiredParametersPresentAndValid = $false
    }
    
    if ($UserParameter.ContainsKey("Cluster") -and ![string]::IsNullOrWhiteSpace($UserParameter["Cluster"])) {
        $ClusterNames = $TargetInventory.attributes.hyperv.clusters.name
        if ($ClusterNames -notcontains $UserParameter["Cluster"]) {
            $ClusterName = $UserParameter["Cluster"]
            $Errors += "Cluster '$ClusterName' does not exist."
            $IsRequiredParametersPresentAndValid = $false
        } else {
            $SelectedCluster = $TargetInventory.attributes.hyperv.clusters | Where-Object { $_.name -eq $UserParameter["Cluster"] }
        }
    } else {
        $Errors += "Cluster is required."
        $IsRequiredParametersPresentAndValid = $false
    }

    $SelectedHost = $null
    if (!$UserParameter.ContainsKey("HostName") -or [string]::IsNullOrWhiteSpace($UserParameter["HostName"])) {
        $Errors += "Host is required."
        $IsRequiredParametersPresentAndValid = $false
    } else {
        if ($null -ne $SelectedCluster) {
            $HostNames = $SelectedCluster.hosts.name
            if ($HostNames -notcontains $UserParameter["HostName"]) {
                $HostName = $UserParameter["HostName"]
                $Errors += "Host '$HostName' does not exist in the selected cluster."
                $IsRequiredParametersPresentAndValid = $false
            } else {
                $SelectedHost = $SelectedCluster.hosts | Where-Object { $_.name -eq $UserParameter["HostName"] }
            }
        }
    }

    return $Errors, $IsRequiredParametersPresentAndValid, $SelectedHost
}

function Confirm-RMHyperVParameter {
    param (
        [hashtable] $UserParameter,
        [System.Object] $TargetInventory,
        [System.Object] $ProjectSettingsResponse
    )

    $Errors = @()

    $CommonErrors, $IsRequiredParametersPresentAndValid, $SelectedHost = Confirm-RMHyperVCommonParameter `
        -UserParameter $UserParameter -TargetInventory $TargetInventory

    $Errors += $CommonErrors

    $NetworkErrors, $IsNetworkValid = Confirm-RMHyperVDestinationNICConfigParameter -UserParameter $UserParameter -SelectedHost $SelectedHost
    $Errors += $NetworkErrors
    if (!$IsNetworkValid) {
        $IsRequiredParametersPresentAndValid = $false
    }

    if (!$UserParameter.ContainsKey("InstallAzureARC") -or !$UserParameter["InstallAzureARC"]) {
        if ($UserParameter.ContainsKey("ConnectARCAgent")) {
            if ($UserParameter["ConnectARCAgent"]) {
                $Errors += "'InstallAzureARC' must be true, when parameter 'ConnectARCAgent' is not empty."
            }
        }
    } elseif ($UserParameter.ContainsKey("InstallAzureARC") -and $UserParameter["InstallAzureARC"] `
                -and $UserParameter.ContainsKey("ConnectARCAgent") -and $UserParameter["ConnectARCAgent"] `
                -and $null -ieq $ProjectSettingsResponse.hyperv.arc_settings) {
        $Errors += "'ConnectARCAgent' cannot be true."
    }

    return $Errors, $IsRequiredParametersPresentAndValid
}

function Confirm-RMHyperVDestinationNICConfigParameter {
    param(
        [hashtable] $UserParameter,
        [System.Object] $SelectedHost
    )

    $Errors = @()
    $IsValid = $true

    if (!$UserParameter.ContainsKey("DestinationNICConfig") -or $null -eq $UserParameter["DestinationNICConfig"] -or $UserParameter["DestinationNICConfig"].Count -eq 0) {
        $Errors += "DestinationNICConfig is required."
        return $Errors, $false
    }

    $VirtualSwitchNames = $SelectedHost.virtual_switches.name
    $ValidIPTypes = @("static", "dhcp")
    $HasStaticNIC = $false

    for ($i = 0; $i -lt $UserParameter["DestinationNICConfig"].Count; $i++) {
        $config = $UserParameter["DestinationNICConfig"][$i]

        if ([string]::IsNullOrEmpty($config.VirtualSwitchName)) {
            $Errors += "VirtualSwitchName is required for each NIC configuration."
            $IsValid = $false
        } elseif ($SelectedHost -and $VirtualSwitchNames -and $VirtualSwitchNames -notcontains $config.VirtualSwitchName) {
            $SwitchName = $config.VirtualSwitchName
            $Errors += "VirtualSwitch '$SwitchName' does not exist on the selected host."
            $IsValid = $false
        }

        $IPType = if ([string]::IsNullOrEmpty($config.IPType)) { "" } else { $config.IPType.ToLower() }
        if ($ValidIPTypes -notcontains $IPType) {
            $Errors += "IPType '$($config.IPType)' is not valid. Must be one of: $($ValidIPTypes -join ', ')"
            $IsValid = $false
            continue
        }

        if ($IPType -eq "static") {
            $HasStaticNIC = $true
            if ([string]::IsNullOrEmpty($config.IPAddress)) {
                $Errors += "'IPAddress' is required for NIC $i when 'IPType' is 'static'."
                $IsValid = $false
            }
            if ([string]::IsNullOrEmpty($config.Netmask)) {
                $Errors += "'Netmask' is required for NIC $i when 'IPType' is 'static'."
                $IsValid = $false
            }
        } else {
            if (![string]::IsNullOrEmpty($config.IPAddress)) {
                $Errors += "'IPAddress' can only be specified for NIC $i when 'IPType' is 'static'."
                $IsValid = $false
            }
            if (![string]::IsNullOrEmpty($config.Netmask)) {
                $Errors += "'Netmask' can only be specified for NIC $i when 'IPType' is 'static'."
                $IsValid = $false
            }
        }
    }

    if ($HasStaticNIC) {
        if (!$UserParameter.ContainsKey("DefaultGateway") -or [string]::IsNullOrEmpty($UserParameter["DefaultGateway"])) {
            $Errors += "'DefaultGateway' is required when a NIC in 'DestinationNICConfig' has 'IPType' set to 'static'."
            $IsValid = $false
        }
    } elseif ($UserParameter.ContainsKey("DefaultGateway") -and ![string]::IsNullOrEmpty($UserParameter["DefaultGateway"])) {
        $Errors += "'DefaultGateway' can only be specified when a NIC in 'DestinationNICConfig' has 'IPType' set to 'static'."
        $IsValid = $false
    }

    return $Errors, $IsValid
}

Export-ModuleMember -Function Start-RMHyperVOSBasedNonInteractiveMigration