From 3c1529cffdbe71c316f7fad729d1b60272c23940 Mon Sep 17 00:00:00 2001 From: Konstantina Chremmou Date: Thu, 28 May 2020 00:12:04 +0100 Subject: [PATCH 1/4] Some script corrections: - In PoSh $null should be on the left side of comparisons. - Aliases should be avoided. - Missing PassThru. Signed-off-by: Konstantina Chremmou --- .../autogen/samples/AutomatedTestCore.ps1 | 116 +++++++++--------- powershell/autogen/samples/HttpTest.ps1 | 14 +-- 2 files changed, 65 insertions(+), 65 deletions(-) diff --git a/powershell/autogen/samples/AutomatedTestCore.ps1 b/powershell/autogen/samples/AutomatedTestCore.ps1 index 7ba57d3..2bf0b78 100644 --- a/powershell/autogen/samples/AutomatedTestCore.ps1 +++ b/powershell/autogen/samples/AutomatedTestCore.ps1 @@ -1,30 +1,30 @@ # -# Copyright (c) Citrix Systems, Inc. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# 1) Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# -# 2) Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE -# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, -# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, -# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED +# Copyright (c) Citrix Systems, Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1) Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# 2) Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials +# provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED # OF THE POSSIBILITY OF SUCH DAMAGE. # @@ -88,7 +88,7 @@ function log_error([String]$msg) { process { - if($err) + if($err) { write-error $msg } @@ -146,7 +146,7 @@ function exec([String]$test_name, [String]$cmd, [String]$expected) $fails.Add($test_name, $_.Exception) break } - + log_info ("Test '{0}' Started: cmd = {1}, expected = {2}" -f $test_name,$cmd,$expected) $result = Invoke-Expression $cmd if ($result -eq $expected) @@ -156,7 +156,7 @@ function exec([String]$test_name, [String]$cmd, [String]$expected) } else { - $exc = new-object Exception("Test '{0}' Failed: expected '{1}'; actual '{2}'" ` + $exc = New-Object Exception("Test '{0}' Failed: expected '{1}'; actual '{2}'" ` -f $test_name,$expected,$result) add_result $out_xml $cmd $test_name $exc $fails.Add($test_name, $exc) @@ -173,7 +173,7 @@ function connect_server([String]$svr, [String]$usr, [String]$pwd) log_info ("connecting to server '{0}'" -f $svr) $session = Connect-XenServer -Server $svr -UserName $usr -Password $pwd -PassThru - if($session -eq $null) + if($null -eq $session) { return $false } @@ -186,7 +186,7 @@ function disconnect_server([String]$svr) log_info ("disconnecting from server '{0}'" -f $svr) Get-XenSession -Server $svr | Disconnect-XenServer - if ((Get-XenSession -Server $svr) -eq $null) + if ($null -eq (Get-XenSession -Server $svr)) { return $true } @@ -205,9 +205,9 @@ function destroy_vm([XenAPI.VM]$vm) } log_info ("destroying vm '{0}'" -f $vm.name_label) - + $vdis = @() - + foreach($vbd in $vm.VBDs) { if((Get-XenVBDProperty -Ref $vbd -XenProperty Mode) -eq [XenAPI.vbd_mode]::RW) @@ -215,9 +215,9 @@ function destroy_vm([XenAPI.VM]$vm) $vdis += Get-XenVBDProperty -Ref $vbd -XenProperty VDI } } - + Remove-XenVM -VM $vm -Async -PassThru | Wait-XenTask -ShowProgress - + foreach($vdi in $vdis) { Remove-XenVDI -VDI $vdi -Async -PassThru | Wait-XenTask -ShowProgress @@ -249,20 +249,20 @@ function install_vm([String]$name, [String]$sr_name) #find a windows template log_info "looking for a Windows template..." - $template = @(Get-XenVM -Name 'Windows *' | where {$_.is_a_template})[0] + $template = @(Get-XenVM -Name 'Windows *' | Where-Object {$_.is_a_template})[0] log_info ("installing vm '{0}' from template '{1}'" -f $template.name_label,$name) - + #clone template log_info ("cloning vm '{0}' to '{1}'" -f $template.name_label,$name) Invoke-XenVM -VM $template -XenAction Clone -NewName $name -Async ` -PassThru | Wait-XenTask -ShowProgress - - $vm = Get-XenVM -Name $name + + $vm = Get-XenVM -Name $name $sr = Get-XenSR -Name $sr_name $other_config = $vm.other_config $other_config["disks"] = $other_config["disks"].Replace('sr=""', 'sr="{0}"' -f $sr.uuid) - + #add cd drive log_info ("creating cd drive for vm '{0}'" -f $vm.name_label) New-XenVBD -VM $vm -VDI $null -Userdevice 3 -Bootable $false -Mode RO ` @@ -270,25 +270,25 @@ function install_vm([String]$name, [String]$sr_name) -QosAlgorithmType "" -QosAlgorithmParams @{} Set-XenVM -VM $vm -OtherConfig $other_config - - #provision vm + + #provision vm log_info ("provisioning vm '{0}'" -f $vm.name_label) Invoke-XenVM -VM $vm -XenAction Provision -Async -PassThru | Wait-XenTask -ShowProgress - + return $true } function uninstall_vm([String]$name) { log_info ("uninstalling vm '{0}'" -f $name) - + $vms = Get-XenVM -Name $name - + foreach($vm in $vms) { destroy_vm($vm) } - + return $true } @@ -305,14 +305,14 @@ function vm_can_boot($vm_name, [XenApi.Host[]] $servers) { Invoke-XenVM -Name $vm_name -XenAction AssertCanBootHere -XenHost $server } - + if ($exceptions.Length -lt $servers.Length) { return $true } - + log_info "No suitable place to boot VM:" - + foreach ($excep in $script:exceptions) { log_info ("Reason: {0}" -f $excep.Message) @@ -358,7 +358,7 @@ function get_default_sr() { log_info ("getting default sr") $pool = Get-XenPool - return (Get-XenPool).default_SR | Get-XenSR + return $pool.default_SR | Get-XenSR } function create_nfs_sr([String]$sr_svr, [String]$sr_path, [String]$sr_name) @@ -370,7 +370,7 @@ function create_nfs_sr([String]$sr_svr, [String]$sr_path, [String]$sr_name) -Shared $true -SmConfig @{} -Async -PassThru ` | Wait-XenTask -ShowProgress -PassThru - if ($sr_opq -eq $null) + if ( $null -eq $sr_opq) { return $false } @@ -391,10 +391,10 @@ function detach_nfs_sr([String]$sr_name) Invoke-XenPBD -PBD $pbd -XenAction Unplug } } - - $sr_opq = Remove-XenSR -Name $sr_name -Async -PassThru | Wait-XenTask -ShowProgress - - if ($sr_opq -eq $null) + + $sr_opq = Remove-XenSR -Name $sr_name -Async -PassThru | Wait-XenTask -ShowProgress -PassThru + + if ($null -eq $sr_opq) { return $true } @@ -452,13 +452,13 @@ foreach($test in $tests) continue } $success = $false - - # Add randomness to the names of the test VM and SR to + + # Add randomness to the names of the test VM and SR to # allow a parallel execution context $cmd = $test[1] $cmd = $cmd -replace "PowerShellAutoTestVM", $vmName $cmd = $cmd -replace "PowerShellAutoTestSR", $srName - + $success = exec $test[0] $cmd $test[2] if ($success) { diff --git a/powershell/autogen/samples/HttpTest.ps1 b/powershell/autogen/samples/HttpTest.ps1 index f6f38df..5aada4b 100644 --- a/powershell/autogen/samples/HttpTest.ps1 +++ b/powershell/autogen/samples/HttpTest.ps1 @@ -1,19 +1,19 @@ # # Copyright (c) Citrix Systems, Inc. # All rights reserved. -# +# # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: -# +# # 1) Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. -# +# # 2) Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials # provided with the distribution. -# +# # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -42,12 +42,12 @@ Connect-XenServer -Server $svr -UserName $usr -Password $pwd ### Create a VM -$template = @(Get-XenVM -Name 'Windows *' | where {$_.is_a_template})[0] +$template = @(Get-XenVM -Name 'Windows *' | Where-Object {$_.is_a_template})[0] Invoke-XenVM -VM $template -XenAction Clone -NewName "testVM" -Async ` -PassThru | Wait-XenTask -ShowProgress - -$vm = Get-XenVM -Name "testVM" + +$vm = Get-XenVM -Name "testVM" $sr = Get-XenSR -Ref (Get-XenPool).default_SR $other_config = $vm.other_config $other_config["disks"] = $other_config["disks"].Replace('sr=""', 'sr="{0}"' -f $sr.uuid) From 22b37c2b4343a4a5f7038ef58a044f41ffb359cd Mon Sep 17 00:00:00 2001 From: Konstantina Chremmou Date: Wed, 27 May 2020 23:52:58 +0100 Subject: [PATCH 2/4] Fixed document format. Signed-off-by: Konstantina Chremmou --- .../autogen/samples/AutomatedTestCore.ps1 | 584 ++++++++---------- powershell/autogen/samples/HttpTest.ps1 | 26 +- 2 files changed, 277 insertions(+), 333 deletions(-) diff --git a/powershell/autogen/samples/AutomatedTestCore.ps1 b/powershell/autogen/samples/AutomatedTestCore.ps1 index 2bf0b78..1580e80 100644 --- a/powershell/autogen/samples/AutomatedTestCore.ps1 +++ b/powershell/autogen/samples/AutomatedTestCore.ps1 @@ -30,16 +30,16 @@ # Powershell Automated Tests -Param([Parameter(Mandatory=$true)][String]$out_xml, - [Parameter(Mandatory=$true)][String]$svr, - [Parameter(Mandatory=$true)][String]$usr, - [Parameter(Mandatory=$true)][String]$pwd, - [Parameter(Mandatory=$true)][String]$sr_svr, - [Parameter(Mandatory=$true)][String]$sr_path) +Param([Parameter(Mandatory = $true)][String]$out_xml, + [Parameter(Mandatory = $true)][String]$svr, + [Parameter(Mandatory = $true)][String]$usr, + [Parameter(Mandatory = $true)][String]$pwd, + [Parameter(Mandatory = $true)][String]$sr_svr, + [Parameter(Mandatory = $true)][String]$sr_path) # Initial Setup -[Net.ServicePointManager]::SecurityProtocol='tls,tls11,tls12' +[Net.ServicePointManager]::SecurityProtocol = 'tls,tls11,tls12' $BestEffort = $false $NoWarnCertificates = $true $info = $true @@ -53,367 +53,315 @@ $Wp = $WarningPreference $Ep = $ErrorPreference $ErrorActionPreference = "Stop" -$VerbosePreference="Continue" -$WarningPreference="Continue" -$ErrorPreference="Continue" +$VerbosePreference = "Continue" +$WarningPreference = "Continue" +$ErrorPreference = "Continue" $ErrorVariable # End Initial Setup # Helper Functions -function log_info([String]$msg) -{ - process - { - if($info) - { - write-verbose $msg - } - } +function log_info([String]$msg) { + process { + if ($info) { + write-verbose $msg + } + } } -function log_warn([String]$msg) -{ - process - { - if($warn) - { - write-warning $msg - } - } +function log_warn([String]$msg) { + process { + if ($warn) { + write-warning $msg + } + } } -function log_error([String]$msg) -{ - process - { - if($err) - { - write-error $msg - } - } +function log_error([String]$msg) { + process { + if ($err) { + write-error $msg + } + } } -function escape_for_xml([String]$content) -{ - return $content.replace("&", "&").replace("'", "'").replace('"', """).replace("<", "<").replace(">", ">") +function escape_for_xml([String]$content) { + return $content.replace("&", "&").replace("'", "'").replace('"', """).replace("<", "<").replace(">", ">") } -function prep_xml_output([String]$out_file) -{ - $date = Get-Date - "" > $out_file - ("Test Run Info: PowerShell bindings test {0}" -f $date) >> $out_file - "" >> $out_file +function prep_xml_output([String]$out_file) { + $date = Get-Date + "" > $out_file + ("Test Run Info: PowerShell bindings test {0}" -f $date) >> $out_file + "" >> $out_file } -function close_xml_output([String]$out_file) -{ - "" >> $out_file - "" >> $out_file +function close_xml_output([String]$out_file) { + "" >> $out_file + "" >> $out_file } -function add_result([String]$out_file,[String]$cmd, [String]$test_name, [Exception]$err) -{ - $out_cmd = escape_for_xml $cmd - $out_test_name = escape_for_xml $test_name - $out_err = escape_for_xml $err - "" >> $out_file - ("{0}" -f $out_test_name) >> $out_file - if (($err -ne $null)) - { - "Fail" >> $out_file - "" >> $out_file - ("Cmd: '{0}'" -f $out_cmd) >> $out_file - ("Exception: {0}" -f $out_err) >> $out_file - "" >> $out_file - } - else - { - "Pass" >> $out_file - "" >> $out_file - } - "" >> $out_file +function add_result([String]$out_file, [String]$cmd, [String]$test_name, [Exception]$err) { + $out_cmd = escape_for_xml $cmd + $out_test_name = escape_for_xml $test_name + $out_err = escape_for_xml $err + "" >> $out_file + ("{0}" -f $out_test_name) >> $out_file + if (($err -ne $null)) { + "Fail" >> $out_file + "" >> $out_file + ("Cmd: '{0}'" -f $out_cmd) >> $out_file + ("Exception: {0}" -f $out_err) >> $out_file + "" >> $out_file + } + else { + "Pass" >> $out_file + "" >> $out_file + } + "" >> $out_file } -function exec([String]$test_name, [String]$cmd, [String]$expected) -{ - trap [Exception] - { - add_result $out_xml $cmd $test $_.Exception - $fails.Add($test_name, $_.Exception) - break - } - - log_info ("Test '{0}' Started: cmd = {1}, expected = {2}" -f $test_name,$cmd,$expected) - $result = Invoke-Expression $cmd - if ($result -eq $expected) - { - add_result $out_xml $cmd $test_name $null - return $true - } - else - { - $exc = New-Object Exception("Test '{0}' Failed: expected '{1}'; actual '{2}'" ` - -f $test_name,$expected,$result) - add_result $out_xml $cmd $test_name $exc - $fails.Add($test_name, $exc) - return $false - } +function exec([String]$test_name, [String]$cmd, [String]$expected) { + trap [Exception] { + add_result $out_xml $cmd $test $_.Exception + $fails.Add($test_name, $_.Exception) + break + } + + log_info ("Test '{0}' Started: cmd = {1}, expected = {2}" -f $test_name, $cmd, $expected) + $result = Invoke-Expression $cmd + if ($result -eq $expected) { + add_result $out_xml $cmd $test_name $null + return $true + } + else { + $exc = New-Object Exception("Test '{0}' Failed: expected '{1}'; actual '{2}'" ` + -f $test_name, $expected, $result) + add_result $out_xml $cmd $test_name $exc + $fails.Add($test_name, $exc) + return $false + } } # End Helper Functions # Connect Functions -function connect_server([String]$svr, [String]$usr, [String]$pwd) -{ - log_info ("connecting to server '{0}'" -f $svr) - $session = Connect-XenServer -Server $svr -UserName $usr -Password $pwd -PassThru +function connect_server([String]$svr, [String]$usr, [String]$pwd) { + log_info ("connecting to server '{0}'" -f $svr) + $session = Connect-XenServer -Server $svr -UserName $usr -Password $pwd -PassThru - if($null -eq $session) - { - return $false - } - return $true + if ($null -eq $session) { + return $false + } + return $true } -function disconnect_server([String]$svr) -{ - log_info ("disconnecting from server '{0}'" -f $svr) - Get-XenSession -Server $svr | Disconnect-XenServer +function disconnect_server([String]$svr) { + log_info ("disconnecting from server '{0}'" -f $svr) + Get-XenSession -Server $svr | Disconnect-XenServer - if ($null -eq (Get-XenSession -Server $svr)) - { - return $true - } - return $false + if ($null -eq (Get-XenSession -Server $svr)) { + return $true + } + return $false } # End Connect Functions # VM Functions -function destroy_vm([XenAPI.VM]$vm) -{ - if ($vm -eq $null) - { - return - } +function destroy_vm([XenAPI.VM]$vm) { + if ($vm -eq $null) { + return + } - log_info ("destroying vm '{0}'" -f $vm.name_label) + log_info ("destroying vm '{0}'" -f $vm.name_label) - $vdis = @() + $vdis = @() - foreach($vbd in $vm.VBDs) - { - if((Get-XenVBDProperty -Ref $vbd -XenProperty Mode) -eq [XenAPI.vbd_mode]::RW) - { - $vdis += Get-XenVBDProperty -Ref $vbd -XenProperty VDI - } - } + foreach ($vbd in $vm.VBDs) { + if ((Get-XenVBDProperty -Ref $vbd -XenProperty Mode) -eq [XenAPI.vbd_mode]::RW) { + $vdis += Get-XenVBDProperty -Ref $vbd -XenProperty VDI + } + } - Remove-XenVM -VM $vm -Async -PassThru | Wait-XenTask -ShowProgress + Remove-XenVM -VM $vm -Async -PassThru | Wait-XenTask -ShowProgress - foreach($vdi in $vdis) - { - Remove-XenVDI -VDI $vdi -Async -PassThru | Wait-XenTask -ShowProgress - } + foreach ($vdi in $vdis) { + Remove-XenVDI -VDI $vdi -Async -PassThru | Wait-XenTask -ShowProgress + } } -function install_vm([String]$name, [String]$sr_name) -{ - trap [Exception] - { - trap [Exception] - { - log_warn "Clean up after failed vm install unsuccessful" - log_info "...failed!" - break - } - - log_info "Attempting to clean up after failed vm install..." - - $vms = Get-XenVM -Name $name - - foreach($vm in $vms) - { - destroy_vm($vm) - } - log_info "...success." - break - } - - #find a windows template - log_info "looking for a Windows template..." - $template = @(Get-XenVM -Name 'Windows *' | Where-Object {$_.is_a_template})[0] - - log_info ("installing vm '{0}' from template '{1}'" -f $template.name_label,$name) - - #clone template - log_info ("cloning vm '{0}' to '{1}'" -f $template.name_label,$name) - Invoke-XenVM -VM $template -XenAction Clone -NewName $name -Async ` - -PassThru | Wait-XenTask -ShowProgress - - $vm = Get-XenVM -Name $name - $sr = Get-XenSR -Name $sr_name - $other_config = $vm.other_config - $other_config["disks"] = $other_config["disks"].Replace('sr=""', 'sr="{0}"' -f $sr.uuid) - - #add cd drive - log_info ("creating cd drive for vm '{0}'" -f $vm.name_label) - New-XenVBD -VM $vm -VDI $null -Userdevice 3 -Bootable $false -Mode RO ` - -Type CD -Unpluggable $true -Empty $true -OtherConfig @{} ` - -QosAlgorithmType "" -QosAlgorithmParams @{} - - Set-XenVM -VM $vm -OtherConfig $other_config - - #provision vm - log_info ("provisioning vm '{0}'" -f $vm.name_label) - Invoke-XenVM -VM $vm -XenAction Provision -Async -PassThru | Wait-XenTask -ShowProgress - - return $true +function install_vm([String]$name, [String]$sr_name) { + trap [Exception] { + trap [Exception] { + log_warn "Clean up after failed vm install unsuccessful" + log_info "...failed!" + break + } + + log_info "Attempting to clean up after failed vm install..." + + $vms = Get-XenVM -Name $name + + foreach ($vm in $vms) { + destroy_vm($vm) + } + log_info "...success." + break + } + + #find a windows template + log_info "looking for a Windows template..." + $template = @(Get-XenVM -Name 'Windows *' | Where-Object { $_.is_a_template })[0] + + log_info ("installing vm '{0}' from template '{1}'" -f $template.name_label, $name) + + #clone template + log_info ("cloning vm '{0}' to '{1}'" -f $template.name_label, $name) + Invoke-XenVM -VM $template -XenAction Clone -NewName $name -Async -PassThru |` + Wait-XenTask -ShowProgress + + $vm = Get-XenVM -Name $name + $sr = Get-XenSR -Name $sr_name + $other_config = $vm.other_config + $other_config["disks"] = $other_config["disks"].Replace('sr=""', 'sr="{0}"' -f $sr.uuid) + + #add cd drive + log_info ("creating cd drive for vm '{0}'" -f $vm.name_label) + New-XenVBD -VM $vm -VDI $null -Userdevice 3 -Bootable $false -Mode RO ` + -Type CD -Unpluggable $true -Empty $true -OtherConfig @{ } ` + -QosAlgorithmType "" -QosAlgorithmParams @{ } + + Set-XenVM -VM $vm -OtherConfig $other_config + + #provision vm + log_info ("provisioning vm '{0}'" -f $vm.name_label) + Invoke-XenVM -VM $vm -XenAction Provision -Async -PassThru | Wait-XenTask -ShowProgress + + return $true } -function uninstall_vm([String]$name) -{ - log_info ("uninstalling vm '{0}'" -f $name) +function uninstall_vm([String]$name) { + log_info ("uninstalling vm '{0}'" -f $name) - $vms = Get-XenVM -Name $name + $vms = Get-XenVM -Name $name - foreach($vm in $vms) - { - destroy_vm($vm) - } + foreach ($vm in $vms) { + destroy_vm($vm) + } - return $true + return $true } -function vm_can_boot($vm_name, [XenApi.Host[]] $servers) -{ - trap [Exception] - { - $script:exceptions += $_.Exception - continue - } - - $script:exceptions = @() - foreach ($server in $servers) - { - Invoke-XenVM -Name $vm_name -XenAction AssertCanBootHere -XenHost $server - } - - if ($exceptions.Length -lt $servers.Length) - { - return $true - } - - log_info "No suitable place to boot VM:" - - foreach ($excep in $script:exceptions) - { - log_info ("Reason: {0}" -f $excep.Message) - } - - return $false +function vm_can_boot($vm_name, [XenApi.Host[]] $servers) { + trap [Exception] { + $script:exceptions += $_.Exception + continue + } + + $script:exceptions = @() + foreach ($server in $servers) { + Invoke-XenVM -Name $vm_name -XenAction AssertCanBootHere -XenHost $server + } + + if ($exceptions.Length -lt $servers.Length) { + return $true + } + + log_info "No suitable place to boot VM:" + + foreach ($excep in $script:exceptions) { + log_info ("Reason: {0}" -f $excep.Message) + } + + return $false } -function start_vm([String]$vm_name) -{ - if (vm_can_boot $vm_name @(Get-XenHost)) - { - log_info ("starting vm '{0}'" -f $vm_name) - } +function start_vm([String]$vm_name) { + if (vm_can_boot $vm_name @(Get-XenHost)) { + log_info ("starting vm '{0}'" -f $vm_name) + } - # even if we cant start it, attempt so we get the exception, reasons have been logged in vm_can_boot - Invoke-XenVM -Name $vm_name -XenAction Start -Async -PassThru | Wait-XenTask -ShowProgress - return Get-XenVM -Name $vm_name | Get-XenVMProperty -XenProperty PowerState + # even if we cant start it, attempt so we get the exception, reasons have been logged in vm_can_boot + Invoke-XenVM -Name $vm_name -XenAction Start -Async -PassThru | Wait-XenTask -ShowProgress + return Get-XenVM -Name $vm_name | Get-XenVMProperty -XenProperty PowerState } -function shutdown_vm([String]$vm_name) -{ - log_info ("shutting down vm '{0}'" -f $vm_name) - Invoke-XenVM -Name $vm_name -XenAction HardShutdown -Async -PassThru | Wait-XenTask -ShowProgress - return (Get-XenVM -Name $vm_name).power_state +function shutdown_vm([String]$vm_name) { + log_info ("shutting down vm '{0}'" -f $vm_name) + Invoke-XenVM -Name $vm_name -XenAction HardShutdown -Async -PassThru | Wait-XenTask -ShowProgress + return (Get-XenVM -Name $vm_name).power_state } # End VM Functions # Host Functions -function get_master() -{ - $pool = Get-XenPool - return Get-XenHost -Ref $pool.master +function get_master() { + $pool = Get-XenPool + return Get-XenHost -Ref $pool.master } # End Host Functions # SR Functions -function get_default_sr() -{ - log_info ("getting default sr") - $pool = Get-XenPool - return $pool.default_SR | Get-XenSR +function get_default_sr() { + log_info ("getting default sr") + $pool = Get-XenPool + return $pool.default_SR | Get-XenSR } -function create_nfs_sr([String]$sr_svr, [String]$sr_path, [String]$sr_name) -{ - log_info ("creating sr {0} at {1}:{2}" -f $sr_name,$sr_svr,$sr_path) - $master = get_master - $sr_opq = New-XenSR -XenHost $master -DeviceConfig @{ "server"=$sr_svr; "serverpath"=$sr_path; "options"="" } ` - -PhysicalSize 0 -NameLabel $sr_name -NameDescription "" -Type "nfs" -ContentType "" ` - -Shared $true -SmConfig @{} -Async -PassThru ` - | Wait-XenTask -ShowProgress -PassThru - - if ( $null -eq $sr_opq) - { - return $false - } - return $true +function create_nfs_sr([String]$sr_svr, [String]$sr_path, [String]$sr_name) { + log_info ("creating sr {0} at {1}:{2}" -f $sr_name, $sr_svr, $sr_path) + $master = get_master + $sr_opq = New-XenSR -XenHost $master -DeviceConfig @{ "server" = $sr_svr; "serverpath" = $sr_path; "options" = "" } ` + -PhysicalSize 0 -NameLabel $sr_name -NameDescription "" -Type "nfs" -ContentType "" ` + -Shared $true -SmConfig @{ } -Async -PassThru |` + Wait-XenTask -ShowProgress -PassThru + + if ( $null -eq $sr_opq) { + return $false + } + return $true } -function detach_nfs_sr([String]$sr_name) -{ - log_info ("destroying sr {0}" -f $sr_name) +function detach_nfs_sr([String]$sr_name) { + log_info ("destroying sr {0}" -f $sr_name) - $pbds = Get-XenPBD - $sr_opq = (Get-XenSR -Name $sr_name).opaque_ref + $pbds = Get-XenPBD + $sr_opq = (Get-XenSR -Name $sr_name).opaque_ref - foreach($pbd in $pbds) - { - if(($pbd.SR.opaque_ref -eq $sr_opq) -and $pbd.currently_attached) - { - Invoke-XenPBD -PBD $pbd -XenAction Unplug + foreach ($pbd in $pbds) { + if (($pbd.SR.opaque_ref -eq $sr_opq) -and $pbd.currently_attached) { + Invoke-XenPBD -PBD $pbd -XenAction Unplug + } } - } - $sr_opq = Remove-XenSR -Name $sr_name -Async -PassThru | Wait-XenTask -ShowProgress -PassThru + $sr_opq = Remove-XenSR -Name $sr_name -Async -PassThru | Wait-XenTask -ShowProgress -PassThru - if ($null -eq $sr_opq) - { - return $true - } - return $false + if ($null -eq $sr_opq) { + return $true + } + return $false } # End SR Functions # Helper Functions -function append_random_string_to([String]$toAppend, $length = 10) -{ - $randomisedString = $toAppend - $charSet = "0123456789abcdefghijklmnopqrstuvwxyz".ToCharArray() - for($i; $i -le $length; $i++) - { - $randomisedString += $charSet | Get-Random - } - return $randomisedString +function append_random_string_to([String]$toAppend, $length = 10) { + $randomisedString = $toAppend + $charSet = "0123456789abcdefghijklmnopqrstuvwxyz".ToCharArray() + for ($i; $i -le $length; $i++) { + $randomisedString += $charSet | Get-Random + } + return $randomisedString } # End Helper Functions @@ -421,61 +369,57 @@ function append_random_string_to([String]$toAppend, $length = 10) # Test List $tests = @( - @("Connect Server", "connect_server $svr $usr $pwd", $true), - @("Create SR", "create_nfs_sr $sr_svr $sr_path PowerShellAutoTestSR", $true), - @("Install VM", "install_vm PowerShellAutoTestVM PowerShellAutoTestSR", $true), - @("Start VM", "start_vm PowerShellAutoTestVM", "Running"), - @("Shutdown VM", "shutdown_vm PowerShellAutoTestVM", "Halted"), - @("Uninstall VM", "uninstall_vm 'PowerShellAutoTestVM'", $true), - @("Destroy SR", "detach_nfs_sr PowerShellAutoTestSR", $true), - @("Disconnect Server", "disconnect_server $svr", $true) - ) + @("Connect Server", "connect_server $svr $usr $pwd", $true), + @("Create SR", "create_nfs_sr $sr_svr $sr_path PowerShellAutoTestSR", $true), + @("Install VM", "install_vm PowerShellAutoTestVM PowerShellAutoTestSR", $true), + @("Start VM", "start_vm PowerShellAutoTestVM", "Running"), + @("Shutdown VM", "shutdown_vm PowerShellAutoTestVM", "Halted"), + @("Uninstall VM", "uninstall_vm 'PowerShellAutoTestVM'", $true), + @("Destroy SR", "detach_nfs_sr PowerShellAutoTestSR", $true), + @("Disconnect Server", "disconnect_server $svr", $true) +) # End Test List # Main Test Execution $complete = 0; $max = $tests.Count; -$fails = @{} +$fails = @{ } prep_xml_output $out_xml $vmName = append_random_string_to "PowerShellAutoTestVM" $srName = append_random_string_to "PowerShellAutoTestSR" -foreach($test in $tests) -{ - trap [Exception] - { - # we encountered an exception in running the test before it completed - # its already been logged, so continue - continue - } - $success = $false - - # Add randomness to the names of the test VM and SR to - # allow a parallel execution context - $cmd = $test[1] - $cmd = $cmd -replace "PowerShellAutoTestVM", $vmName - $cmd = $cmd -replace "PowerShellAutoTestSR", $srName - - $success = exec $test[0] $cmd $test[2] - if ($success) - { - $complete++ - } +foreach ($test in $tests) { + trap [Exception] { + # we encountered an exception in running the test before it completed + # its already been logged, so continue + continue + } + $success = $false + + # Add randomness to the names of the test VM and SR to + # allow a parallel execution context + $cmd = $test[1] + $cmd = $cmd -replace "PowerShellAutoTestVM", $vmName + $cmd = $cmd -replace "PowerShellAutoTestSR", $srName + + $success = exec $test[0] $cmd $test[2] + if ($success) { + $complete++ + } } close_xml_output $out_xml -$result = "Result: {0} completed out of {1}" -f $complete,$max; +$result = "Result: {0} completed out of {1}" -f $complete, $max; write-host $result -f 2 -if($fails.Count -gt 0) -{ - write-host "Failures:" - $fails +if ($fails.Count -gt 0) { + write-host "Failures:" + $fails } $ErrorActionPreference = $Eap diff --git a/powershell/autogen/samples/HttpTest.ps1 b/powershell/autogen/samples/HttpTest.ps1 index 5aada4b..e481295 100644 --- a/powershell/autogen/samples/HttpTest.ps1 +++ b/powershell/autogen/samples/HttpTest.ps1 @@ -29,23 +29,23 @@ # -Param([Parameter(Mandatory=$true)][String]$svr, - [Parameter(Mandatory=$true)][String]$usr, - [Parameter(Mandatory=$true)][String]$pwd, - [Parameter(Mandatory=$true)][String]$patchPath) +Param([Parameter(Mandatory = $true)][String]$svr, + [Parameter(Mandatory = $true)][String]$usr, + [Parameter(Mandatory = $true)][String]$pwd, + [Parameter(Mandatory = $true)][String]$patchPath) ### Connect to a server -[Net.ServicePointManager]::SecurityProtocol='tls,tls11,tls12' +[Net.ServicePointManager]::SecurityProtocol = 'tls,tls11,tls12' Connect-XenServer -Server $svr -UserName $usr -Password $pwd ### Create a VM -$template = @(Get-XenVM -Name 'Windows *' | Where-Object {$_.is_a_template})[0] +$template = @(Get-XenVM -Name 'Windows *' | Where-Object { $_.is_a_template })[0] -Invoke-XenVM -VM $template -XenAction Clone -NewName "testVM" -Async ` - -PassThru | Wait-XenTask -ShowProgress +Invoke-XenVM -VM $template -XenAction Clone -NewName "testVM" -Async -PassThru |` + Wait-XenTask -ShowProgress $vm = Get-XenVM -Name "testVM" $sr = Get-XenSR -Ref (Get-XenPool).default_SR @@ -53,8 +53,8 @@ $other_config = $vm.other_config $other_config["disks"] = $other_config["disks"].Replace('sr=""', 'sr="{0}"' -f $sr.uuid) New-XenVBD -VM $vm -VDI $null -Userdevice 3 -Bootable $false -Mode RO ` - -Type CD -Unpluggable $true -Empty $true -OtherConfig @{} ` - -QosAlgorithmType "" -QosAlgorithmParams @{} + -Type CD -Unpluggable $true -Empty $true -OtherConfig @{ } ` + -QosAlgorithmType "" -QosAlgorithmParams @{ } Set-XenVM -VM $vm -OtherConfig $other_config Invoke-XenVM -VM $vm -XenAction Provision -Async -PassThru | Wait-XenTask -ShowProgress @@ -64,7 +64,7 @@ Invoke-XenVM -VM $vm -XenAction Provision -Async -PassThru | Wait-XenTask -ShowP $path = $env:TEMP + "\vm.xva" -$trackDataReceived = [XenAPI.HTTP+DataCopiedDelegate]{ +$trackDataReceived = [XenAPI.HTTP+DataCopiedDelegate] { param($bytes); Write-Host "Bytes received: $bytes" } @@ -75,7 +75,7 @@ $vm | Remove-XenVM ### Import the previously exported VM using the ProgressDelegate parameter to track send progress -$trackProgress = [XenAPI.HTTP+UpdateProgressDelegate]{ +$trackProgress = [XenAPI.HTTP+UpdateProgressDelegate] { param($percent); Write-Progress -Activity "Importing Vm..." -PercentComplete $percent } @@ -84,7 +84,7 @@ Import-XenVm -XenHost $svr -Path $path -ProgressDelegate $trackProgress ### Upload a patch -$trackProgress = [XenAPI.HTTP+UpdateProgressDelegate]{ +$trackProgress = [XenAPI.HTTP+UpdateProgressDelegate] { param($percent); Write-Progress -Activity "Uploading patch..." -PercentComplete $percent } From c771cab1d6a04bb5aa8635128187d483f895cf57 Mon Sep 17 00:00:00 2001 From: Konstantina Chremmou Date: Thu, 28 May 2020 00:12:47 +0100 Subject: [PATCH 3/4] Added missing line breaks and replaced non-ASCII characters. Signed-off-by: Konstantina Chremmou --- powershell/about_XenServer.help.txt | 80 ++++++++++++++--------------- 1 file changed, 40 insertions(+), 40 deletions(-) diff --git a/powershell/about_XenServer.help.txt b/powershell/about_XenServer.help.txt index 508e673..afc17d4 100644 --- a/powershell/about_XenServer.help.txt +++ b/powershell/about_XenServer.help.txt @@ -2,14 +2,14 @@ XenServer PowerShell Module v@SDK_VERSION@ ---------------------------------- -This document provides a high level walk­through of the XenServer PowerShell Module +This document provides a high level walk-through of the XenServer PowerShell Module and the structure of its cmdlets. XenServer sessions ------------------ -The first cmdlet you will need is Connect‐XenServer to open a session to a server: +The first cmdlet you will need is Connect-XenServer to open a session to a server: PS> Connect-XenServer -Url https:// -UserName user -Password pwd @@ -34,7 +34,7 @@ default session has been specified. Once you have finished interacting with a server, it is good practice to log out using the cmdlet Disconnect-XenServer: - PS> Get‐XenSession | Disconnect‐XenServer + PS> Get-XenSession | Disconnect-XenServer Managing XenAPI objects @@ -45,112 +45,112 @@ The cmdlets fall into the following categories: 1. Class Getters These retrieve a XenAPI object and have names such as Get-XenT, where T is an - exposed XenAPI class. The object to get can be specified by ‐Ref or, for those - that have a uuid or name, ‐Name or ‐Uuid. If no parameters are specified, all + exposed XenAPI class. The object to get can be specified by -Ref or, for those + that have a uuid or name, -Name or -Uuid. If no parameters are specified, all objects of this type are returned. Example: - PS> Get‐XenHost ‐Name "Demo Host" + PS> Get-XenHost -Name "Demo Host" 2. Constructors These create a new XenAPI object and have names such as New-XenT, where T is an exposed XenAPI class. Example: - PS> $vm = Get‐XenVM ‐Name "Demo VM" - PS> New‐XenVBD ‐VM $vm ‐VDI $null ‐Userdevice 3 ‐Bootable $false ‐Mode RO - ‐Type CD ‐Unpluggable $true ‐Empty $true ‐OtherConfig @{} - ‐QosAlgorithmType "" ‐QosAlgorithmParams @{} + PS> $vm = Get-XenVM -Name "Demo VM" + PS> New-XenVBD -VM $vm -VDI $null -Userdevice 3 -Bootable $false -Mode RO ` + -Type CD -Unpluggable $true -Empty $true -OtherConfig @{} ` + -QosAlgorithmType "" -QosAlgorithmParams @{} 3. Class Removers These destroy a XenAPI object and have names such as Remove-XenT, where T is an exposed XenAPI class. To specify the object to remove use the parameter - ‐T, where T is the exposed XenAPI class, or ‐Ref or, for those objects that - have a uuid or name, ‐UUID or ‐Name. Example: + -T, where T is the exposed XenAPI class, or -Ref or, for those objects that + have a uuid or name, -UUID or -Name. Example: - PS> Get‐XenSR ‐Name "Demo SR" | Remove‐XenSR + PS> Get-XenSR -Name "Demo SR" | Remove-XenSR 4. Property Setters These set a field of a XenAPI object and have names such as Set-XenT, where - T is an exposed XenAPI class. To specify the object use the parameter ‐T, where - T is the exposed XenAPI class, or ‐Ref or, for those objects that have a uuid - or name, ‐UUID or ‐Name. The field to set can be specified as an accordingly + T is an exposed XenAPI class. To specify the object use the parameter -T, where + T is the exposed XenAPI class, or -Ref or, for those objects that have a uuid + or name, -UUID or -Name. The field to set can be specified as an accordingly named parameter. Note that more than one fields at a time can be set in a synchronous call. Example: - PS> Get‐XenVM ‐Name "Demo VM" | Set‐XenVM ‐NameLabel "New name" - -NameDescription "New description" + PS> Get-XenVM -Name "Demo VM" |` + Set-XenVM -NameLabel "New name" -NameDescription "New description" 5. Property Adders These add an element to a field of a XenAPI object and have names such as Add-XenT, where T is an exposed XenAPI class. To specify the object use the - parameter ‐T, where T is the exposed XenAPI class, or ‐Ref or, for those objects - that have a uuid or name, ‐UUID or ‐Name. The field to which the element + parameter -T, where T is the exposed XenAPI class, or -Ref or, for those objects + that have a uuid or name, -UUID or -Name. The field to which the element will be added can be specified as an accordingly named parameter. Note that elements can be added to more than one fields at a time in a synchronous call. Example: - PS> Add‐XenHost ‐Name "Demo Host" ‐Tags "Tag1" + PS> Add-XenHost -Name "Demo Host" -Tags "Tag1" 6. Property Removers These remove an element from a field of a XenAPI object and have names such as Remove-XenTProperty, where T is an exposed XenAPI class. To specify the - object use the parameter ‐T, where T is the exposed XenAPI class, or ‐Ref or, - for those objects that have a uuid or name, ‐UUID or ‐Name. The field from + object use the parameter -T, where T is the exposed XenAPI class, or -Ref or, + for those objects that have a uuid or name, -UUID or -Name. The field from which the element will be removed can be specified as an accordingly named parameter. Note that elements can be removed from more than one fields at a time in a synchronous call. Example: - PS> Remove‐XenHostProperty ‐Name "myHost" ‐Tags "tag1" ‐OtherConfig "myKey" + PS> Remove-XenHostProperty -Name "myHost" -Tags "tag1" -OtherConfig "myKey" 7. Property Getters These retrieve the value of a field of a XenAPI object and have names such as Get-XenTProperty, where T is an exposed XenAPI class. To specify the object - use the parameters ‐T, where T is the exposed XenAPI class, or ‐Ref. To specify - the field use the enum parameter ‐XenProperty. Example: + use the parameters -T, where T is the exposed XenAPI class, or -Ref. To specify + the field use the enum parameter -XenProperty. Example: - PS> Get‐XenPIFProperty ‐Ref OpaqueRef:f433bf7b‐2b0c‐5f53‐7018‐7d195addb3ca - ‐XenProperty Network + PS> Get-XenPIFProperty -Ref OpaqueRef:f433bf7b-2b0c-5f53-7018-7d195addb3ca ` + -XenProperty Network 8. Invokers These invoke operations on XenAPI objects and have names such as Invoke-XenT, where T is an exposed XenAPI class. To specify the object use the parameter - ‐T, where T is the exposed XenAPI class, or ‐Ref or, for those objects that - have a uuid or name, ‐UUID or ‐Name. To specify the call to invoke, use the - enum parameter ‐XenAction. Example: + -T, where T is the exposed XenAPI class, or -Ref or, for those objects that + have a uuid or name, -UUID or -Name. To specify the call to invoke, use the + enum parameter -XenAction. Example: - PS> Get‐XenPBD ‐Uuid 1871ac51‐ce6b‐efc3‐7fd0‐28bc65aa39ff | Invoke‐XenPBD - ‐XenAction Unplug + PS> Get-XenPBD -Uuid 1871ac51-ce6b-efc3-7fd0-28bc65aa39ff |` + Invoke-XenPBD -XenAction Unplug Most of the XenAPI calls can be run synchronously or asynchronously. To run a -cmdlet asynchronously use the parameter ‐Async where available. +cmdlet asynchronously use the parameter -Async where available. Note that, in the case of the setters, only one field can be set asynchronously at a time, and in the case of the adders and removers, elements can be added or removed asynchronously to only one field at a time. Also, note that the cmdlets that are not explicit "getters" but return objects, -do so only when the standard parameter ‐PassThru is specified. These cmdlets are -Connect‐XenServer, the constructors, adders, setters, certain invokers, +do so only when the standard parameter -PassThru is specified. These cmdlets are +Connect-XenServer, the constructors, adders, setters, certain invokers, the property removers, as well as all the asynchronous calls from any category. In the latter case, the cmdlet returns a Task object, the progress of which can be tracked by piping it into the cmdlet Wait-XenTask: - PS> Invoke-XenVM -Name $vm_name -XenAction Start -Async -PassThru - | Wait-XenTask -ShowProgress + PS> Invoke-XenVM -Name $vm_name -XenAction Start -Async -PassThru |` + Wait-XenTask -ShowProgress Wait-XenTask, too, can be used with the -PassThru parameter and, where applicable, it returns the opaque reference of the object that would be returned if the call were run synchronously. Finally, as many of the cmdlets handle objects of type XenRef, where T is an -exposed API class, the cmldet ConvertTo‐XenRef can be used to aid conversion +exposed API class, the cmldet ConvertTo-XenRef can be used to aid conversion between the two. Example: - PS> Get‐XenVM ‐Name "Demo VM" | ConvertTo‐XenRef + PS> Get-XenVM -Name "Demo VM" | ConvertTo-XenRef From 35e296d56c26c1620cfa46fa2e9ccbd2c1974a42 Mon Sep 17 00:00:00 2001 From: Konstantina Chremmou Date: Thu, 28 May 2020 04:26:48 +0100 Subject: [PATCH 4/4] CA-340392: Do not allow Invoke-* cmdlets to pass through the object on which the API call is run if the latter returns void. Signed-off-by: Konstantina Chremmou --- powershell/gen_powershell_binding.ml | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/powershell/gen_powershell_binding.ml b/powershell/gen_powershell_binding.ml index 0365702..557e58d 100644 --- a/powershell/gen_powershell_binding.ml +++ b/powershell/gen_powershell_binding.ml @@ -1500,9 +1500,14 @@ and gen_csharp_api_call message classname commonVerb switch = else "" in let syncPipe = gen_csharp_api_call_sync_pipe message classname in let passThruResult = - if switch = "pipe" then syncPipe - else if switch = "passthru" then print_pass_thru syncPipe - else "" in + match (switch, message.msg_result) with + | ("pipe", _) -> syncPipe + | ("passthru", None) -> " + if (PassThru) + WriteWarning(\"-PassThru can only be used with -Async for this cmdlet. Ignoring.\");" + | ("passthru", _) -> print_pass_thru syncPipe + | _ -> "" + in if message.msg_async then sprintf " var contxt = _context as %s;