Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
57 changes: 57 additions & 0 deletions src/Cli/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,63 @@ MSBuild emits final telemetry after `BuildFinished`. `Shutdown` completes one lo
instance. It does not necessarily end the process. Refresh the environment and trace
context for each persistent-server request.

Managed and Native AOT command execution use
`Microsoft.DotNet.Cli.Utils/ProcessLifecycle.cs` as the shared owner of Ctrl+C,
SIGTERM, and process-exit cancellation. The managed entry point initializes it for the
process lifetime; the Native AOT entry point initializes it only while handling a command
in-process and unregisters it before managed fallback. Merely launching a child through
`ProcessReaper.cs` must not initialize CLI lifecycle handling in library hosts.

Pass the lifecycle token through System.CommandLine invocation and command operations.
Process-launch and forwarding helpers must require callers to supply a cancellation
token; do not add tokenless overloads or optional cancellation-token parameters.
The first Ctrl+C requests cooperative cancellation and permits 200 milliseconds for
cleanup; expiration of that deadline requests forceful cancellation, gives observers a
bounded window to terminate and reap child processes, and then exits with the
signal-derived exit code. A second Ctrl+C or SIGTERM exits immediately. Transaction
rollback and other critical operations may use `OverrideSoftCancellationTimeout` to
extend or suspend
the automatic deadline, but the override must never suppress an explicit forceful signal.
Child processes observe cooperative signals directly and are killed only when forceful
cancellation is requested. While a lifecycle-managed external process is running,
`Command` suspends the automatic soft-cancellation deadline so the child can finish
gracefully; a second Ctrl+C or SIGTERM still forces termination. System.CommandLine may
wrap the lifecycle token before it reaches a command action, so process termination must
use lifecycle initialization state rather than token identity to distinguish lifecycle
cancellation from standalone library callers. On Unix, forward SIGTERM to the child
before bounded forceful termination.
`ProcessReaper.cs` owns child-process signal forwarding and cleanup; do not add a
competing command-line termination handler for those signals. MSBuild operations use a
two-second soft-cancellation override so submissions and loggers, including binary
loggers, can finish cancellation cleanup; a second Ctrl+C or SIGTERM still bypasses it.
MTP test execution suspends the automatic deadline while running test applications so
their own first-Ctrl+C handlers can report final results. Its cancellation manager must
observe the shared cooperative and forceful lifecycle tokens: cooperative cancellation
stops queueing new applications, while forceful cancellation kills all registered test
application process trees before the lifecycle exits.

### Cancellation and cleanup

Forward-operation cancellation must not prevent transaction rollback. MSI manifest and
pack rollback create a distinct cancellation scope inside each rollback callback, never
linked to the cancelled forward token; keep the original cancellation exception after
cleanup. The deterministic installer seams are exercised by
[`GivenMsiCancellation`](../../test/dotnet.Tests/CommandTests/Workload/Install/GivenMsiCancellation.cs).
Only roll back MSIs whose installation this transaction actually attempted; mark the
attempt before native execution so partial installs still roll back, but cancellation
before installation and already-installed no-ops cannot remove existing manifests.

`Console.In` synchronizes `ReadLineAsync` as well as `ReadLine`. The
[`run-api` command](dotnet/Commands/Run/Api/RunApiCommand.cs) uses
`Console.OpenStandardInputHandle()` with `FileStream`/`StreamReader` instead. Keep the
cancellable wait: Unix file I/O cannot interrupt an already blocked read, so at most one
runtime worker can remain until process exit. Keep its regression out of process with a
real open stdin pipe; see
[`RunApiCancellationTests`](../../test/dotnet.Tests/CommandTests/Run/RunApiCancellationTests.cs).
On Linux, its helper waits for `/proc/self/task/*/syscall` to report a blocked
`read(0, ...)` before cancelling; an incomplete task alone does not establish that the
runtime worker has started the read.

## Three-project command split

A `dotnet` command or option spans three cooperating projects:
Expand Down
28 changes: 28 additions & 0 deletions src/Cli/Microsoft.DotNet.Cli.CommandLine/CommandExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.CommandLine;

namespace Microsoft.DotNet.Cli.CommandLine;

/// <summary>
/// Extensions that make it easy to wire up cancellable command actions without requiring
/// every command handler in the CLI to be written against the asynchronous System.CommandLine
/// APIs. The synchronous <paramref name="action"/> still receives the <see cref="CancellationToken"/>
/// that System.CommandLine produces (for example when a Ctrl+C/SIGTERM is observed), so that it
/// can be checked or forwarded to cancellable APIs as appropriate.
/// </summary>
public static class CommandExtensions
{
extension(Command command)
{
/// <summary>
/// Sets the action for the command to a synchronous delegate that accepts the
/// <see cref="CancellationToken"/> supplied by System.CommandLine's invocation pipeline.
/// </summary>
public void SetAction(Func<ParseResult, CancellationToken, int> action)
{
command.SetAction((parseResult, cancellationToken) => Task.FromResult(action(parseResult, cancellationToken)));
}
}
}
4 changes: 3 additions & 1 deletion src/Cli/Microsoft.DotNet.Cli.Utils/BuiltInCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,10 @@ internal BuiltInCommand(string commandName, IEnumerable<string> commandArgs, Fun
_stdErr = new StreamForwarder();
}

