| 1 |
# (c) 2025 Ansible Project |
| 2 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
|
| 4 |
#AnsibleRequires -CSharpUtil Ansible._Async |
| 5 |
|
| 6 |
using namespace System.Collections |
| 7 |
using namespace System.Diagnostics |
| 8 |
using namespace System.IO |
| 9 |
using namespace System.IO.Pipes |
| 10 |
using namespace System.Text |
| 11 |
using namespace System.Threading |
| 12 |
|
| 13 |
[CmdletBinding()] |
| 14 |
param ( |
| 15 |
[Parameter(Mandatory)] |
| 16 |
[string] |
| 17 |
$AsyncDir, |
| 18 |
|
| 19 |
[Parameter(Mandatory)] |
| 20 |
[string] |
| 21 |
$AsyncJid, |
| 22 |
|
| 23 |
[Parameter(Mandatory)] |
| 24 |
[int] |
| 25 |
$StartupTimeout |
| 26 |
) |
| 27 |
|
| 28 |
Import-CSharpUtil -Name 'Ansible._Async.cs' |
| 29 |
|
| 30 |
$AsyncDir = [Environment]::ExpandEnvironmentVariables($AsyncDir) |
| 31 |
if (-not [Directory]::Exists($asyncDir)) { |
| 32 |
$null = [Directory]::CreateDirectory($asyncDir) |
| 33 |
} |
| 34 |
|
| 35 |
$parentProcessId = 0 |
| 36 |
$parentProcessHandle = $stdoutReader = $stderrReader = $stdinPipe = $stdoutPipe = $stderrPipe = $asyncProcess = $waitHandle = $null |
| 37 |
try { |
| 38 |
$utf8 = [UTF8Encoding]::new($false) |
| 39 |
$stdinPipe = [AnonymousPipeServerStream]::new([PipeDirection]::Out, [HandleInheritability]::Inheritable) |
| 40 |
$stdoutPipe = [AnonymousPipeServerStream]::new([PipeDirection]::In, [HandleInheritability]::Inheritable) |
| 41 |
$stderrPipe = [AnonymousPipeServerStream]::new([PipeDirection]::In, [HandleInheritability]::Inheritable) |
| 42 |
$stdoutReader = [StreamReader]::new($stdoutPipe, $utf8, $false) |
| 43 |
$stderrReader = [StreamReader]::new($stderrPipe, $utf8, $false) |
| 44 |
$clientWaitHandle = $waitHandle = [Ansible._Async.AsyncUtil]::CreateInheritableEvent() |
| 45 |
|
| 46 |
$stdinHandle = $stdinPipe.ClientSafePipeHandle |
| 47 |
$stdoutHandle = $stdoutPipe.ClientSafePipeHandle |
| 48 |
$stderrHandle = $stderrPipe.ClientSafePipeHandle |
| 49 |
|
| 50 |
$executable = if ($PSVersionTable.PSVersion -lt '6.0') { |
| 51 |
'powershell.exe' |
| 52 |
} |
| 53 |
else { |
| 54 |
'pwsh.exe' |
| 55 |
} |
| 56 |
$executablePath = Join-Path -Path $PSHome -ChildPath $executable |
| 57 |
|
| 58 |
# We need to escape the job of the current process to allow the async |
| 59 |
# process to outlive the Windows job. If the current process is not part of |
| 60 |
# a job or job allows us to breakaway we can spawn the process directly. |
| 61 |
# Otherwise we use WMI Win32_Process.Create to create a process as our user |
| 62 |
# outside the job and use that as the async process parent. The winrm and |
| 63 |
# ssh connection plugin allows breaking away from the job but psrp does not. |
| 64 |
if (-not [Ansible._Async.AsyncUtil]::CanCreateBreakawayProcess()) { |
| 65 |
# We hide the console window and suspend the process to avoid it running |
| 66 |
# anything. We only need the process to be created outside the job and not |
| 67 |
# for it to run. |
| 68 |
$psi = New-CimInstance -ClassName Win32_ProcessStartup -ClientOnly -Property @{ |
| 69 |
CreateFlags = [uint32]4 # CREATE_SUSPENDED |
| 70 |
ShowWindow = [uint16]0 # SW_HIDE |
| 71 |
} |
| 72 |
$procInfo = Invoke-CimMethod -ClassName Win32_Process -Name Create -Arguments @{ |
| 73 |
CommandLine = $executablePath |
| 74 |
ProcessStartupInformation = $psi |
| 75 |
} |
| 76 |
$rc = $procInfo.ReturnValue |
| 77 |
if ($rc -ne 0) { |
| 78 |
$msg = switch ($rc) { |
| 79 |
2 { "Access denied" } |
| 80 |
3 { "Insufficient privilege" } |
| 81 |
8 { "Unknown failure" } |
| 82 |
9 { "Path not found" } |
| 83 |
21 { "Invalid parameter" } |
| 84 |
default { "Other" } |
| 85 |
} |
| 86 |
throw "Failed to start async parent process: $rc $msg" |
| 87 |
} |
| 88 |
|
| 89 |
# WMI returns a UInt32, we want the signed equivalent of those bytes. |
| 90 |
$parentProcessId = [Convert]::ToInt32( |
| 91 |
[Convert]::ToString($procInfo.ProcessId, 16), |
| 92 |
16) |
| 93 |
|
| 94 |
$parentProcessHandle = [Ansible._Async.AsyncUtil]::OpenProcessAsParent($parentProcessId) |
| 95 |
$clientWaitHandle = [Ansible._Async.AsyncUtil]::DuplicateHandleToProcess($waitHandle, $parentProcessHandle) |
| 96 |
$stdinHandle = [Ansible._Async.AsyncUtil]::DuplicateHandleToProcess($stdinHandle, $parentProcessHandle) |
| 97 |
$stdoutHandle = [Ansible._Async.AsyncUtil]::DuplicateHandleToProcess($stdoutHandle, $parentProcessHandle) |
| 98 |
$stderrHandle = [Ansible._Async.AsyncUtil]::DuplicateHandleToProcess($stderrHandle, $parentProcessHandle) |
| 99 |
$stdinPipe.DisposeLocalCopyOfClientHandle() |
| 100 |
$stdoutPipe.DisposeLocalCopyOfClientHandle() |
| 101 |
$stderrPipe.DisposeLocalCopyOfClientHandle() |
| 102 |
} |
| 103 |
|
| 104 |
$localJid = "$AsyncJid.$pid" |
| 105 |
$resultsPath = [Path]::Combine($AsyncDir, $localJid) |
| 106 |
|
| 107 |
$bootstrapWrapper = Get-AnsibleScript -Name bootstrap_wrapper.ps1 |
| 108 |
$execAction = Get-AnsibleExecWrapper -EncodeInputOutput |
| 109 |
|
| 110 |
$execAction.Parameters.ActionParameters = @{ |
| 111 |
ResultPath = $resultsPath |
| 112 |
WaitHandleId = [Int64]$clientWaitHandle.DangerousGetHandle() |
| 113 |
} |
| 114 |
$execWrapper = @{ |
| 115 |
name = 'exec_wrapper-async.ps1' |
| 116 |
script = $execAction.ScriptInfo.Script |
| 117 |
params = $execAction.Parameters |
| 118 |
} | ConvertTo-Json -Compress -Depth 99 |
| 119 |
$asyncInput = "$execWrapper`n`0`0`0`0`n$($execAction.InputData)" |
| 120 |
|
| 121 |
$encCommand = [Convert]::ToBase64String([Encoding]::Unicode.GetBytes($bootstrapWrapper.Script)) |
| 122 |
$asyncCommand = "`"$executablePath`" -NonInteractive -NoProfile -ExecutionPolicy Bypass -EncodedCommand $encCommand" |
| 123 |
|
| 124 |
$asyncProcess = [Ansible._Async.AsyncUtil]::CreateAsyncProcess( |
| 125 |
$executablePath, |
| 126 |
$asyncCommand, |
| 127 |
$stdinHandle, |
| 128 |
$stdoutHandle, |
| 129 |
$stderrHandle, |
| 130 |
$clientWaitHandle, |
| 131 |
$parentProcessHandle, |
| 132 |
$stdoutReader, |
| 133 |
$stderrReader) |
| 134 |
|
| 135 |
# We need to write the result file before the process is started to ensure |
| 136 |
# it can read the file. |
| 137 |
$result = @{ |
| 138 |
started = $true |
| 139 |
finished = $false |
| 140 |
results_file = $resultsPath |
| 141 |
ansible_job_id = $localJid |
| 142 |
_ansible_suppress_tmpdir_delete = $true |
| 143 |
ansible_async_watchdog_pid = $asyncProcess.ProcessId |
| 144 |
} |
| 145 |
$resultJson = ConvertTo-Json -InputObject $result -Depth 99 -Compress |
| 146 |
[File]::WriteAllText($resultsPath, $resultJson, $utf8) |
| 147 |
|
| 148 |
if ($parentProcessHandle) { |
| 149 |
[Ansible._Async.AsyncUtil]::CloseHandleInProcess($stdinHandle, $parentProcessHandle) |
| 150 |
[Ansible._Async.AsyncUtil]::CloseHandleInProcess($stdoutHandle, $parentProcessHandle) |
| 151 |
[Ansible._Async.AsyncUtil]::CloseHandleInProcess($stderrHandle, $parentProcessHandle) |
| 152 |
[Ansible._Async.AsyncUtil]::CloseHandleInProcess($clientWaitHandle, $parentProcessHandle) |
| 153 |
} |
| 154 |
else { |
| 155 |
$stdinPipe.DisposeLocalCopyOfClientHandle() |
| 156 |
$stdoutPipe.DisposeLocalCopyOfClientHandle() |
| 157 |
$stderrPipe.DisposeLocalCopyOfClientHandle() |
| 158 |
} |
| 159 |
|
| 160 |
[Ansible._Async.AsyncUtil]::ResumeThread($asyncProcess.Thread) |
| 161 |
|
| 162 |
# If writing to the pipe fails the process has already ended. |
| 163 |
$procAlive = $true |
| 164 |
$procIn = [StreamWriter]::new($stdinPipe, $utf8) |
| 165 |
try { |
| 166 |
$procIn.WriteLine($asyncInput) |
| 167 |
$procIn.Flush() |
| 168 |
$procIn.Dispose() |
| 169 |
} |
| 170 |
catch [IOException] { |
| 171 |
$procAlive = $false |
| 172 |
} |
| 173 |
|
| 174 |
if ($procAlive) { |
| 175 |
# Wait for the process to signal it has started the async task or if it |
| 176 |
# has ended early/timed out. |
| 177 |
$waitTimespan = [TimeSpan]::FromSeconds($StartupTimeout) |
| 178 |
$handleIdx = [WaitHandle]::WaitAny( |
| 179 |
@( |
| 180 |
[Ansible._Async.ManagedWaitHandle]::new($waitHandle), |
| 181 |
[Ansible._Async.ManagedWaitHandle]::new($asyncProcess.Process) |
| 182 |
), |
| 183 |
$waitTimespan) |
| 184 |
if ($handleIdx -eq [WaitHandle]::WaitTimeout) { |
| 185 |
$msg = -join @( |
| 186 |
"Ansible encountered a timeout while waiting for the async task to start and signal it has started. " |
| 187 |
"This can be affected by the performance of the target - you can increase this timeout using " |
| 188 |
"WIN_ASYNC_STARTUP_TIMEOUT or just for this host using the ansible_win_async_startup_timeout hostvar " |
| 189 |
"if this keeps happening." |
| 190 |
) |
| 191 |
throw $msg |
| 192 |
} |
| 193 |
$procAlive = $handleIdx -eq 0 |
| 194 |
} |
| 195 |
|
| 196 |
if ($procAlive) { |
| 197 |
$resultJson |
| 198 |
} |
| 199 |
else { |
| 200 |
# If the process had ended before it signaled it was ready, we return |
| 201 |
# back the raw output and hope it contains an error. |
| 202 |
Remove-Item -LiteralPath $resultsPath -ErrorAction Ignore |
| 203 |
|
| 204 |
$stdout = $asyncProcess.StdoutReader.GetAwaiter().GetResult() |
| 205 |
$stderr = $asyncProcess.StderrReader.GetAwaiter().GetResult() |
| 206 |
$rc = [Ansible._Async.AsyncUtil]::GetProcessExitCode($asyncProcess.Process) |
| 207 |
|
| 208 |
$host.UI.WriteLine($stdout) |
| 209 |
Write-PowerShellClixmlStderr -Output $stderr |
| 210 |
$host.SetShouldExit($rc) |
| 211 |
} |
| 212 |
} |
| 213 |
finally { |
| 214 |
if ($parentProcessHandle) { $parentProcessHandle.Dispose() } |
| 215 |
if ($parentProcessId) { |
| 216 |
Stop-Process -Id $parentProcessId -Force -ErrorAction Ignore |
| 217 |
} |
| 218 |
if ($stdoutReader) { $stdoutReader.Dispose() } |
| 219 |
if ($stderrReader) { $stderrReader.Dispose() } |
| 220 |
if ($stdinPipe) { $stdinPipe.Dispose() } |
| 221 |
if ($stdoutPipe) { $stdoutPipe.Dispose() } |
| 222 |
if ($stderrPipe) { $stderrPipe.Dispose() } |
| 223 |
if ($asyncProcess) { $asyncProcess.Dispose() } |
| 224 |
if ($waitHandle) { $waitHandle.Dispose() } |
| 225 |
} |