Public/host-management.ps1

function Remove-CSHost {
    <#
    .SYNOPSIS
        Deletes a host.

    .DESCRIPTION
        Wraps the deleteHost API, removing a host from CloudStack. Put the host into
        maintenance first so its workloads migrate off. Accepts host objects on the
        pipeline by their id.

    .PARAMETER Id
        The host to delete. Binds from a piped host's id.

    .EXAMPLE
        Remove-CSHost -Id host-uuid
        Deletes a host after prompting for confirmation.

    .EXAMPLE
        Get-CSHost -Name 'kvm-01' | Remove-CSHost
        Deletes a host located by name.
    #>

    [CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact='High')]
    param(
        [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)][string]$Id
    )
    process {
        if ($PSCmdlet.ShouldProcess("host $Id",'Delete')) { Invoke-CSApiRequest -Command deleteHost -Parameters @{ id=$Id } }
    }
}

function Disable-CSHostHA {
    <#
    .SYNOPSIS
        Disables high availability for a host.

    .DESCRIPTION
        Wraps the disableHAForHost API, turning off HA so the host is no longer
        monitored or fenced by the HA provider. Accepts host objects on the pipeline
        by their id.

    .PARAMETER Id
        The host to disable HA on. Binds from a piped host's id.

    .EXAMPLE
        Disable-CSHostHA -Id host-uuid
        Disables HA for a host.

    .EXAMPLE
        Get-CSHost -Name 'kvm-01' | Disable-CSHostHA
        Disables HA for a host located by name.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)][string]$Id
    )
    process {
        Invoke-CSApiRequest -Command disableHAForHost -Parameters @{ hostid=$Id }
    }
}

function Enable-CSHostHA {
    <#
    .SYNOPSIS
        Enables high availability for a host.

    .DESCRIPTION
        Wraps the enableHAForHost API, turning on HA so the host is monitored and
        fenced by the configured HA provider. Accepts host objects on the pipeline by
        their id.

    .PARAMETER Id
        The host to enable HA on. Binds from a piped host's id.

    .EXAMPLE
        Enable-CSHostHA -Id host-uuid
        Enables HA for a host.

    .EXAMPLE
        Get-CSHost -Name 'kvm-01' | Enable-CSHostHA
        Enables HA for a host located by name.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)][string]$Id
    )
    process {
        Invoke-CSApiRequest -Command enableHAForHost -Parameters @{ hostid=$Id }
    }
}

function Set-CSHostHA {
    <#
    .SYNOPSIS
        Configures host high availability.

    .DESCRIPTION
        Wraps the configureHAForHost API, setting which HA provider manages the host
        (see Get-CSHostHAProvider for the valid provider names). Accepts host objects
        on the pipeline by their id.

    .PARAMETER Id
        The host to configure. Binds from a piped host's id.

    .PARAMETER HaProvider
        The HA provider to use for the host.

    .EXAMPLE
        Set-CSHostHA -Id host-uuid -HaProvider XenServer
        Sets the HA provider for a host.

    .EXAMPLE
        Get-CSHost -Name 'kvm-01' | Set-CSHostHA -HaProvider kvmhaprovider
        Configures the HA provider on a host located by name.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)][string]$Id,
        [Parameter(Mandatory=$true)][string]$HaProvider
    )
    process {
        Invoke-CSApiRequest -Command configureHAForHost -Parameters @{ hostid=$Id; provider=$HaProvider }
    }
}

function Set-CSHostDegraded {
    <#
    .SYNOPSIS
        Marks a host as degraded.

    .DESCRIPTION
        Wraps the declareHostAsDegraded API, flagging an unreachable host as degraded
        so HA can recover its VMs elsewhere. Clear it again with Clear-CSHostDegraded.
        Accepts host objects on the pipeline by their id.

    .PARAMETER Id
        The host to mark degraded. Binds from a piped host's id.

    .PARAMETER Reason
        The reason the host is being declared degraded.

    .EXAMPLE
        Set-CSHostDegraded -Id host-uuid -Reason 'Storage path unavailable'
        Marks a host as degraded with a reason.

    .EXAMPLE
        Get-CSHost -Name 'kvm-01' | Set-CSHostDegraded -Reason 'Unreachable'
        Marks a host located by name as degraded.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)][string]$Id,
        [Parameter(Mandatory=$true)][string]$Reason
    )
    process {
        Invoke-CSApiRequest -Command declareHostAsDegraded -Parameters @{ id=$Id; reason=$Reason }
    }
}