public CommandResult Execute()
public CommandResult Execute(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();

TextWriter originalConsoleOut = _environment.GetConsoleOut();
TextWriter originalConsoleError = _environment.GetConsoleError();
string originalWorkingDirectory = _environment.GetWorkingDirectory();
Expand Down
103 changes: 90 additions & 13 deletions src/Cli/Microsoft.DotNet.Cli.Utils/Command.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,45 @@ public class Command(Process? process, bool trimTrailingNewlines = false, IDicti

private readonly bool _trimTrailingNewlines = trimTrailingNewlines;

public CommandResult Execute()
private bool _logProcess = true;

private bool _suspendSoftCancellationTimeout = true;

public CommandResult Execute(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return ExecuteCore(processStarted: null, cancellationToken);
}

public CommandResult Execute(Action<Process>? processStarted, CancellationToken cancellationToken)
{
return Execute(null);
cancellationToken.ThrowIfCancellationRequested();
return ExecuteCore(processStarted, cancellationToken);
}
public CommandResult Execute(Action<Process>? processStarted)

internal Command WithoutProcessLogging()
{
Reporter.Verbose.WriteLine(string.Format(
LocalizableStrings.RunningFileNameArguments,
_process.StartInfo.FileName,
_process.StartInfo.Arguments));
ThrowIfRunning();
_logProcess = false;
return this;
}

internal Command WithoutSoftCancellationTimeoutOverride()
{
ThrowIfRunning();
_suspendSoftCancellationTimeout = false;
return this;
}

private CommandResult ExecuteCore(Action<Process>? processStarted, CancellationToken cancellationToken)
{
if (_logProcess)
{
Reporter.Verbose.WriteLine(string.Format(
LocalizableStrings.RunningFileNameArguments,
_process.StartInfo.FileName,
_process.StartInfo.Arguments));
}

ThrowIfRunning();

Expand All @@ -39,34 +68,64 @@ public CommandResult Execute(Action<Process>? processStarted)
_process.EnableRaisingEvents = true;

Stopwatch? sw = null;
if (CommandLoggingContext.IsVerbose)
if (_logProcess && CommandLoggingContext.IsVerbose)
{
sw = Stopwatch.StartNew();

Reporter.Verbose.WriteLine($"> {Command.FormatProcessInfo(_process.StartInfo)}".White());
}

using (var reaper = ProcessReaper.Create(_process))
using (ProcessLifecycle.IsInitialized && _suspendSoftCancellationTimeout
? ProcessLifecycle.OverrideSoftCancellationTimeout(Timeout.InfiniteTimeSpan)
: null)
{
_process.Start();
processStarted?.Invoke(_process);
reaper.NotifyProcessStarted();

Reporter.Verbose.WriteLine(string.Format(
LocalizableStrings.ProcessId,
_process.Id));
if (_logProcess)
{
Reporter.Verbose.WriteLine(string.Format(
LocalizableStrings.ProcessId,
_process.Id));
}

var taskOut = _stdOut?.BeginRead(_process.StandardOutput);
var taskErr = _stdErr?.BeginRead(_process.StandardError);
_process.WaitForExit();

CancellationToken processTerminationToken =
ProcessLifecycle.GetProcessTerminationToken(cancellationToken);
if (!processTerminationToken.CanBeCanceled)
{
_process.WaitForExit();
}
else
{
bool cancellationWon = false;
while (!_process.WaitForExit(milliseconds: 100))
{
if (processTerminationToken.IsCancellationRequested)
{
cancellationWon = true;
TerminateProcess(reaper, _process);
break;
}
}

if (cancellationWon)
{
cancellationToken.ThrowIfCancellationRequested();
}
}

taskOut?.Wait();
taskErr?.Wait();
}

var exitCode = _process.ExitCode;

if (CommandLoggingContext.IsVerbose)
if (_logProcess && CommandLoggingContext.IsVerbose)
{
Debug.Assert(sw is not null);
var message = string.Format(
Expand All @@ -91,6 +150,24 @@ public CommandResult Execute(Action<Process>? processStarted)
_stdErr?.CapturedOutput);
}

private static void TerminateProcess(ProcessReaper reaper, Process process)
{
try
{
reaper.TerminateProcess();
}
catch (InvalidOperationException) when (process.HasExited)
{
// The process exited before termination reached it.
}
catch (System.ComponentModel.Win32Exception) when (process.HasExited)
{
// The process exited while its process tree was being enumerated.
}

process.WaitForExit();
}

public ICommand WorkingDirectory(string? projectDirectory)
{
_process.StartInfo.WorkingDirectory = projectDirectory;
Expand Down
7 changes: 4 additions & 3 deletions src/Cli/Microsoft.DotNet.Cli.Utils/ExponentialRetry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,15 +69,16 @@ public static async Task<T> ExecuteWithRetry<T>(Func<T> action,
}

public static async Task<T> ExecuteWithRetryOnFailure<T>(Func<Task<T>> action,
CancellationToken cancellationToken,
int maxRetryCount = 3,
Func<IEnumerable<Task>>? timer = null)
{
timer = timer ?? (() => Timer(Intervals));
timer ??= () => Timer(Intervals, cancellationToken);
return await ExecuteAsyncWithRetry(action, result => result != null && !result.Equals(default), maxRetryCount, timer);
}

public static IEnumerable<Task> Timer(IEnumerable<TimeSpan> interval)
public static IEnumerable<Task> Timer(IEnumerable<TimeSpan> interval, CancellationToken cancellationToken)
{
return interval.Select(Task.Delay);
return interval.Select(delay => Task.Delay(delay, cancellationToken));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ namespace Microsoft.DotNet.Cli.Utils.Extensions;

public static class LockFileFormatExtensions
{
public static async Task<LockFile> ReadWithLock(this LockFileFormat subject, string path)
public static async Task<LockFile> ReadWithLock(
this LockFileFormat subject,
string path,
CancellationToken cancellationToken)
{
return await ConcurrencyUtilities.ExecuteWithFileLockedAsync(
path,
Expand All @@ -26,6 +29,6 @@ public static async Task<LockFile> ReadWithLock(this LockFileFormat subject, str

return lockFile;
},
CancellationToken.None);
cancellationToken);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,56 +7,49 @@ namespace Microsoft.DotNet.Cli.Utils.Extensions;

internal static class ProcessStartInfoExtensions
{
public static int Execute(this ProcessStartInfo startInfo)
public static int Execute(this ProcessStartInfo startInfo, CancellationToken cancellationToken)
=> Execute(startInfo, suspendSoftCancellationTimeout: true, cancellationToken);

internal static int Execute(
this ProcessStartInfo startInfo,
bool suspendSoftCancellationTimeout,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(startInfo);

var process = new Process
using var process = new Process
{
StartInfo = startInfo
};

using (var reaper = ProcessReaper.Create(process))
Command command = new Command(process).WithoutProcessLogging();
if (!suspendSoftCancellationTimeout)
{
process.Start();
reaper.NotifyProcessStarted();
process.WaitForExit();
command.WithoutSoftCancellationTimeoutOverride();
}

return process.ExitCode;
return command.Execute(cancellationToken).ExitCode;
}

public static int ExecuteAndCaptureOutput(this ProcessStartInfo startInfo, out string? stdOut, out string? stdErr)
public static int ExecuteAndCaptureOutput(
this ProcessStartInfo startInfo,
out string? stdOut,
out string? stdErr,
CancellationToken cancellationToken)
{
var outStream = new StreamForwarder().Capture();
var errStream = new StreamForwarder().Capture();

startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;

var process = new Process
using var process = new Process
{
StartInfo = startInfo,
EnableRaisingEvents = true
StartInfo = startInfo
};

using (var reaper = ProcessReaper.Create(process))
{
process.Start();
reaper.NotifyProcessStarted();

var taskOut = outStream.BeginRead(process.StandardOutput);
var taskErr = errStream.BeginRead(process.StandardError);

process.WaitForExit();

taskOut.Wait();
taskErr.Wait();

stdOut = outStream.CapturedOutput;
stdErr = errStream.CapturedOutput;
}
CommandResult result = new Command(process)
.WithoutProcessLogging()
.CaptureStdOut()
.CaptureStdErr()
.Execute(cancellationToken);

return process.ExitCode;
stdOut = result.StdOut;
stdErr = result.StdErr;
return result.ExitCode;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,9 @@ public ForwardingAppImplementation(
_allArgs = allArgs.ToArray();
}

public int Execute()
public int Execute(CancellationToken cancellationToken)
{
return GetProcessStartInfo().Execute();
return GetProcessStartInfo().Execute(cancellationToken);
}

public ProcessStartInfo GetProcessStartInfo()
Expand Down
2 changes: 1 addition & 1 deletion src/Cli/Microsoft.DotNet.Cli.Utils/ICommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace Microsoft.DotNet.Cli.Utils;

public interface ICommand
{
CommandResult Execute();
CommandResult Execute(CancellationToken cancellationToken);

ICommand WorkingDirectory(string projectDirectory);

Expand Down
Loading
Loading