File: src\Aspire.Hosting\Dcp\Process\ProcessUtil.cs
Web Access
Project: src\src\Aspire.Hosting.Dotnet\Aspire.Hosting.Dotnet.csproj (Aspire.Hosting.Dotnet)
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
 
using System.Diagnostics;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Text;
using Aspire.Hosting.Utils;
 
namespace Aspire.Hosting.Dcp.Process;
 
internal static partial class ProcessUtil
{
    #region Native Methods
 
    [LibraryImport("libc", SetLastError = true, EntryPoint = "kill")]
    private static partial int sys_kill(int pid, int sig);
 
    #endregion
 
    private static readonly TimeSpan s_processExitTimeout = TimeSpan.FromSeconds(5);
 
    public static (Task<ProcessResult>, IAsyncDisposable) Run(ProcessSpec processSpec)
    {
        if (processSpec.Arguments is not null && processSpec.ArgumentList is not null)
        {
            throw new ArgumentException($"Specify either {nameof(ProcessSpec.Arguments)} or {nameof(ProcessSpec.ArgumentList)}, not both.", nameof(processSpec));
        }
 
        var retainedOutputLineCount = processSpec.RetainedOutputLineCount ?? (processSpec.ThrowOnNonZeroReturnCode ? ProcessSpec.DefaultRetainedOutputLineCount : 0);
        ArgumentOutOfRangeException.ThrowIfNegative(retainedOutputLineCount);
 
        ProcessOutputCapture? outputCapture = retainedOutputLineCount > 0
            ? new(retainedOutputLineCount)
            : null;
 
        var resolvedExecutablePath = processSpec.ResolveExecutablePath
            ? PathLookupHelper.ResolveExecutablePath(processSpec.ExecutablePath, processSpec.EnvironmentVariables)
            : processSpec.ExecutablePath;
 
        var process = new System.Diagnostics.Process()
        {
            StartInfo =
            {
                FileName = resolvedExecutablePath,
                WorkingDirectory = processSpec.WorkingDirectory ?? string.Empty,
                Arguments = processSpec.Arguments ?? string.Empty,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                RedirectStandardInput = processSpec.StandardInputContent != null,
                UseShellExecute = false,
                CreateNoWindow = true,
                WindowStyle = ProcessWindowStyle.Hidden,
            },
            EnableRaisingEvents = true
        };
 
        if (processSpec.ArgumentList is not null)
        {
            foreach (var argument in processSpec.ArgumentList)
            {
                process.StartInfo.ArgumentList.Add(argument);
            }
        }
 
        if (!processSpec.InheritEnv)
        {
            process.StartInfo.Environment.Clear();
        }
 
        foreach (var (key, value) in processSpec.EnvironmentVariables)
        {
            process.StartInfo.Environment[key] = value;
        }
 
        // WaitForExitAsync also waits for redirected output to reach EOF. Descendants may
        // inherit those pipes, so observe the root's exit independently of output draining.
        // See https://github.com/dotnet/runtime/issues/29232#issuecomment-1451584094.
        var processExited = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
        var stopRequested = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
        process.Exited += (_, _) => processExited.TrySetResult();
        var processLifetimeTcs = new TaskCompletionSource<ProcessResult>();
 
        process.Start();
        processSpec.OnStart?.Invoke(process.Id);
 
        _ = Task.Run(async () =>
        {
            using var inputCancellation = new CancellationTokenSource();
            using var outputCancellation = new CancellationTokenSource();
            try
            {
                var stdoutTask = ReadOutputAsync(process.StandardOutput, processSpec.OnOutputData, outputCancellation.Token);
                var stderrTask = ReadOutputAsync(process.StandardError, processSpec.OnErrorData, outputCancellation.Token);
                var inputTask = WriteStandardInputAsync(inputCancellation.Token);
                IOException? inputError = null;
                var inputShutdownRequested = false;
                try
                {
                    // A descendant can inherit stdin after the root exits. Allow an in-flight write
                    // to finish, but cancel it if the root is gone or disposal is requested and the
                    // pipe stays full; otherwise it can retain the complete input indefinitely.
                    var first = await Task.WhenAny(inputTask, processExited.Task, stopRequested.Task).ConfigureAwait(false);
                    if (first != inputTask && !inputTask.IsCompleted)
                    {
                        if (processExited.Task.IsCompleted && !stopRequested.Task.IsCompleted)
                        {
                            await Task.WhenAny(inputTask, stopRequested.Task, Task.Delay(s_processExitTimeout)).ConfigureAwait(false);
                        }
 
                        if (!inputTask.IsCompleted)
                        {
                            inputCancellation.Cancel();
                        }
                    }
 
                    await inputTask.ConfigureAwait(false);
                }
                catch (OperationCanceledException ex) when (inputCancellation.IsCancellationRequested)
                {
                    inputError = new IOException("Standard input could not be fully written before the process exited or was stopped.", ex);
                }
                catch (IOException ex)
                {
                    inputError = ex;
                }
 
                if (inputError is not null)
                {
                    // A child can reject input before emitting diagnostics and exiting. Give it
                    // the normal exit grace period, but do not wait indefinitely if it stays alive.
                    try
                    {
                        await processExited.Task.WaitAsync(s_processExitTimeout).ConfigureAwait(false);
                    }
                    catch (TimeoutException)
                    {
                        if (!process.HasExited)
                        {
                            // Once the grace period expires with a live root, the input error
                            // owns the result even if natural exit races the shutdown attempt.
                            inputShutdownRequested = true;
                            Kill(process, processSpec.KillEntireProcessTree);
                        }
                    }
                }
 
                await processExited.Task.ConfigureAwait(false);
                var outputTask = Task.WhenAll(stdoutTask, stderrTask);
                try
                {
                    await outputTask.WaitAsync(s_processExitTimeout).ConfigureAwait(false);
                }
                catch (TimeoutException)
                {
                    // Once the root is gone, reparented descendants cannot reliably be killed
                    // through Process.Kill. Cancel our reads after allowing buffered diagnostics
                    // to drain, and wait for any active callbacks before returning the result.
                    outputCancellation.Cancel();
                    await outputTask.ConfigureAwait(false);
                }
 
                processSpec.OnStop?.Invoke(process.ExitCode);
 
                // Like text capture, preserve a natural nonzero result for caller-defined result
                // handling. A zero exit cannot hide incomplete input, nor can an exit after
                // we committed to shutting down a child that outlived its input-error grace.
                if (inputError is not null && (inputShutdownRequested || process.ExitCode == 0))
                {
                    ExceptionDispatchInfo.Capture(inputError).Throw();
                }
 
                if (processSpec.ThrowOnNonZeroReturnCode && process.ExitCode != 0)
                {
                    var message = $"Command {processSpec.ExecutablePath} {FormatProcessArgumentsForDisplay(processSpec)} returned non-zero exit code {process.ExitCode}";
 
                    if (outputCapture?.TotalLineCount > 0)
                    {
                        message = $"{message}{Environment.NewLine}{outputCapture.GetFormattedOutput()}";
                    }
 
                    processLifetimeTcs.TrySetException(new InvalidOperationException(message));
                }
                else
                {
                    processLifetimeTcs.TrySetResult(CreateProcessResult(process.ExitCode, outputCapture));
                }
            }
            catch (Exception ex)
            {
                inputCancellation.Cancel();
                outputCancellation.Cancel();
                processLifetimeTcs.TrySetException(ex);
            }
        });
 
        return (processLifetimeTcs.Task, new ProcessDisposable(process, processLifetimeTcs.Task, processSpec.KillEntireProcessTree, stopRequested));
 
        async Task WriteStandardInputAsync(CancellationToken cancellationToken)
        {
            if (processSpec.StandardInputContent is not null)
            {
                var writer = process.StandardInput;
                try
                {
                    await writer.WriteLineAsync(processSpec.StandardInputContent.AsMemory(), cancellationToken).ConfigureAwait(false);
                    await writer.FlushAsync(cancellationToken).ConfigureAwait(false);
                }
                finally
                {
                    // Flush only on success; closing the writer could retry a failed write and
                    // replace the original exception. Closing its stream still delivers EOF.
                    writer.BaseStream.Close();
                }
            }
        }
 
        async Task ReadOutputAsync(StreamReader reader, Action<string>? onData, CancellationToken cancellationToken)
        {
            // Start both readers independently, even when a stream has buffered data or a callback blocks.
            await Task.Yield();
            using (reader)
            {
                var buffer = new char[1024];
                var line = new StringBuilder();
                var previousWasCarriageReturn = false;
 
                while (true)
                {
                    int count;
                    try
                    {
                        count = await reader.ReadAsync(buffer.AsMemory(), cancellationToken).ConfigureAwait(false);
                    }
                    catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
                    {
                        break;
                    }
                    catch (IOException)
                    {
                        // Process's asynchronous line reader also treats a broken output pipe as EOF.
                        break;
                    }
 
                    if (count == 0)
                    {
                        break;
                    }
 
                    for (var i = 0; i < count; i++)
                    {
                        var c = buffer[i];
                        if (c is '\r' or '\n')
                        {
                            if (c == '\n' && previousWasCarriageReturn)
                            {
                                previousWasCarriageReturn = false;
                                continue;
                            }
 
                            EmitLine();
                            previousWasCarriageReturn = c == '\r';
                        }
                        else
                        {
                            previousWasCarriageReturn = false;
                            line.Append(c);
                        }
                    }
                }
 
                // Preserve an unterminated diagnostic even if a descendant prevented EOF.
                EmitLine();
 
                void EmitLine()
                {
                    if (line.Length == 0)
                    {
                        return;
                    }
 
                    var text = line.ToString();
                    line.Clear();
                    outputCapture?.Add(text);
                    onData?.Invoke(text);
                }
            }
        }
    }
 