function Clear-CSHostDegraded {
    <#
    .SYNOPSIS
        Clears a host's degraded status.

    .DESCRIPTION
        Wraps the cancelHostAsDegraded API, returning a host previously marked with
        Set-CSHostDegraded to normal status. Accepts host objects on the pipeline by
        their id.

    .PARAMETER Id
        The host to clear. Binds from a piped host's id.

    .EXAMPLE
        Clear-CSHostDegraded -Id host-uuid
        Clears a host's degraded status.

    .EXAMPLE
        Get-CSHost -Name 'kvm-01' | Clear-CSHostDegraded
        Clears the degraded status of a host located by name.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)][string]$Id
    )
    process {
        Invoke-CSApiRequest -Command cancelHostAsDegraded -Parameters @{ id=$Id }
    }
}

function Start-CSHostMaintenance {
    <#
    .SYNOPSIS
        Prepares a host for maintenance.

    .DESCRIPTION
        Wraps the prepareHostForMaintenance API, migrating VMs off the host and
        putting it into maintenance mode. Cancel it again with Stop-CSHostMaintenance.
        Accepts host objects on the pipeline by their id.

    .PARAMETER Id
        The host to put into maintenance. Binds from a piped host's id.

    .EXAMPLE
        Start-CSHostMaintenance -Id host-uuid
        Puts a host into maintenance mode.

    .EXAMPLE
        Get-CSHost -Name 'kvm-01' | Start-CSHostMaintenance
        Puts a host located by name into maintenance.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)][string]$Id
    )
    process {
        Invoke-CSApiRequest -Command prepareHostForMaintenance -Parameters @{ id=$Id }
    }
}

function Stop-CSHostMaintenance {
    <#
    .SYNOPSIS
        Cancels host maintenance preparation.

    .DESCRIPTION
        Wraps the cancelHostMaintenance API, bringing a host out of maintenance mode
        and back into service. Accepts host objects on the pipeline by their id.

    .PARAMETER Id
        The host to bring out of maintenance. Binds from a piped host's id.

    .EXAMPLE
        Stop-CSHostMaintenance -Id host-uuid
        Cancels maintenance on a host.

    .EXAMPLE
        Get-CSHost -Name 'kvm-01' | Stop-CSHostMaintenance
        Cancels maintenance on a host located by name.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)][string]$Id
    )
    process {
        Invoke-CSApiRequest -Command cancelHostMaintenance -Parameters @{ id=$Id }
    }
}

function Repair-CSHostConnection {
    <#
    .SYNOPSIS
        Reconnects a host to CloudStack management.

    .DESCRIPTION
        Wraps the reconnectHost API, forcing the management server to re-establish its
        connection to a host's agent. Accepts host objects on the pipeline by their
        id.

    .PARAMETER Id
        The host to reconnect. Binds from a piped host's id.

    .EXAMPLE
        Repair-CSHostConnection -Id host-uuid
        Reconnects a host to the management server.

    .EXAMPLE
        Get-CSHost -Name 'kvm-01' | Repair-CSHostConnection
        Reconnects a host located by name.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)][string]$Id
    )
    process {
        Invoke-CSApiRequest -Command reconnectHost -Parameters @{ id=$Id }
    }
}

function Clear-CSHostReservation {
    <#
    .SYNOPSIS
        Releases a host reservation.

    .DESCRIPTION
        Wraps the releaseHostReservation API, freeing a host that the allocator has
        reserved for a single account/domain so it can be used more broadly. Accepts
        host objects on the pipeline by their id.

    .PARAMETER Id
        The host to release. Binds from a piped host's id.

    .EXAMPLE
        Clear-CSHostReservation -Id host-uuid
        Releases a host reservation.

    .EXAMPLE
        Get-CSHost -Name 'kvm-01' | Clear-CSHostReservation
        Releases the reservation on a host located by name.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)][string]$Id
    )
    process {
        Invoke-CSApiRequest -Command releaseHostReservation -Parameters @{ id=$Id }
    }
}

