windows command changed to use CreateProcess (#30253)

* windows command changed to use CreateProcess

* change to get become to work
This commit is contained in:
Jordan Borean 2017-09-14 02:58:49 +10:00 committed by Matt Davis
commit 6d196eaa98
6 changed files with 669 additions and 221 deletions

View file

@ -1,88 +1,16 @@
#!powershell
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# WANT_JSON
# POWERSHELL_COMMON
# Copyright (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#Requires -Module Ansible.ModuleUtils.Legacy.psm1
#Requires -Module Ansible.ModuleUtils.CommandUtil.psm1
# TODO: add check mode support
Set-StrictMode -Version 2
$ErrorActionPreference = "Stop"
$helper_def = @'
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
namespace Ansible.Command
{
public static class NativeUtil
{
[DllImport("shell32.dll", SetLastError = true)]
static extern IntPtr CommandLineToArgvW([MarshalAs(UnmanagedType.LPWStr)] string lpCmdLine, out int pNumArgs);
public static string[] ParseCommandLine(string cmdline)
{
int numArgs;
IntPtr ret = CommandLineToArgvW(cmdline, out numArgs);
if (ret == IntPtr.Zero)
throw new Exception(String.Format("Error parsing command line: {0}", new Win32Exception(Marshal.GetLastWin32Error()).Message));
IntPtr[] strptrs = new IntPtr[numArgs];
Marshal.Copy(ret, strptrs, 0, numArgs);
string[] cmdlineParts = strptrs.Select(s=>Marshal.PtrToStringUni(s)).ToArray();
Marshal.FreeHGlobal(ret);
return cmdlineParts;
}
public static void GetProcessOutput(StreamReader stdoutStream, StreamReader stderrStream, out string stdout, out string stderr)
{
var sowait = new EventWaitHandle(false, EventResetMode.ManualReset);
var sewait = new EventWaitHandle(false, EventResetMode.ManualReset);
string so = null, se = null;
ThreadPool.QueueUserWorkItem((s)=>
{
so = stdoutStream.ReadToEnd();
sowait.Set();
});
ThreadPool.QueueUserWorkItem((s) =>
{
se = stderrStream.ReadToEnd();
sewait.Set();
});
foreach(var wh in new WaitHandle[] { sowait, sewait })
wh.WaitOne();
stdout = so;
stderr = se;
}
}
}
'@
$ErrorActionPreference = 'Stop'
$params = Parse-Args $args -supports_check_mode $false
@ -106,61 +34,24 @@ If($removes -and -not $(Test-Path -Path $removes)) {
Exit-Json @{msg="skipped, since $removes does not exist";cmd=$raw_command_line;changed=$false;skipped=$true;rc=0}
}
Add-Type -TypeDefinition $helper_def
$exec_args = $null
# FUTURE: extract this code to separate module_utils as Windows module API version of run_command
# Parse the command-line with the Win32 parser to get the application name to run. The Win32 parser
# will deal with quoting/escaping for us...
# FUTURE: no longer necessary once we switch to raw Win32 CreateProcess
$parsed_command_line = [Ansible.Command.NativeUtil]::ParseCommandLine($raw_command_line);
$exec_application = $parsed_command_line[0]
If($parsed_command_line.Length -gt 1) {
# lop the application off, then rejoin the args as a single string
$exec_args = $parsed_command_line[1..$($parsed_command_line.Length-1)] -join " "
}
$proc = New-Object System.Diagnostics.Process
$psi = $proc.StartInfo
$psi.FileName = $exec_application
$psi.Arguments = $exec_args
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$psi.UseShellExecute = $false
If ($chdir) {
$psi.WorkingDirectory = $chdir
}
$start_datetime = [DateTime]::UtcNow
Try {
$proc.Start() | Out-Null # will always return $true for non shell-exec cases
}
Catch [System.ComponentModel.Win32Exception] {
# fail nicely for "normal" error conditions
# FUTURE: this probably won't work on Nano Server
$excep = $_
Exit-Json @{msg = $excep.Exception.Message; cmd = $raw_command_line; changed = $false; rc = $excep.Exception.NativeErrorCode}
try {
$command_result = Run-Command -command $raw_command_line -working_directory $chdir
} catch {
$result.changed = $false
try {
$result.rc = $_.Exception.NativeErrorCode
} catch {
$result.rc = 2
}
Fail-Json -obj $result -message $_.Exception.Message
}
$stdout = $stderr = [string] $null
[Ansible.Command.NativeUtil]::GetProcessOutput($proc.StandardOutput, $proc.StandardError, [ref] $stdout, [ref] $stderr) | Out-Null
$result.stdout = $stdout
$result.stderr = $stderr
# TODO: decode CLIXML stderr output (and other streams?)
$proc.WaitForExit() | Out-Null
$result.rc = $proc.ExitCode
$result.stdout = $command_result.stdout
$result.stderr = $command_result.stderr
$result.rc = $command_result.rc
$end_datetime = [DateTime]::UtcNow
$result.start = $start_datetime.ToString("yyyy-MM-dd hh:mm:ss.ffffff")
$result.end = $end_datetime.ToString("yyyy-MM-dd hh:mm:ss.ffffff")
$result.delta = $($end_datetime - $start_datetime).ToString("h\:mm\:ss\.ffffff")

View file

@ -1,65 +1,17 @@
#!powershell
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# WANT_JSON
# POWERSHELL_COMMON
# Copyright (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#Requires -Module Ansible.ModuleUtils.Legacy.psm1
#Requires -Module Ansible.ModuleUtils.CommandUtil.psm1
# TODO: add check mode support
Set-StrictMode -Version 2
$ErrorActionPreference = "Stop"
$helper_def = @"
using System.Diagnostics;
using System.IO;
using System.Threading;
namespace Ansible.Shell
{
public class ProcessUtil
{
public static void GetProcessOutput(StreamReader stdoutStream, StreamReader stderrStream, out string stdout, out string stderr)
{
var sowait = new EventWaitHandle(false, EventResetMode.ManualReset);
var sewait = new EventWaitHandle(false, EventResetMode.ManualReset);
string so = null, se = null;
ThreadPool.QueueUserWorkItem((s)=>
{
so = stdoutStream.ReadToEnd();
sowait.Set();
});
ThreadPool.QueueUserWorkItem((s) =>
{
se = stderrStream.ReadToEnd();
sewait.Set();
});
foreach(var wh in new WaitHandle[] { sowait, sewait })
wh.WaitOne();
stdout = so;
stderr = se;
}
}
}
"@
# Cleanse CLIXML from stderr (sift out error stream data, discard others for now)
Function Cleanse-Stderr($raw_stderr) {
Try {
@ -110,12 +62,9 @@ If($removes -and -not $(Test-Path $removes)) {
Exit-Json @{msg="skipped, since $removes does not exist";cmd=$raw_command_line;changed=$false;skipped=$true;rc=0}
}
Add-Type -TypeDefinition $helper_def
$exec_args = $null
If(-not $executable -or $executable -eq "powershell") {
$exec_application = "powershell"
$exec_application = "powershell.exe"
# force input encoding to preamble-free UTF8 so PS sub-processes (eg, Start-Job) don't blow up
$raw_command_line = "[Console]::InputEncoding = New-Object Text.UTF8Encoding `$false; " + $raw_command_line
@ -123,53 +72,37 @@ If(-not $executable -or $executable -eq "powershell") {
# Base64 encode the command so we don't have to worry about the various levels of escaping
$encoded_command = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($raw_command_line))
$exec_args = @("-noninteractive", "-encodedcommand", $encoded_command)
$exec_args = "-noninteractive -encodedcommand $encoded_command"
}
Else {
# FUTURE: support arg translation from executable (or executable_args?) to process arguments for arbitrary interpreter?
$exec_application = $executable
$exec_args = @("/c", $raw_command_line)
}
$proc = New-Object System.Diagnostics.Process
$psi = $proc.StartInfo
$psi.FileName = $exec_application
$psi.Arguments = $exec_args
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$psi.UseShellExecute = $false
If ($chdir) {
$psi.WorkingDirectory = $chdir
if (-not ($exec_application.EndsWith(".exe"))) {
$exec_application = "$($exec_application).exe"
}
$exec_args = "/c $raw_command_line"
}
$command = "$exec_application $exec_args"
$start_datetime = [DateTime]::UtcNow
Try {
$proc.Start() | Out-Null # will always return $true for non shell-exec cases
try {
$command_result = Run-Command -command $command -working_directory $chdir
} catch {
$result.changed = $false
try {
$result.rc = $_.Exception.NativeErrorCode
} catch {
$result.rc = 2
}
Fail-Json -obj $result -message $_.Exception.Message
}
Catch [System.ComponentModel.Win32Exception] {
# fail nicely for "normal" error conditions
# FUTURE: this probably won't work on Nano Server
$excep = $_
Exit-Json @{msg = $excep.Exception.Message; cmd = $raw_command_line; changed = $false; rc = $excep.Exception.NativeErrorCode}
}
$stdout = $stderr = [string] $null
[Ansible.Shell.ProcessUtil]::GetProcessOutput($proc.StandardOutput, $proc.StandardError, [ref] $stdout, [ref] $stderr) | Out-Null
$result.stdout = $stdout
$result.stderr = Cleanse-Stderr $stderr
# TODO: decode CLIXML stderr output (and other streams?)
$proc.WaitForExit() | Out-Null
$result.rc = $proc.ExitCode
$result.stdout = $command_result.stdout
$result.stderr = Cleanse-Stderr $command_result.stderr
$result.rc = $command_result.rc
$end_datetime = [DateTime]::UtcNow
$result.start = $start_datetime.ToString("yyyy-MM-dd hh:mm:ss.ffffff")
$result.end = $end_datetime.ToString("yyyy-MM-dd hh:mm:ss.ffffff")
$result.delta = $($end_datetime - $start_datetime).ToString("h\:mm\:ss\.ffffff")