    private static string FormatProcessArgumentsForDisplay(ProcessSpec processSpec)
    {
        return processSpec.Arguments ?? string.Join(" ", processSpec.ArgumentList?.Select(FormatProcessArgumentForDisplay) ?? []);
    }
 
    private static string FormatProcessArgumentForDisplay(string argument)
    {
        // This string is only for diagnostics and EventSource payloads; ProcessStartInfo.ArgumentList is still what
        // supplies argv to the child process. Quote values using the same escaping shape expected by Windows command
        // lines so spaces, quotes, and empty strings are readable instead of ambiguous.
        // See https://learn.microsoft.com/cpp/c-language/parsing-c-command-line-arguments
        if (argument.Length > 0 && !argument.Any(static c => char.IsWhiteSpace(c) || c == '"'))
        {
            return argument;
        }
 
        var builder = new StringBuilder(argument.Length + 2);
        builder.Append('"');
 
        var backslashCount = 0;
        foreach (var c in argument)
        {
            if (c == '\\')
            {
                backslashCount++;
                continue;
            }
 
            if (c == '"')
            {
                builder.Append('\\', backslashCount * 2 + 1);
                builder.Append('"');
            }
            else
            {
                builder.Append('\\', backslashCount);
                builder.Append(c);
            }
 
            backslashCount = 0;
        }
 
        builder.Append('\\', backslashCount * 2);
        builder.Append('"');
 
        return builder.ToString();
    }
 