function Set-CSHost {
    <#
    .SYNOPSIS
        Updates host configuration.

    .DESCRIPTION
        Wraps the updateHost API. Only the attributes you supply are changed; use
        -AllocationState to enable or disable the host for allocation and -HostTags to
        set its tags. Accepts host objects on the pipeline by their id.

    .PARAMETER Id
        The host to update. Binds from a piped host's id.

    .PARAMETER AllocationState
        Enable or Disable the host for allocation.

    .PARAMETER HostTags
        Comma-separated host tags.

    .PARAMETER OsCategoryId
        OS category ID to assign to the host.

    .PARAMETER Url
        Connection URL for the host.

    .PARAMETER Username
        Connection username for the host.

    .PARAMETER Password
        Connection password for the host.

    .EXAMPLE
        Set-CSHost -Id host-uuid -AllocationState Enable
        Enables a host for allocation.

    .EXAMPLE
        Get-CSHost -Name 'kvm-01' | Set-CSHost -HostTags 'ssd,gpu'
        Sets the tags on a host located by name.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)][string]$Id,
        [ValidateSet('Enable','Disable')][string]$AllocationState,
        [string]$HostTags,
        [string]$OsCategoryId,
        [string]$Url,
        [string]$Username,
        [string]$Password
    )
    process {
        $p=@{id=$Id}
        foreach($k in @('AllocationState','HostTags','OsCategoryId','Url','Username','Password')){if($PSBoundParameters.ContainsKey($k)){$p[$k.ToLowerInvariant()]=(Get-Variable $k -ValueOnly)}}
        Invoke-CSApiRequest -Command updateHost -Parameters $p
    }
}

function Set-CSHostPassword {
    <#
    .SYNOPSIS
        Changes host or cluster connection credentials.

    .DESCRIPTION
        Wraps the updateHostPassword API, updating the management server's stored
        credentials for a single host (-HostId) or every host in a cluster
        (-ClusterId); the two are mutually exclusive. -UpdatePasswordOnHost also
        changes the password on the host itself.

    .PARAMETER Username
        The connection username.

    .PARAMETER Password
        The new connection password.

    .PARAMETER HostId
        Update credentials for this single host.

    .PARAMETER ClusterId
        Update credentials for every host in this cluster.

    .PARAMETER UpdatePasswordOnHost
        Also change the password on the host itself, not just the stored copy.

    .EXAMPLE
        Set-CSHostPassword -HostId host-uuid -Username root -Password 'use-a-secret-store'
        Updates the stored credentials for one host.

    .EXAMPLE
        Set-CSHostPassword -ClusterId cluster-uuid -Username root -Password 'use-a-secret-store' -UpdatePasswordOnHost
        Updates every host in a cluster and applies the password on the hosts.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)][string]$Username,
        [Parameter(Mandatory=$true)][string]$Password,
        [string]$HostId,
        [string]$ClusterId,
        [switch]$UpdatePasswordOnHost
    )
    if($PSBoundParameters.ContainsKey('HostId') -and $PSBoundParameters.ContainsKey('ClusterId')){throw 'Specify HostId or ClusterId, not both.'}
    $p=@{username=$Username;password=$Password}
    if($PSBoundParameters.ContainsKey('HostId')){$p.hostid=$HostId}
    if($PSBoundParameters.ContainsKey('ClusterId')){$p.clusterid=$ClusterId}
    if($UpdatePasswordOnHost){$p.update_passwd_on_host='true'}
    Invoke-CSApiRequest -Command updateHostPassword -Parameters $p
}

function Get-CSHostTag {
    <#
    .SYNOPSIS
        Lists tags on a host.

    .DESCRIPTION
        Wraps the listHostTags API, returning the tags recorded for a host (the tags
        service offerings match against for placement).

    .PARAMETER Id
        The host whose tags to list.

    .EXAMPLE
        Get-CSHostTag -Id host-uuid
        Lists the tags on a host.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)][string]$Id
    )
    $r=Invoke-CSApiRequest -Command listHostTags -Parameters @{ id=$Id }
    if($r.listhosttagsresponse.hosttag){$r.listhosttagsresponse.hosttag}
}

function Get-CSHostHAProvider {
    <#
    .SYNOPSIS
        Lists available HA providers for a hypervisor.

    .DESCRIPTION
        Wraps the listHostHAProviders API, returning the HA provider names valid for a
        given hypervisor (used with Set-CSHostHA).

    .PARAMETER Hypervisor
        The hypervisor type to list HA providers for.

    .EXAMPLE
        Get-CSHostHAProvider -Hypervisor KVM
        Lists the HA providers available for KVM hosts.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)][string]$Hypervisor
    )
    $r=Invoke-CSApiRequest -Command listHostHAProviders -Parameters @{ hypervisor=$Hypervisor }
    if($r.listhosthaprovidersresponse.haprovider){$r.listhosthaprovidersresponse.haprovider}
}

function Get-CSHostHAResource {
    <#
    .SYNOPSIS
        Lists HA resources configured for hosts.

    .DESCRIPTION
        Wraps the listHostHAResources API, returning the HA state of hosts, optionally
        filtered to a single host.

    .PARAMETER HostId
        Filter to a single host.

    .EXAMPLE
        Get-CSHostHAResource
        Lists the HA state of every host.

    .EXAMPLE
        Get-CSHostHAResource -HostId host-uuid
        Shows the HA state of one host.
    #>

    [CmdletBinding()]
    param(
        [string]$HostId
    )
    $p=@{}
    if($PSBoundParameters.ContainsKey('HostId')){$p.hostid=$HostId}
    $r=Invoke-CSApiRequest -Command listHostHAResources -Parameters $p
    if($r.listhostharesourcesresponse.haresource){$r.listhostharesourcesresponse.haresource}
}

function Get-CSHostDedicated {
    <#
    .SYNOPSIS
        Lists dedicated hosts.

    .DESCRIPTION
        Wraps the listDedicatedHosts API, showing which hosts have been reserved for
        which accounts or domains (see Set-CSHostDedicated).

    .PARAMETER HostId
        Filter by host ID.

    .PARAMETER Name
        Filter by name.

    .PARAMETER ZoneId
        Filter by zone ID.

    .PARAMETER Account
        Filter by account name.

    .PARAMETER DomainId
        Filter by domain ID.

    .PARAMETER Page
        Page number of results to return.

    .PARAMETER PageSize
        Number of results per page.

    .EXAMPLE
        Get-CSHostDedicated -ZoneId zone-uuid
        Lists the dedicated hosts in a zone.

    .EXAMPLE
        Get-CSHostDedicated -DomainId domain-uuid
        Lists the hosts dedicated to a domain.
    #>

    [CmdletBinding()]
    param(
        [string]$HostId,
        [string]$Name,
        [string]$ZoneId,
        [string]$Account,
        [string]$DomainId,
        [int]$Page,
        [int]$PageSize
    )
    $p=@{}
    foreach($k in @('HostId','Name','ZoneId','Account','DomainId','Page','PageSize')){if($PSBoundParameters.ContainsKey($k)){$api=$k -replace 'HostId$','id' -replace 'ZoneId$','zoneid' -replace 'DomainId$','domainid'; $p[$api.ToLowerInvariant()]=(Get-Variable $k -ValueOnly)}}
    $r=Invoke-CSApiRequest -Command listDedicatedHosts -Parameters $p
    if($r.listdedicatedhostsresponse.host){$r.listdedicatedhostsresponse.host}
}