    private static ProcessResult CreateProcessResult(int exitCode, ProcessOutputCapture? outputCapture)
    {
        if (outputCapture is null)
        {
            return new ProcessResult(exitCode);
        }
 
        return new ProcessResult(exitCode, outputCapture.ToArray(), outputCapture.TotalLineCount);
    }
 
    private static void Kill(System.Diagnostics.Process process, bool entireProcessTree)
    {
        try
        {
            process.Kill(entireProcessTree);
        }
        catch (Exception ex) when ((ex is InvalidOperationException or System.ComponentModel.Win32Exception) && process.HasExited)
        {
            // Natural exit can race the shutdown attempt.
        }
    }
 
    private sealed class ProcessDisposable : IAsyncDisposable
    {
        private readonly System.Diagnostics.Process _process;
        private readonly Task _processLifetimeTask;
        private readonly bool _entireProcessTree;
        private readonly TaskCompletionSource _stopRequested;
        private int _disposed;
 
        public ProcessDisposable(System.Diagnostics.Process process, Task processLifetimeTask, bool entireProcessTree, TaskCompletionSource stopRequested)
        {
            _process = process;
            _processLifetimeTask = processLifetimeTask;
            _entireProcessTree = entireProcessTree;
            _stopRequested = stopRequested;
        }
 
        public async ValueTask DisposeAsync()
        {
            if (Interlocked.Exchange(ref _disposed, 1) != 0)
            {
                return;
            }
 
            _stopRequested.TrySetResult();
            try
            {
                if (_process.HasExited && _processLifetimeTask.IsCompleted)
                {
                    return;
                }
 
                if (!_process.HasExited)
                {
                    if (OperatingSystem.IsWindows())
                    {
                        if (!_process.CloseMainWindow())
                        {
                            Kill(_process, _entireProcessTree);
                        }
                    }
                    else
                    {
                        sys_kill(_process.Id, sig: 2); // SIGINT
                    }
                }
 
                try
                {
                    await _processLifetimeTask.WaitAsync(s_processExitTimeout).ConfigureAwait(false);
                }
                catch (IOException) when (_process.HasExited)
                {
                    // The lifetime task reports the input error to its own caller.
                }
                catch (InvalidOperationException) when (_process.HasExited && _processLifetimeTask.IsFaulted)
                {
                    // A nonzero exit is also reported by the lifetime task.
                }
                catch (TimeoutException)
                {
                    if (!_process.HasExited)
                    {
                        Kill(_process, entireProcessTree: true);
                    }
 
                    try
                    {
                        await _processLifetimeTask.WaitAsync(s_processExitTimeout).ConfigureAwait(false);
                    }
                    catch (IOException) when (_process.HasExited)
                    {
                        // Killing the child can break a pending stdin write as well.
                    }
                    catch (InvalidOperationException) when (_process.HasExited && _processLifetimeTask.IsFaulted)
                    {
                        // A nonzero exit is also reported by the lifetime task.
                    }
                    catch (TimeoutException)
                    {
                        // A caller's output callback may still be running; do not dispose its process underneath it.
                    }
                }
 
                if (!_process.HasExited)
                {
                    // Always try to kill the entire process tree here if all of the above has failed.
                    Kill(_process, entireProcessTree: true);
                }
            }
            finally
            {
                if (_processLifetimeTask.IsCompleted)
                {
                    _process.Dispose();
                }
            }
        }
    }
}