function Find-CSHostForMigration {
    <#
    .SYNOPSIS
        Finds eligible destination hosts for VM migration.

    .DESCRIPTION
        Wraps the findHostsForMigration API, returning the hosts a running VM can be
        live-migrated to, with suitability flags.

    .PARAMETER VirtualMachineId
        The VM to find migration targets for.

    .PARAMETER HostId
        Restrict the search to a specific host.

    .PARAMETER Keyword
        Filter by keyword.

    .PARAMETER Page
        Page number of results to return.

    .PARAMETER PageSize
        Number of results per page.

    .EXAMPLE
        Find-CSHostForMigration -VirtualMachineId vm-uuid
        Lists the hosts a VM can be migrated to.

    .EXAMPLE
        Find-CSHostForMigration -VirtualMachineId $vmId | Where-Object suitableformigration
        Lists only the hosts that are suitable migration targets.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)][string]$VirtualMachineId,
        [string]$HostId,
        [string]$Keyword,
        [int]$Page,
        [int]$PageSize
    )
    $p=@{virtualmachineid=$VirtualMachineId}
    foreach($k in @('HostId','Keyword','Page','PageSize')){if($PSBoundParameters.ContainsKey($k)){$n=if($k -eq 'HostId'){'hostid'}else{$k.ToLowerInvariant()};$p[$n]=(Get-Variable $k -ValueOnly)}}
    $r=Invoke-CSApiRequest -Command findHostsForMigration -Parameters $p
    if($r.findhostsformigrationresponse.host){$r.findhostsformigrationresponse.host}
}

function Set-CSHostDedicated {
    <#
    .SYNOPSIS
        Dedicates a host to a domain or account.

    .DESCRIPTION
        Wraps dedicateHost, reserving a host so only the given domain (or -Account
        within it) can run instances on it. Release it again with
        Clear-CSHostDedicated, and see current dedications with Get-CSHostDedicated.
        This is an asynchronous job; use -Wait to block until it finishes. Accepts
        host objects on the pipeline.

    .PARAMETER HostId
        The host to dedicate. Binds from a piped host's id.

    .PARAMETER DomainId
        The domain to dedicate the host to

    .PARAMETER Account
        Dedicate the host to this account within -DomainId

    .PARAMETER Wait
        Wait for the async job to finish and return the dedication

    .EXAMPLE
        Set-CSHostDedicated -HostId $hostId -DomainId $domainId -Wait
        Dedicates a host to a domain.

    .EXAMPLE
        Get-CSHost -Name 'kvm-01' | Set-CSHostDedicated -DomainId $domainId -Account 'engineering' -Wait
        Dedicates a host piped in by object to one account.
    #>

    [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
    param(
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [Alias('Id')]
        [string]$HostId,

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

        [string]$Account,

        [switch]$Wait
    )

    process {
        $apiParams = @{ hostid = $HostId; domainid = $DomainId }
        if ($PSBoundParameters.ContainsKey('Account')) { $apiParams['account'] = $Account }
        $owner = if ($Account) { "account $Account" } else { "domain $DomainId" }
        if ($PSCmdlet.ShouldProcess("host $HostId", "Dedicate to $owner")) {
            Invoke-CSAsyncApiRequest -Command 'dedicateHost' -Parameters $apiParams -Wait:$Wait
        }
    }
}

function Clear-CSHostDedicated {
    <#
    .SYNOPSIS
        Releases a host's dedication back to the system.

    .DESCRIPTION
        Wraps releaseDedicatedHost, undoing a dedication made with
        Set-CSHostDedicated so any account can run instances on the host again. This
        is an asynchronous job; use -Wait to block until it finishes. Accepts host
        objects on the pipeline.

    .PARAMETER HostId
        The host to release. Binds from a piped host's id.

    .PARAMETER Wait
        Wait for the async job to finish and return the result

    .EXAMPLE
        Clear-CSHostDedicated -HostId $hostId -Wait
        Releases a host's dedication.

    .EXAMPLE
        Get-CSHost -Name 'kvm-01' | Clear-CSHostDedicated -Wait
        Releases a host piped in by object.
    #>

    [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
    param(
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [Alias('Id')]
        [string]$HostId,

        [switch]$Wait
    )

    process {
        if ($PSCmdlet.ShouldProcess("host $HostId", 'Release dedication')) {
            Invoke-CSAsyncApiRequest -Command 'releaseDedicatedHost' -Parameters @{ hostid = $HostId } -Wait:$Wait
        }
    }
}