diff --git a/src/Cli/AGENTS.md b/src/Cli/AGENTS.md index fe6969097a38..8beaf31170ef 100644 --- a/src/Cli/AGENTS.md +++ b/src/Cli/AGENTS.md @@ -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: diff --git a/src/Cli/Microsoft.DotNet.Cli.CommandLine/CommandExtensions.cs b/src/Cli/Microsoft.DotNet.Cli.CommandLine/CommandExtensions.cs new file mode 100644 index 000000000000..6bb1c7680932 --- /dev/null +++ b/src/Cli/Microsoft.DotNet.Cli.CommandLine/CommandExtensions.cs @@ -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; + +/// +/// 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 still receives the +/// 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. +/// +public static class CommandExtensions +{ + extension(Command command) + { + /// + /// Sets the action for the command to a synchronous delegate that accepts the + /// supplied by System.CommandLine's invocation pipeline. + /// + public void SetAction(Func action) + { + command.SetAction((parseResult, cancellationToken) => Task.FromResult(action(parseResult, cancellationToken))); + } + } +} diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/BuiltInCommand.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/BuiltInCommand.cs index d8fb130f272f..fda4d06f02fd 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/BuiltInCommand.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/BuiltInCommand.cs @@ -34,8 +34,10 @@ internal BuiltInCommand(string commandName, IEnumerable 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(); diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/Command.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/Command.cs index 0624738a66c0..0c3764760f7c 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/Command.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/Command.cs @@ -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? processStarted, CancellationToken cancellationToken) { - return Execute(null); + cancellationToken.ThrowIfCancellationRequested(); + return ExecuteCore(processStarted, cancellationToken); } - public CommandResult Execute(Action? 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? processStarted, CancellationToken cancellationToken) + { + if (_logProcess) + { + Reporter.Verbose.WriteLine(string.Format( + LocalizableStrings.RunningFileNameArguments, + _process.StartInfo.FileName, + _process.StartInfo.Arguments)); + } ThrowIfRunning(); @@ -39,7 +68,7 @@ public CommandResult Execute(Action? processStarted) _process.EnableRaisingEvents = true; Stopwatch? sw = null; - if (CommandLoggingContext.IsVerbose) + if (_logProcess && CommandLoggingContext.IsVerbose) { sw = Stopwatch.StartNew(); @@ -47,18 +76,48 @@ public CommandResult Execute(Action? processStarted) } 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(); @@ -66,7 +125,7 @@ public CommandResult Execute(Action? processStarted) var exitCode = _process.ExitCode; - if (CommandLoggingContext.IsVerbose) + if (_logProcess && CommandLoggingContext.IsVerbose) { Debug.Assert(sw is not null); var message = string.Format( @@ -91,6 +150,24 @@ public CommandResult Execute(Action? 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; diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/ExponentialRetry.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/ExponentialRetry.cs index d3631c1a6346..50043d7fa8b5 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/ExponentialRetry.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/ExponentialRetry.cs @@ -69,15 +69,16 @@ public static async Task ExecuteWithRetry(Func action, } public static async Task ExecuteWithRetryOnFailure(Func> action, + CancellationToken cancellationToken, int maxRetryCount = 3, Func>? 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 Timer(IEnumerable interval) + public static IEnumerable Timer(IEnumerable interval, CancellationToken cancellationToken) { - return interval.Select(Task.Delay); + return interval.Select(delay => Task.Delay(delay, cancellationToken)); } } diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/Extensions/LockFileFormatExtensions.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/Extensions/LockFileFormatExtensions.cs index eec603000473..68702339a60d 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/Extensions/LockFileFormatExtensions.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/Extensions/LockFileFormatExtensions.cs @@ -8,7 +8,10 @@ namespace Microsoft.DotNet.Cli.Utils.Extensions; public static class LockFileFormatExtensions { - public static async Task ReadWithLock(this LockFileFormat subject, string path) + public static async Task ReadWithLock( + this LockFileFormat subject, + string path, + CancellationToken cancellationToken) { return await ConcurrencyUtilities.ExecuteWithFileLockedAsync( path, @@ -26,6 +29,6 @@ public static async Task ReadWithLock(this LockFileFormat subject, str return lockFile; }, - CancellationToken.None); + cancellationToken); } } diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/Extensions/ProcessStartInfoExtensions.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/Extensions/ProcessStartInfoExtensions.cs index 46198b39b803..de03e41cdc4f 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/Extensions/ProcessStartInfoExtensions.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/Extensions/ProcessStartInfoExtensions.cs @@ -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; } } diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/ForwardingAppImplementation.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/ForwardingAppImplementation.cs index 1b2058d17744..baa8b7f099dd 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/ForwardingAppImplementation.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/ForwardingAppImplementation.cs @@ -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() diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/ICommand.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/ICommand.cs index 6e9856a5297a..e268f8635042 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/ICommand.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/ICommand.cs @@ -5,7 +5,7 @@ namespace Microsoft.DotNet.Cli.Utils; public interface ICommand { - CommandResult Execute(); + CommandResult Execute(CancellationToken cancellationToken); ICommand WorkingDirectory(string projectDirectory); diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/MSBuildForwardingAppWithoutLogging.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/MSBuildForwardingAppWithoutLogging.cs index f484fc5fb715..c8a11194230a 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/MSBuildForwardingAppWithoutLogging.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/MSBuildForwardingAppWithoutLogging.cs @@ -180,13 +180,19 @@ public void EnvironmentVariable(string name, string? value) /// /// Run the MSBuild arguments that have been previously specified. /// - public int Execute() => Execute(workingDirectory: null); + public int Execute(CancellationToken cancellationToken) => Execute(workingDirectory: null, cancellationToken); - /// + /// /// /// When specified, run out-of-process in this directory without changing the caller's directory. /// - public int Execute(string? workingDirectory) + public int Execute(string? workingDirectory, CancellationToken cancellationToken) + => Execute(workingDirectory, suspendSoftCancellationTimeout: true, cancellationToken); + + internal int Execute( + string? workingDirectory, + bool suspendSoftCancellationTimeout, + CancellationToken cancellationToken) { if (workingDirectory is not null && _forwardingApp is null) { @@ -201,13 +207,13 @@ public int Execute(string? workingDirectory) startInfo.WorkingDirectory = workingDirectory; } - return startInfo.Execute(); + return startInfo.Execute(suspendSoftCancellationTimeout, cancellationToken); } else { if (RuntimeFeature.IsDynamicCodeSupported) { - return ExecuteInProc(GetAllArguments()); + return ExecuteInProc(GetAllArguments(), cancellationToken); } else { @@ -222,15 +228,20 @@ public int Execute(string? workingDirectory) /// After execution, the original environment variables are restored for any remaining cleanup work the dotnet CLI needs to perform. /// [RequiresDynamicCode("Calls MSBuildApp.Main, which is not AOT-safe")] - public int ExecuteInProc(string[] arguments) + public int ExecuteInProc(string[] arguments, CancellationToken cancellationToken) { + cancellationToken.ThrowIfCancellationRequested(); + using var _ = SetEnvironmentVariables(_msbuildRequiredEnvironmentVariables); + using CancellationTokenRegistration cancellationRegistration = cancellationToken.Register( + static () => Build.Execution.BuildManager.DefaultBuildManager.CancelAllSubmissions()); + try { // Execute MSBuild in the current process by calling its Main method. return Build.CommandLine.MSBuildApp.Main(arguments); } - catch (Exception exception) + catch (Exception exception) when (exception is not OperationCanceledException) { // MSBuild, like all well-behaved CLI tools, handles all exceptions. In the unlikely case // that something still escapes, we print the exception and fail the call. Non-localized diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/NativeMethods.txt b/src/Cli/Microsoft.DotNet.Cli.Utils/NativeMethods.txt index 634b3b0f4554..761a5121f6f1 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/NativeMethods.txt +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/NativeMethods.txt @@ -37,6 +37,7 @@ SafeArrayUnlock SendMessageTimeout SetInformationJobObject SetConsoleCtrlHandler +TerminateJobObject WinVerifyTrust // Interfaces diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/ProcessLifecycle.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/ProcessLifecycle.cs new file mode 100644 index 000000000000..eea4a40c4704 --- /dev/null +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/ProcessLifecycle.cs @@ -0,0 +1,304 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace Microsoft.DotNet.Cli.Utils; + +internal static class ProcessLifecycle +{ + private const int SigIntExitCode = 130; + private const int SigTermExitCode = 143; + private static readonly TimeSpan s_defaultSoftCancellationTimeout = TimeSpan.FromMilliseconds(200); + private static readonly TimeSpan s_forcefulExitFallbackTimeout = TimeSpan.FromMilliseconds(500); + private static readonly object s_lock = new(); + private static readonly CancellationTokenSource s_cancellationTokenSource = new(); + private static readonly CancellationTokenSource s_forcefulCancellationTokenSource = new(); + private static readonly Dictionary s_softCancellationTimeoutOverrides = []; +#if NET + private static PosixSignalRegistration? s_sigTermRegistration; +#endif + private static Timer? s_forcefulCancellationTimer; + private static Timer? s_forcefulExitTimer; + private static int s_initializationCount; + private static int s_nextTimeoutOverrideId; + private static int s_forcefulCancellationTimerVersion; + private static int s_cancellationRequested; + private static int s_forcefulCancellationRequested; + private static int s_signalExitCode; + + public static CancellationToken CancellationToken => s_cancellationTokenSource.Token; + + internal static CancellationToken ForcefulCancellationToken => s_forcefulCancellationTokenSource.Token; + + internal static bool IsSignalTerminationRequested => Volatile.Read(ref s_signalExitCode) != 0; + + internal static bool IsSigTermRequested => Volatile.Read(ref s_signalExitCode) == SigTermExitCode; + + internal static bool IsForcefulCancellationRequested => Volatile.Read(ref s_forcefulCancellationRequested) != 0; + + internal static bool IsInitialized => Volatile.Read(ref s_initializationCount) != 0; + + internal static IDisposable Initialize() + { + lock (s_lock) + { + if (s_initializationCount++ == 0) + { + Console.CancelKeyPress += HandleCancelKeyPress; + AppDomain.CurrentDomain.ProcessExit += HandleProcessExit; +#if NET + s_sigTermRegistration = PosixSignalRegistration.Create(PosixSignal.SIGTERM, HandleSigTerm); +#endif + } + } + + return new Initialization(); + } + + internal static IDisposable OverrideSoftCancellationTimeout(TimeSpan timeout) + { + if (timeout < TimeSpan.Zero && timeout != Timeout.InfiniteTimeSpan) + { + throw new ArgumentOutOfRangeException(nameof(timeout)); + } + + lock (s_lock) + { + int id = ++s_nextTimeoutOverrideId; + s_softCancellationTimeoutOverrides.Add(id, timeout); + ScheduleForcefulCancellation_NoLock(); + return new SoftCancellationTimeoutOverride(id); + } + } + + internal static CancellationToken GetProcessTerminationToken(CancellationToken cancellationToken) + // System.CommandLine links the invocation token before passing it to command + // actions, so lifecycle-originated tokens do not retain identity here. + => IsInitialized + ? s_forcefulCancellationTokenSource.Token + : cancellationToken; + + internal static bool TryGetSignalExitCode(CancellationToken cancellationToken, out int exitCode) + { + exitCode = Volatile.Read(ref s_signalExitCode); + return cancellationToken == s_cancellationTokenSource.Token && exitCode != 0; + } + + private static void HandleCancelKeyPress(object? sender, ConsoleCancelEventArgs eventArgs) + { + eventArgs.Cancel = true; + + if (!RequestSoftCancellation(SigIntExitCode)) + { + RequestForcefulCancellation(SigIntExitCode, terminateProcess: true); + } + } + +#if NET + private static void HandleSigTerm(PosixSignalContext context) + { + context.Cancel = true; + RequestForcefulCancellation(SigTermExitCode, terminateProcess: true); + } +#endif + + private static void HandleProcessExit(object? sender, EventArgs eventArgs) + { + bool cancel; + lock (s_lock) + { + cancel = s_cancellationRequested == 0; + s_cancellationRequested = 1; + } + + if (cancel) + { + s_cancellationTokenSource.Cancel(); + } + } + + private static bool RequestSoftCancellation(int exitCode) + { + lock (s_lock) + { + if (s_cancellationRequested != 0) + { + return false; + } + + s_cancellationRequested = 1; + s_signalExitCode = exitCode; + ScheduleForcefulCancellation_NoLock(); + } + + s_cancellationTokenSource.Cancel(); + return true; + } + + private static void RequestForcefulCancellation(int exitCode, bool terminateProcess) + { + bool cancel = false; + bool exitImmediately = false; + lock (s_lock) + { + if (s_forcefulCancellationRequested != 0) + { + if (terminateProcess) + { + s_signalExitCode = exitCode; + exitImmediately = true; + } + } + else + { + s_cancellationRequested = 1; + s_forcefulCancellationRequested = 1; + s_signalExitCode = exitCode; + CancelForcefulCancellationTimer_NoLock(); + cancel = true; + } + } + + if (exitImmediately) + { + Environment.Exit(exitCode); + } + + if (cancel) + { + try + { + s_forcefulCancellationTokenSource.Cancel(); + if (!terminateProcess) + { + s_cancellationTokenSource.Cancel(); + } + } + finally + { + if (terminateProcess) + { + Environment.Exit(exitCode); + } + } + } + } + + private static void ScheduleForcefulCancellation_NoLock() + { + if (s_cancellationRequested == 0 || s_forcefulCancellationRequested != 0 || s_signalExitCode == 0) + { + return; + } + + TimeSpan timeout = s_defaultSoftCancellationTimeout; + foreach (TimeSpan timeoutOverride in s_softCancellationTimeoutOverrides.Values) + { + if (timeoutOverride == Timeout.InfiniteTimeSpan) + { + timeout = Timeout.InfiniteTimeSpan; + break; + } + + if (timeoutOverride > timeout) + { + timeout = timeoutOverride; + } + } + + CancelForcefulCancellationTimer_NoLock(); + if (timeout != Timeout.InfiniteTimeSpan) + { + int version = s_forcefulCancellationTimerVersion; + s_forcefulCancellationTimer = new Timer( + static state => ForceAfterSoftCancellationTimeout((int)state!), + version, + timeout, + Timeout.InfiniteTimeSpan); + } + } + + private static void ForceAfterSoftCancellationTimeout(int version) + { + int exitCode; + lock (s_lock) + { + if (version != s_forcefulCancellationTimerVersion || + s_forcefulCancellationRequested != 0 || + s_signalExitCode == 0) + { + return; + } + + s_forcefulCancellationRequested = 1; + exitCode = s_signalExitCode; + CancelForcefulCancellationTimer_NoLock(); + // Give forceful-token observers a bounded chance to terminate and reap child processes. + s_forcefulExitTimer = new Timer( + static state => Environment.Exit((int)state!), + exitCode, + s_forcefulExitFallbackTimeout, + Timeout.InfiniteTimeSpan); + } + + try + { + s_forcefulCancellationTokenSource.Cancel(); + } + catch (AggregateException) + { + Environment.Exit(exitCode); + } + } + + private static void CancelForcefulCancellationTimer_NoLock() + { + s_forcefulCancellationTimerVersion++; + s_forcefulCancellationTimer?.Dispose(); + s_forcefulCancellationTimer = null; + } + + private sealed class Initialization : IDisposable + { + private int _disposed; + + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) + { + return; + } + + lock (s_lock) + { + if (--s_initializationCount == 0) + { + Console.CancelKeyPress -= HandleCancelKeyPress; + AppDomain.CurrentDomain.ProcessExit -= HandleProcessExit; +#if NET + s_sigTermRegistration?.Dispose(); + s_sigTermRegistration = null; +#endif + } + } + } + } + + private sealed class SoftCancellationTimeoutOverride(int id) : IDisposable + { + private int _disposed; + + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) + { + return; + } + + lock (s_lock) + { + s_softCancellationTimeoutOverrides.Remove(id); + ScheduleForcefulCancellation_NoLock(); + } + } + } +} diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/ProcessReaper.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/ProcessReaper.cs index 4a22431cd14d..40826bd7aca1 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/ProcessReaper.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/ProcessReaper.cs @@ -30,6 +30,7 @@ namespace Microsoft.DotNet.Cli.Utils; /// internal class ProcessReaper : IDisposable { + private static readonly TimeSpan s_forcefulSigTermGracePeriod = TimeSpan.FromSeconds(1); private readonly Process _process; #if TARGET_WINDOWS @@ -69,6 +70,17 @@ public override void NotifyProcessStarted() } } + public override void TerminateProcess() + { + if (_job is not null && + PInvoke.TerminateJobObject((HANDLE)_job.DangerousGetHandle(), uint.MaxValue)) + { + return; + } + + base.TerminateProcess(); + } + private static SafeWaitHandle? AssignProcessToJobObject(HANDLE process) { HANDLE job = PInvoke.CreateJobObject(null, null); @@ -135,6 +147,8 @@ public override void Dispose() #if !TARGET_WINDOWS && NET private sealed class UnixProcessReaper : ProcessReaper { + private readonly PosixSignalRegistration _sigTermRegistration; + // Coordinates Dispose (typically the main thread) with HandleProcessExit, // which is raised on the AppDomain.ProcessExit thread when the CLI itself is // shutting down (for example when a SIGTERM handler calls Environment.Exit). @@ -147,14 +161,29 @@ private sealed class UnixProcessReaper : ProcessReaper // ProcessExit callback that starts after Dispose has run simply becomes a no-op. private readonly Lock _shutdownLock = new(); private bool _shuttingDown; + private int _sigTermRequested; public UnixProcessReaper(Process process) : base(process) { AppDomain.CurrentDomain.ProcessExit += HandleProcessExit; + _sigTermRegistration = PosixSignalRegistration.Create( + PosixSignal.SIGTERM, + context => + { + if (ProcessLifecycle.IsInitialized) + { + return; + } + + context.Cancel = true; + Volatile.Write(ref _sigTermRequested, 1); + Environment.Exit(143); + }); } public override void Dispose() { + _sigTermRegistration.Dispose(); AppDomain.CurrentDomain.ProcessExit -= HandleProcessExit; // If a ProcessExit driven shutdown is already running on another thread, @@ -184,18 +213,34 @@ private void HandleProcessExit(object? sender, EventArgs args) try { - // If the target is still running, forward SIGTERM so it can shut - // down as well. Signal returns false if the process already exited, - // and throws Win32Exception if the signal could not be delivered. - if (!_process.WaitForExit(0)) + ProcessExitStatus? exitStatus = null; + bool forwardSigTermWithGrace = + ProcessLifecycle.IsSigTermRequested || + Volatile.Read(ref _sigTermRequested) != 0; + + if (ProcessLifecycle.IsForcefulCancellationRequested && + !ProcessLifecycle.IsSigTermRequested) { - _process.SafeHandle.Signal(PosixSignal.SIGTERM); + TerminateProcess(); + } + else + { + // Forward SIGTERM before escalating so the child observes the + // same hard-shutdown signal as the CLI. + if (_process.Signal(PosixSignal.SIGTERM) && + forwardSigTermWithGrace && + !_process.TryWaitForExitStatus(s_forcefulSigTermGracePeriod, out exitStatus)) + { + TerminateProcess(); + } } - // If SIGTERM was ignored by the target, then we'll still wait. - _process.WaitForExit(); + exitStatus ??= _process.WaitForExitStatus(); - Environment.ExitCode = _process.ExitCode; + if (!ProcessLifecycle.IsSignalTerminationRequested) + { + Environment.ExitCode = exitStatus.ExitCode; + } } catch (InvalidOperationException) { @@ -250,11 +295,109 @@ private ProcessReaper(Process process) /// public virtual void NotifyProcessStarted() { } + public virtual void TerminateProcess() + { +#if NET + _process.Kill(entireProcessTree: true); +#else + _process.Kill(); +#endif + } + public virtual void Dispose() { Console.CancelKeyPress -= HandleCancelKeyPress; } + internal static void ForwardSigTermAndTerminate(IEnumerable processes) + { +#if !TARGET_WINDOWS && NET + var activeProcesses = new List(); + foreach (Process process in processes) + { + try + { + if (!process.HasExited) + { + activeProcesses.Add(process); + } + } + catch (Exception ex) when (ex is InvalidOperationException or Win32Exception) + { + Reporter.Verbose.WriteLine($"Exception checking child process state during SIGTERM forwarding:\n{ex}"); + } + } + + var signaledProcesses = new HashSet(); + + foreach (Process process in activeProcesses) + { + try + { + if (process.Signal(PosixSignal.SIGTERM)) + { + signaledProcesses.Add(process); + } + } + catch (Exception ex) when (ex is InvalidOperationException or Win32Exception) + { + Reporter.Verbose.WriteLine($"Exception forwarding SIGTERM to child process:\n{ex}"); + } + } + + Stopwatch stopwatch = Stopwatch.StartNew(); + foreach (Process process in activeProcesses) + { + if (signaledProcesses.Contains(process)) + { + TimeSpan remaining = s_forcefulSigTermGracePeriod - stopwatch.Elapsed; + if (remaining > TimeSpan.Zero) + { + try + { + if (process.WaitForExit((int)Math.Ceiling(remaining.TotalMilliseconds))) + { + continue; + } + } + catch (InvalidOperationException ex) + { + Reporter.Verbose.WriteLine($"Exception waiting for child process after SIGTERM:\n{ex}"); + continue; + } + } + } + + try + { + if (!process.HasExited) + { + process.Kill(entireProcessTree: true); + } + } + catch (Exception ex) when (ex is InvalidOperationException or Win32Exception) + { + Reporter.Verbose.WriteLine($"Exception killing child process after SIGTERM grace period:\n{ex}"); + } + } +#else + foreach (Process process in processes) + { + try + { + if (!process.HasExited) + { + process.Kill(); + } + } + catch (InvalidOperationException ex) + { + Reporter.Verbose.WriteLine($"Exception killing child process:\n{ex}"); + } + } +#endif + } + private void HandleCancelKeyPress(object? sender, ConsoleCancelEventArgs e) { // Ignore SIGINT/SIGQUIT so that the process can handle the signal diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/Properties/AssemblyInfo.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/Properties/AssemblyInfo.cs index ff1652fc2ff9..bd2ebe1b9afa 100644 --- a/src/Cli/Microsoft.DotNet.Cli.Utils/Properties/AssemblyInfo.cs +++ b/src/Cli/Microsoft.DotNet.Cli.Utils/Properties/AssemblyInfo.cs @@ -12,6 +12,7 @@ [assembly: InternalsVisibleTo("dotnet-run.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: InternalsVisibleTo("Microsoft.DotNet.Configurer, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: InternalsVisibleTo("Microsoft.DotNet.Tools.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] +[assembly: InternalsVisibleTo("Microsoft.DotNet.Cli.Utils.ProcessLifecycle.TestApp, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: InternalsVisibleTo("Microsoft.DotNet.Cli.Utils.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: InternalsVisibleTo("Microsoft.DotNet.TestFramework, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: InternalsVisibleTo("Microsoft.DotNet.ShellShim.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] diff --git a/src/Cli/Microsoft.TemplateEngine.Cli/IReporterExtensions.cs b/src/Cli/Microsoft.TemplateEngine.Cli/IReporterExtensions.cs index 6e62009ade59..124f66b093ff 100644 --- a/src/Cli/Microsoft.TemplateEngine.Cli/IReporterExtensions.cs +++ b/src/Cli/Microsoft.TemplateEngine.Cli/IReporterExtensions.cs @@ -1,7 +1,6 @@ // 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 Microsoft.DotNet.Cli.Utils; namespace Microsoft.TemplateEngine.Cli @@ -23,21 +22,21 @@ internal static void WriteCommand(this IReporter reporter, string command, int i } /// - /// Writes formatted command output from . + /// Writes formatted command output from . /// - internal static void WriteCommandOutput(this IReporter reporter, Process process) + internal static void WriteCommandOutput(this IReporter reporter, CommandResult commandResult) { - if (process.StartInfo.RedirectStandardOutput || process.StartInfo.RedirectStandardError) + if (commandResult.StartInfo.RedirectStandardOutput || commandResult.StartInfo.RedirectStandardError) { reporter.WriteLine(LocalizableStrings.CommandOutput); } - if (process.StartInfo.RedirectStandardOutput) + if (commandResult.StartInfo.RedirectStandardOutput) { - reporter.WriteStdOut(process.StandardOutput.ReadToEnd()); + reporter.WriteStdOut(commandResult.StdOut ?? string.Empty); } - if (process.StartInfo.RedirectStandardError) + if (commandResult.StartInfo.RedirectStandardError) { - reporter.WriteStdErr(process.StandardError.ReadToEnd()); + reporter.WriteStdErr(commandResult.StdErr ?? string.Empty); } } diff --git a/src/Cli/Microsoft.TemplateEngine.Cli/PostActionDispatcher.cs b/src/Cli/Microsoft.TemplateEngine.Cli/PostActionDispatcher.cs index c6f113525312..c9ed36da0249 100644 --- a/src/Cli/Microsoft.TemplateEngine.Cli/PostActionDispatcher.cs +++ b/src/Cli/Microsoft.TemplateEngine.Cli/PostActionDispatcher.cs @@ -66,7 +66,7 @@ internal PostActionDispatcher(IEngineEnvironmentSettings environment, Func set to true, the result will be anyway.
/// Note that is a flags enum, and can contain multiple status if multiple post actions failed with different reason. /// - internal PostActionExecutionStatus Process(ITemplateCreationResult creationResult, bool isDryRun, AllowRunScripts canRunScripts) + internal PostActionExecutionStatus Process(ITemplateCreationResult creationResult, bool isDryRun, AllowRunScripts canRunScripts, CancellationToken cancellationToken) { _ = creationResult ?? throw new ArgumentNullException(nameof(creationResult)); _ = creationResult.CreationEffects ?? throw new ArgumentNullException(nameof(creationResult.CreationEffects)); @@ -134,7 +134,7 @@ internal PostActionExecutionStatus Process(ITemplateCreationResult creationResul } else if (canRunScripts == AllowRunScripts.Yes) { - result |= ProcessAction(creationResult.CreationEffects, creationResult.CreationResult!, creationResult.OutputBaseDirectory, action, actionProcessor); + result |= ProcessAction(creationResult.CreationEffects, creationResult.CreationResult!, creationResult.OutputBaseDirectory, action, actionProcessor, cancellationToken); } else if (canRunScripts == AllowRunScripts.Prompt) { @@ -143,7 +143,7 @@ internal PostActionExecutionStatus Process(ITemplateCreationResult creationResul // Otherwise return cancelled, indicating the action was not run. if (AskUserIfActionShouldRun(action)) { - result |= ProcessAction(creationResult.CreationEffects, creationResult.CreationResult!, creationResult.OutputBaseDirectory, action, actionProcessor); + result |= ProcessAction(creationResult.CreationEffects, creationResult.CreationResult!, creationResult.OutputBaseDirectory, action, actionProcessor, cancellationToken); } else { @@ -154,7 +154,7 @@ internal PostActionExecutionStatus Process(ITemplateCreationResult creationResul } else // other post action { - result |= ProcessAction(creationResult.CreationEffects, creationResult.CreationResult!, creationResult.OutputBaseDirectory, action, actionProcessor); + result |= ProcessAction(creationResult.CreationEffects, creationResult.CreationResult!, creationResult.OutputBaseDirectory, action, actionProcessor, cancellationToken); } if (result != PostActionExecutionStatus.Success) { @@ -213,13 +213,14 @@ private PostActionExecutionStatus ProcessAction( ICreationResult creationResult, string outputBaseDirectory, IPostAction action, - IPostActionProcessor actionProcessor) + IPostActionProcessor actionProcessor, + CancellationToken cancellationToken) { //catch all exceptions on post action execution //post actions can be added using components and it's not sure if they handle exceptions properly try { - if (actionProcessor.Process(_environment, action, creationEffects, creationResult, outputBaseDirectory)) + if (actionProcessor.Process(_environment, action, creationEffects, creationResult, outputBaseDirectory, cancellationToken)) { return PostActionExecutionStatus.Success; } @@ -228,7 +229,7 @@ private PostActionExecutionStatus ProcessAction( DisplayInstructionsForAction(action, useErrorOutput: true); return PostActionExecutionStatus.Failure; } - catch (Exception e) + catch (Exception e) when (e is not OperationCanceledException) { Reporter.Error.WriteLine(LocalizableStrings.PostActionFailedInstructionHeader); Reporter.Verbose.WriteLine(LocalizableStrings.Generic_Details, e.ToString()); diff --git a/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/AddJsonPropertyPostActionProcessor.cs b/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/AddJsonPropertyPostActionProcessor.cs index 184eac990168..9486b540c6f5 100644 --- a/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/AddJsonPropertyPostActionProcessor.cs +++ b/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/AddJsonPropertyPostActionProcessor.cs @@ -83,7 +83,8 @@ protected override bool ProcessInternal( IPostAction action, ICreationEffects creationEffects, ICreationResult templateCreationResult, - string outputBasePath) + string outputBasePath, + CancellationToken cancellationToken) { if (!action.Args.TryGetValue(JsonFileNameArgument, out string? jsonFileName)) { diff --git a/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/ChmodPostActionProcessor.cs b/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/ChmodPostActionProcessor.cs index 3fb827553386..0c3797f63653 100644 --- a/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/ChmodPostActionProcessor.cs +++ b/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/ChmodPostActionProcessor.cs @@ -14,7 +14,7 @@ internal class ChmodPostActionProcessor : PostActionProcessorBase public override Guid Id => ActionProcessorId; - protected override bool ProcessInternal(IEngineEnvironmentSettings environment, IPostAction actionConfig, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath) + protected override bool ProcessInternal(IEngineEnvironmentSettings environment, IPostAction actionConfig, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath, CancellationToken cancellationToken) { bool allSucceeded = true; foreach (KeyValuePair entry in actionConfig.Args) diff --git a/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/IPostActionProcessor.cs b/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/IPostActionProcessor.cs index 186845e014bb..e6e350290851 100644 --- a/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/IPostActionProcessor.cs +++ b/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/IPostActionProcessor.cs @@ -18,7 +18,8 @@ public interface IPostActionProcessor : IIdentifiedComponent /// the results of the template dry run. /// the results of the template instantiation. /// the output directory the template was instantiated to. + /// token observed while processing the post action. /// true if the post action is executed successfully, false otherwise. - bool Process(IEngineEnvironmentSettings environment, IPostAction action, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath); + bool Process(IEngineEnvironmentSettings environment, IPostAction action, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath, CancellationToken cancellationToken); } } diff --git a/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/InstructionDisplayPostActionProcessor.cs b/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/InstructionDisplayPostActionProcessor.cs index 2e57e4b0f9a2..a2006a292110 100644 --- a/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/InstructionDisplayPostActionProcessor.cs +++ b/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/InstructionDisplayPostActionProcessor.cs @@ -13,7 +13,7 @@ internal class InstructionDisplayPostActionProcessor : PostActionProcessorBase public override Guid Id => ActionProcessorId; - protected override bool ProcessInternal(IEngineEnvironmentSettings environment, IPostAction actionConfig, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath) + protected override bool ProcessInternal(IEngineEnvironmentSettings environment, IPostAction actionConfig, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath, CancellationToken cancellationToken) { Reporter.Output.WriteLine(LocalizableStrings.PostActionDescription, actionConfig.Description); Reporter.Output.WriteLine(LocalizableStrings.PostActionInstructions, actionConfig.ManualInstructions); diff --git a/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/PostActionProcessorBase.cs b/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/PostActionProcessorBase.cs index 35e41b8652a3..3df751a5db19 100644 --- a/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/PostActionProcessorBase.cs +++ b/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/PostActionProcessorBase.cs @@ -17,14 +17,15 @@ public bool Process( IPostAction action, ICreationEffects creationEffects, ICreationResult templateCreationResult, - string outputBasePath) + string outputBasePath, + CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace(outputBasePath)) { throw new ArgumentException($"'{nameof(outputBasePath)}' cannot be null or whitespace.", nameof(outputBasePath)); } outputBasePath = Path.GetFullPath(outputBasePath); - return ProcessInternal(environment, action, creationEffects, templateCreationResult, outputBasePath); + return ProcessInternal(environment, action, creationEffects, templateCreationResult, outputBasePath, cancellationToken); } /// @@ -118,7 +119,8 @@ protected abstract bool ProcessInternal( IPostAction action, ICreationEffects creationEffects, ICreationResult templateCreationResult, - string outputBasePath); + string outputBasePath, + CancellationToken cancellationToken); private static bool TryParseAsJson(string targetFiles, out IReadOnlyList paths) { diff --git a/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/ProcessStartPostActionProcessor.cs b/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/ProcessStartPostActionProcessor.cs index b09219d2b17a..575c78a02022 100644 --- a/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/ProcessStartPostActionProcessor.cs +++ b/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/ProcessStartPostActionProcessor.cs @@ -10,11 +10,23 @@ namespace Microsoft.TemplateEngine.Cli.PostActionProcessors { internal class ProcessStartPostActionProcessor : PostActionProcessorBase { + private readonly Func _commandFactory; + internal static readonly Guid ActionProcessorId = new("3A7C4B45-1F5D-4A30-959A-51B88E82B5D2"); + public ProcessStartPostActionProcessor() + : this(process => new Command(process)) + { + } + + internal ProcessStartPostActionProcessor(Func commandFactory) + { + _commandFactory = commandFactory; + } + public override Guid Id => ActionProcessorId; - protected override bool ProcessInternal(IEngineEnvironmentSettings environment, IPostAction actionConfig, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath) + protected override bool ProcessInternal(IEngineEnvironmentSettings environment, IPostAction actionConfig, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath, CancellationToken cancellationToken) { if (!actionConfig.Args.TryGetValue("executable", out string? executable) || string.IsNullOrWhiteSpace(executable)) { @@ -50,25 +62,27 @@ protected override bool ProcessInternal(IEngineEnvironmentSettings environment, Reporter.Output.WriteLine(LocalizableStrings.RunningCommand, command); string resolvedExecutablePath = ResolveExecutableFilePath(environment.Host.FileSystem, executable, outputBasePath); - Process? commandResult = System.Diagnostics.Process.Start(new ProcessStartInfo + using Process process = new() { - RedirectStandardError = redirectStandardError, - RedirectStandardOutput = redirectStandardOutput, - UseShellExecute = false, - CreateNoWindow = false, - WorkingDirectory = outputBasePath, - FileName = resolvedExecutablePath, - Arguments = args - }); - - if (commandResult == null) + StartInfo = new ProcessStartInfo + { + UseShellExecute = false, + CreateNoWindow = false, + WorkingDirectory = outputBasePath, + FileName = resolvedExecutablePath, + Arguments = args + } + }; + ICommand commandToExecute = _commandFactory(process); + if (redirectStandardOutput) { - Reporter.Error.WriteLine(LocalizableStrings.CommandFailed); - Reporter.Verbose.WriteLine("Unable to start sub-process."); - return false; + commandToExecute.CaptureStdOut(); } - - commandResult.WaitForExit(); + if (redirectStandardError) + { + commandToExecute.CaptureStdErr(); + } + CommandResult commandResult = commandToExecute.Execute(cancellationToken); if (commandResult.ExitCode != 0) { @@ -83,7 +97,7 @@ protected override bool ProcessInternal(IEngineEnvironmentSettings environment, return true; } } - catch (Exception ex) + catch (Exception ex) when (ex is not OperationCanceledException) { Reporter.Error.WriteLine(LocalizableStrings.CommandFailed); Reporter.Error.WriteLine(ex.Message); diff --git a/src/Cli/Microsoft.TemplateEngine.Cli/TemplateInvoker.cs b/src/Cli/Microsoft.TemplateEngine.Cli/TemplateInvoker.cs index bec7b86fe9f7..99f5d33761af 100644 --- a/src/Cli/Microsoft.TemplateEngine.Cli/TemplateInvoker.cs +++ b/src/Cli/Microsoft.TemplateEngine.Cli/TemplateInvoker.cs @@ -57,11 +57,39 @@ internal async Task InvokeTemplateAsync(TemplateCommandArgs te string? packageName = string.IsNullOrEmpty(templatePackage?.Identifier) ? null : Sha256Hasher.HashWithNormalizedCasing(templatePackage.Identifier); string? packageVersion = string.IsNullOrEmpty(templatePackage?.Version) ? null : Sha256Hasher.HashWithNormalizedCasing(templatePackage.Version); + return await InvokeTemplateAsync( + () => CreateTemplateAsync(templateArgs, cancellationToken), + success => TelemetryEventEntry.TrackEvent( + TelemetryConstants.CreateEvent, + new Dictionary + { + { TelemetryConstants.Language, templateLanguage }, + { TelemetryConstants.ArgError, "False" }, + { TelemetryConstants.Framework, framework }, + { TelemetryConstants.TemplateName, templateName }, + { TelemetryConstants.TemplateShortName, templateShortNames }, + { TelemetryConstants.PackageName, packageName }, + { TelemetryConstants.PackageVersion, packageVersion }, + { TelemetryConstants.IsTemplateThirdParty, (!isMicrosoftAuthored).ToString() }, + { TelemetryConstants.CreationResult, success.ToString() }, + { TelemetryConstants.Auth, auth } + })).ConfigureAwait(false); + } + + internal static async Task InvokeTemplateAsync( + Func> createTemplateAsync, + Action trackTelemetry) + { bool success = true; try { - return await CreateTemplateAsync(templateArgs, cancellationToken).ConfigureAwait(false); + return await createTemplateAsync().ConfigureAwait(false); + } + catch (OperationCanceledException) + { + success = false; + throw; } catch (ContentGenerationException cx) { @@ -78,28 +106,13 @@ internal async Task InvokeTemplateAsync(TemplateCommandArgs te { success = false; Reporter.Error.WriteLine(ex.Message.Bold().Red()); + return NewCommandStatus.CreateFailed; } finally { - TelemetryEventEntry.TrackEvent( - TelemetryConstants.CreateEvent, - new Dictionary - { - { TelemetryConstants.Language, templateLanguage }, - { TelemetryConstants.ArgError, "False" }, - { TelemetryConstants.Framework, framework }, - { TelemetryConstants.TemplateName, templateName }, - { TelemetryConstants.TemplateShortName, templateShortNames }, - { TelemetryConstants.PackageName, packageName }, - { TelemetryConstants.PackageVersion, packageVersion }, - { TelemetryConstants.IsTemplateThirdParty, (!isMicrosoftAuthored).ToString() }, - { TelemetryConstants.CreationResult, success.ToString() }, - { TelemetryConstants.Auth, auth } - }); + trackTelemetry(success); } - return NewCommandStatus.CreateFailed; - } private static string GetChangeString(ChangeKind kind) @@ -218,7 +231,7 @@ private async Task CreateTemplateAsync(TemplateCommandArgs tem Reporter.Output.WriteLine(LocalizableStrings.ThirdPartyNotices, templateArgs.Template.ThirdPartyNotices); } - return HandlePostActions(instantiateResult, templateArgs); + return HandlePostActions(instantiateResult, templateArgs, cancellationToken); case CreationResultStatus.CreateFailed: case CreationResultStatus.CondtionsEvaluationMismatch: Reporter.Error.WriteLine(string.Format(LocalizableStrings.CreateFailed, resultTemplateName, instantiateResult.ErrorMessage).Bold().Red()); @@ -308,10 +321,10 @@ private async Task CreateTemplateAsync(TemplateCommandArgs tem } } - private NewCommandStatus HandlePostActions(ITemplateCreationResult creationResult, TemplateCommandArgs args) + private NewCommandStatus HandlePostActions(ITemplateCreationResult creationResult, TemplateCommandArgs args, CancellationToken cancellationToken) { using var postActionActivity = Activities.Source.StartActivity("post-actions"); - PostActionExecutionStatus result = _postActionDispatcher.Process(creationResult, args.IsDryRun, args.AllowScripts ?? AllowRunScripts.Prompt); + PostActionExecutionStatus result = _postActionDispatcher.Process(creationResult, args.IsDryRun, args.AllowScripts ?? AllowRunScripts.Prompt, cancellationToken); return result switch { diff --git a/src/Cli/dotnet-aot/DESIGN.md b/src/Cli/dotnet-aot/DESIGN.md index cb42fd722b59..95ed38642d30 100644 --- a/src/Cli/dotnet-aot/DESIGN.md +++ b/src/Cli/dotnet-aot/DESIGN.md @@ -73,7 +73,7 @@ graph TD AotCheck{"DOTNET_CLI_ENABLEAOT
not disabled?"} Parse["Parser.Parse(args)"] Fast{"Command handled
by AOT path?"} - Invoke["Parser.Invoke()"] + Invoke["Parser.InvokeAsync(..., lifecycleToken)"] HostInit["ManagedHost.RunApp()"] Entry --> AotCheck AotCheck -- "Yes" --> Parse --> Fast @@ -142,7 +142,7 @@ command, ...) or an implicit file-based app (`dotnet app.cs`). The bridge's the managed CLI uses — minus the MSBuild/NuGet project-tools resolver — via `CommandResolver.TryResolveCommandSpec(new DefaultCommandResolverPolicy(), ...)`, then invokes the resolved `CommandSpec` out-of-process through -`CommandFactoryUsingResolver` + `Command.Execute()`. The resolution step is +`CommandFactoryUsingResolver` + `Command.Execute(lifecycleToken)`. The resolution step is side-effect free, so the bridge defers to the managed CLI whenever it cannot handle the invocation: unsupported implicit file-based shapes, commands that only the full project-tools resolver can find, anything that does @@ -204,11 +204,11 @@ sequenceDiagram alt DOTNET_CLI_ENABLEAOT enabled (default) aot->>aot: Parser.Parse(args) alt Built-in command handled by AOT - aot->>aot: Parser.Invoke(parseResult) + aot->>aot: Parser.InvokeAsync(parseResult, lifecycleToken) aot-->>dn: exit code else External command that resolves in AOT (tool / PATH / app-base) aot->>aot: TryInvokeExternalCommand → TryResolveCommandSpec - aot->>tool: Command.Execute() (out of process) + aot->>tool: Command.Execute(lifecycleToken) (out of process) tool-->>aot: exit code aot-->>dn: exit code else Command not handled, unresolved, or unsupported file-based shape @@ -276,10 +276,18 @@ The two projects have **different entry-point shapes and do not share a per-invocation telemetry/signal/first-run setup. It has no managed `Main` and does not compile any `Program.cs`. - **`src/Cli/dotnet/Program.cs`** — the managed CLI entry point with telemetry, - signal handlers, and workload checks. It carries no `#if CLI_AOT` branches and + finalization, and workload checks. It carries no `#if CLI_AOT` branches and is not linked into the AOT build. (The `hostfxr_run_app` fallback above invokes *this* `Program.Main` from the managed `dotnet.dll` at runtime — not from the AOT binary.) +- **`Microsoft.DotNet.Cli.Utils.ProcessLifecycle`** — the shared managed/AOT + owner for Ctrl+C, SIGTERM, and process-exit cancellation. The first signal + cancels the token passed through command invocation and starts a two-second + forced-termination fallback; a repeated signal retains the operating system's + immediate termination behavior. While a launched child owns signal handling, + `ProcessReaper` suppresses lifecycle cancellation so Ctrl+C remains with the + child and SIGTERM is forwarded during process exit; an unresponsive child is + terminated after the same two-second timeout. Code that genuinely needs to be identical between the two entry points lives in `src/Cli/dotnet/CommandInvocation.cs` (`ExecuteInternalCommand`), which both diff --git a/src/Cli/dotnet-aot/NativeEntryPoint.cs b/src/Cli/dotnet-aot/NativeEntryPoint.cs index 8599bc342647..e83459429634 100644 --- a/src/Cli/dotnet-aot/NativeEntryPoint.cs +++ b/src/Cli/dotnet-aot/NativeEntryPoint.cs @@ -54,7 +54,40 @@ static int Execute( args[i] = PlatformStringMarshaller.ConvertToManaged(argv[i]) ?? string.Empty; } - return ExecuteCore(hostPath, dotnetRoot, sdkDir, hostfxrPath, args); + return ExecuteCoreForNativeEntryPoint( + hostPath, + dotnetRoot, + sdkDir, + hostfxrPath, + args, + default); + } + + internal static int ExecuteCoreForNativeEntryPoint( + string hostPath, string dotnetRoot, string sdkDir, + string hostfxrPath, string[] args, + CancellationToken cancellationToken) + { + try + { + return ExecuteCoreWithCancellation( + hostPath, + dotnetRoot, + sdkDir, + hostfxrPath, + args, + cancellationToken); + } + catch (OperationCanceledException) when ( + ProcessLifecycle.TryGetSignalExitCode(ProcessLifecycle.CancellationToken, out int signalExitCode)) + { + return signalExitCode; + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + // Exceptions cannot cross the native entry-point boundary. + return 1; + } } public static ITelemetryClient? TelemetryClient { get; private set; } @@ -70,6 +103,18 @@ static int Execute( internal static int ExecuteCore( string hostPath, string dotnetRoot, string sdkDir, string hostfxrPath, string[] args) + => ExecuteCoreWithCancellation( + hostPath, + dotnetRoot, + sdkDir, + hostfxrPath, + args, + default); + + internal static int ExecuteCoreWithCancellation( + string hostPath, string dotnetRoot, string sdkDir, + string hostfxrPath, string[] args, + CancellationToken cancellationToken) { // Match the managed entry point before any localized resources are read. The AOT host does // not run Program.Main, so it must apply DOTNET_CLI_UI_LANGUAGE/VSLANG itself. @@ -185,6 +230,10 @@ internal static int ExecuteCore( if (EnvironmentVariableParser.ParseBool(Environment.GetEnvironmentVariable(EnvironmentVariableNames.DOTNET_CLI_ENABLEAOT), defaultValue: true)) { + using IDisposable? processLifecycle = + cancellationToken == default ? ProcessLifecycle.Initialize() : null; + CancellationToken aotCancellationToken = + processLifecycle is null ? cancellationToken : ProcessLifecycle.CancellationToken; ParseResult? parseResult = null; using (var parse = Activities.Source.StartActivity("parse")) { @@ -220,7 +269,7 @@ internal static int ExecuteCore( { try { - exitCode = CommandInvocation.ExecuteInternalCommand(parseResult); + exitCode = CommandInvocation.ExecuteInternalCommand(parseResult, aotCancellationToken); success = true; aotHandledInProcess = true; SendAotParserTelemetry(parseResult, globalJsonState); @@ -236,7 +285,15 @@ internal static int ExecuteCore( // or local tool, a command on the PATH, ...) or an implicit file-based app (`dotnet app.cs`). // Resolve and invoke external commands in AOT when possible; defer file-based apps, legacy // project tools, and anything that does not resolve to the managed CLI. - else if (parseResult is not null && TryInvokeExternalCommand(parseResult, args, sdkDirectory, mainActivity, globalJsonState, out exitCode, out success)) + else if (parseResult is not null && TryInvokeExternalCommand( + parseResult, + args, + sdkDirectory, + mainActivity, + globalJsonState, + aotCancellationToken, + out exitCode, + out success)) { aotHandledInProcess = true; return exitCode; @@ -305,7 +362,15 @@ internal static int ExecuteCore( /// unsupported file-based app shapes, legacy project tools, commands that do not resolve in AOT, /// or any resolution error. External commands take precedence over implicit file-based apps. ///
- private static bool TryInvokeExternalCommand(ParseResult parseResult, string[] args, string sdkDir, Activity? mainActivity, string? globalJsonState, out int exitCode, out bool success) + private static bool TryInvokeExternalCommand( + ParseResult parseResult, + string[] args, + string sdkDir, + Activity? mainActivity, + string? globalJsonState, + CancellationToken cancellationToken, + out int exitCode, + out bool success) { exitCode = 1; success = false; @@ -346,7 +411,7 @@ private static bool TryInvokeExternalCommand(ParseResult parseResult, string[] a { try { - exitCode = AotRunCommand.Execute(fileBasedRunParseResult); + exitCode = AotRunCommand.Execute(fileBasedRunParseResult, cancellationToken); success = true; mainActivity?.SetDisplayName(fileBasedRunParseResult); SendAotParserTelemetry(fileBasedRunParseResult, globalJsonState); @@ -356,7 +421,7 @@ private static bool TryInvokeExternalCommand(ParseResult parseResult, string[] a { return false; } - catch (Exception exception) + catch (Exception exception) when (exception is not OperationCanceledException) { exitCode = Parser.ExceptionHandler(exception, fileBasedRunParseResult); success = false; @@ -392,11 +457,11 @@ private static bool TryInvokeExternalCommand(ParseResult parseResult, string[] a try { Microsoft.DotNet.Cli.Utils.Command command = CommandFactoryUsingResolver.CreateOrThrow(commandName, commandSpec); - exitCode = command.Execute().ExitCode; + exitCode = command.Execute(cancellationToken).ExitCode; success = true; return true; } - catch (Exception ex) + catch (Exception ex) when (ex is not OperationCanceledException) { // The command was resolved and may have already executed, so it must not be re-run via // the managed CLI. Report the failure exactly as the managed invocation path would. diff --git a/src/Cli/dotnet/BuildServer/IBuildServer.cs b/src/Cli/dotnet/BuildServer/IBuildServer.cs index a46c2090d8d1..aee5bbedd727 100644 --- a/src/Cli/dotnet/BuildServer/IBuildServer.cs +++ b/src/Cli/dotnet/BuildServer/IBuildServer.cs @@ -11,5 +11,5 @@ internal interface IBuildServer string Name { get; } - void Shutdown(); + void Shutdown(CancellationToken cancellationToken); } diff --git a/src/Cli/dotnet/BuildServer/MSBuildServer.cs b/src/Cli/dotnet/BuildServer/MSBuildServer.cs index 2a837623b015..7256636e4ca8 100644 --- a/src/Cli/dotnet/BuildServer/MSBuildServer.cs +++ b/src/Cli/dotnet/BuildServer/MSBuildServer.cs @@ -13,8 +13,10 @@ internal class MSBuildServer : IBuildServer public string Name => CliStrings.MSBuildServer; - public void Shutdown() + public void Shutdown(CancellationToken cancellationToken) { + cancellationToken.ThrowIfCancellationRequested(); BuildManager.DefaultBuildManager.ShutdownAllNodes(); + cancellationToken.ThrowIfCancellationRequested(); } } diff --git a/src/Cli/dotnet/BuildServer/RazorServer.cs b/src/Cli/dotnet/BuildServer/RazorServer.cs index 3773d1f1c115..4bf259b85103 100644 --- a/src/Cli/dotnet/BuildServer/RazorServer.cs +++ b/src/Cli/dotnet/BuildServer/RazorServer.cs @@ -22,8 +22,10 @@ internal class RazorServer( public RazorPidFile PidFile { get; } = pidFile ?? throw new ArgumentNullException(nameof(pidFile)); - public void Shutdown() + public void Shutdown(CancellationToken cancellationToken) { + cancellationToken.ThrowIfCancellationRequested(); + if (!_fileSystem.File.Exists(PidFile.ServerPath.Value)) { // The razor server path doesn't exist anymore so trying to shut it down would fail @@ -45,7 +47,7 @@ public void Shutdown() .CaptureStdOut() .CaptureStdErr(); - var result = command.Execute(); + var result = command.Execute(cancellationToken); if (result.ExitCode != 0) { throw new BuildServerException( diff --git a/src/Cli/dotnet/BuildServer/VBCSCompilerServer.cs b/src/Cli/dotnet/BuildServer/VBCSCompilerServer.cs index e9c12cad1f40..1d22422ed72a 100644 --- a/src/Cli/dotnet/BuildServer/VBCSCompilerServer.cs +++ b/src/Cli/dotnet/BuildServer/VBCSCompilerServer.cs @@ -28,12 +28,12 @@ internal class VBCSCompilerServer(ICommandFactory commandFactory = null) : IBuil public string Name => CliStrings.VBCSCompilerServer; - public void Shutdown() + public void Shutdown(CancellationToken cancellationToken) { List errors = null; // Shutdown the compiler from the SDK. - execute(_commandFactory.Create("exec", [VBCSCompilerPath, s_shutdownArg]), ref errors); + execute(_commandFactory.Create("exec", [VBCSCompilerPath, s_shutdownArg]), cancellationToken, ref errors); // Shutdown toolset compilers. Reporter.Verbose.WriteLine($"Shutting down '{s_toolsetPackageName}' compilers."); @@ -48,7 +48,7 @@ public void Shutdown() Reporter.Verbose.WriteLine($"Found '{vbcsCompilerPath}'."); if (File.Exists(vbcsCompilerPath)) { - execute(CommandFactoryUsingResolver.Create(vbcsCompilerPath, [s_shutdownArg]), ref errors); + execute(CommandFactoryUsingResolver.Create(vbcsCompilerPath, [s_shutdownArg]), cancellationToken, ref errors); } } } @@ -61,13 +61,13 @@ public void Shutdown() string.Join(Environment.NewLine, errors))); } - static void execute(ICommand command, ref List errors) + static void execute(ICommand command, CancellationToken cancellationToken, ref List errors) { command = command .CaptureStdOut() .CaptureStdErr(); - var result = command.Execute(); + var result = command.Execute(cancellationToken); if (result.ExitCode != 0) { errors ??= []; diff --git a/src/Cli/dotnet/CliTransaction.cs b/src/Cli/dotnet/CliTransaction.cs index ac970de9717e..6d04e439c8e8 100644 --- a/src/Cli/dotnet/CliTransaction.cs +++ b/src/Cli/dotnet/CliTransaction.cs @@ -3,6 +3,8 @@ #nullable disable +using Microsoft.DotNet.Cli.Utils; + namespace Microsoft.DotNet.Cli; internal interface ITransactionContext @@ -45,6 +47,9 @@ public void Run(Action action) } catch (Exception) { + using IDisposable softCancellationTimeout = + ProcessLifecycle.OverrideSoftCancellationTimeout(Timeout.InfiniteTimeSpan); + // Roll back transaction RollbackStarted?.Invoke(); @@ -72,6 +77,9 @@ public void Run(Action action) } finally { + using IDisposable softCancellationTimeout = + ProcessLifecycle.OverrideSoftCancellationTimeout(Timeout.InfiniteTimeSpan); + foreach (var cleanupAction in transactionContext.CleanupActions) { cleanupAction(); diff --git a/src/Cli/dotnet/CommandBase.cs b/src/Cli/dotnet/CommandBase.cs index a1ca04d55522..c0099580a8bd 100644 --- a/src/Cli/dotnet/CommandBase.cs +++ b/src/Cli/dotnet/CommandBase.cs @@ -21,7 +21,7 @@ protected CommandBase(ParseResult parseResult) protected CommandBase() { } - public abstract int Execute(); + public abstract int Execute(CancellationToken cancellationToken); } public abstract class CommandBase(ParseResult parseResult) : CommandBase(parseResult) diff --git a/src/Cli/dotnet/CommandFactory/CommandResolution/MSBuildProject.cs b/src/Cli/dotnet/CommandFactory/CommandResolution/MSBuildProject.cs index aa64c76d1e51..7ae054964278 100644 --- a/src/Cli/dotnet/CommandFactory/CommandResolution/MSBuildProject.cs +++ b/src/Cli/dotnet/CommandFactory/CommandResolution/MSBuildProject.cs @@ -147,8 +147,9 @@ public LockFile GetLockFile() GetLockFilePathFromIntermediateBaseOutputPath(); return new LockFileFormat() - .ReadWithLock(lockFilePath) - .Result; + .ReadWithLock(lockFilePath, ProcessLifecycle.CancellationToken) + .GetAwaiter() + .GetResult(); } public bool TryGetLockFile(out LockFile lockFile) @@ -169,8 +170,9 @@ public bool TryGetLockFile(out LockFile lockFile) } lockFile = new LockFileFormat() - .ReadWithLock(lockFilePath) - .Result; + .ReadWithLock(lockFilePath, ProcessLifecycle.CancellationToken) + .GetAwaiter() + .GetResult(); return true; } diff --git a/src/Cli/dotnet/CommandFactory/CommandResolution/ProjectToolsCommandResolver.cs b/src/Cli/dotnet/CommandFactory/CommandResolution/ProjectToolsCommandResolver.cs index e94272a4c385..7433916381e4 100644 --- a/src/Cli/dotnet/CommandFactory/CommandResolution/ProjectToolsCommandResolver.cs +++ b/src/Cli/dotnet/CommandFactory/CommandResolution/ProjectToolsCommandResolver.cs @@ -233,7 +233,7 @@ private static async Task FileExistsWithLock(string path) return await ConcurrencyUtilities.ExecuteWithFileLockedAsync( path, lockedToken => Task.FromResult(File.Exists(path)), - CancellationToken.None); + ProcessLifecycle.CancellationToken); } private bool TryGetToolLockFile( @@ -245,7 +245,7 @@ private bool TryGetToolLockFile( lockFile = null; var lockFilePath = GetToolLockFilePath(toolLibrary, framework, nugetPackagesRoot); - if (!FileExistsWithLock(lockFilePath).Result) + if (!FileExistsWithLock(lockFilePath).GetAwaiter().GetResult()) { return false; } @@ -253,8 +253,9 @@ private bool TryGetToolLockFile( try { lockFile = new LockFileFormat() - .ReadWithLock(lockFilePath) - .Result; + .ReadWithLock(lockFilePath, ProcessLifecycle.CancellationToken) + .GetAwaiter() + .GetResult(); } catch (FileFormatException) { @@ -399,7 +400,7 @@ internal void GenerateDepsJsonFile( { result = forwardingAppWithoutLogging .GetProcessStartInfo() - .ExecuteAndCaptureOutput(out stdOut, out stdErr); + .ExecuteAndCaptureOutput(out stdOut, out stdErr, ProcessLifecycle.CancellationToken); } else { @@ -413,7 +414,7 @@ internal void GenerateDepsJsonFile( Console.SetOut(outWriter); Console.SetError(errWriter); - result = forwardingAppWithoutLogging.Execute(); + result = forwardingAppWithoutLogging.Execute(ProcessLifecycle.CancellationToken); stdOut = outWriter.ToString(); stdErr = errWriter.ToString(); diff --git a/src/Cli/dotnet/CommandInvocation.cs b/src/Cli/dotnet/CommandInvocation.cs index eb405317d8d5..3937d0b4d13c 100644 --- a/src/Cli/dotnet/CommandInvocation.cs +++ b/src/Cli/dotnet/CommandInvocation.cs @@ -18,20 +18,20 @@ namespace Microsoft.DotNet.Cli; internal static class CommandInvocation { /// - /// Invokes a built-in command in-process via , applying the + /// Invokes a built-in command in-process via , applying the /// same exit-code handling on both the managed CLI and the NativeAOT bridge (including the "new" /// command's 127 adjustment and ). Errors are reported and /// converted to an exit code, except that under NativeAOT a /// is allowed to propagate so the bridge can fall back to hosting the managed CLI. /// - internal static int ExecuteInternalCommand(ParseResult parseResult) + internal static int ExecuteInternalCommand(ParseResult parseResult, CancellationToken cancellationToken) { Debug.Assert(parseResult.CanBeInvoked()); int exitCode; using var _ = Activities.Source.StartActivity("invocation"); try { - exitCode = Parser.Invoke(parseResult); + exitCode = Parser.InvokeAsync(parseResult, cancellationToken).GetAwaiter().GetResult(); if (parseResult.Errors.Any()) { exitCode = AdjustExitCodeForNew(); @@ -45,6 +45,11 @@ internal static int ExecuteInternalCommand(ParseResult parseResult) throw; } #endif + catch (OperationCanceledException) when ( + ProcessLifecycle.TryGetSignalExitCode(cancellationToken, out int signalExitCode)) + { + exitCode = signalExitCode; + } catch (Exception exception) { exitCode = Parser.ExceptionHandler(exception, parseResult); diff --git a/src/Cli/dotnet/Commands/Build/BuildCommand.cs b/src/Cli/dotnet/Commands/Build/BuildCommand.cs index b0276710516d..d2b09b04d223 100644 --- a/src/Cli/dotnet/Commands/Build/BuildCommand.cs +++ b/src/Cli/dotnet/Commands/Build/BuildCommand.cs @@ -57,10 +57,10 @@ public static CommandBase FromParseResult(ParseResult parseResult, string? msbui ); } - public static int Run(ParseResult parseResult) + public static int Run(ParseResult parseResult, CancellationToken cancellationToken) { parseResult.HandleDebugSwitch(); - return FromParseResult(parseResult).Execute(); + return FromParseResult(parseResult).Execute(cancellationToken); } } diff --git a/src/Cli/dotnet/Commands/BuildServer/BuildServerCommandParser.cs b/src/Cli/dotnet/Commands/BuildServer/BuildServerCommandParser.cs index 9d5495404745..c380a9aa393b 100644 --- a/src/Cli/dotnet/Commands/BuildServer/BuildServerCommandParser.cs +++ b/src/Cli/dotnet/Commands/BuildServer/BuildServerCommandParser.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.CommandLine; +using Microsoft.DotNet.Cli.CommandLine; using Microsoft.DotNet.Cli.Commands.BuildServer.Shutdown; using Microsoft.DotNet.Cli.Extensions; @@ -12,6 +13,6 @@ internal static class BuildServerCommandParser public static void ConfigureCommand(BuildServerCommandDefinition command) { command.SetAction(parseResult => parseResult.HandleMissingCommand()); - command.ShutdownCommand.SetAction(parseResult => new BuildServerShutdownCommand(parseResult).Execute()); + command.ShutdownCommand.SetAction((parseResult, cancellationToken) => new BuildServerShutdownCommand(parseResult).Execute(cancellationToken)); } } diff --git a/src/Cli/dotnet/Commands/BuildServer/Shutdown/BuildServerShutdownCommand.cs b/src/Cli/dotnet/Commands/BuildServer/Shutdown/BuildServerShutdownCommand.cs index 5ec87704b255..d50b90223d5e 100644 --- a/src/Cli/dotnet/Commands/BuildServer/Shutdown/BuildServerShutdownCommand.cs +++ b/src/Cli/dotnet/Commands/BuildServer/Shutdown/BuildServerShutdownCommand.cs @@ -48,9 +48,11 @@ public BuildServerShutdownCommand( _reporter = reporter ?? Reporter.Output; } - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { - var tasks = StartShutdown(); + cancellationToken.ThrowIfCancellationRequested(); + + var tasks = StartShutdown(cancellationToken); if (tasks.Count == 0) { @@ -61,13 +63,24 @@ public override int Execute() bool success = true; while (tasks.Count > 0) { - var index = WaitForResult([.. tasks.Select(t => t.Item2)]); + var index = WaitForResult([.. tasks.Select(t => t.Item2)], cancellationToken); var (server, task) = tasks[index]; - if (task.IsFaulted) + if (task.IsCanceled) + { + task.GetAwaiter().GetResult(); + } + else if (task.IsFaulted) { + AggregateException exception = task.Exception; + if (exception.Flatten().InnerExceptions is [OperationCanceledException cancellationException] && + cancellationException.CancellationToken == cancellationToken) + { + throw cancellationException; + } + success = false; - WriteFailureMessage(server, task.Exception); + WriteFailureMessage(server, exception); } else { @@ -80,25 +93,25 @@ public override int Execute() return success ? 0 : 1; } - private List<(IBuildServer, Task)> StartShutdown() + private List<(IBuildServer, Task)> StartShutdown(CancellationToken cancellationToken) { var tasks = new List<(IBuildServer, Task)>(); foreach (var server in _serverProvider.EnumerateBuildServers(_enumerationFlags)) { WriteShutdownMessage(server); - tasks.Add((server, Task.Run(() => server.Shutdown()))); + tasks.Add((server, Task.Run(() => server.Shutdown(cancellationToken)))); } return tasks; } - private int WaitForResult(Task[] tasks) + private int WaitForResult(Task[] tasks, CancellationToken cancellationToken) { if (_useOrderedWait) { - return Task.WaitAny(tasks.First()); + return Task.WaitAny([tasks.First()], cancellationToken); } - return Task.WaitAny(tasks); + return Task.WaitAny(tasks, cancellationToken); } private void WriteShutdownMessage(IBuildServer server) diff --git a/src/Cli/dotnet/Commands/Clean/CleanCommand.cs b/src/Cli/dotnet/Commands/Clean/CleanCommand.cs index 5584a77f2461..22a1255bc96e 100644 --- a/src/Cli/dotnet/Commands/Clean/CleanCommand.cs +++ b/src/Cli/dotnet/Commands/Clean/CleanCommand.cs @@ -48,9 +48,9 @@ public static CommandBase FromParseResult(ParseResult result, string? msbuildPat ); } - public static int Run(ParseResult parseResult) + public static int Run(ParseResult parseResult, CancellationToken cancellationToken) { parseResult.HandleDebugSwitch(); - return FromParseResult(parseResult).Execute(); + return FromParseResult(parseResult).Execute(cancellationToken); } } diff --git a/src/Cli/dotnet/Commands/Clean/CleanCommandParser.cs b/src/Cli/dotnet/Commands/Clean/CleanCommandParser.cs index 9322157a7f5c..1513705be6d2 100644 --- a/src/Cli/dotnet/Commands/Clean/CleanCommandParser.cs +++ b/src/Cli/dotnet/Commands/Clean/CleanCommandParser.cs @@ -14,6 +14,6 @@ public static void ConfigureCommand(CleanCommandDefinition command) command.SetAction(CleanCommand.Run); command.FrameworkOption.AddCompletions(CliCompletion.TargetFrameworksFromProjectFile); command.ConfigurationOption.AddCompletions(CliCompletion.ConfigurationsFromProjectFileOrDefaults); - command.FileBasedAppsCommand.SetAction(parseResult => new CleanFileBasedAppArtifactsCommand(parseResult).Execute()); + command.FileBasedAppsCommand.SetAction((parseResult, cancellationToken) => new CleanFileBasedAppArtifactsCommand(parseResult).Execute(cancellationToken)); } } diff --git a/src/Cli/dotnet/Commands/Clean/FileBasedAppArtifacts/CleanFileBasedAppArtifactsCommand.cs b/src/Cli/dotnet/Commands/Clean/FileBasedAppArtifacts/CleanFileBasedAppArtifactsCommand.cs index 847afe143398..65d255472098 100644 --- a/src/Cli/dotnet/Commands/Clean/FileBasedAppArtifacts/CleanFileBasedAppArtifactsCommand.cs +++ b/src/Cli/dotnet/Commands/Clean/FileBasedAppArtifacts/CleanFileBasedAppArtifactsCommand.cs @@ -13,7 +13,7 @@ namespace Microsoft.DotNet.Cli.Commands.Clean.FileBasedAppArtifacts; internal sealed class CleanFileBasedAppArtifactsCommand(ParseResult parseResult) : CommandBase(parseResult) { - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { bool dryRun = _parseResult.GetValue(Definition.DryRunOption); diff --git a/src/Cli/dotnet/Commands/Format/FormatCommand.cs b/src/Cli/dotnet/Commands/Format/FormatCommand.cs index 6cad47691e82..df537554fa9c 100644 --- a/src/Cli/dotnet/Commands/Format/FormatCommand.cs +++ b/src/Cli/dotnet/Commands/Format/FormatCommand.cs @@ -8,9 +8,9 @@ namespace Microsoft.DotNet.Cli.Commands.Format; public sealed class FormatCommand(IEnumerable argsToForward) : FormatForwardingApp(argsToForward) { - public static int Run(string[] args) + public static int Run(string[] args, CancellationToken cancellationToken) { DebugHelper.HandleDebugSwitch(ref args); - return new FormatForwardingApp(args).Execute(); + return new FormatForwardingApp(args).Execute(cancellationToken); } } diff --git a/src/Cli/dotnet/Commands/Format/FormatCommandParser.cs b/src/Cli/dotnet/Commands/Format/FormatCommandParser.cs index 1ea261db2bbf..cdd14168509a 100644 --- a/src/Cli/dotnet/Commands/Format/FormatCommandParser.cs +++ b/src/Cli/dotnet/Commands/Format/FormatCommandParser.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.CommandLine; +using Microsoft.DotNet.Cli.CommandLine; namespace Microsoft.DotNet.Cli.Commands.Format; @@ -9,6 +10,7 @@ internal static class FormatCommandParser { public static void ConfigureCommand(FormatCommandDefinition command) { - command.SetAction(parseResult => FormatCommand.Run(parseResult.GetValue(command.Arguments) ?? [])); + command.SetAction((parseResult, cancellationToken) => + FormatCommand.Run(parseResult.GetValue(command.Arguments) ?? [], cancellationToken)); } } diff --git a/src/Cli/dotnet/Commands/Fsi/FsiCommand.cs b/src/Cli/dotnet/Commands/Fsi/FsiCommand.cs index d37b524438f6..cab7832d2373 100644 --- a/src/Cli/dotnet/Commands/Fsi/FsiCommand.cs +++ b/src/Cli/dotnet/Commands/Fsi/FsiCommand.cs @@ -7,9 +7,9 @@ namespace Microsoft.DotNet.Cli.Commands.Fsi; public sealed class FsiCommand { - public static int Run(string[] args) + public static int Run(string[] args, CancellationToken cancellationToken) { DebugHelper.HandleDebugSwitch(ref args); - return new FsiForwardingApp(args).Execute(); + return new FsiForwardingApp(args).Execute(cancellationToken); } } diff --git a/src/Cli/dotnet/Commands/Fsi/FsiCommandParser.cs b/src/Cli/dotnet/Commands/Fsi/FsiCommandParser.cs index 1ac42cdc4a12..051cf81e5806 100644 --- a/src/Cli/dotnet/Commands/Fsi/FsiCommandParser.cs +++ b/src/Cli/dotnet/Commands/Fsi/FsiCommandParser.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.CommandLine; +using Microsoft.DotNet.Cli.CommandLine; namespace Microsoft.DotNet.Cli.Commands.Fsi; @@ -9,6 +10,7 @@ internal static class FsiCommandParser { public static void ConfigureCommand(FsiCommandDefinition command) { - command.SetAction(parseResult => FsiCommand.Run(parseResult.GetValue(command.Arguments) ?? [])); + command.SetAction((parseResult, cancellationToken) => + FsiCommand.Run(parseResult.GetValue(command.Arguments) ?? [], cancellationToken)); } } diff --git a/src/Cli/dotnet/Commands/Hidden/Add/AddCommandParser.cs b/src/Cli/dotnet/Commands/Hidden/Add/AddCommandParser.cs index 23f41a0e945e..d4773cfc96af 100644 --- a/src/Cli/dotnet/Commands/Hidden/Add/AddCommandParser.cs +++ b/src/Cli/dotnet/Commands/Hidden/Add/AddCommandParser.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.CommandLine; +using Microsoft.DotNet.Cli.CommandLine; using Microsoft.DotNet.Cli.Commands.Package; using Microsoft.DotNet.Cli.Commands.Reference.Add; using Microsoft.DotNet.Cli.Extensions; @@ -15,6 +16,6 @@ public static void ConfigureCommand(AddCommandDefinition command) command.SetAction(parseResult => parseResult.HandleMissingCommand()); PackageCommandParser.ConfigureAddCommand(command.PackageCommand); - command.ReferenceCommand.SetAction(parseResult => new ReferenceAddCommand(parseResult).Execute()); + command.ReferenceCommand.SetAction((parseResult, cancellationToken) => new ReferenceAddCommand(parseResult).Execute(cancellationToken)); } } diff --git a/src/Cli/dotnet/Commands/Hidden/List/ListCommandParser.cs b/src/Cli/dotnet/Commands/Hidden/List/ListCommandParser.cs index d98fd9f6fc7c..16970557d8d6 100644 --- a/src/Cli/dotnet/Commands/Hidden/List/ListCommandParser.cs +++ b/src/Cli/dotnet/Commands/Hidden/List/ListCommandParser.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.CommandLine; +using Microsoft.DotNet.Cli.CommandLine; using Microsoft.DotNet.Cli.Commands.Package.List; using Microsoft.DotNet.Cli.Commands.Reference.List; using Microsoft.DotNet.Cli.Extensions; @@ -14,7 +15,7 @@ public static void ConfigureCommand(ListCommandDefinition command) { command.SetAction(parseResult => parseResult.HandleMissingCommand()); - command.PackageCommand.SetAction(parseResult => new PackageListCommand(parseResult).Execute()); - command.ReferenceCommand.SetAction(parseResult => new ReferenceListCommand(parseResult).Execute()); + command.PackageCommand.SetAction((parseResult, cancellationToken) => new PackageListCommand(parseResult).Execute(cancellationToken)); + command.ReferenceCommand.SetAction((parseResult, cancellationToken) => new ReferenceListCommand(parseResult).Execute(cancellationToken)); } } diff --git a/src/Cli/dotnet/Commands/Hidden/Remove/RemoveCommandParser.cs b/src/Cli/dotnet/Commands/Hidden/Remove/RemoveCommandParser.cs index c8f558c1b7ff..c9d83b090453 100644 --- a/src/Cli/dotnet/Commands/Hidden/Remove/RemoveCommandParser.cs +++ b/src/Cli/dotnet/Commands/Hidden/Remove/RemoveCommandParser.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.CommandLine; +using Microsoft.DotNet.Cli.CommandLine; using Microsoft.DotNet.Cli.Commands.Package.Remove; using Microsoft.DotNet.Cli.Commands.Reference.Remove; using Microsoft.DotNet.Cli.Extensions; @@ -14,7 +15,7 @@ public static void ConfigureCommand(RemoveCommandDefinition command) { command.SetAction(parseResult => parseResult.HandleMissingCommand()); - command.PackageCommand.SetAction(parseResult => new PackageRemoveCommand(parseResult).Execute()); - command.ReferenceCommand.SetAction(parseResult => new ReferenceRemoveCommand(parseResult).Execute()); + command.PackageCommand.SetAction((parseResult, cancellationToken) => new PackageRemoveCommand(parseResult).Execute(cancellationToken)); + command.ReferenceCommand.SetAction((parseResult, cancellationToken) => new ReferenceRemoveCommand(parseResult).Execute(cancellationToken)); } } diff --git a/src/Cli/dotnet/Commands/MSBuild/MSBuildCommand.cs b/src/Cli/dotnet/Commands/MSBuild/MSBuildCommand.cs index 57a922005fc2..ed4acedc667e 100644 --- a/src/Cli/dotnet/Commands/MSBuild/MSBuildCommand.cs +++ b/src/Cli/dotnet/Commands/MSBuild/MSBuildCommand.cs @@ -42,10 +42,10 @@ public static MSBuildCommand FromParseResult(ParseResult parseResult, string? ms msbuildPath: msbuildPath); } - public static int Run(ParseResult parseResult) + public static int Run(ParseResult parseResult, CancellationToken cancellationToken) { parseResult.HandleDebugSwitch(); - return FromParseResult(parseResult).Execute(); + return FromParseResult(parseResult).Execute(cancellationToken); } } diff --git a/src/Cli/dotnet/Commands/MSBuild/MSBuildCommandParser.cs b/src/Cli/dotnet/Commands/MSBuild/MSBuildCommandParser.cs index 662e6fbec7dc..de083b57fdcc 100644 --- a/src/Cli/dotnet/Commands/MSBuild/MSBuildCommandParser.cs +++ b/src/Cli/dotnet/Commands/MSBuild/MSBuildCommandParser.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.CommandLine; +using Microsoft.DotNet.Cli.CommandLine; namespace Microsoft.DotNet.Cli.Commands.MSBuild; diff --git a/src/Cli/dotnet/Commands/MSBuild/MSBuildForwardingApp.cs b/src/Cli/dotnet/Commands/MSBuild/MSBuildForwardingApp.cs index 0cca20ca7f89..c6e0a2b2b1f3 100644 --- a/src/Cli/dotnet/Commands/MSBuild/MSBuildForwardingApp.cs +++ b/src/Cli/dotnet/Commands/MSBuild/MSBuildForwardingApp.cs @@ -28,6 +28,9 @@ namespace Microsoft.DotNet.Cli.Commands.MSBuild; /// public class MSBuildForwardingApp : CommandBase { + // MSBuild cancellation needs time to finish nodes and close loggers such as the binary logger. + internal static readonly TimeSpan BuildSoftCancellationTimeout = TimeSpan.FromSeconds(2); + private readonly MSBuildForwardingAppWithoutLogging _forwardingAppWithoutLogging; /// @@ -130,15 +133,21 @@ private void InitializeRequiredEnvironmentVariables() internal string[] GetArgumentTokensToMSBuild() => _forwardingAppWithoutLogging.GetAllArguments(); - public override int Execute() => Execute(workingDirectory: null); + public override int Execute(CancellationToken cancellationToken) => Execute(workingDirectory: null, cancellationToken); - internal virtual int ExecuteOutOfProc(string workingDirectory) => Execute(workingDirectory); + internal virtual int ExecuteOutOfProc(string workingDirectory, CancellationToken cancellationToken) => Execute(workingDirectory, cancellationToken); - private int Execute(string? workingDirectory) + private int Execute(string? workingDirectory, CancellationToken cancellationToken) { + using IDisposable softCancellationTimeout = + ProcessLifecycle.OverrideSoftCancellationTimeout(BuildSoftCancellationTimeout); + // Ignore Ctrl-C for the remainder of the command's execution // Forwarding commands will just spawn the child process and exit Console.CancelKeyPress += (sender, e) => { e.Cancel = true; }; - return _forwardingAppWithoutLogging.Execute(workingDirectory); + return _forwardingAppWithoutLogging.Execute( + workingDirectory, + suspendSoftCancellationTimeout: false, + cancellationToken); } } diff --git a/src/Cli/dotnet/Commands/New/DotnetCommandCallbacks.cs b/src/Cli/dotnet/Commands/New/DotnetCommandCallbacks.cs index 84c961b615cb..4505ccbbac2a 100644 --- a/src/Cli/dotnet/Commands/New/DotnetCommandCallbacks.cs +++ b/src/Cli/dotnet/Commands/New/DotnetCommandCallbacks.cs @@ -13,7 +13,7 @@ namespace Microsoft.DotNet.Cli.Commands.New; internal static class DotnetCommandCallbacks { - internal static bool AddPackageReference(string projectPath, string packageName, string? version) + internal static bool AddPackageReference(string projectPath, string packageName, string? version, CancellationToken cancellationToken) { PathUtility.EnsureAllPathsExist([projectPath], CliStrings.CommonFileNotFound, allowDirectories: false); IEnumerable commandArgs = ["add", projectPath, "package", packageName]; @@ -28,10 +28,10 @@ internal static bool AddPackageReference(string projectPath, string packageName, AddCommandParser.ConfigureCommand(addCommand); var addPackageReferenceCommand = new PackageAddCommand(addCommand.Parse([.. commandArgs])); - return addPackageReferenceCommand.Execute() == 0; + return addPackageReferenceCommand.Execute(cancellationToken) == 0; } - internal static bool AddProjectReference(string projectPath, string projectToAdd) + internal static bool AddProjectReference(string projectPath, string projectToAdd, CancellationToken cancellationToken) { PathUtility.EnsureAllPathsExist([projectPath], CliStrings.CommonFileNotFound, allowDirectories: false); PathUtility.EnsureAllPathsExist([projectToAdd], CliStrings.CommonFileNotFound, allowDirectories: false); @@ -41,17 +41,17 @@ internal static bool AddProjectReference(string projectPath, string projectToAdd AddCommandParser.ConfigureCommand(addCommand); var addProjectReferenceCommand = new ReferenceAddCommand(addCommand.Parse([.. commandArgs])); - return addProjectReferenceCommand.Execute() == 0; + return addProjectReferenceCommand.Execute(cancellationToken) == 0; } - internal static bool RestoreProject(string pathToRestore) + internal static bool RestoreProject(string pathToRestore, CancellationToken cancellationToken) { PathUtility.EnsureAllPathsExist([pathToRestore], CliStrings.CommonFileNotFound, allowDirectories: true); // for the implicit restore we do not want the terminal logger to emit any output unless there are errors - return RestoreCommand.Run([pathToRestore, "-tlp:verbosity=quiet", "--no-logo"]) == 0; + return RestoreCommand.Run([pathToRestore, "-tlp:verbosity=quiet", "--no-logo"], cancellationToken) == 0; } - internal static bool AddProjectsToSolution(string solutionPath, IReadOnlyList projectsToAdd, string? solutionFolder, bool? inRoot) + internal static bool AddProjectsToSolution(string solutionPath, IReadOnlyList projectsToAdd, string? solutionFolder, bool? inRoot, CancellationToken cancellationToken) { PathUtility.EnsureAllPathsExist([solutionPath], CliStrings.CommonFileNotFound, allowDirectories: false); PathUtility.EnsureAllPathsExist(projectsToAdd, CliStrings.CommonFileNotFound, allowDirectories: false); @@ -70,6 +70,6 @@ internal static bool AddProjectsToSolution(string solutionPath, IReadOnlyList? addPackageReferenceCallback = null, - Func? addProjectReferenceCallback = null) : PostActionProcessorBase + Func? addPackageReferenceCallback = null, + Func? addProjectReferenceCallback = null) : PostActionProcessorBase { - private readonly Func _addPackageReferenceCallback = addPackageReferenceCallback ?? DotnetCommandCallbacks.AddPackageReference; - private readonly Func _addProjectReferenceCallback = addProjectReferenceCallback ?? DotnetCommandCallbacks.AddProjectReference; + private readonly Func _addPackageReferenceCallback = addPackageReferenceCallback ?? DotnetCommandCallbacks.AddPackageReference; + private readonly Func _addProjectReferenceCallback = addProjectReferenceCallback ?? DotnetCommandCallbacks.AddProjectReference; public override Guid Id => ActionProcessorId; @@ -32,7 +32,7 @@ internal static IReadOnlyList FindProjFileAtOrAbovePath(IPhysicalFileSys } } - protected override bool ProcessInternal(IEngineEnvironmentSettings environment, IPostAction action, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath) + protected override bool ProcessInternal(IEngineEnvironmentSettings environment, IPostAction action, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath, CancellationToken cancellationToken) { IReadOnlyList? projectsToProcess = GetConfiguredFiles(action.Args, creationEffects, "targetFiles", outputBasePath); @@ -80,7 +80,7 @@ protected override bool ProcessInternal(IEngineEnvironmentSettings environment, bool success = true; foreach (string projectFile in projectsToProcess) { - success &= AddReference(action, projectFile, outputBasePath, creationEffects); + success &= AddReference(action, projectFile, outputBasePath, creationEffects, cancellationToken); if (!success) { @@ -111,7 +111,7 @@ private static IReadOnlyList FindExistingTargetFiles(IPhysicalFileSystem return foundFiles ?? []; } - private bool AddReference(IPostAction actionConfig, string projectFile, string outputBasePath, ICreationEffects creationEffects) + private bool AddReference(IPostAction actionConfig, string projectFile, string outputBasePath, ICreationEffects creationEffects, CancellationToken cancellationToken) { if (actionConfig.Args == null || !actionConfig.Args.TryGetValue("reference", out string? referenceToAdd)) { @@ -132,12 +132,12 @@ private bool AddReference(IPostAction actionConfig, string projectFile, string o string relativeProjectReference = referenceNameChange ?? referenceToAdd; referenceToAdd = Path.GetFullPath(relativeProjectReference, outputBasePath); - return AddProjectReference(projectFile, referenceToAdd); + return AddProjectReference(projectFile, referenceToAdd, cancellationToken); } else if (string.Equals(referenceType, "package", StringComparison.OrdinalIgnoreCase)) { actionConfig.Args.TryGetValue("version", out string? version); - return AddPackageReference(projectFile, referenceToAdd, version); + return AddPackageReference(projectFile, referenceToAdd, version, cancellationToken); } else if (string.Equals(referenceType, "framework", StringComparison.OrdinalIgnoreCase)) { @@ -151,7 +151,7 @@ private bool AddReference(IPostAction actionConfig, string projectFile, string o } } - private bool AddPackageReference(string projectPath, string packageName, string? version) + private bool AddPackageReference(string projectPath, string packageName, string? version, CancellationToken cancellationToken) { try { @@ -163,7 +163,7 @@ private bool AddPackageReference(string projectPath, string packageName, string? { Reporter.Output.WriteLine(string.Format(CliCommandStrings.PostAction_AddReference_AddPackageReference_WithVersion, packageName, version, projectPath)); } - bool succeeded = _addPackageReferenceCallback(projectPath, packageName, version); + bool succeeded = _addPackageReferenceCallback(projectPath, packageName, version, cancellationToken); if (succeeded) { Reporter.Output.WriteLine(CliCommandStrings.PostAction_AddReference_Succeeded); @@ -174,19 +174,19 @@ private bool AddPackageReference(string projectPath, string packageName, string? } return succeeded; } - catch (Exception e) + catch (Exception e) when (e is not OperationCanceledException) { Reporter.Error.WriteLine(string.Format(CliCommandStrings.PostAction_AddReference_AddPackageReference_Failed, e.Message)); return false; } } - private bool AddProjectReference(string projectPath, string projectToAdd) + private bool AddProjectReference(string projectPath, string projectToAdd, CancellationToken cancellationToken) { try { Reporter.Output.WriteLine(string.Format(CliCommandStrings.PostAction_AddReference_AddProjectReference, projectToAdd, projectPath)); - bool succeeded = _addProjectReferenceCallback(projectPath, projectToAdd); + bool succeeded = _addProjectReferenceCallback(projectPath, projectToAdd, cancellationToken); if (succeeded) { Reporter.Output.WriteLine(CliCommandStrings.PostAction_AddReference_Succeeded); @@ -197,7 +197,7 @@ private bool AddProjectReference(string projectPath, string projectToAdd) } return succeeded; } - catch (Exception e) + catch (Exception e) when (e is not OperationCanceledException) { Reporter.Error.WriteLine(string.Format(CliCommandStrings.PostAction_AddReference_AddProjectReference_Failed, e.Message)); return false; diff --git a/src/Cli/dotnet/Commands/New/PostActions/DotnetRestorePostActionProcessor.cs b/src/Cli/dotnet/Commands/New/PostActions/DotnetRestorePostActionProcessor.cs index 189242819869..75f094ad0d79 100644 --- a/src/Cli/dotnet/Commands/New/PostActions/DotnetRestorePostActionProcessor.cs +++ b/src/Cli/dotnet/Commands/New/PostActions/DotnetRestorePostActionProcessor.cs @@ -7,15 +7,15 @@ namespace Microsoft.DotNet.Cli.Commands.New.PostActions; -internal class DotnetRestorePostActionProcessor(Func? restoreCallback = null) : PostActionProcessorBase +internal class DotnetRestorePostActionProcessor(Func? restoreCallback = null) : PostActionProcessorBase { - private readonly Func _restoreCallback = restoreCallback ?? DotnetCommandCallbacks.RestoreProject; + private readonly Func _restoreCallback = restoreCallback ?? DotnetCommandCallbacks.RestoreProject; public override Guid Id => ActionProcessorId; internal static Guid ActionProcessorId { get; } = new Guid("210D431B-A78B-4D2F-B762-4ED3E3EA9025"); - protected override bool ProcessInternal(IEngineEnvironmentSettings environment, IPostAction actionConfig, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath) + protected override bool ProcessInternal(IEngineEnvironmentSettings environment, IPostAction actionConfig, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath, CancellationToken cancellationToken) { bool allSucceeded = true; IEnumerable targetFiles = GetConfiguredFiles(actionConfig.Args, creationEffects, "files", outputBasePath); @@ -39,17 +39,17 @@ protected override bool ProcessInternal(IEngineEnvironmentSettings environment, foreach (string pathToRestore in targetFiles) { - allSucceeded &= RestoreProject(pathToRestore); + allSucceeded &= RestoreProject(pathToRestore, cancellationToken); } return allSucceeded; } - private bool RestoreProject(string pathToRestore) + private bool RestoreProject(string pathToRestore, CancellationToken cancellationToken) { try { Reporter.Output.WriteLine(string.Format(CliCommandStrings.PostAction_Restore_Running, pathToRestore)); - bool succeeded = _restoreCallback(pathToRestore); + bool succeeded = _restoreCallback(pathToRestore, cancellationToken); if (!succeeded) { Reporter.Error.WriteLine(CliCommandStrings.PostAction_Restore_Failed); @@ -60,7 +60,7 @@ private bool RestoreProject(string pathToRestore) } return succeeded; } - catch (Exception e) + catch (Exception e) when (e is not OperationCanceledException) { Reporter.Error.WriteLine(string.Format(CliCommandStrings.PostAction_Restore_RestoreFailed, e.Message)); return false; diff --git a/src/Cli/dotnet/Commands/New/PostActions/DotnetSlnPostActionProcessor.cs b/src/Cli/dotnet/Commands/New/PostActions/DotnetSlnPostActionProcessor.cs index 960f68269035..54302530c399 100644 --- a/src/Cli/dotnet/Commands/New/PostActions/DotnetSlnPostActionProcessor.cs +++ b/src/Cli/dotnet/Commands/New/PostActions/DotnetSlnPostActionProcessor.cs @@ -9,9 +9,9 @@ namespace Microsoft.DotNet.Cli.Commands.New.PostActions; -internal class DotnetSlnPostActionProcessor(Func, string?, bool?, bool>? addProjToSolutionCallback = null) : PostActionProcessorBase +internal class DotnetSlnPostActionProcessor(Func, string?, bool?, CancellationToken, bool>? addProjToSolutionCallback = null) : PostActionProcessorBase { - private readonly Func, string?, bool?, bool> _addProjToSolutionCallback = addProjToSolutionCallback ?? DotnetCommandCallbacks.AddProjectsToSolution; + private readonly Func, string?, bool?, CancellationToken, bool> _addProjToSolutionCallback = addProjToSolutionCallback ?? DotnetCommandCallbacks.AddProjectsToSolution; public override Guid Id => ActionProcessorId; @@ -87,7 +87,7 @@ internal static bool TryGetProjectFilesToAdd(IPostAction actionConfig, ICreation } } - protected override bool ProcessInternal(IEngineEnvironmentSettings environment, IPostAction action, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath) + protected override bool ProcessInternal(IEngineEnvironmentSettings environment, IPostAction action, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath, CancellationToken cancellationToken) { IReadOnlyList nearestSlnFilesFound = FindSolutionFilesAtOrAbovePath(environment.Host.FileSystem, outputBasePath); if (nearestSlnFilesFound.Count != 1) @@ -129,14 +129,14 @@ protected override bool ProcessInternal(IEngineEnvironmentSettings environment, { Reporter.Output.WriteLine(string.Format(CliCommandStrings.PostAction_AddProjToSln_Running, string.Join(" ", projectFiles), nearestSlnFilesFound[0], solutionFolder)); } - return AddProjectsToSolution(nearestSlnFilesFound[0], projectFiles, solutionFolder, inRoot); + return AddProjectsToSolution(nearestSlnFilesFound[0], projectFiles, solutionFolder, inRoot, cancellationToken); } - private bool AddProjectsToSolution(string solutionPath, IReadOnlyList projectsToAdd, string? solutionFolder, bool? inRoot) + private bool AddProjectsToSolution(string solutionPath, IReadOnlyList projectsToAdd, string? solutionFolder, bool? inRoot, CancellationToken cancellationToken) { try { - bool succeeded = _addProjToSolutionCallback(solutionPath, projectsToAdd, solutionFolder, inRoot); + bool succeeded = _addProjToSolutionCallback(solutionPath, projectsToAdd, solutionFolder, inRoot, cancellationToken); if (!succeeded) { Reporter.Error.WriteLine(CliCommandStrings.PostAction_AddProjToSln_Failed_NoReason); diff --git a/src/Cli/dotnet/Commands/NuGet/NuGetCommand.cs b/src/Cli/dotnet/Commands/NuGet/NuGetCommand.cs index 1a68c691d84f..dd7ea1519101 100644 --- a/src/Cli/dotnet/Commands/NuGet/NuGetCommand.cs +++ b/src/Cli/dotnet/Commands/NuGet/NuGetCommand.cs @@ -13,20 +13,21 @@ namespace Microsoft.DotNet.Cli.Commands.NuGet; internal class NuGetCommand { - public static int Run(string[] args, bool isFileBasedApp = false) + public static int Run(string[] args, CancellationToken cancellationToken, bool isFileBasedApp = false) { #if CLI_AOT // The in-process NuGet runner relies on NuGet.CommandLine.XPlat, which isn't AOT-compatible, // so AOT always forwards to the out-of-process NuGet CLI. - return Run(args, new NuGetCommandRunner()); + return Run(args, new NuGetCommandRunner(), cancellationToken); #else return Run(args, isFileBasedApp ? new InProcessNuGetCommandRunner(NuGetVirtualProjectBuilder.Instance) - : new NuGetCommandRunner()); + : new NuGetCommandRunner(), + cancellationToken); #endif } - public static int Run(ParseResult parseResult) + public static int Run(ParseResult parseResult, CancellationToken cancellationToken) { ICommandRunner runner; @@ -46,10 +47,10 @@ public static int Run(ParseResult parseResult) } #endif - return Run(parseResult.GetArguments(), runner); + return Run(parseResult.GetArguments(), runner, cancellationToken); } - public static int Run(string[] args, ICommandRunner nugetCommandRunner) + public static int Run(string[] args, ICommandRunner nugetCommandRunner, CancellationToken cancellationToken) { DebugHelper.HandleDebugSwitch(ref args); @@ -63,16 +64,16 @@ public static int Run(string[] args, ICommandRunner nugetCommandRunner) if (args[i] == "-?") args[i] = "--help"; } - return nugetCommandRunner.Run(args); + return nugetCommandRunner.Run(args, cancellationToken); } private class NuGetCommandRunner : ICommandRunner { - public int Run(string[] args) + public int Run(string[] args, CancellationToken cancellationToken) { var nugetApp = new NuGetForwardingApp(args); nugetApp.WithEnvironmentVariable(EnvironmentVariableNames.DOTNET_HOST_PATH, GetDotnetPath()); - return nugetApp.Execute(); + return nugetApp.Execute(cancellationToken); } } @@ -84,13 +85,17 @@ private class InProcessNuGetCommandRunner(NuGetVirtualProjectBuilder virtualProj "IL2026", Justification = "This runner is excluded from CLI_AOT builds")] - public int Run(string[] args) + public int Run(string[] args, CancellationToken cancellationToken) { + cancellationToken.ThrowIfCancellationRequested(); + var originalDotNetHostPath = Environment.GetEnvironmentVariable(EnvironmentVariableNames.DOTNET_HOST_PATH); Environment.SetEnvironmentVariable(EnvironmentVariableNames.DOTNET_HOST_PATH, GetDotnetPath()); try { - return global::NuGet.CommandLine.XPlat.Program.Run(args, virtualProjectBuilder); + int exitCode = global::NuGet.CommandLine.XPlat.Program.Run(args, virtualProjectBuilder); + cancellationToken.ThrowIfCancellationRequested(); + return exitCode; } finally { diff --git a/src/Cli/dotnet/Commands/NuGet/NuGetCommandParser.cs b/src/Cli/dotnet/Commands/NuGet/NuGetCommandParser.cs index c7de8029cbdd..153d11018685 100644 --- a/src/Cli/dotnet/Commands/NuGet/NuGetCommandParser.cs +++ b/src/Cli/dotnet/Commands/NuGet/NuGetCommandParser.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.CommandLine; +using Microsoft.DotNet.Cli.CommandLine; namespace Microsoft.DotNet.Cli.Commands.NuGet; @@ -17,4 +18,3 @@ public static void ConfigureCommand(Command command) } } } - diff --git a/src/Cli/dotnet/Commands/Pack/PackCommand.cs b/src/Cli/dotnet/Commands/Pack/PackCommand.cs index 3af1dc310118..8ca13c6cc285 100644 --- a/src/Cli/dotnet/Commands/Pack/PackCommand.cs +++ b/src/Cli/dotnet/Commands/Pack/PackCommand.cs @@ -23,13 +23,19 @@ public class PackCommand( string? msbuildPath = null ) : RestoringCommand(msbuildArgs, noRestore, msbuildPath: msbuildPath) { - public static CommandBase FromArgs(string[] args, string? msbuildPath = null) + public static CommandBase FromArgs( + string[] args, + CancellationToken cancellationToken, + string? msbuildPath = null) { var parseResult = Parser.Parse(["dotnet", "pack", .. args]); - return FromParseResult(parseResult, msbuildPath); + return FromParseResult(parseResult, cancellationToken, msbuildPath); } - public static CommandBase FromParseResult(ParseResult parseResult, string? msbuildPath = null) + public static CommandBase FromParseResult( + ParseResult parseResult, + CancellationToken cancellationToken, + string? msbuildPath = null) { var definition = (PackCommandDefinition)parseResult.CommandResult.Command; @@ -68,7 +74,8 @@ public static CommandBase FromParseResult(ParseResult parseResult, string? msbui new ReleasePropertyProjectLocator.DependentCommandOptions( otherArgs, parseResult.HasOption(definition.ConfigurationOption) ? parseResult.GetValue(definition.ConfigurationOption) : null - ) + ), + cancellationToken ); return msbuildArgs.CloneWithAdditionalProperties(projectLocator.GetCustomDefaultConfigurationValueIfSpecified()); }); @@ -133,7 +140,7 @@ public static int RunPackCommand(ParseResult parseResult) return 0; } - public static int Run(ParseResult parseResult) + public static int Run(ParseResult parseResult, CancellationToken cancellationToken) { var definition = (PackCommandDefinition)parseResult.CommandResult.Command; @@ -148,6 +155,6 @@ public static int Run(ParseResult parseResult) } // Fallback to MSBuild-based packing - return FromParseResult(parseResult).Execute(); + return FromParseResult(parseResult, cancellationToken).Execute(cancellationToken); } } diff --git a/src/Cli/dotnet/Commands/Package/Add/PackageAddCommand.cs b/src/Cli/dotnet/Commands/Package/Add/PackageAddCommand.cs index 22cb8361f6c2..488403a92d7f 100644 --- a/src/Cli/dotnet/Commands/Package/Add/PackageAddCommand.cs +++ b/src/Cli/dotnet/Commands/Package/Add/PackageAddCommand.cs @@ -22,7 +22,7 @@ public PackageAddCommand(ParseResult parseResult) _packageId = parseResult.GetValue(Definition.PackageIdArgument); } - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { var (fileOrDirectory, allowedAppKinds) = PackageCommandParser.ProcessPathOptions(Definition.FileOption, Definition.ProjectOption, Definition.GetProjectOrFileArgument(), _parseResult); @@ -61,7 +61,7 @@ public override int Execute() throw new GracefulException(string.Format(CliCommandStrings.CmdDGFileIOException, projectFilePath), ioex); } - GetProjectDependencyGraph(projectFilePath, tempDgFilePath, isFileBasedApp); + GetProjectDependencyGraph(projectFilePath, tempDgFilePath, isFileBasedApp, cancellationToken); } var args = TransformArgs( @@ -69,14 +69,17 @@ public override int Execute() tempDgFilePath, projectFilePath); - var result = NuGetCommand.Run(args, isFileBasedApp); - - DisposeTemporaryFile(tempDgFilePath); - - return result; + try + { + return NuGetCommand.Run(args, cancellationToken, isFileBasedApp); + } + finally + { + DisposeTemporaryFile(tempDgFilePath); + } } - private static void GetProjectDependencyGraph(string projectFilePath, string dgFilePath, bool isFileBasedApp) + private static void GetProjectDependencyGraph(string projectFilePath, string dgFilePath, bool isFileBasedApp, CancellationToken cancellationToken) { int result; if (isFileBasedApp) @@ -96,7 +99,7 @@ private static void GetProjectDependencyGraph(string projectFilePath, string dgF NoRestore = true, NoCache = true, NoWriteBuildMarkers = true, - }.Execute(); + }.Execute(cancellationToken); } else { @@ -122,7 +125,7 @@ private static void GetProjectDependencyGraph(string projectFilePath, string dgF // Set verbosity to quiet to avoid cluttering the output for this 'inner' build "-v:quiet" - ]).Execute(); + ]).Execute(cancellationToken); } if (result != 0) diff --git a/src/Cli/dotnet/Commands/Package/List/PackageListCommand.cs b/src/Cli/dotnet/Commands/Package/List/PackageListCommand.cs index a661412adc73..0b6edee25617 100644 --- a/src/Cli/dotnet/Commands/Package/List/PackageListCommand.cs +++ b/src/Cli/dotnet/Commands/Package/List/PackageListCommand.cs @@ -19,7 +19,7 @@ namespace Microsoft.DotNet.Cli.Commands.Package.List; internal sealed class PackageListCommand(ParseResult parseResult) : CommandBase(parseResult) { - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { var (fileOrDirectory, allowedAppKinds) = PackageCommandParser.ProcessPathOptions(Definition.FileOption, Definition.ProjectOption, Definition.GetProjectOrFileArgument(), _parseResult); @@ -37,15 +37,15 @@ public override int Execute() { ReportOutputFormat formatOption = _parseResult.GetValue(Definition.FormatOption); bool interactive = _parseResult.GetValue(Definition.InteractiveOption); - restoreExitCode = RunRestore(projectFile, formatOption, interactive, isFileBasedApp); + restoreExitCode = RunRestore(projectFile, formatOption, interactive, isFileBasedApp, cancellationToken); } return restoreExitCode == 0 - ? NuGetCommand.Run(TransformArgs(projectFile), isFileBasedApp) + ? NuGetCommand.Run(TransformArgs(projectFile), cancellationToken, isFileBasedApp) : restoreExitCode; } - private static int RunRestore(string projectOrSolution, ReportOutputFormat formatOption, bool interactive, bool isFileBasedApp) + private static int RunRestore(string projectOrSolution, ReportOutputFormat formatOption, bool interactive, bool isFileBasedApp, CancellationToken cancellationToken) { CommandBase command; if (isFileBasedApp) @@ -85,9 +85,10 @@ private static int RunRestore(string projectOrSolution, ReportOutputFormat forma try { - exitCode = command.Execute(); + cancellationToken.ThrowIfCancellationRequested(); + exitCode = command.Execute(cancellationToken); } - catch (Exception) + catch (Exception ex) when (ex is not OperationCanceledException) { exitCode = 1; } diff --git a/src/Cli/dotnet/Commands/Package/PackageCommandParser.cs b/src/Cli/dotnet/Commands/Package/PackageCommandParser.cs index 9144f5c2a3dd..1d2eb5ac1842 100644 --- a/src/Cli/dotnet/Commands/Package/PackageCommandParser.cs +++ b/src/Cli/dotnet/Commands/Package/PackageCommandParser.cs @@ -10,6 +10,7 @@ using Microsoft.DotNet.Cli.Commands.Package.Search; using Microsoft.DotNet.Cli.Commands.Run; using Microsoft.DotNet.Cli.Extensions; +using Microsoft.DotNet.Cli.Utils; using Microsoft.Extensions.EnvironmentAbstractions; using NuGet.Versioning; @@ -21,14 +22,14 @@ public static void ConfigureCommand(PackageCommandDefinition command) { command.SetAction((parseResult) => parseResult.HandleMissingCommand()); - command.RemoveCommand.SetAction(parseResult => new PackageRemoveCommand(parseResult).Execute()); - command.ListCommand.SetAction(parseResult => new PackageListCommand(parseResult).Execute()); + command.RemoveCommand.SetAction((parseResult, cancellationToken) => new PackageRemoveCommand(parseResult).Execute(cancellationToken)); + command.ListCommand.SetAction((parseResult, cancellationToken) => new PackageListCommand(parseResult).Execute(cancellationToken)); ConfigureAddCommand(command.AddCommand); - command.SearchCommand.SetAction(parseResult => + command.SearchCommand.SetAction((parseResult, cancellationToken) => { var command = new PackageSearchCommand(parseResult); - int exitCode = command.Execute(); + int exitCode = command.Execute(cancellationToken); if (exitCode == 1) { @@ -45,7 +46,10 @@ internal static void ConfigureAddCommand(PackageAddCommandDefinitionBase def) { // we should take --prerelease flags into account for version completion var allowPrerelease = context.ParseResult.GetValue(def.PrereleaseOption); - return QueryNuGet(context.WordToComplete, allowPrerelease, CancellationToken.None).Result.Select(packageId => new CompletionItem(packageId)); + return QueryNuGet(context.WordToComplete, allowPrerelease, ProcessLifecycle.CancellationToken) + .GetAwaiter() + .GetResult() + .Select(packageId => new CompletionItem(packageId)); }); def.VersionOption.CompletionSources.Add(context => @@ -55,8 +59,9 @@ internal static void ConfigureAddCommand(PackageAddCommandDefinitionBase def) { // we should take --prerelease flags into account for version completion var allowPrerelease = context.ParseResult.GetValue(def.PrereleaseOption); - return QueryVersionsForPackage(packageId.Id, context.WordToComplete, allowPrerelease, CancellationToken.None) - .Result + return QueryVersionsForPackage(packageId.Id, context.WordToComplete, allowPrerelease, ProcessLifecycle.CancellationToken) + .GetAwaiter() + .GetResult() .Select(version => new CompletionItem(version.ToNormalizedString())); } else @@ -65,7 +70,7 @@ internal static void ConfigureAddCommand(PackageAddCommandDefinitionBase def) } }); - def.SetAction(parseResult => new PackageAddCommand(parseResult).Execute()); + def.SetAction((parseResult, cancellationToken) => new PackageAddCommand(parseResult).Execute(cancellationToken)); } private static async Task> QueryNuGet(string packageStem, bool allowPrerelease, CancellationToken cancellationToken) @@ -76,7 +81,7 @@ private static async Task> QueryNuGet(string packageStem, bo var versions = await downloader.GetPackageIdsAsync(packageStem, allowPrerelease, cancellationToken: cancellationToken); return versions; } - catch (Exception) + catch (Exception ex) when (ex is not OperationCanceledException) { return []; } @@ -90,7 +95,7 @@ private static async Task> QueryVersionsForPackage(str var versions = await downloader.GetPackageVersionsAsync(new(packageId), versionFragment, allowPrerelease, cancellationToken: cancellationToken); return versions; } - catch (Exception) + catch (Exception ex) when (ex is not OperationCanceledException) { return []; } diff --git a/src/Cli/dotnet/Commands/Package/Remove/PackageRemoveCommand.cs b/src/Cli/dotnet/Commands/Package/Remove/PackageRemoveCommand.cs index 8c1901d13d06..53e145e2f072 100644 --- a/src/Cli/dotnet/Commands/Package/Remove/PackageRemoveCommand.cs +++ b/src/Cli/dotnet/Commands/Package/Remove/PackageRemoveCommand.cs @@ -15,7 +15,7 @@ internal sealed class PackageRemoveCommand(ParseResult parseResult) : CommandBas { private readonly PackageRemoveCommandDefinitionBase _definition = (PackageRemoveCommandDefinitionBase)parseResult.CommandResult.Command; - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { var arguments = _parseResult.GetValue(_definition.CmdPackageArgument) ?? []; @@ -50,7 +50,7 @@ public override int Execute() projectFilePath = Path.GetFullPath(projectFilePath); } - var result = NuGetCommand.Run(TransformArgs(packageToRemove, projectFilePath), isFileBasedApp); + var result = NuGetCommand.Run(TransformArgs(packageToRemove, projectFilePath), cancellationToken, isFileBasedApp); return result; } diff --git a/src/Cli/dotnet/Commands/Package/Search/PackageSearchCommand.cs b/src/Cli/dotnet/Commands/Package/Search/PackageSearchCommand.cs index bedb88c51c1e..eaa2c5989da9 100644 --- a/src/Cli/dotnet/Commands/Package/Search/PackageSearchCommand.cs +++ b/src/Cli/dotnet/Commands/Package/Search/PackageSearchCommand.cs @@ -10,7 +10,7 @@ namespace Microsoft.DotNet.Cli.Commands.Package.Search; internal sealed class PackageSearchCommand(ParseResult parseResult) : CommandBase(parseResult) { - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { var args = new List { @@ -25,6 +25,6 @@ public override int Execute() } args.AddRange(_parseResult.OptionValuesToBeForwarded(Definition)); - return NuGetCommand.Run([.. args]); + return NuGetCommand.Run([.. args], cancellationToken); } } diff --git a/src/Cli/dotnet/Commands/Project/Convert/ProjectConvertCommand.cs b/src/Cli/dotnet/Commands/Project/Convert/ProjectConvertCommand.cs index 95530742f329..8871903bda9c 100644 --- a/src/Cli/dotnet/Commands/Project/Convert/ProjectConvertCommand.cs +++ b/src/Cli/dotnet/Commands/Project/Convert/ProjectConvertCommand.cs @@ -36,10 +36,12 @@ public ProjectConvertCommand(ParseResult parseResult) _interactive = parseResult.GetValue(Definition.InteractiveOption); } - public override int Execute() => ExecuteAsync().AsTask().GetAwaiter().GetResult(); + public override int Execute(CancellationToken cancellationToken) => ExecuteAsync(cancellationToken).AsTask().GetAwaiter().GetResult(); - public async ValueTask ExecuteAsync() + public async ValueTask ExecuteAsync(CancellationToken cancellationToken) { + cancellationToken.ThrowIfCancellationRequested(); + // Check the entry point file path. string file = Path.GetFullPath(_file); if (!VirtualProjectBuilder.IsValidEntryPointPath(file)) diff --git a/src/Cli/dotnet/Commands/Project/ProjectCommandParser.cs b/src/Cli/dotnet/Commands/Project/ProjectCommandParser.cs index b4ba64b24b27..eb0067bc6391 100644 --- a/src/Cli/dotnet/Commands/Project/ProjectCommandParser.cs +++ b/src/Cli/dotnet/Commands/Project/ProjectCommandParser.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; +using Microsoft.DotNet.Cli.CommandLine; using Microsoft.DotNet.Cli.Commands.Project.Convert; using Microsoft.DotNet.Cli.Extensions; @@ -13,6 +14,6 @@ internal sealed class ProjectCommandParser public static void ConfigureCommand(ProjectCommandDefinition command) { command.SetAction(parseResult => parseResult.HandleMissingCommand()); - command.ConvertCommand.SetAction(parseResult => new ProjectConvertCommand(parseResult).Execute()); + command.ConvertCommand.SetAction((parseResult, cancellationToken) => new ProjectConvertCommand(parseResult).Execute(cancellationToken)); } } diff --git a/src/Cli/dotnet/Commands/Publish/PublishCommand.cs b/src/Cli/dotnet/Commands/Publish/PublishCommand.cs index 0dc35f71eab9..0c60202e0cbc 100644 --- a/src/Cli/dotnet/Commands/Publish/PublishCommand.cs +++ b/src/Cli/dotnet/Commands/Publish/PublishCommand.cs @@ -22,13 +22,19 @@ private PublishCommand( { } - public static CommandBase FromArgs(string[] args, string? msbuildPath = null) + public static CommandBase FromArgs( + string[] args, + CancellationToken cancellationToken, + string? msbuildPath = null) { var parseResult = Parser.Parse(["dotnet", "publish", .. args]); - return FromParseResult(parseResult); + return FromParseResult(parseResult, cancellationToken, msbuildPath); } - public static CommandBase FromParseResult(ParseResult parseResult, string? msbuildPath = null) + public static CommandBase FromParseResult( + ParseResult parseResult, + CancellationToken cancellationToken, + string? msbuildPath = null) { var definition = (PublishCommandDefinition)parseResult.CommandResult.Command; @@ -75,17 +81,21 @@ public static CommandBase FromParseResult(ParseResult parseResult, string? msbui parseResult.HasOption(definition.ConfigurationOption) ? parseResult.GetValue(definition.ConfigurationOption) : null, parseResult.HasOption(definition.FrameworkOption) ? parseResult.GetValue(definition.FrameworkOption) : null ); - var projectLocator = new ReleasePropertyProjectLocator(msbuildArgs.GlobalProperties, MSBuildPropertyNames.PUBLISH_RELEASE, options); + var projectLocator = new ReleasePropertyProjectLocator( + msbuildArgs.GlobalProperties, + MSBuildPropertyNames.PUBLISH_RELEASE, + options, + cancellationToken); var releaseModeProperties = projectLocator.GetCustomDefaultConfigurationValueIfSpecified(); return msbuildArgs.CloneWithAdditionalProperties(releaseModeProperties); } ); } - public static int Run(ParseResult parseResult) + public static int Run(ParseResult parseResult, CancellationToken cancellationToken) { parseResult.HandleDebugSwitch(); - return FromParseResult(parseResult).Execute(); + return FromParseResult(parseResult, cancellationToken).Execute(cancellationToken); } } diff --git a/src/Cli/dotnet/Commands/Reference/Add/ReferenceAddCommand.cs b/src/Cli/dotnet/Commands/Reference/Add/ReferenceAddCommand.cs index 129d29663aeb..6cb9d70c9eba 100644 --- a/src/Cli/dotnet/Commands/Reference/Add/ReferenceAddCommand.cs +++ b/src/Cli/dotnet/Commands/Reference/Add/ReferenceAddCommand.cs @@ -28,7 +28,7 @@ public ReferenceAddCommand(ParseResult parseResult) parseResult); } - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { using var projects = new ProjectCollection(); bool interactive = _parseResult.GetValue(Definition.InteractiveOption); diff --git a/src/Cli/dotnet/Commands/Reference/List/ReferenceListCommand.cs b/src/Cli/dotnet/Commands/Reference/List/ReferenceListCommand.cs index 3988eb7314d1..0c0735bb8c2b 100644 --- a/src/Cli/dotnet/Commands/Reference/List/ReferenceListCommand.cs +++ b/src/Cli/dotnet/Commands/Reference/List/ReferenceListCommand.cs @@ -30,7 +30,7 @@ public ReferenceListCommand(ParseResult parseResult) parseResult); } - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { if (_allowedAppKinds.HasFlag(AppKinds.FileBased) && VirtualProjectBuilder.IsValidEntryPointPath(_fileOrDirectory)) { diff --git a/src/Cli/dotnet/Commands/Reference/ReferenceCommandParser.cs b/src/Cli/dotnet/Commands/Reference/ReferenceCommandParser.cs index eccd1f478e17..7b3c858f4f09 100644 --- a/src/Cli/dotnet/Commands/Reference/ReferenceCommandParser.cs +++ b/src/Cli/dotnet/Commands/Reference/ReferenceCommandParser.cs @@ -17,15 +17,15 @@ public static void ConfigureCommand(ReferenceCommandDefinition command) { command.SetAction(parseResult => parseResult.HandleMissingCommand()); - command.AddCommand.SetAction(parseResult => new ReferenceAddCommand(parseResult).Execute()); + command.AddCommand.SetAction((parseResult, cancellationToken) => new ReferenceAddCommand(parseResult).Execute(cancellationToken)); command.AddCommand.FrameworkOption.AddCompletions(CliCompletion.TargetFrameworksFromProjectFile); - command.ListCommand.SetAction(parseResult => new ReferenceListCommand(parseResult).Execute()); + command.ListCommand.SetAction((parseResult, cancellationToken) => new ReferenceListCommand(parseResult).Execute(cancellationToken)); var projectPathArgument = command.RemoveCommand.ProjectPathArgument; projectPathArgument.CompletionSources.Add(CliCompletion.ProjectReferencesFromProjectFile); projectPathArgument.IsDynamic = true; - command.RemoveCommand.SetAction(parseResult => new ReferenceRemoveCommand(parseResult).Execute()); + command.RemoveCommand.SetAction((parseResult, cancellationToken) => new ReferenceRemoveCommand(parseResult).Execute(cancellationToken)); } } diff --git a/src/Cli/dotnet/Commands/Reference/Remove/ReferenceRemoveCommand.cs b/src/Cli/dotnet/Commands/Reference/Remove/ReferenceRemoveCommand.cs index c4fa44b06551..d550238c8321 100644 --- a/src/Cli/dotnet/Commands/Reference/Remove/ReferenceRemoveCommand.cs +++ b/src/Cli/dotnet/Commands/Reference/Remove/ReferenceRemoveCommand.cs @@ -34,7 +34,7 @@ public ReferenceRemoveCommand(ParseResult parseResult) } } - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { if (_allowedAppKinds.HasFlag(AppKinds.FileBased) && VirtualProjectBuilder.IsValidEntryPointPath(_fileOrDirectory)) { diff --git a/src/Cli/dotnet/Commands/Restore/RestoreCommand.cs b/src/Cli/dotnet/Commands/Restore/RestoreCommand.cs index 8f2e96fb3f91..5fad4338b62d 100644 --- a/src/Cli/dotnet/Commands/Restore/RestoreCommand.cs +++ b/src/Cli/dotnet/Commands/Restore/RestoreCommand.cs @@ -62,17 +62,17 @@ public static MSBuildForwardingApp CreateForwarding(MSBuildArgs msbuildArgs, str return forwardingApp; } - public static int Run(string[] args) + public static int Run(string[] args, CancellationToken cancellationToken) { DebugHelper.HandleDebugSwitch(ref args); - return FromArgs(args).Execute(); + return FromArgs(args).Execute(cancellationToken); } - public static int Run(ParseResult parseResult) + public static int Run(ParseResult parseResult, CancellationToken cancellationToken) { parseResult.HandleDebugSwitch(); - return FromParseResult(parseResult).Execute(); + return FromParseResult(parseResult).Execute(cancellationToken); } } diff --git a/src/Cli/dotnet/Commands/Restore/RestoringCommand.cs b/src/Cli/dotnet/Commands/Restore/RestoringCommand.cs index eb69124622ed..8527f629150d 100644 --- a/src/Cli/dotnet/Commands/Restore/RestoringCommand.cs +++ b/src/Cli/dotnet/Commands/Restore/RestoringCommand.cs @@ -31,6 +31,8 @@ public class RestoringCommand : MSBuildForwardingApp public MSBuildForwardingApp? SeparateRestoreCommand { get; } private readonly bool AdvertiseWorkloadUpdates; + private readonly string _userProfileDir; + private readonly string _workingDirectory; public RestoringCommand( MSBuildArgs msbuildArgs, @@ -51,8 +53,8 @@ internal RestoringCommand( string workingDirectory) : base(GetCommandArguments(msbuildArgs, noRestore), msbuildPath) { - userProfileDir = CliFolderPathCalculator.DotnetUserProfileFolderPath; - Task.Run(() => WorkloadManifestUpdater.BackgroundUpdateAdvertisingManifestsAsync(userProfileDir, workingDirectory)); + _userProfileDir = userProfileDir ?? CliFolderPathCalculator.DotnetUserProfileFolderPath; + _workingDirectory = workingDirectory; SdkVulnerabilityNotifier.BackgroundUpdateCacheIfNeeded(); SeparateRestoreCommand = GetSeparateRestoreCommand(msbuildArgs, noRestore, msbuildPath); AdvertiseWorkloadUpdates = advertiseWorkloadUpdates ?? msbuildArgs.OtherMSBuildArgs.All(arg => FlagsThatTriggerSilentRestore.All(f => !arg.Contains(f, StringComparison.OrdinalIgnoreCase))); @@ -238,18 +240,22 @@ private static bool IsExcludedFromSeparateRestore(string argument) private static bool TriggersSilentSeparateRestore(string argument) => FlagsThatTriggerSilentSeparateRestore.Any(p => argument.StartsWith(p, StringComparison.OrdinalIgnoreCase)); - public override int Execute() => Execute(workingDirectory: null); + public override int Execute(CancellationToken cancellationToken) => Execute(workingDirectory: null, cancellationToken); - internal override int ExecuteOutOfProc(string workingDirectory) => Execute(workingDirectory); + internal override int ExecuteOutOfProc(string workingDirectory, CancellationToken cancellationToken) => Execute(workingDirectory, cancellationToken); - private int Execute(string? workingDirectory) + private int Execute(string? workingDirectory, CancellationToken cancellationToken) { + _ = Task.Run( + () => WorkloadManifestUpdater.BackgroundUpdateAdvertisingManifestsAsync(_userProfileDir, _workingDirectory, cancellationToken), + cancellationToken); + int exitCode; if (SeparateRestoreCommand != null) { exitCode = workingDirectory is null - ? SeparateRestoreCommand.Execute() - : SeparateRestoreCommand.ExecuteOutOfProc(workingDirectory); + ? SeparateRestoreCommand.Execute(cancellationToken) + : SeparateRestoreCommand.ExecuteOutOfProc(workingDirectory, cancellationToken); if (exitCode != 0) { return exitCode; @@ -257,8 +263,8 @@ private int Execute(string? workingDirectory) } exitCode = workingDirectory is null - ? base.Execute() - : base.ExecuteOutOfProc(workingDirectory); + ? base.Execute(cancellationToken) + : base.ExecuteOutOfProc(workingDirectory, cancellationToken); if (AdvertiseWorkloadUpdates) { WorkloadManifestUpdater.AdvertiseWorkloadUpdates(); diff --git a/src/Cli/dotnet/Commands/Run/AotRunCommand.cs b/src/Cli/dotnet/Commands/Run/AotRunCommand.cs index a317dd7be817..60849a602c74 100644 --- a/src/Cli/dotnet/Commands/Run/AotRunCommand.cs +++ b/src/Cli/dotnet/Commands/Run/AotRunCommand.cs @@ -27,21 +27,23 @@ internal static class AotRunCommand /// /// The shared run command definition. internal static void ConfigureCommand(RunCommandDefinition command) - => command.SetAction(parseResult => Execute(parseResult, Launch)); + => command.SetAction((parseResult, cancellationToken) => Execute(parseResult, cancellationToken)); /// /// Executes an eligible file-based application through the Native AOT launcher. /// /// The parsed run invocation. + /// Token observed while launching the invocation. /// The launched process exit code. - internal static int Execute(ParseResult parseResult) - => Execute(parseResult, Launch); + internal static int Execute(ParseResult parseResult, CancellationToken cancellationToken) + => Execute(parseResult, invocation => Launch(invocation, cancellationToken), cancellationToken); /// /// Plans and executes an eligible file-based application using an injected launcher. /// /// The parsed run invocation. /// Launches the committed invocation. + /// Token observed while launching the invocation. /// The current directory used for discovery and relative paths. /// The launcher exit code. /// The invocation cannot be handled safely by the Native AOT path. @@ -49,8 +51,10 @@ internal static int Execute(ParseResult parseResult) internal static int Execute( ParseResult parseResult, Func launch, + CancellationToken cancellationToken, string? currentDirectory = null) { + cancellationToken.ThrowIfCancellationRequested(); currentDirectory ??= Environment.CurrentDirectory; var definition = (RunCommandDefinition)parseResult.CommandResult.Command; if (!TryGetEligibleInvocationInputs( @@ -193,12 +197,14 @@ internal static int Execute( FileBasedAppRunPlan.MarkArtifactsPathUsed(artifactsPath); } + cancellationToken.ThrowIfCancellationRequested(); int exitCode = launch(new AotRunInvocation( command, commandArguments, launchEnvironment, workingDirectory, artifactsPath)); + cancellationToken.ThrowIfCancellationRequested(); return exitCode; } @@ -228,7 +234,7 @@ private static void EnsureLaunchProfileDoesNotRequireMSBuild( } } - private static int Launch(AotRunInvocation invocation) + private static int Launch(AotRunInvocation invocation, CancellationToken cancellationToken) { var commandSpec = new CommandSpec( invocation.Command, @@ -244,7 +250,7 @@ private static int Launch(AotRunInvocation invocation) Console.CancelKeyPress += cancelHandler; try { - return command.Execute().ExitCode; + return command.Execute(cancellationToken).ExitCode; } finally { diff --git a/src/Cli/dotnet/Commands/Run/Api/RunApiCommand.cs b/src/Cli/dotnet/Commands/Run/Api/RunApiCommand.cs index 4cfd783a4fe0..8d95026a0aea 100644 --- a/src/Cli/dotnet/Commands/Run/Api/RunApiCommand.cs +++ b/src/Cli/dotnet/Commands/Run/Api/RunApiCommand.cs @@ -20,26 +20,43 @@ namespace Microsoft.DotNet.Cli.Commands.Run.Api; [RequiresDynamicCode("Uses MSBuild Object Model types, which are not AOT-safe")] internal sealed class RunApiCommand(ParseResult parseResult) : CommandBase(parseResult) { - public override int Execute() + public override int Execute(CancellationToken cancellationToken) => + ExecuteAsync(cancellationToken).GetAwaiter().GetResult(); + + internal async Task ExecuteAsync(CancellationToken cancellationToken) { - for (string? line; (line = Console.ReadLine()) != null;) + try { - if (string.IsNullOrWhiteSpace(line)) - { - continue; - } - - try + using var inputHandle = Console.OpenStandardInputHandle(); + using Stream inputStream = inputHandle.IsInvalid ? Stream.Null : new FileStream(inputHandle, FileAccess.Read); + using var inputReader = new StreamReader(inputStream, Console.InputEncoding, detectEncodingFromByteOrderMarks: false); + // Unix FileStream cancellation cannot interrupt a read already blocked in the OS. + for (string? line; (line = await inputReader.ReadLineAsync(cancellationToken).AsTask() + .WaitAsync(cancellationToken).ConfigureAwait(false)) != null;) { - RunApiInput input = JsonSerializer.Deserialize(line, RunFileApiJsonSerializerContext.Default.RunApiInput)!; - RunApiOutput output = input.Execute(); - Respond(output); - } - catch (Exception ex) - { - Respond(new RunApiOutput.Error { Message = ex.Message, Details = ex.ToString() }); + if (string.IsNullOrWhiteSpace(line)) + { + continue; + } + + try + { + RunApiInput input = JsonSerializer.Deserialize(line, RunFileApiJsonSerializerContext.Default.RunApiInput)!; + RunApiOutput output = input.Execute(); + Respond(output); + } + catch (Exception ex) + { + Respond(new RunApiOutput.Error { Message = ex.Message, Details = ex.ToString() }); + } } } + catch (OperationCanceledException) when ( + cancellationToken.IsCancellationRequested && + !ProcessLifecycle.IsSignalTerminationRequested) + { + // A standalone caller cancelled the stdin read; exit the loop gracefully. + } return 0; diff --git a/src/Cli/dotnet/Commands/Run/Api/RunApiCommandParser.cs b/src/Cli/dotnet/Commands/Run/Api/RunApiCommandParser.cs index 2c4225bea076..7f9d43248b73 100644 --- a/src/Cli/dotnet/Commands/Run/Api/RunApiCommandParser.cs +++ b/src/Cli/dotnet/Commands/Run/Api/RunApiCommandParser.cs @@ -3,6 +3,7 @@ using System.CommandLine; using System.Diagnostics.CodeAnalysis; +using Microsoft.DotNet.Cli.CommandLine; namespace Microsoft.DotNet.Cli.Commands.Run.Api; @@ -11,6 +12,6 @@ internal sealed class RunApiCommandParser [RequiresDynamicCode("Uses MSBuild Object Model types, which are not AOT-safe")] public static void ConfigureCommand(RunApiCommandDefinition command) { - command.SetAction(parseResult => new RunApiCommand(parseResult).Execute()); + command.SetAction((parseResult, cancellationToken) => new RunApiCommand(parseResult).Execute(cancellationToken)); } } diff --git a/src/Cli/dotnet/Commands/Run/CSharpCompilerCommand.cs b/src/Cli/dotnet/Commands/Run/CSharpCompilerCommand.cs index 168a5ddbfb7e..272d647179ac 100644 --- a/src/Cli/dotnet/Commands/Run/CSharpCompilerCommand.cs +++ b/src/Cli/dotnet/Commands/Run/CSharpCompilerCommand.cs @@ -77,8 +77,10 @@ private partial class CSharpCompilerCommandJsonSerializerContext : JsonSerialize /// /// Whether the returned error code should not cause the build to fail but instead fallback to full MSBuild. /// - public int Execute(out bool fallbackToNormalBuild) + public int Execute(CancellationToken cancellationToken, out bool fallbackToNormalBuild) { + cancellationToken.ThrowIfCancellationRequested(); + // Write .rsp file and other intermediate build outputs. PrepareAuxiliaryFiles(out string rspPath); @@ -120,12 +122,13 @@ public int Execute(out bool fallbackToNormalBuild) clientDirectory: ClientDirectory, buildEnvironment: StandardBuildEnvironment.Instance, logger, - cancellationToken: default); + cancellationToken); // Process the response. - var exitCode = ProcessBuildResponse(responseTask.Result, out fallbackToNormalBuild); + var exitCode = ProcessBuildResponse(responseTask.GetAwaiter().GetResult(), out fallbackToNormalBuild); // Copy from obj to bin only if the build succeeded. + cancellationToken.ThrowIfCancellationRequested(); if (exitCode == 0 && BuildResultFile != null && CSharpCommandLineParser.Default.Parse(CscArguments, BaseDirectory, sdkDirectory: null) is { OutputFileName: { } outputFileName } parsedArgs) diff --git a/src/Cli/dotnet/Commands/Run/RunCommand.cs b/src/Cli/dotnet/Commands/Run/RunCommand.cs index 392a7cf906fd..1f1f756578e0 100644 --- a/src/Cli/dotnet/Commands/Run/RunCommand.cs +++ b/src/Cli/dotnet/Commands/Run/RunCommand.cs @@ -141,7 +141,7 @@ public RunCommand( EnvironmentVariables = environmentVariables; } - public int Execute() + public int Execute(CancellationToken cancellationToken) { // Create a single logger for all MSBuild operations (device selection + build/run) // File-based runs (.cs files) don't support device selection and should use the existing logger behavior @@ -198,7 +198,8 @@ public int Execute() out projectBuilder, selector?.IntermediateOutputPath, selector?.HasRuntimeEnvironmentVariableSupport ?? false, - requiresProjectExpansion); + requiresProjectExpansion, + cancellationToken); runPropertiesFromEvaluation = projectBuilder?.LastBuild.Level == BuildLevel.All; } else if (EntryPointFileFullPath is not null && launchProfileParseResult.Profile is not ExecutableLaunchProfile) @@ -245,7 +246,7 @@ public int Execute() // Ignore Ctrl-C for the remainder of the command's execution Console.CancelKeyPress += (sender, e) => { e.Cancel = true; }; - return targetCommand.Execute().ExitCode; + return targetCommand.Execute(cancellationToken).ExitCode; } catch (InvalidProjectFileException e) { @@ -518,13 +519,14 @@ private void EnsureProjectIsBuilt( out VirtualProjectBuildingCommand? projectBuilder, string? intermediateOutputPath, bool hasRuntimeEnvironmentVariableSupport, - bool requiresProjectExpansion) + bool requiresProjectExpansion, + CancellationToken cancellationToken) { int buildResult; if (EntryPointFileFullPath is not null) { projectBuilder = CreateProjectBuilder(); - buildResult = projectBuilder.Execute(); + buildResult = projectBuilder.Execute(cancellationToken); projectFactory = requiresProjectExpansion || !CanUseRunPropertiesForCscBuiltProgram(projectBuilder.LastBuild.Level, projectBuilder.LastBuild.Cache?.PreviousEntry) ? projectBuilder.CreateProjectInstance : null; @@ -552,7 +554,7 @@ private void EnsureProjectIsBuilt( buildArgs, NoRestore || _restoreDoneForDeviceSelection, advertiseWorkloadUpdates: false - ).Execute(); + ).Execute(cancellationToken); } finally { @@ -1075,11 +1077,11 @@ bool UsingRunCommandShorthandProjectOption(ParseResult parseResult) } } - public static int Run(ParseResult parseResult) + public static int Run(ParseResult parseResult, CancellationToken cancellationToken) { parseResult.HandleDebugSwitch(); - return FromParseResult(parseResult).Execute(); + return FromParseResult(parseResult).Execute(cancellationToken); } public static ParseResult ModifyParseResultForShorthandProjectOption(ParseResult parseResult) diff --git a/src/Cli/dotnet/Commands/Run/VirtualProjectBuildingCommand.cs b/src/Cli/dotnet/Commands/Run/VirtualProjectBuildingCommand.cs index ae43fca9600a..b3c4d5348c06 100644 --- a/src/Cli/dotnet/Commands/Run/VirtualProjectBuildingCommand.cs +++ b/src/Cli/dotnet/Commands/Run/VirtualProjectBuildingCommand.cs @@ -13,6 +13,7 @@ using Microsoft.Build.Logging.SimpleErrorLogger; using Microsoft.CodeAnalysis; using Microsoft.DotNet.Cli.Commands.Clean.FileBasedAppArtifacts; +using Microsoft.DotNet.Cli.Commands.MSBuild; using Microsoft.DotNet.Cli.Commands.Restore; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.Cli.Utils.Extensions; @@ -106,8 +107,10 @@ public VirtualProjectBuildingCommand( #if !CLI_AOT [UnconditionalSuppressMessage("AOT", "IL2026", Justification = "Temporary unblock for dotnet/msbuild#14064 (MSBuild build APIs are now [RequiresUnreferencedCode]). dotnet CLI runs MSBuild in-proc (not trimmed). Remove when dotnet/sdk#55225 is fixed.")] [UnconditionalSuppressMessage("AOT", "IL3050", Justification ="In non-AOT mode we have MSBuild available, so using types from it is safe.")] - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { + cancellationToken.ThrowIfCancellationRequested(); + bool msbuildGet = MSBuildArgs.GetProperty is [_, ..] || MSBuildArgs.GetItem is [_, ..] || MSBuildArgs.GetTargetResult is [_, ..]; bool evalOnly = msbuildGet && Builder.RequestedTargets is null or []; bool minimizeStdOut = msbuildGet && MSBuildArgs.GetResultOutputFile is null or []; @@ -175,7 +178,7 @@ public override int Execute() CscArguments = cache.PreviousEntry?.CscArguments ?? [], BuildResultFile = cache.PreviousEntry?.BuildResultFile, } - .Execute(out bool fallbackToNormalBuild); + .Execute(cancellationToken, out bool fallbackToNormalBuild); if (!fallbackToNormalBuild) { @@ -210,7 +213,10 @@ public override int Execute() CleanFileBasedAppArtifactsCommand.StartAutomaticCleanupIfNeeded(); } + using IDisposable softCancellationTimeout = + ProcessLifecycle.OverrideSoftCancellationTimeout(MSBuildForwardingApp.BuildSoftCancellationTimeout); IDisposable? environmentScope = null; + bool buildStarted = false; try { Dictionary additionalEnvironmentVariables = []; @@ -243,6 +249,10 @@ public override int Execute() }; BuildManager.DefaultBuildManager.BeginBuild(parameters); + buildStarted = true; + using CancellationTokenRegistration cancellationRegistration = cancellationToken.Register( + static () => BuildManager.DefaultBuildManager.CancelAllSubmissions()); + cancellationToken.ThrowIfCancellationRequested(); int exitCode = 0; ProjectInstance? projectInstance = null; @@ -254,7 +264,10 @@ public override int Execute() if (!NoRestore && !evalOnly) { var restoreRequest = new BuildRequestData( - CreateProjectInstance(projectCollection, additionalGlobalProperties: GetAdditionalRestoreGlobalProperties(MSBuildArgs.RestoreGlobalProperties)), + CreateProjectInstance( + projectCollection, + additionalGlobalProperties: GetAdditionalRestoreGlobalProperties(MSBuildArgs.RestoreGlobalProperties), + cancellationToken), targetsToBuild: ["Restore"], hostServices: null, // We don't include ClearCachesAfterBuild flag unlike MSBuild's implicit restore @@ -263,6 +276,7 @@ public override int Execute() BuildRequestDataFlags.SkipNonexistentTargets | BuildRequestDataFlags.IgnoreMissingEmptyAndInvalidImports | BuildRequestDataFlags.FailOnUnresolvedSdk); var restoreResult = BuildManager.DefaultBuildManager.BuildRequest(restoreRequest); + cancellationToken.ThrowIfCancellationRequested(); if (restoreResult.OverallResult != BuildResultCode.Success) { exitCode = 1; @@ -279,13 +293,14 @@ public override int Execute() ? requestedTargets : [Constants.Build, Constants.CoreCompile]; var buildRequest = new BuildRequestData( - CreateProjectInstance(projectCollection), + CreateProjectInstance(projectCollection, additionalGlobalProperties: null, cancellationToken), targetsToBuild: effectiveTargets, hostServices: null, // SkipNonexistentTargets: CoreCompile doesn't exist in the outer build of multi-target projects. BuildRequestDataFlags.SkipNonexistentTargets); var buildResult = BuildManager.DefaultBuildManager.BuildRequest(buildRequest); + cancellationToken.ThrowIfCancellationRequested(); if (buildResult.OverallResult != BuildResultCode.Success) { exitCode = 1; @@ -306,7 +321,7 @@ public override int Execute() CacheCscArguments(cache, buildResult); WriteCscRsp(cache); - CollectAdditionalSources(cache, buildRequest.ProjectInstance); + CollectAdditionalSources(cache, buildRequest.ProjectInstance, cancellationToken); CollectBuildOutputs(cache, buildRequest.ProjectInstance); MarkBuildSuccess(cache); @@ -320,16 +335,13 @@ public override int Execute() // Print build information. if (msbuildGet) { - projectInstance ??= CreateProjectInstance(projectCollection); - PrintBuildInformation(projectCollection, projectInstance, buildOrRestoreResult); + projectInstance ??= CreateProjectInstance(projectCollection, additionalGlobalProperties: null, cancellationToken); + PrintBuildInformation(projectCollection, projectInstance, buildOrRestoreResult, cancellationToken); } - BuildManager.DefaultBuildManager.EndBuild(); - consoleLogger = null; // avoid double disposal which would throw - return exitCode; } - catch (Exception e) + catch (Exception e) when (e is not OperationCanceledException) { Reporter.Error.WriteLine(CommandLoggingContext.IsVerbose ? e.ToString().Red().Bold() : @@ -338,6 +350,12 @@ public override int Execute() } finally { + if (buildStarted) + { + BuildManager.DefaultBuildManager.EndBuild(); + consoleLogger = null; // avoid double disposal which would throw + } + environmentScope?.Dispose(); if (binaryLogger?.IsValueCreated == true) binaryLogger.Value.ReallyShutdown(); consoleLogger?.Shutdown(); @@ -517,16 +535,20 @@ bool CanSaveCache(ProjectInstance projectInstance) } [RequiresDynamicCode("Uses MSBuild Object Model types, which are not AOT-safe")] - void CollectAdditionalSources(FileBasedAppCacheInfo cache, ProjectInstance projectInstance) + void CollectAdditionalSources(FileBasedAppCacheInfo cache, ProjectInstance projectInstance, CancellationToken cancellationToken) { Debug.Assert(cache.CurrentEntry.AdditionalSources.Count == 0); + cancellationToken.ThrowIfCancellationRequested(); var entryPointFileDirectory = Path.GetDirectoryName(Builder.EntryPointFileFullPath); Debug.Assert(entryPointFileDirectory != null); var mapping = Builder.GetItemMappingAsync(projectInstance.Wrap(), ErrorReporters.IgnoringReporter).AsTask().GetAwaiter().GetResult(); + cancellationToken.ThrowIfCancellationRequested(); foreach (var entry in mapping) { + cancellationToken.ThrowIfCancellationRequested(); + if (string.Equals(entry.ItemType, "None", StringComparison.OrdinalIgnoreCase)) { continue; @@ -545,8 +567,13 @@ void CollectAdditionalSources(FileBasedAppCacheInfo cache, ProjectInstance proje cache.CurrentEntry.AdditionalSources.Remove(RunFileBuildCacheEntry.AdditionalSource.Create(Builder.EntryPointFileFullPath)); } - void PrintBuildInformation(ProjectCollection projectCollection, ProjectInstance projectInstance, BuildResult? buildOrRestoreResult) + void PrintBuildInformation( + ProjectCollection projectCollection, + ProjectInstance projectInstance, + BuildResult? buildOrRestoreResult, + CancellationToken cancellationToken) { + cancellationToken.ThrowIfCancellationRequested(); var resultOutputFile = MSBuildArgs.GetResultOutputFile is [{ } file, ..] ? file : null; // If a single property is requested, don't print as JSON. @@ -577,6 +604,7 @@ void PrintBuildInformation(ProjectCollection projectCollection, ProjectInstance foreach (var propertyName in MSBuildArgs.GetProperty) { + cancellationToken.ThrowIfCancellationRequested(); writer.WriteString(propertyName, projectInstance.GetPropertyValue(propertyName)); } @@ -590,6 +618,7 @@ void PrintBuildInformation(ProjectCollection projectCollection, ProjectInstance foreach (var itemName in MSBuildArgs.GetItem) { + cancellationToken.ThrowIfCancellationRequested(); writer.WritePropertyName(itemName); writer.WriteStartArray(); @@ -626,6 +655,7 @@ void PrintBuildInformation(ProjectCollection projectCollection, ProjectInstance foreach (var targetName in MSBuildArgs.GetTargetResult) { + cancellationToken.ThrowIfCancellationRequested(); var targetResult = buildOrRestoreResult.ResultsByTarget[targetName]; writer.WritePropertyName(targetName); @@ -795,12 +825,28 @@ private void MarkBuildSuccess(FileBasedAppCacheInfo cache) [RequiresDynamicCode("Uses MSBuild Object Model types, which are not AOT-safe")] public ProjectInstance CreateProjectInstance(ProjectCollection projectCollection) { - return CreateProjectInstance(projectCollection, additionalGlobalProperties: null); + return CreateProjectInstance( + projectCollection, + additionalGlobalProperties: null, + ProcessLifecycle.CancellationToken); } [RequiresDynamicCode("Uses MSBuild Object Model types, which are not AOT-safe")] public ProjectInstance CreateProjectInstance(ProjectCollection projectCollection, IDictionary? additionalGlobalProperties = null) { + return CreateProjectInstance( + projectCollection, + additionalGlobalProperties, + ProcessLifecycle.CancellationToken); + } + + [RequiresDynamicCode("Uses MSBuild Object Model types, which are not AOT-safe")] + private ProjectInstance CreateProjectInstance( + ProjectCollection projectCollection, + IDictionary? additionalGlobalProperties, + CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); var projectCollectionWrapped = projectCollection.Wrap(); var result = Builder.CreateProjectInstanceAsync( @@ -808,6 +854,7 @@ public ProjectInstance CreateProjectInstance(ProjectCollection projectCollection ThrowingReporter, Directives, additionalGlobalProperties).AsTask().GetAwaiter().GetResult(); + cancellationToken.ThrowIfCancellationRequested(); EvaluatedDirectives = result.EvaluatedDirectives; diff --git a/src/Cli/dotnet/Commands/Sdk/Check/BundleOutputWriter.cs b/src/Cli/dotnet/Commands/Sdk/Check/BundleOutputWriter.cs index ef6afb5592ec..2d6a64042893 100644 --- a/src/Cli/dotnet/Commands/Sdk/Check/BundleOutputWriter.cs +++ b/src/Cli/dotnet/Commands/Sdk/Check/BundleOutputWriter.cs @@ -12,7 +12,8 @@ namespace Microsoft.DotNet.Cli.Commands.Sdk.Check; internal class BundleOutputWriter( ProductCollection productCollection, IProductCollectionProvider productCollectionProvider, - IReporter reporter) + IReporter reporter, + CancellationToken cancellationToken) { protected ProductCollection _productCollection = productCollection; @@ -20,6 +21,8 @@ internal class BundleOutputWriter( protected readonly IReporter _reporter = reporter; + protected readonly CancellationToken _cancellationToken = cancellationToken; + protected bool? BundleIsMaintenance(INetBundleInfo bundle) { return _productCollection diff --git a/src/Cli/dotnet/Commands/Sdk/Check/IProductCollectionProvider.cs b/src/Cli/dotnet/Commands/Sdk/Check/IProductCollectionProvider.cs index 2effbab2e20e..a58baba3a675 100644 --- a/src/Cli/dotnet/Commands/Sdk/Check/IProductCollectionProvider.cs +++ b/src/Cli/dotnet/Commands/Sdk/Check/IProductCollectionProvider.cs @@ -9,7 +9,7 @@ namespace Microsoft.DotNet.Cli.Commands.Sdk.Check; public interface IProductCollectionProvider { - ProductCollection GetProductCollection(Uri uri = null, string filePath = null); + ProductCollection GetProductCollection(CancellationToken cancellationToken, Uri uri = null, string filePath = null); - IEnumerable GetProductReleases(Product product); + IEnumerable GetProductReleases(Product product, CancellationToken cancellationToken); } diff --git a/src/Cli/dotnet/Commands/Sdk/Check/ProductCollectionProvider.cs b/src/Cli/dotnet/Commands/Sdk/Check/ProductCollectionProvider.cs index 0c3ff39c8940..b44cba0618a6 100644 --- a/src/Cli/dotnet/Commands/Sdk/Check/ProductCollectionProvider.cs +++ b/src/Cli/dotnet/Commands/Sdk/Check/ProductCollectionProvider.cs @@ -10,31 +10,41 @@ namespace Microsoft.DotNet.Cli.Commands.Sdk.Check; public class ProductCollectionProvider : IProductCollectionProvider { - public ProductCollection GetProductCollection(Uri uri = null, string filePath = null) + public ProductCollection GetProductCollection( + CancellationToken cancellationToken, + Uri uri = null, + string filePath = null) { try { - return uri != null ? Task.Run(() => ProductCollection.GetAsync(uri.ToString())).Result : - filePath != null ? Task.Run(() => ProductCollection.GetFromFileAsync(filePath, false)).Result : - Task.Run(() => ProductCollection.GetAsync()).Result; + cancellationToken.ThrowIfCancellationRequested(); + Task productCollection = uri != null + ? ProductCollection.GetAsync(uri.ToString()) + : filePath != null + ? ProductCollection.GetFromFileAsync(filePath, false) + : ProductCollection.GetAsync(); + + return productCollection.WaitAsync(cancellationToken).GetAwaiter().GetResult(); } - catch (Exception e) + catch (Exception e) when (e is not OperationCanceledException) { throw new GracefulException(string.Format(CliCommandStrings.ReleasesLibraryFailed, e.Message)); } } - public IEnumerable GetProductReleases(Deployment.DotNet.Releases.Product product) + public IEnumerable GetProductReleases( + Deployment.DotNet.Releases.Product product, + CancellationToken cancellationToken) { try { - return product.GetReleasesAsync().Result; + cancellationToken.ThrowIfCancellationRequested(); + return product.GetReleasesAsync() + .WaitAsync(cancellationToken) + .GetAwaiter() + .GetResult(); } - catch (Exception ex) when (ex is HttpRequestException || - ex is FileNotFoundException || - ex is AggregateException aggregateEx && - (aggregateEx.InnerException is HttpRequestException || - aggregateEx.InnerException is FileNotFoundException)) + catch (Exception ex) when (ex is HttpRequestException || ex is FileNotFoundException) { // Return empty collection if releases are not available (e.g., unreleased preview versions) // This handles cases where the releases.json file doesn't exist yet for a version diff --git a/src/Cli/dotnet/Commands/Sdk/Check/RuntimeOutputWriter.cs b/src/Cli/dotnet/Commands/Sdk/Check/RuntimeOutputWriter.cs index 0746c9ada5e1..327e0901dee7 100644 --- a/src/Cli/dotnet/Commands/Sdk/Check/RuntimeOutputWriter.cs +++ b/src/Cli/dotnet/Commands/Sdk/Check/RuntimeOutputWriter.cs @@ -11,7 +11,8 @@ internal class RuntimeOutputWriter( IEnumerable runtimeInfo, ProductCollection productCollection, IProductCollectionProvider productCollectionProvider, - IReporter reporter) : BundleOutputWriter(productCollection, productCollectionProvider, reporter) + IReporter reporter, + CancellationToken cancellationToken) : BundleOutputWriter(productCollection, productCollectionProvider, reporter, cancellationToken) { private readonly IEnumerable _runtimeInfo = runtimeInfo; diff --git a/src/Cli/dotnet/Commands/Sdk/Check/SdkCheckCommand.cs b/src/Cli/dotnet/Commands/Sdk/Check/SdkCheckCommand.cs index 695f77b61ebc..a9b2ec8d0910 100644 --- a/src/Cli/dotnet/Commands/Sdk/Check/SdkCheckCommand.cs +++ b/src/Cli/dotnet/Commands/Sdk/Check/SdkCheckCommand.cs @@ -38,7 +38,7 @@ public SdkCheckCommand( _productCollectionProvider = productCollectionProvider == null ? new ProductCollectionProvider() : productCollectionProvider; } - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { if (_sdkCheckConfig != null && !string.IsNullOrEmpty(_sdkCheckConfig.CommandOutputReplacementString)) { @@ -48,14 +48,16 @@ public override int Execute() } else { + cancellationToken.ThrowIfCancellationRequested(); try { var productCollection = _productCollectionProvider.GetProductCollection( + cancellationToken, _sdkCheckConfig?.ReleasesUri == null ? null : new Uri(_sdkCheckConfig.ReleasesUri), _sdkCheckConfig?.ReleasesFilePath == null ? null : _sdkCheckConfig.ReleasesFilePath); var environmentInfo = _netBundleProvider.GetDotnetEnvironmentInfo(_dotnetPath); - var sdkFormatter = new SdkOutputWriter(environmentInfo.SdkInfo, productCollection, _productCollectionProvider, _reporter); - var runtimeFormatter = new RuntimeOutputWriter(environmentInfo.RuntimeInfo, productCollection, _productCollectionProvider, _reporter); + var sdkFormatter = new SdkOutputWriter(environmentInfo.SdkInfo, productCollection, _productCollectionProvider, _reporter, cancellationToken); + var runtimeFormatter = new RuntimeOutputWriter(environmentInfo.RuntimeInfo, productCollection, _productCollectionProvider, _reporter, cancellationToken); sdkFormatter.PrintSdkInfo(); _reporter.WriteLine(); @@ -80,12 +82,12 @@ public override int Execute() return 0; } - public static int Run(ParseResult parseResult) + public static int Run(ParseResult parseResult, CancellationToken cancellationToken) { #if CLI_AOT - return new SdkCheckCommand(parseResult, dotnetRoot: NativeEntryPoint.DotnetRoot).Execute(); + return new SdkCheckCommand(parseResult, dotnetRoot: NativeEntryPoint.DotnetRoot).Execute(cancellationToken); #else - return new SdkCheckCommand(parseResult).Execute(); + return new SdkCheckCommand(parseResult).Execute(cancellationToken); #endif } } diff --git a/src/Cli/dotnet/Commands/Sdk/Check/SdkOutputWriter.cs b/src/Cli/dotnet/Commands/Sdk/Check/SdkOutputWriter.cs index 0ee9e8b5d225..dfb42409bae0 100644 --- a/src/Cli/dotnet/Commands/Sdk/Check/SdkOutputWriter.cs +++ b/src/Cli/dotnet/Commands/Sdk/Check/SdkOutputWriter.cs @@ -11,7 +11,8 @@ internal class SdkOutputWriter( IEnumerable sdkInfo, ProductCollection productCollection, IProductCollectionProvider productCollectionProvider, - IReporter reporter) : BundleOutputWriter(productCollection, productCollectionProvider, reporter) + IReporter reporter, + CancellationToken cancellationToken) : BundleOutputWriter(productCollection, productCollectionProvider, reporter, cancellationToken) { private readonly IEnumerable _sdkInfo = sdkInfo; @@ -83,7 +84,7 @@ private bool NewerSdkPatchExists(NetSdkInfo bundle) else { // Fetch detailed product release information - var productReleases = _productCollectionProvider.GetProductReleases(product); + var productReleases = _productCollectionProvider.GetProductReleases(product, _cancellationToken); var featureBandVersions = productReleases .SelectMany(release => release.Sdks) .Select(sdk => sdk.Version) diff --git a/src/Cli/dotnet/Commands/Sdk/SdkCommandParser.cs b/src/Cli/dotnet/Commands/Sdk/SdkCommandParser.cs index 71e308437dba..f6bd8fd9aedd 100644 --- a/src/Cli/dotnet/Commands/Sdk/SdkCommandParser.cs +++ b/src/Cli/dotnet/Commands/Sdk/SdkCommandParser.cs @@ -3,6 +3,7 @@ using System.CommandLine; using Microsoft.DotNet.Cli.Commands.Sdk.Check; +using Microsoft.DotNet.Cli.CommandLine; using Microsoft.DotNet.Cli.Extensions; namespace Microsoft.DotNet.Cli.Commands.Sdk; diff --git a/src/Cli/dotnet/Commands/Solution/Add/SolutionAddCommand.cs b/src/Cli/dotnet/Commands/Solution/Add/SolutionAddCommand.cs index 9f5a17f45de1..7b7d555a1c8e 100644 --- a/src/Cli/dotnet/Commands/Solution/Add/SolutionAddCommand.cs +++ b/src/Cli/dotnet/Commands/Solution/Add/SolutionAddCommand.cs @@ -51,7 +51,7 @@ public SolutionAddCommand(ParseResult parseResult) _solutionFileFullPath = SlnFileFactory.GetSolutionFileFullPath(_fileOrDirectory, includeSolutionFilterFiles: true); } - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { if (_projects.Count == 0) { @@ -70,12 +70,12 @@ public override int Execute() // Check if we're working with a solution filter file if (_solutionFileFullPath.HasExtension(SlnfFileHelper.SlnfExtension)) { - AddProjectsToSolutionFilter(fullProjectPaths); + AddProjectsToSolutionFilter(fullProjectPaths, cancellationToken); } else { // Add projects to the solution - AddProjectsToSolutionAsync(fullProjectPaths, CancellationToken.None).GetAwaiter().GetResult(); + AddProjectsToSolutionAsync(fullProjectPaths, cancellationToken).GetAwaiter().GetResult(); } return 0; } @@ -128,7 +128,7 @@ public override int Execute() private async Task AddProjectsToSolutionAsync(IEnumerable projectPaths, CancellationToken cancellationToken) { - SolutionModel solution = SlnFileFactory.CreateFromFileOrDirectory(_solutionFileFullPath); + SolutionModel solution = SlnFileFactory.CreateFromFileOrDirectory(_solutionFileFullPath, cancellationToken); Debug.Assert(solution.SerializerExtension is not null); ISolutionSerializer serializer = solution.SerializerExtension.Serializer; @@ -280,7 +280,9 @@ static bool IsInSameFolderHierarchy(SolutionItemModel? projectParent, SolutionFo } } - private void AddProjectsToSolutionFilter(IEnumerable projectPaths) + private void AddProjectsToSolutionFilter( + IEnumerable projectPaths, + CancellationToken cancellationToken) { // Solution filter files don't support --in-root or --solution-folder options if (_inRoot || !string.IsNullOrEmpty(_solutionFolderPath)) @@ -289,11 +291,11 @@ private void AddProjectsToSolutionFilter(IEnumerable projectPaths) } // Load the filtered solution to get the parent solution path and existing projects - SolutionModel filteredSolution = SlnFileFactory.CreateFromFilteredSolutionFile(_solutionFileFullPath); + SolutionModel filteredSolution = SlnFileFactory.CreateFromFilteredSolutionFile(_solutionFileFullPath, cancellationToken); string parentSolutionPath = filteredSolution.Description!; // The parent solution path is stored in Description // Load the parent solution to validate projects exist in it - SolutionModel parentSolution = SlnFileFactory.CreateFromFileOrDirectory(parentSolutionPath); + SolutionModel parentSolution = SlnFileFactory.CreateFromFileOrDirectory(parentSolutionPath, cancellationToken); // Get existing projects in the filter (already normalized to OS separator by CreateFromFilteredSolutionFile) var existingProjects = filteredSolution.SolutionProjects.Select(p => p.FilePath).ToHashSet(); diff --git a/src/Cli/dotnet/Commands/Solution/List/SolutionListCommand.cs b/src/Cli/dotnet/Commands/Solution/List/SolutionListCommand.cs index 4026d1afa86b..0d1025ecc78e 100644 --- a/src/Cli/dotnet/Commands/Solution/List/SolutionListCommand.cs +++ b/src/Cli/dotnet/Commands/Solution/List/SolutionListCommand.cs @@ -21,23 +21,23 @@ public SolutionListCommand(ParseResult parseResult) _displaySolutionFolders = parseResult.GetValue(Definition.SolutionFolderOption); } - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { string solutionFileFullPath = SlnFileFactory.GetSolutionFileFullPath(_fileOrDirectory, includeSolutionFilterFiles: true); try { - ListAllProjectsAsync(solutionFileFullPath); + ListAllProjects(solutionFileFullPath, cancellationToken); return 0; } - catch (Exception ex) + catch (Exception ex) when (ex is not OperationCanceledException) { throw new GracefulException(CliStrings.InvalidSolutionFormatString, solutionFileFullPath, ex.Message); } } - private void ListAllProjectsAsync(string solutionFileFullPath) + private void ListAllProjects(string solutionFileFullPath, CancellationToken cancellationToken) { - SolutionModel solution = SlnFileFactory.CreateFromFileOrDirectory(solutionFileFullPath); + SolutionModel solution = SlnFileFactory.CreateFromFileOrDirectory(solutionFileFullPath, cancellationToken); string[] paths; if (_displaySolutionFolders) { diff --git a/src/Cli/dotnet/Commands/Solution/Migrate/SolutionMigrateCommand.cs b/src/Cli/dotnet/Commands/Solution/Migrate/SolutionMigrateCommand.cs index 47ef19bdf6dc..8781bb3b4b01 100644 --- a/src/Cli/dotnet/Commands/Solution/Migrate/SolutionMigrateCommand.cs +++ b/src/Cli/dotnet/Commands/Solution/Migrate/SolutionMigrateCommand.cs @@ -23,7 +23,7 @@ public SolutionMigrateCommand(ParseResult parseResult, IReporter reporter = null } - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { string slnFileFullPath = SlnFileFactory.GetSolutionFileFullPath(_slnFileOrDirectory); if (slnFileFullPath.HasExtension(".slnx")) @@ -33,10 +33,10 @@ public override int Execute() string slnxFileFullPath = Path.ChangeExtension(slnFileFullPath, "slnx"); try { - ConvertToSlnxAsync(slnFileFullPath, slnxFileFullPath, CancellationToken.None).Wait(); + ConvertToSlnxAsync(slnFileFullPath, slnxFileFullPath, cancellationToken).GetAwaiter().GetResult(); return 0; } - catch (Exception ex) + catch (Exception ex) when (ex is not OperationCanceledException) { throw new GracefulException(ex.Message, ex); } @@ -44,7 +44,7 @@ public override int Execute() private async Task ConvertToSlnxAsync(string filePath, string slnxFilePath, CancellationToken cancellationToken) { - SolutionModel solution = SlnFileFactory.CreateFromFileOrDirectory(filePath); + SolutionModel solution = SlnFileFactory.CreateFromFileOrDirectory(filePath, cancellationToken); await SolutionSerializers.SlnXml.SaveAsync(slnxFilePath, solution, cancellationToken); _reporter.WriteLine(CliCommandStrings.SlnxGenerated, slnxFilePath); } diff --git a/src/Cli/dotnet/Commands/Solution/Remove/SolutionRemoveCommand.cs b/src/Cli/dotnet/Commands/Solution/Remove/SolutionRemoveCommand.cs index 8e18861ec3ac..4d48da867b84 100644 --- a/src/Cli/dotnet/Commands/Solution/Remove/SolutionRemoveCommand.cs +++ b/src/Cli/dotnet/Commands/Solution/Remove/SolutionRemoveCommand.cs @@ -25,7 +25,7 @@ public SolutionRemoveCommand(ParseResult parseResult) SolutionArgumentValidator.ParseAndValidateArguments(_fileOrDirectory, _projects, SolutionArgumentValidator.CommandType.Remove); } - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { string solutionFileFullPath = SlnFileFactory.GetSolutionFileFullPath(_fileOrDirectory, includeSolutionFilterFiles: true); if (_projects.Count == 0) @@ -46,15 +46,15 @@ public override int Execute() // Check if we're working with a solution filter file if (solutionFileFullPath.HasExtension(SlnfFileHelper.SlnfExtension)) { - RemoveProjectsFromSolutionFilter(solutionFileFullPath, relativeProjectPaths); + RemoveProjectsFromSolutionFilter(solutionFileFullPath, relativeProjectPaths, cancellationToken); } else { - RemoveProjectsAsync(solutionFileFullPath, relativeProjectPaths, CancellationToken.None).GetAwaiter().GetResult(); + RemoveProjectsAsync(solutionFileFullPath, relativeProjectPaths, cancellationToken).GetAwaiter().GetResult(); } return 0; } - catch (Exception ex) when (ex is not GracefulException) + catch (Exception ex) when (ex is not GracefulException and not OperationCanceledException) { if (ex is SolutionException || ex.InnerException is SolutionException) { @@ -66,7 +66,7 @@ public override int Execute() private static async Task RemoveProjectsAsync(string solutionFileFullPath, IEnumerable projectPaths, CancellationToken cancellationToken) { - SolutionModel solution = SlnFileFactory.CreateFromFileOrDirectory(solutionFileFullPath); + SolutionModel solution = SlnFileFactory.CreateFromFileOrDirectory(solutionFileFullPath, cancellationToken); ISolutionSerializer serializer = solution.SerializerExtension.Serializer; // set UTF-8 BOM encoding for .sln @@ -139,10 +139,13 @@ private static async Task RemoveProjectsAsync(string solutionFileFullPath, IEnum await serializer.SaveAsync(solutionFileFullPath, solution, cancellationToken); } - private static void RemoveProjectsFromSolutionFilter(string slnfFileFullPath, IEnumerable projectPaths) + private static void RemoveProjectsFromSolutionFilter( + string slnfFileFullPath, + IEnumerable projectPaths, + CancellationToken cancellationToken) { // Load the filtered solution to get the parent solution path and existing projects - SolutionModel filteredSolution = SlnFileFactory.CreateFromFilteredSolutionFile(slnfFileFullPath); + SolutionModel filteredSolution = SlnFileFactory.CreateFromFilteredSolutionFile(slnfFileFullPath, cancellationToken); string parentSolutionPath = filteredSolution.Description!; // The parent solution path is stored in Description // Get existing projects in the filter diff --git a/src/Cli/dotnet/Commands/Solution/SolutionCommandParser.cs b/src/Cli/dotnet/Commands/Solution/SolutionCommandParser.cs index 64c9fd3b840f..782aa67aa8a3 100644 --- a/src/Cli/dotnet/Commands/Solution/SolutionCommandParser.cs +++ b/src/Cli/dotnet/Commands/Solution/SolutionCommandParser.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.CommandLine; +using Microsoft.DotNet.Cli.CommandLine; using Microsoft.DotNet.Cli.Extensions; #if !CLI_AOT using Microsoft.DotNet.Cli.Commands.Solution.Add; @@ -21,10 +22,10 @@ public static void ConfigureCommand(SolutionCommandDefinition command) // 'sln add' requires MSBuild, so it falls back to the managed CLI. command.AddCommand.SetAction((Func)(_ => throw new CommandNotAvailableInAotException())); #else - command.AddCommand.SetAction(parseResult => new SolutionAddCommand(parseResult).Execute()); + command.AddCommand.SetAction((parseResult, cancellationToken) => new SolutionAddCommand(parseResult).Execute(cancellationToken)); #endif - command.ListCommand.SetAction(parseResult => new SolutionListCommand(parseResult).Execute()); - command.MigrateCommand.SetAction(parseResult => new SolutionMigrateCommand(parseResult).Execute()); - command.RemoveCommand.SetAction(parseResult => new SolutionRemoveCommand(parseResult).Execute()); + command.ListCommand.SetAction((parseResult, cancellationToken) => new SolutionListCommand(parseResult).Execute(cancellationToken)); + command.MigrateCommand.SetAction((parseResult, cancellationToken) => new SolutionMigrateCommand(parseResult).Execute(cancellationToken)); + command.RemoveCommand.SetAction((parseResult, cancellationToken) => new SolutionRemoveCommand(parseResult).Execute(cancellationToken)); } } diff --git a/src/Cli/dotnet/Commands/Test/MTP/CtrlCCancellationManager.cs b/src/Cli/dotnet/Commands/Test/MTP/CtrlCCancellationManager.cs index c2d10c0ed96e..89b2cbd8335a 100644 --- a/src/Cli/dotnet/Commands/Test/MTP/CtrlCCancellationManager.cs +++ b/src/Cli/dotnet/Commands/Test/MTP/CtrlCCancellationManager.cs @@ -1,24 +1,26 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Concurrent; using System.Diagnostics; using Microsoft.DotNet.Cli.Utils; namespace Microsoft.DotNet.Cli.Commands.Test; /// -/// Mirrors the two-stage Ctrl+C cancellation UX implemented in Microsoft.Testing.Platform +/// Mirrors the two-stage cancellation UX implemented in Microsoft.Testing.Platform /// (testfx PR #8581 / SDK issue https://github.com/dotnet/sdk/issues/50732) at the -/// dotnet test orchestrator level: +/// dotnet test orchestrator level. It can observe either console Ctrl+C directly +/// or the shared CLI lifecycle's cooperative and forceful cancellation tokens: /// /// First Ctrl+C: cooperative cancellation. The is signaled so the /// queue stops scheduling new test apps; running test apps are left alone so they can /// gracefully report their final state via IPC (their own testfx-side Ctrl+C handler will /// cancel the session inside the child process). -/// Second Ctrl+C: force exit. Every registered child process is killed -/// (entireProcessTree: true) and the host process exits with -/// (=3). +/// Forceful cancellation: SIGTERM is forwarded to every registered child with a +/// bounded grace period, while a repeated Ctrl+C kills every registered process tree +/// immediately. When this manager owns the console handler, a second Ctrl+C also exits +/// with (=3); otherwise the shared process +/// lifecycle owns the host exit. /// Any further presses are no-ops (the state machine is idempotent). /// /// @@ -31,12 +33,21 @@ internal sealed class CtrlCCancellationManager : IDisposable private readonly CancellationTokenSource _cancellationTokenSource = new(); private readonly Action _onFirstCtrlC; private readonly Action _exitAction; - private readonly ConcurrentDictionary _processes = new(); + private readonly Lock _processesLock = new(); + private readonly HashSet _processes = []; private readonly bool _subscribedToConsole; + private readonly CancellationTokenRegistration _cooperativeCancellationRegistration; + private readonly CancellationTokenRegistration _forcefulCancellationRegistration; private int _state = StateIdle; + private int _forwardSigTerm; private int _disposed; - public CtrlCCancellationManager(Action onFirstCtrlC, Action? exitAction = null, bool subscribeToConsole = true) + public CtrlCCancellationManager( + Action onFirstCtrlC, + Action? exitAction = null, + bool subscribeToConsole = true, + CancellationToken cooperativeCancellationToken = default, + CancellationToken forcefulCancellationToken = default) { _onFirstCtrlC = onFirstCtrlC ?? throw new ArgumentNullException(nameof(onFirstCtrlC)); _exitAction = exitAction ?? Environment.Exit; @@ -46,6 +57,12 @@ public CtrlCCancellationManager(Action onFirstCtrlC, Action? exitAction = n Console.CancelKeyPress += OnConsoleCancelKeyPress; _subscribedToConsole = true; } + + _cooperativeCancellationRegistration = + cooperativeCancellationToken.Register(() => HandleCooperativeCancellation()); + _forcefulCancellationRegistration = + forcefulCancellationToken.Register( + () => HandleForcefulCancellation(ProcessLifecycle.IsSigTermRequested)); } /// @@ -56,20 +73,28 @@ public CtrlCCancellationManager(Action onFirstCtrlC, Action? exitAction = n public CancellationToken Token => _cancellationTokenSource.Token; /// - /// Registers a child test-app process so it will be killed if the user requests a force exit - /// (second Ctrl+C). If the manager is already in the forcing state when this is called, the - /// process is killed immediately to avoid orphaning a child that started during the force - /// exit race window. + /// Starts and registers a child test-app process as one operation with respect to forceful + /// cancellation. Returns without starting a process when forceful + /// cancellation has already begun. /// - public void Register(Process process) + public Process? StartAndRegister(Func startProcess) { - ArgumentNullException.ThrowIfNull(process); - - _processes.TryAdd(process, 0); + ArgumentNullException.ThrowIfNull(startProcess); - if (Volatile.Read(ref _state) == StateForcing) + lock (_processesLock) { - TryKill(process); + if (Volatile.Read(ref _state) == StateForcing) + { + return null; + } + + Process? process = startProcess(); + if (process is not null) + { + _processes.Add(process); + } + + return process; } } @@ -77,7 +102,10 @@ public void Unregister(Process process) { ArgumentNullException.ThrowIfNull(process); - _processes.TryRemove(process, out _); + lock (_processesLock) + { + _processes.Remove(process); + } } /// @@ -85,6 +113,8 @@ public void Unregister(Process process) /// internal void SimulateCtrlC() => HandleCtrlC(); + internal bool IsForcing => Volatile.Read(ref _state) == StateForcing; + private void OnConsoleCancelKeyPress(object? sender, ConsoleCancelEventArgs e) { // Suppress the runtime's default Ctrl+C handling on every press, including the second one, @@ -96,48 +126,87 @@ private void OnConsoleCancelKeyPress(object? sender, ConsoleCancelEventArgs e) } private void HandleCtrlC() + { + if (HandleCooperativeCancellation()) + { + return; + } + + if (HandleForcefulCancellation(forwardSigTerm: false)) + { + _exitAction(ExitCode.TestSessionAborted); + } + } + + private bool HandleCooperativeCancellation() { // First press: Idle -> Cancelling. Signal the token, invoke the UI callback. - if (Interlocked.CompareExchange(ref _state, StateCancelling, StateIdle) == StateIdle) + if (Interlocked.CompareExchange(ref _state, StateCancelling, StateIdle) != StateIdle) { - // CancellationTokenSource.Cancel() can throw an AggregateException if any registered - // callback throws, or an ObjectDisposedException if Dispose races with a Ctrl+C press - // (e.g. user presses Ctrl+C while we're tearing down). Swallow both — we still want the - // state machine to advance and the UI callback to run. - try - { - _cancellationTokenSource.Cancel(); - } - catch (Exception ex) when (ex is AggregateException or ObjectDisposedException) - { - Logger.LogTrace($"Exception during CtrlCCancellationManager cancel:\n{ex}"); - } + return false; + } - // The UI callback (typically TerminalTestReporter.StartCancelling) must not be able to - // affect cancellation state — wrap it best-effort. - try - { - _onFirstCtrlC(); - } - catch (Exception ex) - { - Logger.LogTrace($"Exception during CtrlCCancellationManager first-press UI callback:\n{ex}"); - } + // CancellationTokenSource.Cancel() can throw an AggregateException if any registered + // callback throws, or an ObjectDisposedException if Dispose races with a Ctrl+C press + // (e.g. user presses Ctrl+C while we're tearing down). Swallow both — we still want the + // state machine to advance and the UI callback to run. + try + { + _cancellationTokenSource.Cancel(); + } + catch (Exception ex) when (ex is AggregateException or ObjectDisposedException) + { + Logger.LogTrace($"Exception during CtrlCCancellationManager cancel:\n{ex}"); + } - return; + // The UI callback (typically TerminalTestReporter.StartCancelling) must not be able to + // affect cancellation state — wrap it best-effort. + try + { + _onFirstCtrlC(); + } + catch (Exception ex) + { + Logger.LogTrace($"Exception during CtrlCCancellationManager first-press UI callback:\n{ex}"); } - // Second press: Cancelling -> Forcing. Kill every registered child and exit. - // We intentionally do not print any additional message here because the user already saw - // the "Press Ctrl+C again to force exit." hint and the exit itself is the confirmation. - if (Interlocked.CompareExchange(ref _state, StateForcing, StateCancelling) == StateCancelling) + return true; + } + + private bool HandleForcefulCancellation(bool forwardSigTerm) + { + // A second Ctrl+C transitions Cancelling -> Forcing. A forceful lifecycle signal such as + // SIGTERM can transition directly from Idle -> Forcing. + if (forwardSigTerm) { - foreach (var process in _processes.Keys) - { - TryKill(process); - } + Volatile.Write(ref _forwardSigTerm, 1); + } - _exitAction(ExitCode.TestSessionAborted); + int previousState = Interlocked.Exchange(ref _state, StateForcing); + if (previousState == StateForcing) + { + return false; + } + + lock (_processesLock) + { + TerminateProcesses([.. _processes], forwardSigTerm); + } + + return true; + } + + private static void TerminateProcesses(IReadOnlyCollection processes, bool forwardSigTerm) + { + if (forwardSigTerm) + { + ProcessReaper.ForwardSigTermAndTerminate(processes); + return; + } + + foreach (Process process in processes) + { + TryKill(process); } } @@ -170,6 +239,8 @@ public void Dispose() Console.CancelKeyPress -= OnConsoleCancelKeyPress; } + _cooperativeCancellationRegistration.Dispose(); + _forcefulCancellationRegistration.Dispose(); _cancellationTokenSource.Dispose(); } } diff --git a/src/Cli/dotnet/Commands/Test/MTP/ITestHandler.cs b/src/Cli/dotnet/Commands/Test/MTP/ITestHandler.cs index 78a4db7ac3d5..3cfd5bfc27e7 100644 --- a/src/Cli/dotnet/Commands/Test/MTP/ITestHandler.cs +++ b/src/Cli/dotnet/Commands/Test/MTP/ITestHandler.cs @@ -5,7 +5,7 @@ namespace Microsoft.DotNet.Cli.Commands.Test; internal interface ITestHandler { - bool Initialize(); + bool Initialize(CancellationToken cancellationToken); /// /// All modules that will be run. Available after a successful so the diff --git a/src/Cli/dotnet/Commands/Test/MTP/MSBuildHandler.cs b/src/Cli/dotnet/Commands/Test/MTP/MSBuildHandler.cs index bdc23fecf473..b87c2c7b389e 100644 --- a/src/Cli/dotnet/Commands/Test/MTP/MSBuildHandler.cs +++ b/src/Cli/dotnet/Commands/Test/MTP/MSBuildHandler.cs @@ -17,7 +17,7 @@ internal sealed class MSBuildHandler(BuildOptions buildOptions, MSBuildSession b private readonly ConcurrentBag _testApplications = []; - public bool Initialize() + public bool Initialize(CancellationToken cancellationToken) { PathOptions pathOptions = _buildOptions.PathOptions; @@ -27,8 +27,8 @@ public bool Initialize() } (IEnumerable projects, int buildExitCode) = isSolution ? - MSBuildUtility.GetProjectsFromSolution(projectOrSolutionFilePath, _buildOptions, _buildSession) : - MSBuildUtility.GetProjectsFromProject(projectOrSolutionFilePath, _buildOptions, _buildSession); + MSBuildUtility.GetProjectsFromSolution(projectOrSolutionFilePath, _buildOptions, _buildSession, cancellationToken) : + MSBuildUtility.GetProjectsFromProject(projectOrSolutionFilePath, _buildOptions, _buildSession, cancellationToken); LogProjectProperties(projects); diff --git a/src/Cli/dotnet/Commands/Test/MTP/MSBuildUtility.cs b/src/Cli/dotnet/Commands/Test/MTP/MSBuildUtility.cs index 53c65c7d5809..ba3262e0bd73 100644 --- a/src/Cli/dotnet/Commands/Test/MTP/MSBuildUtility.cs +++ b/src/Cli/dotnet/Commands/Test/MTP/MSBuildUtility.cs @@ -31,12 +31,13 @@ internal static class MSBuildUtility public static (IEnumerable Projects, int BuildExitCode) GetProjectsFromSolution( string solutionFilePath, BuildOptions buildOptions, - MSBuildSession buildSession) + MSBuildSession buildSession, + CancellationToken cancellationToken) { using var _ = MSBuildForwardingAppWithoutLogging.SetMSBuildRequiredEnvironmentVariables(); solutionFilePath = Path.GetFullPath(solutionFilePath, buildSession.WorkingDirectory); - int buildExitCode = BuildOrRestoreProjectOrSolution(solutionFilePath, buildOptions, buildSession); + int buildExitCode = BuildOrRestoreProjectOrSolution(solutionFilePath, buildOptions, buildSession, cancellationToken); if (buildExitCode != 0) { @@ -75,7 +76,7 @@ public static (IEnumerable Projects, int BuildExitCode) GetProjectsFromProject( string projectFilePath, BuildOptions buildOptions, - MSBuildSession buildSession) + MSBuildSession buildSession, + CancellationToken cancellationToken) { using var _ = MSBuildForwardingAppWithoutLogging.SetMSBuildRequiredEnvironmentVariables(); @@ -106,10 +108,10 @@ public static (IEnumerable(), exitCode); @@ -397,7 +400,11 @@ private static (string? PositionalProjectOrSolution, string? PositionalTestModul } [RequiresDynamicCode("Uses MSBuild Object Model types, which are not AOT-safe")] - private static int BuildOrRestoreProjectOrSolution(string filePath, BuildOptions buildOptions, MSBuildSession buildSession) + private static int BuildOrRestoreProjectOrSolution( + string filePath, + BuildOptions buildOptions, + MSBuildSession buildSession, + CancellationToken cancellationToken) { if (buildOptions.HasNoBuild) { @@ -454,8 +461,8 @@ private static int BuildOrRestoreProjectOrSolution(string filePath, BuildOptions workingDirectory: buildSession.WorkingDirectory); return buildSession.RequiresOutOfProcessBuild - ? command.ExecuteOutOfProc(buildSession.WorkingDirectory) - : command.Execute(); + ? command.ExecuteOutOfProc(buildSession.WorkingDirectory, cancellationToken) + : command.Execute(cancellationToken); } finally { @@ -470,7 +477,8 @@ private static (ConcurrentBag projects, BuildOptions buildOptions, IReadOnlyDictionary globalProperties, - MSBuildSession buildSession) + MSBuildSession buildSession, + CancellationToken cancellationToken) { var allProjects = new ConcurrentBag(); var solutionProjects = projects.ToArray(); @@ -564,6 +572,7 @@ private static (ConcurrentBag> CustomHelpLayout() WriteHelpOptions(context); Console.WriteLine(CliCommandStrings.HelpWaitingForOptionsAndExtensions); - Run(context.ParseResult, isHelp: true); + // This help-rendering path is invoked synchronously from System.CommandLine's HelpBuilder + // override, so use the process-wide token that tracks Ctrl+C and process shutdown. + Run(context.ParseResult, isHelp: true, Utils.ProcessLifecycle.CancellationToken); if (_commandLineOptionNameToModuleNames.IsEmpty) { diff --git a/src/Cli/dotnet/Commands/Test/MTP/MicrosoftTestingPlatformTestCommand.cs b/src/Cli/dotnet/Commands/Test/MTP/MicrosoftTestingPlatformTestCommand.cs index d8c7758af641..fd7c7c5ab93b 100644 --- a/src/Cli/dotnet/Commands/Test/MTP/MicrosoftTestingPlatformTestCommand.cs +++ b/src/Cli/dotnet/Commands/Test/MTP/MicrosoftTestingPlatformTestCommand.cs @@ -29,7 +29,7 @@ internal partial class MicrosoftTestingPlatformTestCommand private const string ZeroTestsPolicyOptionName = "--zero-tests-policy"; private const string ZeroTestsPolicyStrictArgument = "strict"; - public int Run(ParseResult parseResult, bool isHelp) + public int Run(ParseResult parseResult, bool isHelp, CancellationToken cancellationToken) { var definition = (TestCommandDefinition.MicrosoftTestingPlatform)parseResult.CommandResult.Command; string invocationWorkingDirectory = Directory.GetCurrentDirectory(); @@ -113,7 +113,7 @@ public int Run(ParseResult parseResult, bool isHelp) : RuntimeFeature.IsDynamicCodeSupported ? new MSBuildHandler(buildOptions, buildSession) : throw new PlatformNotSupportedException("Dynamic code is not supported on this platform."); - if (!testHandler.Initialize()) + if (!testHandler.Initialize(cancellationToken)) { return ExitCode.GenericFailure; } @@ -176,7 +176,16 @@ public int Run(ParseResult parseResult, bool isHelp) : parseResult.GetValue(definition.TimeoutOption), onCancellation: _ => output.MarkCancelled()); - using var ctrlC = new CtrlCCancellationManager(output.StartCancelling); + using IDisposable? lifecycleCancellationTimeout = ProcessLifecycle.IsInitialized + ? ProcessLifecycle.OverrideSoftCancellationTimeout(Timeout.InfiniteTimeSpan) + : null; + using var ctrlC = new CtrlCCancellationManager( + output.StartCancelling, + subscribeToConsole: !ProcessLifecycle.IsInitialized, + cooperativeCancellationToken: cancellationToken, + forcefulCancellationToken: ProcessLifecycle.IsInitialized + ? ProcessLifecycle.ForcefulCancellationToken + : default); using var queueCancellation = CancellationTokenSource.CreateLinkedTokenSource(ctrlC.Token, testRunPolicy.Token); var artifactPostProcessingManager = new ArtifactPostProcessingManager(); int? exitCode = null; @@ -247,14 +256,22 @@ public int Run(ParseResult parseResult, bool isHelp) } exitCode = actionQueue.ApplyExitCodeIgnorePolicy(exitCode.Value); + cancellationToken.ThrowIfCancellationRequested(); return exitCode.Value; } finally { - output.TestExecutionCompleted(DateTimeOffset.Now, exitCode); + output.TestExecutionCompleted( + DateTimeOffset.Now, + GetExitCodeForReporting(exitCode, cancellationToken.IsCancellationRequested)); } } + internal static int? GetExitCodeForReporting(int? exitCode, bool cancellationRequested) + => cancellationRequested && exitCode == ExitCode.Success + ? ExitCode.TestSessionAborted + : exitCode; + /// /// Decides whether the artifacts of a finished run should be consolidated. /// @@ -1027,9 +1044,9 @@ private static TerminalTestReporter InitializeOutput(int degreeOfParallelism, Pa ShowFlakyTests = GetShowFlakyTests(parseResult.GetArguments()), }); - // Ctrl+C handling is wired in Run() through CtrlCCancellationManager so that - // a second press can force-kill running test app child processes and exit with - // ExitCode.TestSessionAborted (see issue https://github.com/dotnet/sdk/issues/50732). + // Cancellation is wired in Run() through CtrlCCancellationManager so the first Ctrl+C + // stops scheduling without interrupting test reporting, while shared lifecycle forceful + // cancellation kills running test app child processes. // Retry-specific rendering is enabled authoritatively by the retry orchestrator handshake. // Keep the raw option check only for older platform versions that support retries but do not diff --git a/src/Cli/dotnet/Commands/Test/MTP/TestApplication.cs b/src/Cli/dotnet/Commands/Test/MTP/TestApplication.cs index f78013f563ac..60ea6bb5b7b1 100644 --- a/src/Cli/dotnet/Commands/Test/MTP/TestApplication.cs +++ b/src/Cli/dotnet/Commands/Test/MTP/TestApplication.cs @@ -105,14 +105,15 @@ public async Task RunAsync(CtrlCCancellationManager ctrlC) { Logger.LogTrace($"Starting test process with command '{processStartInfo.FileName}' and arguments '{GetArgumentsForLogging(processStartInfo.Arguments)}'."); - process = Process.Start(processStartInfo)!; + process = ctrlC.StartAndRegister(() => Process.Start(processStartInfo)); + if (process is null) + { + return ExitCode.TestSessionAborted; + } + _testRunPolicy?.OnTestApplicationStarted(); testApplicationStarted = true; - // Register with the Ctrl+C manager so a force-exit (second Ctrl+C) kills this process - // tree even if the child's own cooperative cancellation hangs. - ctrlC.Register(process); - // Reading from process stdout/stderr is done on separate threads to avoid blocking IO on the threadpool. // Note: even with 'process.StandardOutput.ReadToEndAsync()' or 'process.BeginOutputReadLine()', we ended up with // many TP threads just doing synchronous IO, slowing down the progress of the test run. diff --git a/src/Cli/dotnet/Commands/Test/MTP/TestModulesFilterHandler.cs b/src/Cli/dotnet/Commands/Test/MTP/TestModulesFilterHandler.cs index 255c931f18aa..fcd72c23c7d6 100644 --- a/src/Cli/dotnet/Commands/Test/MTP/TestModulesFilterHandler.cs +++ b/src/Cli/dotnet/Commands/Test/MTP/TestModulesFilterHandler.cs @@ -40,7 +40,7 @@ public TestModulesFilterHandler(string testModules, ParseResult parseResult) _testModulePaths = GetMatchedModulePaths(_testModules, _testModulesRoot); } - public bool Initialize() + public bool Initialize(CancellationToken cancellationToken) { // If the root directory is not valid, we simply return if (string.IsNullOrEmpty(_testModulesRoot) || !Directory.Exists(_testModulesRoot)) diff --git a/src/Cli/dotnet/Commands/Test/TestCommandParser.cs b/src/Cli/dotnet/Commands/Test/TestCommandParser.cs index 0677e6c73c06..72e41a2457c4 100644 --- a/src/Cli/dotnet/Commands/Test/TestCommandParser.cs +++ b/src/Cli/dotnet/Commands/Test/TestCommandParser.cs @@ -21,7 +21,7 @@ public static void ConfigureCommand(TestCommandDefinition command) case TestCommandDefinition.MicrosoftTestingPlatform mtp: var impl = new MicrosoftTestingPlatformTestCommand(); - mtp.SetAction(parseResult => impl.Run(parseResult, isHelp: false)); + mtp.SetAction((parseResult, cancellationToken) => impl.Run(parseResult, isHelp: false, cancellationToken)); mtp.CustomHelpLayoutProvider = impl; break; diff --git a/src/Cli/dotnet/Commands/Test/VSTest/TestCommand.cs b/src/Cli/dotnet/Commands/Test/VSTest/TestCommand.cs index 967490f1b135..f3e29c9296e8 100644 --- a/src/Cli/dotnet/Commands/Test/VSTest/TestCommand.cs +++ b/src/Cli/dotnet/Commands/Test/VSTest/TestCommand.cs @@ -19,7 +19,7 @@ public class TestCommand( bool noRestore, string? msbuildPath = null) : RestoringCommand(msbuildArgs, noRestore, msbuildPath) { - public static int Run(ParseResult parseResult) + public static int Run(ParseResult parseResult, CancellationToken cancellationToken) { parseResult.HandleDebugSwitch(); @@ -50,7 +50,7 @@ public static int Run(ParseResult parseResult) // When we have settings, we want to exclude the '--' as it doesn't end up in unmatched tokens, so we pass settings.Length - 1 if (ContainsBuiltTestSources(parseResult, GetSettingsCount(settings))) { - int exitCode = ForwardToVSTestConsole(parseResult, args, settings, testSessionCorrelationId); + int exitCode = ForwardToVSTestConsole(parseResult, args, settings, testSessionCorrelationId, cancellationToken); // Reached only when the invocation completed, whether the tests passed or failed. An invocation that // throws or is interrupted deliberately leaves the artifacts on disk for diagnosis. @@ -58,7 +58,7 @@ public static int Run(ParseResult parseResult) return exitCode; } - int msbuildExitCode = ForwardToMsbuild(parseResult, settings, testSessionCorrelationId); + int msbuildExitCode = ForwardToMsbuild(parseResult, settings, testSessionCorrelationId, cancellationToken); VSTestArtifactsDirectory.Delete(); return msbuildExitCode; @@ -84,7 +84,7 @@ public static int Run(ParseResult parseResult) return settings.Length - 1; } - private static int ForwardToMsbuild(ParseResult parseResult, string[] settings, string testSessionCorrelationId) + private static int ForwardToMsbuild(ParseResult parseResult, string[] settings, string testSessionCorrelationId, CancellationToken cancellationToken) { var definition = (TestCommandDefinition.VSTest)parseResult.CommandResult.Command; @@ -133,10 +133,14 @@ private static int ForwardToMsbuild(ParseResult parseResult, string[] settings, additionalBuildProperties = ["--property:VsTestUseMSBuildOutput=true"]; } - int exitCode = FromParseResult(parseResult, settings, testSessionCorrelationId, additionalBuildProperties).Execute(); + int exitCode = FromParseResult(parseResult, settings, testSessionCorrelationId, additionalBuildProperties).Execute(cancellationToken); // We run post processing also if execution is failed for possible partial successful result to post process. - exitCode |= RunArtifactPostProcessingIfNeeded(testSessionCorrelationId, parseResult.GetValue(definition.DiagOption), FeatureFlag.Instance); + exitCode |= RunArtifactPostProcessingIfNeeded( + testSessionCorrelationId, + parseResult.GetValue(definition.DiagOption), + FeatureFlag.Instance, + cancellationToken); return exitCode; } @@ -156,7 +160,12 @@ static string[] SetLegacyVSTestWorkarounds(string NodeWindowEnvironmentName) } } - private static int ForwardToVSTestConsole(ParseResult parseResult, string[] args, string[] settings, string testSessionCorrelationId) + private static int ForwardToVSTestConsole( + ParseResult parseResult, + string[] args, + string[] settings, + string testSessionCorrelationId, + CancellationToken cancellationToken) { var definition = (TestCommandDefinition.VSTest)parseResult.CommandResult.Command; @@ -177,10 +186,14 @@ private static int ForwardToVSTestConsole(ParseResult parseResult, string[] args convertedArgs.Add($"--testSessionCorrelationId:{testSessionCorrelationId}"); } - int exitCode = new VSTestForwardingApp(convertedArgs).Execute(); + int exitCode = new VSTestForwardingApp(convertedArgs).Execute(cancellationToken); // We run post processing also if execution is failed for possible partial successful result to post process. - exitCode |= RunArtifactPostProcessingIfNeeded(testSessionCorrelationId, parseResult.GetValue(definition.DiagOption), FeatureFlag.Instance); + exitCode |= RunArtifactPostProcessingIfNeeded( + testSessionCorrelationId, + parseResult.GetValue(definition.DiagOption), + FeatureFlag.Instance, + cancellationToken); return exitCode; } @@ -293,7 +306,11 @@ private static TestCommand FromParseResult(ParseResult result, string[] settings return testCommand; } - internal static int RunArtifactPostProcessingIfNeeded(string testSessionCorrelationId, string? diag, FeatureFlag disableFeatureFlag) + internal static int RunArtifactPostProcessingIfNeeded( + string testSessionCorrelationId, + string? diag, + FeatureFlag disableFeatureFlag, + CancellationToken cancellationToken) { if (disableFeatureFlag.IsSet(FeatureFlag.DISABLE_ARTIFACTS_POSTPROCESSING)) { @@ -320,7 +337,7 @@ internal static int RunArtifactPostProcessingIfNeeded(string testSessionCorrelat // The post-processing run receives the same artifacts directory as the collecting run did, so it resolves // the same session subdirectory. The whole directory is removed once the invocation completes, so there is // nothing to clean up here. - return new VSTestForwardingApp(artifactsPostProcessArgs).Execute(); + return new VSTestForwardingApp(artifactsPostProcessArgs).Execute(cancellationToken); } /// diff --git a/src/Cli/dotnet/Commands/Tool/Execute/ToolExecuteCommand.cs b/src/Cli/dotnet/Commands/Tool/Execute/ToolExecuteCommand.cs index d8b045e6131a..36f41d4d635a 100644 --- a/src/Cli/dotnet/Commands/Tool/Execute/ToolExecuteCommand.cs +++ b/src/Cli/dotnet/Commands/Tool/Execute/ToolExecuteCommand.cs @@ -53,7 +53,7 @@ public ToolExecuteCommand(ParseResult result, ToolManifestFinder? toolManifestFi _toolManifestFinder = toolManifestFinder ?? new ToolManifestFinder(new DirectoryPath(currentWorkingDirectory ?? Directory.GetCurrentDirectory())); } - public override int Execute() => ExecuteAsync(CancellationToken.None).GetAwaiter().GetResult(); + public override int Execute(CancellationToken cancellationToken) => ExecuteAsync(cancellationToken).GetAwaiter().GetResult(); internal async Task ExecuteAsync(CancellationToken cancellationToken) { @@ -110,7 +110,12 @@ internal async Task ExecuteAsync(CancellationToken cancellationToken) _toolManifestFinder, localToolsResolverCache); - return ToolRunCommand.ExecuteCommand(localToolsCommandResolver, toolManifestPackage.CommandNames.Single().Value, _forwardArguments, _allowRollForward); + return ToolRunCommand.ExecuteCommand( + localToolsCommandResolver, + toolManifestPackage.CommandNames.Single().Value, + _forwardArguments, + _allowRollForward, + cancellationToken); } } @@ -187,6 +192,7 @@ internal async Task ExecuteAsync(CancellationToken cancellationToken) toolPackage = _toolPackageDownloader.InstallPackage( downloadPackageLocation, packageId: packageId, + cancellationToken: cancellationToken, verbosity: _verbosity, versionRange: new VersionRange(bestVersion!, true, bestVersion!, true), isGlobalToolRollForward: false, @@ -199,7 +205,7 @@ internal async Task ExecuteAsync(CancellationToken cancellationToken) toolExecuteActivity?.SetTag("tool.runner", toolPackage.Command.Runner); var commandSpec = ToolCommandSpecCreator.CreateToolCommandSpec(toolPackage.Command.Name.Value, toolPackage.Command.Executable.Value, toolPackage.Command.Runner, _allowRollForward, _forwardArguments); var command = CommandFactoryUsingResolver.Create(commandSpec); - var result = command.Execute(); + var result = command.Execute(cancellationToken); return result.ExitCode; } diff --git a/src/Cli/dotnet/Commands/Tool/Install/ProjectRestorer.cs b/src/Cli/dotnet/Commands/Tool/Install/ProjectRestorer.cs index 80ce0531e945..b32c113c6db4 100644 --- a/src/Cli/dotnet/Commands/Tool/Install/ProjectRestorer.cs +++ b/src/Cli/dotnet/Commands/Tool/Install/ProjectRestorer.cs @@ -20,6 +20,7 @@ internal class ProjectRestorer(IReporter reporter = null, public void Restore(FilePath project, PackageLocation packageLocation, + CancellationToken cancellationToken, string verbosity = null) { List argsToPassToRestore = [project.Value]; @@ -48,7 +49,7 @@ public void Restore(FilePath project, .OnErrorLine(line => WriteLine(_errorReporter, line, project)); } - var result = command.Execute(); + var result = command.Execute(cancellationToken); if (result.ExitCode != 0) { throw new ToolPackageException(CliCommandStrings.ToolInstallationRestoreFailed); diff --git a/src/Cli/dotnet/Commands/Tool/Install/ToolInstallCommand.cs b/src/Cli/dotnet/Commands/Tool/Install/ToolInstallCommand.cs index 51f76f3a6fa7..cd49b182c5f5 100644 --- a/src/Cli/dotnet/Commands/Tool/Install/ToolInstallCommand.cs +++ b/src/Cli/dotnet/Commands/Tool/Install/ToolInstallCommand.cs @@ -28,8 +28,8 @@ public ToolInstallCommand( _framework = parseResult.GetValue(Definition.FrameworkOption); } - public override int Execute() - => ExecuteAsync(CancellationToken.None).GetAwaiter().GetResult(); + public override int Execute(CancellationToken cancellationToken) + => ExecuteAsync(cancellationToken).GetAwaiter().GetResult(); internal async Task ExecuteAsync(CancellationToken cancellationToken) { @@ -55,7 +55,7 @@ internal async Task ExecuteAsync(CancellationToken cancellationToken) CliCommandStrings.LocalOptionDoesNotSupportFrameworkOption)); } - return (_toolInstallLocalCommand ?? new ToolInstallLocalCommand(_parseResult)).Execute(); + return (_toolInstallLocalCommand ?? new ToolInstallLocalCommand(_parseResult)).Execute(cancellationToken); } } } diff --git a/src/Cli/dotnet/Commands/Tool/Install/ToolInstallGlobalOrToolPathCommand.cs b/src/Cli/dotnet/Commands/Tool/Install/ToolInstallGlobalOrToolPathCommand.cs index b5ac8af7b4d8..701d9599505e 100644 --- a/src/Cli/dotnet/Commands/Tool/Install/ToolInstallGlobalOrToolPathCommand.cs +++ b/src/Cli/dotnet/Commands/Tool/Install/ToolInstallGlobalOrToolPathCommand.cs @@ -139,7 +139,7 @@ public static T GetValueOrDefault(Option option, T defaultOption, ParseRes return defaultOption; } - public override int Execute() => ExecuteAsync(CancellationToken.None).GetAwaiter().GetResult(); + public override int Execute(CancellationToken cancellationToken) => ExecuteAsync(cancellationToken).GetAwaiter().GetResult(); internal async Task ExecuteAsync(CancellationToken cancellationToken) { @@ -250,6 +250,7 @@ private async Task ExecuteInstallCommandAsync( IToolPackage newInstalledPackage = toolPackageDownloader.InstallPackage( new PackageLocation(nugetConfig: GetConfigFile(), sourceFeedOverrides: _source, additionalFeeds: _addSource), packageId: packageId, + cancellationToken: cancellationToken, versionRange: versionRange, targetFramework: _framework, verbosity: _verbosity, @@ -272,9 +273,16 @@ private async Task ExecuteInstallCommandAsync( framework = string.IsNullOrEmpty(_framework) ? null : NuGetFramework.Parse(_framework); } var shimActivity = Activities.Source.StartActivity("create-shell-shim"); - string appHostSourceDirectory = _shellShimTemplateFinder.ResolveAppHostSourceDirectoryAsync(_architecture, framework, RuntimeInformation.ProcessArchitecture).Result; - - shellShimRepository.CreateShim(newInstalledPackage.Command, newInstalledPackage.PackagedShims); + string appHostSourceDirectory = _shellShimTemplateFinder.ResolveAppHostSourceDirectoryAsync( + _architecture, + framework, + RuntimeInformation.ProcessArchitecture, + cancellationToken).GetAwaiter().GetResult(); + + shellShimRepository.CreateShim( + newInstalledPackage.Command, + cancellationToken, + newInstalledPackage.PackagedShims); shimActivity?.Dispose(); foreach (string w in newInstalledPackage.Warnings) diff --git a/src/Cli/dotnet/Commands/Tool/Install/ToolInstallLocalCommand.cs b/src/Cli/dotnet/Commands/Tool/Install/ToolInstallLocalCommand.cs index 03de7b8a4b35..df9dba23446c 100644 --- a/src/Cli/dotnet/Commands/Tool/Install/ToolInstallLocalCommand.cs +++ b/src/Cli/dotnet/Commands/Tool/Install/ToolInstallLocalCommand.cs @@ -77,13 +77,13 @@ public ToolInstallLocalCommand( _allowPackageDowngrade = parseResult.GetValue(Definition.AllowPackageDowngradeOption); } - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { if (_updateAll) { foreach (var (manifestPackage, _) in ((IToolManifestInspector)_toolManifestFinder).Inspect()) { - ExecuteInstallCommand(manifestPackage.PackageId, versionRange: null); + ExecuteInstallCommand(manifestPackage.PackageId, versionRange: null, cancellationToken); } return 0; @@ -98,10 +98,10 @@ public override int Execute() _parseResult.GetValue(Definition.VersionOption), _parseResult.GetValue(Definition.PrereleaseOption)); - return ExecuteInstallCommand(packageId, versionRange); + return ExecuteInstallCommand(packageId, versionRange, cancellationToken); } - private int ExecuteInstallCommand(PackageId packageId, VersionRange? versionRange) + private int ExecuteInstallCommand(PackageId packageId, VersionRange? versionRange, CancellationToken cancellationToken) { FilePath manifestFile = GetManifestFilePath(); @@ -118,11 +118,11 @@ private int ExecuteInstallCommand(PackageId packageId, VersionRange? versionRang if (!existingPackageWithPackageId.Any()) { - return InstallNewTool(manifestFile, packageId, versionRange); + return InstallNewTool(manifestFile, packageId, versionRange, cancellationToken); } var existingPackage = existingPackageWithPackageId.Single(); - var toolDownloadedPackage = _toolLocalPackageInstaller.Install(manifestFile, packageId, versionRange); + var toolDownloadedPackage = _toolLocalPackageInstaller.Install(manifestFile, packageId, versionRange, cancellationToken); InstallToolUpdate(existingPackage, toolDownloadedPackage, manifestFile, packageId); @@ -179,10 +179,14 @@ public int InstallToolUpdate(ToolManifestPackage existingPackage, IToolPackage t return 0; } - public int InstallNewTool(FilePath manifestFile, PackageId packageId, VersionRange? versionRange) + public int InstallNewTool( + FilePath manifestFile, + PackageId packageId, + VersionRange? versionRange, + CancellationToken cancellationToken) { IToolPackage toolDownloadedPackage = - _toolLocalPackageInstaller.Install(manifestFile, packageId, versionRange); + _toolLocalPackageInstaller.Install(manifestFile, packageId, versionRange, cancellationToken); _toolManifestEditor.Add( manifestFile, diff --git a/src/Cli/dotnet/Commands/Tool/Install/ToolInstallLocalInstaller.cs b/src/Cli/dotnet/Commands/Tool/Install/ToolInstallLocalInstaller.cs index a29693931cae..8edc995629d8 100644 --- a/src/Cli/dotnet/Commands/Tool/Install/ToolInstallLocalInstaller.cs +++ b/src/Cli/dotnet/Commands/Tool/Install/ToolInstallLocalInstaller.cs @@ -23,7 +23,11 @@ internal sealed class ToolInstallLocalInstaller( private readonly IToolPackageDownloader _toolPackageDownloader = toolPackageDownloader ?? ToolPackageFactory.CreateToolPackageStoresAndDownloader(runtimeJsonPathForTests: runtimeJsonPathForTests).downloader; - public IToolPackage Install(FilePath manifestFile, PackageId packageId, VersionRange? versionRange) + public IToolPackage Install( + FilePath manifestFile, + PackageId packageId, + VersionRange? versionRange, + CancellationToken cancellationToken) { if (!string.IsNullOrEmpty(configFilePath) && !File.Exists(configFilePath)) { @@ -54,6 +58,7 @@ public IToolPackage Install(FilePath manifestFile, PackageId packageId, VersionR additionalFeeds: sources, rootConfigDirectory: rootConfigDirectory), packageId, + cancellationToken, verbosity: verbosity, versionRange, TargetFrameworkToInstall, diff --git a/src/Cli/dotnet/Commands/Tool/List/ToolListCommand.cs b/src/Cli/dotnet/Commands/Tool/List/ToolListCommand.cs index 9f61adac241f..d8b48c6c2f2b 100644 --- a/src/Cli/dotnet/Commands/Tool/List/ToolListCommand.cs +++ b/src/Cli/dotnet/Commands/Tool/List/ToolListCommand.cs @@ -14,7 +14,7 @@ internal sealed class ToolListCommand( private readonly ToolListGlobalOrToolPathCommand _toolListGlobalOrToolPathCommand = toolListGlobalOrToolPathCommand ?? new(result); private readonly ToolListLocalCommand _toolListLocalCommand = toolListLocalCommand ?? new(result); - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { Definition.LocationOptions.EnsureNoConflictGlobalLocalToolPathOption( _parseResult, @@ -24,6 +24,6 @@ public override int Execute() ? _toolListGlobalOrToolPathCommand : _toolListLocalCommand; - return command.Execute(); + return command.Execute(cancellationToken); } } diff --git a/src/Cli/dotnet/Commands/Tool/List/ToolListGlobalOrToolPathCommand.cs b/src/Cli/dotnet/Commands/Tool/List/ToolListGlobalOrToolPathCommand.cs index c77daec25986..2edc21f65bfa 100644 --- a/src/Cli/dotnet/Commands/Tool/List/ToolListGlobalOrToolPathCommand.cs +++ b/src/Cli/dotnet/Commands/Tool/List/ToolListGlobalOrToolPathCommand.cs @@ -23,7 +23,7 @@ internal sealed class ToolListGlobalOrToolPathCommand( private readonly IReporter _errorReporter = reporter ?? Reporter.Error; private readonly CreateToolPackageStore _createToolPackageStore = createToolPackageStore ?? ToolPackageFactory.CreateToolPackageStoreQuery; - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { var toolPathOption = _parseResult.GetValue(Definition.LocationOptions.ToolPathOption); var packageIdArgument = _parseResult.GetValue(Definition.PackageIdArgument); diff --git a/src/Cli/dotnet/Commands/Tool/List/ToolListLocalCommand.cs b/src/Cli/dotnet/Commands/Tool/List/ToolListLocalCommand.cs index bf277d9a472d..33df0aae5a1e 100644 --- a/src/Cli/dotnet/Commands/Tool/List/ToolListLocalCommand.cs +++ b/src/Cli/dotnet/Commands/Tool/List/ToolListLocalCommand.cs @@ -29,7 +29,7 @@ public ToolListLocalCommand( new ToolManifestFinder(new DirectoryPath(Directory.GetCurrentDirectory())); } - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { var packageIdArgument = _parseResult.GetValue(Definition.PackageIdArgument); PackageId? packageId = string.IsNullOrWhiteSpace(packageIdArgument) ? null : new(packageIdArgument); diff --git a/src/Cli/dotnet/Commands/Tool/Restore/ToolPackageRestorer.cs b/src/Cli/dotnet/Commands/Tool/Restore/ToolPackageRestorer.cs index b823a68ec19a..a758d8e96e11 100644 --- a/src/Cli/dotnet/Commands/Tool/Restore/ToolPackageRestorer.cs +++ b/src/Cli/dotnet/Commands/Tool/Restore/ToolPackageRestorer.cs @@ -69,6 +69,7 @@ public async Task InstallPackageAsync( sourceFeedOverrides: _overrideSources, rootConfigDirectory: package.FirstEffectDirectory), package.PackageId, + cancellationToken, verbosity: _verbosity, ToVersionRangeWithOnlyOneVersion(package.Version), targetFramework, diff --git a/src/Cli/dotnet/Commands/Tool/Restore/ToolRestoreCommand.cs b/src/Cli/dotnet/Commands/Tool/Restore/ToolRestoreCommand.cs index 8e992f20cd63..f2d17e186a1d 100644 --- a/src/Cli/dotnet/Commands/Tool/Restore/ToolRestoreCommand.cs +++ b/src/Cli/dotnet/Commands/Tool/Restore/ToolRestoreCommand.cs @@ -73,7 +73,7 @@ public ToolRestoreCommand( _restoreActionConfig = Definition.RestoreOptions.ToRestoreActionConfig(result); } - public override int Execute() => ExecuteAsync(CancellationToken.None).GetAwaiter().GetResult(); + public override int Execute(CancellationToken cancellationToken) => ExecuteAsync(cancellationToken).GetAwaiter().GetResult(); internal async Task ExecuteAsync(CancellationToken cancellationToken) { diff --git a/src/Cli/dotnet/Commands/Tool/Run/ToolRunCommand.cs b/src/Cli/dotnet/Commands/Tool/Run/ToolRunCommand.cs index 72262f1294c0..91e71d9016af 100644 --- a/src/Cli/dotnet/Commands/Tool/Run/ToolRunCommand.cs +++ b/src/Cli/dotnet/Commands/Tool/Run/ToolRunCommand.cs @@ -26,12 +26,17 @@ public ToolRunCommand(ParseResult result, LocalToolsCommandResolver? localToolsC _allowRollForward = result.GetValue(Definition.RollForwardOption); } - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { - return ExecuteCommand(_localToolsCommandResolver, _toolCommandName, _forwardArgument, _allowRollForward); + return ExecuteCommand(_localToolsCommandResolver, _toolCommandName, _forwardArgument, _allowRollForward, cancellationToken); } - public static int ExecuteCommand(LocalToolsCommandResolver commandResolver, string? toolCommandName, IEnumerable? argumentsToForward, bool allowRollForward) + public static int ExecuteCommand( + LocalToolsCommandResolver commandResolver, + string? toolCommandName, + IEnumerable? argumentsToForward, + bool allowRollForward, + CancellationToken cancellationToken) { using var _ = Activities.Source.StartActivity("execute-local-tool"); CommandSpec? commandSpec = commandResolver.ResolveStrict(new CommandResolverArguments() @@ -46,7 +51,7 @@ public static int ExecuteCommand(LocalToolsCommandResolver commandResolver, stri throw new GracefulException([string.Format(CliCommandStrings.CannotFindCommandName, toolCommandName)], isUserError: false); } - var result = CommandFactoryUsingResolver.Create(commandSpec).Execute(); + var result = CommandFactoryUsingResolver.Create(commandSpec).Execute(cancellationToken); return result.ExitCode; } } diff --git a/src/Cli/dotnet/Commands/Tool/Search/ToolSearchCommand.cs b/src/Cli/dotnet/Commands/Tool/Search/ToolSearchCommand.cs index 3845b81f29d1..d27cbbbe6954 100644 --- a/src/Cli/dotnet/Commands/Tool/Search/ToolSearchCommand.cs +++ b/src/Cli/dotnet/Commands/Tool/Search/ToolSearchCommand.cs @@ -17,7 +17,7 @@ internal sealed class ToolSearchCommand( private readonly INugetToolSearchApiRequest _nugetToolSearchApiRequest = nugetToolSearchApiRequest ?? new NugetToolSearchApiRequest(); private readonly SearchResultPrinter _searchResultPrinter = new(Reporter.Output); - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { var isDetailed = _parseResult.GetValue(Definition.DetailOption); if (!PathUtility.CheckForNuGetInNuGetConfig()) @@ -28,7 +28,7 @@ public override int Execute() IReadOnlyCollection searchResultPackages = NugetSearchApiResultDeserializer.Deserialize( - _nugetToolSearchApiRequest.GetResult(GetNugetSearchApiParameter()).GetAwaiter().GetResult()); + _nugetToolSearchApiRequest.GetResult(GetNugetSearchApiParameter(), cancellationToken).GetAwaiter().GetResult()); _searchResultPrinter.Print(isDetailed, searchResultPackages); diff --git a/src/Cli/dotnet/Commands/Tool/Store/StoreCommand.cs b/src/Cli/dotnet/Commands/Tool/Store/StoreCommand.cs index 1345eb26f2c7..9086adde91b3 100644 --- a/src/Cli/dotnet/Commands/Tool/Store/StoreCommand.cs +++ b/src/Cli/dotnet/Commands/Tool/Store/StoreCommand.cs @@ -44,10 +44,10 @@ public static StoreCommand FromParseResult(ParseResult result, string msbuildPat return new StoreCommand(msbuildArgs, msbuildPath); } - public static int Run(ParseResult parseResult) + public static int Run(ParseResult parseResult, CancellationToken cancellationToken) { parseResult.HandleDebugSwitch(); - return FromParseResult(parseResult).Execute(); + return FromParseResult(parseResult).Execute(cancellationToken); } } diff --git a/src/Cli/dotnet/Commands/Tool/ToolCommandParser.cs b/src/Cli/dotnet/Commands/Tool/ToolCommandParser.cs index 2ec4797bd4f6..ae8d8992bb74 100644 --- a/src/Cli/dotnet/Commands/Tool/ToolCommandParser.cs +++ b/src/Cli/dotnet/Commands/Tool/ToolCommandParser.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.CommandLine; +using Microsoft.DotNet.Cli.CommandLine; #if !CLI_AOT using Microsoft.DotNet.Cli.Commands.Tool.Execute; using Microsoft.DotNet.Cli.Commands.Tool.Install; @@ -27,26 +28,28 @@ public static void ConfigureCommand(ToolCommandDefinition command) // `--global`/`--tool-path` variants and `install`/`update`/`restore`/`execute` keep the // default fallback because they depend on NuGet package install/restore infrastructure that // isn't AOT-ready. NativeEntryPoint catches the exception and hosts the managed CLI. - command.ListCommand.SetAction(parseResult => + command.ListCommand.SetAction((parseResult, cancellationToken) => command.ListCommand.LocationOptions.IsGlobalOrToolPath(parseResult) ? throw new CommandNotAvailableInAotException() - : new ToolListLocalCommand(parseResult).Execute()); - command.UninstallCommand.SetAction(parseResult => + : new ToolListLocalCommand(parseResult).Execute(cancellationToken)); + command.UninstallCommand.SetAction((parseResult, cancellationToken) => command.UninstallCommand.LocationOptions.IsGlobalOrToolPath(parseResult) ? throw new CommandNotAvailableInAotException() - : new ToolUninstallLocalCommand(parseResult).Execute()); - command.RunCommand.SetAction(parseResult => new ToolRunCommand(parseResult).Execute()); - command.SearchCommand.SetAction(parseResult => new ToolSearchCommand(parseResult).Execute()); + : new ToolUninstallLocalCommand(parseResult).Execute(cancellationToken)); + command.RunCommand.SetAction((parseResult, cancellationToken) => new ToolRunCommand(parseResult).Execute(cancellationToken)); + command.SearchCommand.SetAction( + (parseResult, cancellationToken) => new ToolSearchCommand(parseResult).Execute(cancellationToken)); #else command.SetAction(parseResult => parseResult.HandleMissingCommand()); command.InstallCommand.SetAction((parseResult, cancellationToken) => new ToolInstallCommand(parseResult).ExecuteAsync(cancellationToken)); - command.UninstallCommand.SetAction(parseResult => new ToolUninstallCommand(parseResult).Execute()); + command.UninstallCommand.SetAction((parseResult, cancellationToken) => new ToolUninstallCommand(parseResult).Execute(cancellationToken)); command.UpdateCommand.SetAction((parseResult, cancellationToken) => new ToolUpdateCommand(parseResult).ExecuteAsync(cancellationToken)); - command.ListCommand.SetAction(parseResult => new ToolListCommand(parseResult).Execute()); - command.RunCommand.SetAction(parseResult => new ToolRunCommand(parseResult).Execute()); - command.SearchCommand.SetAction(parseResult => new ToolSearchCommand(parseResult).Execute()); + command.ListCommand.SetAction((parseResult, cancellationToken) => new ToolListCommand(parseResult).Execute(cancellationToken)); + command.RunCommand.SetAction((parseResult, cancellationToken) => new ToolRunCommand(parseResult).Execute(cancellationToken)); + command.SearchCommand.SetAction( + (parseResult, cancellationToken) => new ToolSearchCommand(parseResult).Execute(cancellationToken)); command.RestoreCommand.SetAction((parseResult, cancellationToken) => new ToolRestoreCommand(parseResult).ExecuteAsync(cancellationToken)); command.ExecuteCommand.SetAction((parseResult, cancellationToken) => diff --git a/src/Cli/dotnet/Commands/Tool/Uninstall/ToolUninstallCommand.cs b/src/Cli/dotnet/Commands/Tool/Uninstall/ToolUninstallCommand.cs index 9490fa597fd6..b734ee031fb7 100644 --- a/src/Cli/dotnet/Commands/Tool/Uninstall/ToolUninstallCommand.cs +++ b/src/Cli/dotnet/Commands/Tool/Uninstall/ToolUninstallCommand.cs @@ -27,7 +27,7 @@ public ToolUninstallCommand( _toolPath = result.GetValue(Definition.LocationOptions.ToolPathOption); } - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { Definition.LocationOptions.EnsureNoConflictGlobalLocalToolPathOption( _parseResult, @@ -39,11 +39,11 @@ public override int Execute() if (_global || !string.IsNullOrWhiteSpace(_toolPath)) { - return _toolUninstallGlobalOrToolPathCommand.Execute(); + return _toolUninstallGlobalOrToolPathCommand.Execute(cancellationToken); } else { - return _toolUninstallLocalCommand.Execute(); + return _toolUninstallLocalCommand.Execute(cancellationToken); } } } diff --git a/src/Cli/dotnet/Commands/Tool/Uninstall/ToolUninstallGlobalOrToolPathCommand.cs b/src/Cli/dotnet/Commands/Tool/Uninstall/ToolUninstallGlobalOrToolPathCommand.cs index 7007c8042be0..747c26287c30 100644 --- a/src/Cli/dotnet/Commands/Tool/Uninstall/ToolUninstallGlobalOrToolPathCommand.cs +++ b/src/Cli/dotnet/Commands/Tool/Uninstall/ToolUninstallGlobalOrToolPathCommand.cs @@ -27,7 +27,7 @@ internal sealed class ToolUninstallGlobalOrToolPathCommand( private readonly CreateToolPackageStoresAndUninstaller _createToolPackageStoresAndUninstaller = createToolPackageStoreAndUninstaller ?? ToolPackageFactory.CreateToolPackageStoresAndUninstaller; - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { var global = _parseResult.GetValue(Definition.LocationOptions.GlobalOption); var toolPath = _parseResult.GetValue(Definition.LocationOptions.ToolPathOption); diff --git a/src/Cli/dotnet/Commands/Tool/Uninstall/ToolUninstallLocalCommand.cs b/src/Cli/dotnet/Commands/Tool/Uninstall/ToolUninstallLocalCommand.cs index b50dac23fc1f..3bb493b93d06 100644 --- a/src/Cli/dotnet/Commands/Tool/Uninstall/ToolUninstallLocalCommand.cs +++ b/src/Cli/dotnet/Commands/Tool/Uninstall/ToolUninstallLocalCommand.cs @@ -38,7 +38,7 @@ public ToolUninstallLocalCommand( _toolManifestEditor = toolManifestEditor ?? new ToolManifestEditor(); } - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { (FilePath? manifestFileOptional, string warningMessage) = _toolManifestFinder.ExplicitManifestOrFindManifestContainPackageId(_explicitManifestFile, _packageId); diff --git a/src/Cli/dotnet/Commands/Tool/Update/ToolUpdateCommand.cs b/src/Cli/dotnet/Commands/Tool/Update/ToolUpdateCommand.cs index 17916b6206e3..f4f05e6c5462 100644 --- a/src/Cli/dotnet/Commands/Tool/Update/ToolUpdateCommand.cs +++ b/src/Cli/dotnet/Commands/Tool/Update/ToolUpdateCommand.cs @@ -111,8 +111,8 @@ private void EnsureNoConflictUpdateAllVersionOption( } } - public override int Execute() - => ExecuteAsync(CancellationToken.None).GetAwaiter().GetResult(); + public override int Execute(CancellationToken cancellationToken) + => ExecuteAsync(cancellationToken).GetAwaiter().GetResult(); internal async Task ExecuteAsync(CancellationToken cancellationToken) { @@ -140,7 +140,7 @@ internal async Task ExecuteAsync(CancellationToken cancellationToken) } else { - return _toolUpdateLocalCommand.Execute(); + return _toolUpdateLocalCommand.Execute(cancellationToken); } } } diff --git a/src/Cli/dotnet/Commands/Tool/Update/ToolUpdateGlobalOrToolPathCommand.cs b/src/Cli/dotnet/Commands/Tool/Update/ToolUpdateGlobalOrToolPathCommand.cs index d2b7020dc5eb..fd75731808d9 100644 --- a/src/Cli/dotnet/Commands/Tool/Update/ToolUpdateGlobalOrToolPathCommand.cs +++ b/src/Cli/dotnet/Commands/Tool/Update/ToolUpdateGlobalOrToolPathCommand.cs @@ -45,8 +45,8 @@ public ToolUpdateGlobalOrToolPathCommand(ParseResult parseResult, store: _store); } - public override int Execute() - => ExecuteAsync(CancellationToken.None).GetAwaiter().GetResult(); + public override int Execute(CancellationToken cancellationToken) + => ExecuteAsync(cancellationToken).GetAwaiter().GetResult(); internal async Task ExecuteAsync(CancellationToken cancellationToken) { diff --git a/src/Cli/dotnet/Commands/Tool/Update/ToolUpdateLocalCommand.cs b/src/Cli/dotnet/Commands/Tool/Update/ToolUpdateLocalCommand.cs index 17f696b27330..fda7266ece07 100644 --- a/src/Cli/dotnet/Commands/Tool/Update/ToolUpdateLocalCommand.cs +++ b/src/Cli/dotnet/Commands/Tool/Update/ToolUpdateLocalCommand.cs @@ -48,9 +48,9 @@ public ToolUpdateLocalCommand( _reporter)); } - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { - _toolInstallLocalCommand.Value.Execute(); + _toolInstallLocalCommand.Value.Execute(cancellationToken); return 0; } diff --git a/src/Cli/dotnet/Commands/VSTest/VSTestCommand.cs b/src/Cli/dotnet/Commands/VSTest/VSTestCommand.cs index 1efea21b8c7a..bac27c3d38fb 100644 --- a/src/Cli/dotnet/Commands/VSTest/VSTestCommand.cs +++ b/src/Cli/dotnet/Commands/VSTest/VSTestCommand.cs @@ -12,7 +12,7 @@ namespace Microsoft.DotNet.Cli.Commands.VSTest; public class VSTestCommand { - public static int Run(ParseResult parseResult) + public static int Run(ParseResult parseResult, CancellationToken cancellationToken) { parseResult.HandleDebugSwitch(); @@ -32,10 +32,14 @@ public static int Run(ParseResult parseResult) VSTestForwardingApp vsTestforwardingApp = new(args); - int exitCode = vsTestforwardingApp.Execute(); + int exitCode = vsTestforwardingApp.Execute(cancellationToken); // We run post processing also if execution is failed for possible partial successful result to post process. - exitCode |= TestCommand.RunArtifactPostProcessingIfNeeded(testSessionCorrelationId, diag: null, FeatureFlag.Instance); + exitCode |= TestCommand.RunArtifactPostProcessingIfNeeded( + testSessionCorrelationId, + diag: null, + FeatureFlag.Instance, + cancellationToken); // Reached only when the invocation completed, whether the tests passed or failed. An invocation that // throws or is interrupted deliberately leaves the artifacts on disk for diagnosis. diff --git a/src/Cli/dotnet/Commands/VSTest/VSTestCommandParser.cs b/src/Cli/dotnet/Commands/VSTest/VSTestCommandParser.cs index 039c2a52f618..18b62b9c1511 100644 --- a/src/Cli/dotnet/Commands/VSTest/VSTestCommandParser.cs +++ b/src/Cli/dotnet/Commands/VSTest/VSTestCommandParser.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.CommandLine; +using Microsoft.DotNet.Cli.CommandLine; namespace Microsoft.DotNet.Cli.Commands.VSTest; @@ -9,6 +10,6 @@ internal static class VSTestCommandParser { public static void ConfigureCommand(VSTestCommandDefinition command) { - command.SetAction(VSTestCommand.Run); + command.SetAction((parseResult, cancellationToken) => VSTestCommand.Run(parseResult, cancellationToken)); } } diff --git a/src/Cli/dotnet/Commands/Workload/Clean/WorkloadCleanCommand.cs b/src/Cli/dotnet/Commands/Workload/Clean/WorkloadCleanCommand.cs index 773e2cce59e5..c8385f2d42a0 100644 --- a/src/Cli/dotnet/Commands/Workload/Clean/WorkloadCleanCommand.cs +++ b/src/Cli/dotnet/Commands/Workload/Clean/WorkloadCleanCommand.cs @@ -46,15 +46,16 @@ public WorkloadCleanCommand( _workloadInstaller = WorkloadInstallerFactory.GetWorkloadInstaller(Reporter, sdkFeatureBand, creationResult.WorkloadResolver, Verbosity, creationResult.UserProfileDir, VerifySignatures, PackageDownloader, creationResult.DotnetPath); } - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { - ExecuteGarbageCollection(); + ExecuteGarbageCollection(cancellationToken); return 0; } - private void ExecuteGarbageCollection() + private void ExecuteGarbageCollection(CancellationToken cancellationToken) { _workloadInstaller.GarbageCollect(workloadVersion => _workloadResolverFactory.CreateForWorkloadSet(_dotnetPath, _sdkVersion.ToString(), _userProfileDir, workloadVersion), + cancellationToken, cleanAllPacks: _cleanAll); DisplayUninstallableVSWorkloads(); diff --git a/src/Cli/dotnet/Commands/Workload/Config/WorkloadConfigCommand.cs b/src/Cli/dotnet/Commands/Workload/Config/WorkloadConfigCommand.cs index 67565a46d8fa..5cc4cdbbf9ce 100644 --- a/src/Cli/dotnet/Commands/Workload/Config/WorkloadConfigCommand.cs +++ b/src/Cli/dotnet/Commands/Workload/Config/WorkloadConfigCommand.cs @@ -44,7 +44,7 @@ public WorkloadConfigCommand( _workloadInstaller = WorkloadInstallerFactory.GetWorkloadInstaller(Reporter, _sdkFeatureBand, creationResult.WorkloadResolver, Verbosity, creationResult.UserProfileDir, VerifySignatures, PackageDownloader, creationResult.DotnetPath); } - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { // When we support multiple configuration values, it would be nice if we could process and display them in the order they are passed. // It seems that the parser doesn't give us a good way to do that, however diff --git a/src/Cli/dotnet/Commands/Workload/Elevate/WorkloadElevateCommand.cs b/src/Cli/dotnet/Commands/Workload/Elevate/WorkloadElevateCommand.cs index c300aeec35bb..10760cdc6957 100644 --- a/src/Cli/dotnet/Commands/Workload/Elevate/WorkloadElevateCommand.cs +++ b/src/Cli/dotnet/Commands/Workload/Elevate/WorkloadElevateCommand.cs @@ -13,7 +13,7 @@ namespace Microsoft.DotNet.Cli.Commands.Workload.Elevate; internal class WorkloadElevateCommand(ParseResult parseResult) : WorkloadCommandBase(parseResult) { - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { if (!OperatingSystem.IsWindows()) { diff --git a/src/Cli/dotnet/Commands/Workload/History/WorkloadHistoryCommand.cs b/src/Cli/dotnet/Commands/Workload/History/WorkloadHistoryCommand.cs index dbc522dd4ff1..efd7e1113277 100644 --- a/src/Cli/dotnet/Commands/Workload/History/WorkloadHistoryCommand.cs +++ b/src/Cli/dotnet/Commands/Workload/History/WorkloadHistoryCommand.cs @@ -40,7 +40,7 @@ public WorkloadHistoryCommand( packageSourceLocation: null); } - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { var displayRecords = WorkloadHistoryDisplay.ProcessWorkloadHistoryRecords(_workloadInstaller.GetWorkloadHistoryRecords(_sdkFeatureBand.ToString()), out bool unknownRecordsPresent); diff --git a/src/Cli/dotnet/Commands/Workload/Install/FileBasedInstaller.cs b/src/Cli/dotnet/Commands/Workload/Install/FileBasedInstaller.cs index 1d14639910e3..aefc7e42fc53 100644 --- a/src/Cli/dotnet/Commands/Workload/Install/FileBasedInstaller.cs +++ b/src/Cli/dotnet/Commands/Workload/Install/FileBasedInstaller.cs @@ -100,8 +100,13 @@ IEnumerable GetPacksInWorkloads(IEnumerable workloadIds) return packs; } - public WorkloadSet InstallWorkloadSet(ITransactionContext context, string workloadSetVersion, DirectoryPath? offlineCache = null) + public WorkloadSet InstallWorkloadSet( + ITransactionContext context, + string workloadSetVersion, + CancellationToken cancellationToken, + DirectoryPath? offlineCache = null) { + cancellationToken.ThrowIfCancellationRequested(); var workloadSetFeatureBand = SdkFeatureBand.FromWorkloadSetVersion(workloadSetVersion, out var workloadSetPackageVersion); var workloadSetPackageId = GetManifestPackageId(new ManifestId(WorkloadManifestUpdater.WorkloadSetManifestId), workloadSetFeatureBand); @@ -109,7 +114,7 @@ public WorkloadSet InstallWorkloadSet(ITransactionContext context, string worklo try { - InstallPackage(workloadSetPackageId, workloadSetPackageVersion, workloadSetPath, context, offlineCache); + InstallPackage(workloadSetPackageId, workloadSetPackageVersion, workloadSetPath, context, cancellationToken, offlineCache); context.Run( action: () => { @@ -120,7 +125,7 @@ public WorkloadSet InstallWorkloadSet(ITransactionContext context, string worklo RemoveWorkloadSetInstallationRecord(workloadSetVersion, workloadSetFeatureBand, _sdkFeatureBand); }); } - catch (Exception ex) + catch (Exception ex) when (ex is not OperationCanceledException) { throw new Exception(string.Format(CliCommandStrings.FailedToInstallWorkloadSet, workloadSetVersion, ex.Message), ex); } @@ -128,25 +133,40 @@ public WorkloadSet InstallWorkloadSet(ITransactionContext context, string worklo return WorkloadSet.FromWorkloadSetFolder(workloadSetPath, workloadSetVersion, _sdkFeatureBand); } - public WorkloadSet GetWorkloadSetContents(string workloadSetVersion) => GetWorkloadSetContentsAsync(workloadSetVersion).GetAwaiter().GetResult(); + public WorkloadSet GetWorkloadSetContents(string workloadSetVersion, CancellationToken cancellationToken) + => GetWorkloadSetContentsAsync(workloadSetVersion, cancellationToken).GetAwaiter().GetResult(); - public async Task GetWorkloadSetContentsAsync(string workloadSetVersion) + public async Task GetWorkloadSetContentsAsync( + string workloadSetVersion, + CancellationToken cancellationToken) { var workloadSetFeatureBand = SdkFeatureBand.FromWorkloadSetVersion(workloadSetVersion, out var workloadSetPackageVersion); var packagePath = await _nugetPackageDownloader.DownloadPackageAsync(GetManifestPackageId(new ManifestId(WorkloadManifestUpdater.WorkloadSetManifestId), workloadSetFeatureBand), - new NuGetVersion(workloadSetPackageVersion), _packageSourceLocation); + cancellationToken, new NuGetVersion(workloadSetPackageVersion), _packageSourceLocation); var tempExtractionDir = Path.Combine(_tempPackagesDir.Value, $"{WorkloadManifestUpdater.WorkloadSetManifestId}-{workloadSetPackageVersion}-extracted"); - await ExtractManifestAsync(packagePath, tempExtractionDir); + await ExtractManifestAsync(packagePath, tempExtractionDir, cancellationToken); return WorkloadSet.FromWorkloadSetFolder(tempExtractionDir, workloadSetVersion, _sdkFeatureBand); } - public void InstallWorkloads(IEnumerable workloadIds, SdkFeatureBand sdkFeatureBand, ITransactionContext transactionContext, DirectoryPath? offlineCache = null) + public void InstallWorkloads( + IEnumerable workloadIds, + SdkFeatureBand sdkFeatureBand, + ITransactionContext transactionContext, + CancellationToken cancellationToken, + DirectoryPath? offlineCache = null) { - InstallWorkloads(workloadIds, sdkFeatureBand, transactionContext, overwriteExistingPacks: false, offlineCache); + InstallWorkloads(workloadIds, sdkFeatureBand, transactionContext, cancellationToken, overwriteExistingPacks: false, offlineCache); } - public void InstallWorkloads(IEnumerable workloadIds, SdkFeatureBand sdkFeatureBand, ITransactionContext transactionContext, bool overwriteExistingPacks, DirectoryPath? offlineCache = null) + public void InstallWorkloads( + IEnumerable workloadIds, + SdkFeatureBand sdkFeatureBand, + ITransactionContext transactionContext, + CancellationToken cancellationToken, + bool overwriteExistingPacks, + DirectoryPath? offlineCache = null) { + cancellationToken.ThrowIfCancellationRequested(); var packInfos = GetPacksInWorkloads(workloadIds); List packsToInstall = []; foreach (var packInfo in packInfos) @@ -169,6 +189,7 @@ public void InstallWorkloads(IEnumerable workloadIds, SdkFeatureBand { var packagePath = _nugetPackageDownloader .DownloadPackageAsync(new PackageId(packInfo.ResolvedPackageId), + cancellationToken, new NuGetVersion(packInfo.Version), _packageSourceLocation).GetAwaiter().GetResult(); tempFilesToDelete.Add(packagePath); @@ -215,7 +236,10 @@ public void InstallWorkloads(IEnumerable workloadIds, SdkFeatureBand } Directory.CreateDirectory(tempExtractionDir); - var packFiles = _nugetPackageDownloader.ExtractPackageAsync(packagePath, new DirectoryPath(tempExtractionDir)).GetAwaiter().GetResult(); + var packFiles = _nugetPackageDownloader.ExtractPackageAsync( + packagePath, + new DirectoryPath(tempExtractionDir), + cancellationToken).GetAwaiter().GetResult(); if (overwriteExistingPacks && Directory.Exists(packInfo.Path)) { @@ -265,9 +289,19 @@ public void InstallWorkloads(IEnumerable workloadIds, SdkFeatureBand } } - public void RepairWorkloads(IEnumerable workloadIds, SdkFeatureBand sdkFeatureBand, DirectoryPath? offlineCache = null) + public void RepairWorkloads( + IEnumerable workloadIds, + SdkFeatureBand sdkFeatureBand, + CancellationToken cancellationToken, + DirectoryPath? offlineCache = null) { - CliTransaction.RunNew(context => InstallWorkloads(workloadIds, sdkFeatureBand, context, overwriteExistingPacks: true, offlineCache)); + CliTransaction.RunNew(context => InstallWorkloads( + workloadIds, + sdkFeatureBand, + context, + cancellationToken, + overwriteExistingPacks: true, + offlineCache)); } string GetManifestInstallDirForFeatureBand(string sdkFeatureBand) @@ -275,8 +309,13 @@ string GetManifestInstallDirForFeatureBand(string sdkFeatureBand) return Path.Combine(_workloadRootDir, "sdk-manifests", sdkFeatureBand); } - public void InstallWorkloadManifest(ManifestVersionUpdate manifestUpdate, ITransactionContext transactionContext, DirectoryPath? offlineCache = null) + public void InstallWorkloadManifest( + ManifestVersionUpdate manifestUpdate, + ITransactionContext transactionContext, + CancellationToken cancellationToken, + DirectoryPath? offlineCache = null) { + cancellationToken.ThrowIfCancellationRequested(); var newManifestPath = Path.Combine(GetManifestInstallDirForFeatureBand(manifestUpdate.NewFeatureBand), manifestUpdate.ManifestId.ToString(), manifestUpdate.NewVersion.ToString()); _reporter.WriteLine(string.Format(CliCommandStrings.InstallingWorkloadManifest, manifestUpdate.ManifestId, manifestUpdate.NewVersion)); @@ -285,7 +324,7 @@ public void InstallWorkloadManifest(ManifestVersionUpdate manifestUpdate, ITrans { var newManifestPackageId = GetManifestPackageId(manifestUpdate.ManifestId, new SdkFeatureBand(manifestUpdate.NewFeatureBand)); - InstallPackage(newManifestPackageId, manifestUpdate.NewVersion.ToString(), newManifestPath, transactionContext, offlineCache); + InstallPackage(newManifestPackageId, manifestUpdate.NewVersion.ToString(), newManifestPath, transactionContext, cancellationToken, offlineCache); transactionContext.Run( action: () => @@ -297,13 +336,19 @@ public void InstallWorkloadManifest(ManifestVersionUpdate manifestUpdate, ITrans RemoveManifestInstallationRecord(manifestUpdate.ManifestId, manifestUpdate.NewVersion, new SdkFeatureBand(manifestUpdate.NewFeatureBand), _sdkFeatureBand); }); } - catch (Exception e) + catch (Exception e) when (e is not OperationCanceledException) { throw new Exception(string.Format(CliCommandStrings.FailedToInstallWorkloadManifest, manifestUpdate.ManifestId, manifestUpdate.NewVersion, e.Message), e); } } - void InstallPackage(PackageId packageId, string packageVersion, string targetFolder, ITransactionContext transactionContext, DirectoryPath? offlineCache) + void InstallPackage( + PackageId packageId, + string packageVersion, + string targetFolder, + ITransactionContext transactionContext, + CancellationToken cancellationToken, + DirectoryPath? offlineCache) { string packagePath = null; string tempBackupDir = null; @@ -315,7 +360,7 @@ void InstallPackage(PackageId packageId, string packageVersion, string targetFol if (offlineCache == null || !offlineCache.HasValue) { packagePath = _nugetPackageDownloader.DownloadPackageAsync(packageId, - new NuGetVersion(packageVersion), _packageSourceLocation).GetAwaiter().GetResult(); + cancellationToken, new NuGetVersion(packageVersion), _packageSourceLocation).GetAwaiter().GetResult(); } else { @@ -337,7 +382,7 @@ void InstallPackage(PackageId packageId, string packageVersion, string targetFol FileAccessRetrier.RetryOnMoveAccessFailure(() => DirectoryPath.MoveDirectory(targetFolder, tempBackupDir)); } - ExtractManifestAsync(packagePath, targetFolder).GetAwaiter().GetResult(); + ExtractManifestAsync(packagePath, targetFolder, cancellationToken).GetAwaiter().GetResult(); }, rollback: () => @@ -394,8 +439,13 @@ public IEnumerable GetDownloads(IEnumerable worklo return [.. packs.Select(p => new WorkloadDownload(p.Id, p.ResolvedPackageId, p.Version))]; } - public void GarbageCollect(Func getResolverForWorkloadSet, DirectoryPath? offlineCache = null, bool cleanAllPacks = false) + public void GarbageCollect( + Func getResolverForWorkloadSet, + CancellationToken cancellationToken, + DirectoryPath? offlineCache = null, + bool cleanAllPacks = false) { + cancellationToken.ThrowIfCancellationRequested(); var globalJsonWorkloadSetVersions = GetGlobalJsonWorkloadSetVersions(_sdkFeatureBand); var garbageCollector = new WorkloadGarbageCollector(_workloadRootDir, @@ -654,8 +704,11 @@ public void Shutdown() public PackageId GetManifestPackageId(ManifestId manifestId, SdkFeatureBand featureBand) => _manifestInstaller.GetManifestPackageId(manifestId, featureBand); - public Task ExtractManifestAsync(string nupkgPath, string targetPath) - => _manifestInstaller.ExtractManifestAsync(nupkgPath, targetPath); + public Task ExtractManifestAsync( + string nupkgPath, + string targetPath, + CancellationToken cancellationToken) + => _manifestInstaller.ExtractManifestAsync(nupkgPath, targetPath, cancellationToken); private bool PackIsInstalled(PackInfo packInfo) { diff --git a/src/Cli/dotnet/Commands/Workload/Install/FileBasedManifestInstaller.cs b/src/Cli/dotnet/Commands/Workload/Install/FileBasedManifestInstaller.cs index 584ded780460..fc1860cd04ad 100644 --- a/src/Cli/dotnet/Commands/Workload/Install/FileBasedManifestInstaller.cs +++ b/src/Cli/dotnet/Commands/Workload/Install/FileBasedManifestInstaller.cs @@ -36,8 +36,12 @@ public PackageId GetManifestPackageId(ManifestId manifestId, SdkFeatureBand feat } } - public async Task ExtractManifestAsync(string nupkgPath, string targetPath) + public async Task ExtractManifestAsync( + string nupkgPath, + string targetPath, + CancellationToken cancellationToken) { + cancellationToken.ThrowIfCancellationRequested(); var extractionPath = Path.Combine(tempPackagesDir.Value, "dotnet-sdk-advertising-temp", $"{Path.GetFileName(nupkgPath)}-extracted"); if (Directory.Exists(extractionPath)) { @@ -47,7 +51,10 @@ public async Task ExtractManifestAsync(string nupkgPath, string targetPath) try { Directory.CreateDirectory(extractionPath); - await nugetPackageDownloader.ExtractPackageAsync(nupkgPath, new DirectoryPath(extractionPath)); + await nugetPackageDownloader.ExtractPackageAsync( + nupkgPath, + new DirectoryPath(extractionPath), + cancellationToken); if (Directory.Exists(targetPath)) { Directory.Delete(targetPath, true); diff --git a/src/Cli/dotnet/Commands/Workload/Install/IInstaller.cs b/src/Cli/dotnet/Commands/Workload/Install/IInstaller.cs index 18d2dd3ea256..cb28410f0009 100644 --- a/src/Cli/dotnet/Commands/Workload/Install/IInstaller.cs +++ b/src/Cli/dotnet/Commands/Workload/Install/IInstaller.cs @@ -14,17 +14,38 @@ internal interface IInstaller : IWorkloadManifestInstaller { int ExitCode { get; } - WorkloadSet GetWorkloadSetContents(string workloadVersion); - - void InstallWorkloads(IEnumerable workloadIds, SdkFeatureBand sdkFeatureBand, ITransactionContext transactionContext, DirectoryPath? offlineCache = null); - - void RepairWorkloads(IEnumerable workloadIds, SdkFeatureBand sdkFeatureBand, DirectoryPath? offlineCache = null); - - void GarbageCollect(Func getResolverForWorkloadSet, DirectoryPath? offlineCache = null, bool cleanAllPacks = false); - - WorkloadSet InstallWorkloadSet(ITransactionContext context, string workloadSetVersion, DirectoryPath? offlineCache = null); - - void InstallWorkloadManifest(ManifestVersionUpdate manifestUpdate, ITransactionContext transactionContext, DirectoryPath? offlineCache = null); + WorkloadSet GetWorkloadSetContents(string workloadVersion, CancellationToken cancellationToken); + + void InstallWorkloads( + IEnumerable workloadIds, + SdkFeatureBand sdkFeatureBand, + ITransactionContext transactionContext, + CancellationToken cancellationToken, + DirectoryPath? offlineCache = null); + + void RepairWorkloads( + IEnumerable workloadIds, + SdkFeatureBand sdkFeatureBand, + CancellationToken cancellationToken, + DirectoryPath? offlineCache = null); + + void GarbageCollect( + Func getResolverForWorkloadSet, + CancellationToken cancellationToken, + DirectoryPath? offlineCache = null, + bool cleanAllPacks = false); + + WorkloadSet InstallWorkloadSet( + ITransactionContext context, + string workloadSetVersion, + CancellationToken cancellationToken, + DirectoryPath? offlineCache = null); + + void InstallWorkloadManifest( + ManifestVersionUpdate manifestUpdate, + ITransactionContext transactionContext, + CancellationToken cancellationToken, + DirectoryPath? offlineCache = null); IWorkloadInstallationRecordRepository GetWorkloadInstallationRecordRepository(); diff --git a/src/Cli/dotnet/Commands/Workload/Install/IWorkloadManifestInstaller.cs b/src/Cli/dotnet/Commands/Workload/Install/IWorkloadManifestInstaller.cs index 058ebc9327da..d555368d8c57 100644 --- a/src/Cli/dotnet/Commands/Workload/Install/IWorkloadManifestInstaller.cs +++ b/src/Cli/dotnet/Commands/Workload/Install/IWorkloadManifestInstaller.cs @@ -10,5 +10,5 @@ internal interface IWorkloadManifestInstaller { PackageId GetManifestPackageId(ManifestId manifestId, SdkFeatureBand featureBand); - Task ExtractManifestAsync(string nupkgPath, string targetPath); + Task ExtractManifestAsync(string nupkgPath, string targetPath, CancellationToken cancellationToken); } diff --git a/src/Cli/dotnet/Commands/Workload/Install/IWorkloadManifestUpdater.cs b/src/Cli/dotnet/Commands/Workload/Install/IWorkloadManifestUpdater.cs index 0ab59552e0f3..d1a787170bff 100644 --- a/src/Cli/dotnet/Commands/Workload/Install/IWorkloadManifestUpdater.cs +++ b/src/Cli/dotnet/Commands/Workload/Install/IWorkloadManifestUpdater.cs @@ -10,9 +10,13 @@ namespace Microsoft.DotNet.Cli.Commands.Workload.Install; internal interface IWorkloadManifestUpdater { - Task UpdateAdvertisingManifestsAsync(bool includePreviews, bool useWorkloadSets = false, DirectoryPath? offlineCache = null); + Task UpdateAdvertisingManifestsAsync( + CancellationToken cancellationToken, + bool includePreviews, + bool useWorkloadSets = false, + DirectoryPath? offlineCache = null); - Task BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(); + Task BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(CancellationToken cancellationToken); IEnumerable CalculateManifestUpdates(); @@ -21,7 +25,11 @@ internal interface IWorkloadManifestUpdater IEnumerable CalculateManifestUpdatesFromHistory(WorkloadHistoryState state); IEnumerable CalculateManifestUpdatesForWorkloadSet(WorkloadSet workloadSet); - Task> GetManifestPackageDownloadsAsync(bool includePreviews, SdkFeatureBand providedSdkFeatureBand, SdkFeatureBand installedSdkFeatureBand); + Task> GetManifestPackageDownloadsAsync( + CancellationToken cancellationToken, + bool includePreviews, + SdkFeatureBand providedSdkFeatureBand, + SdkFeatureBand installedSdkFeatureBand); IEnumerable GetUpdatableWorkloadsToAdvertise(IEnumerable installedWorkloads); diff --git a/src/Cli/dotnet/Commands/Workload/Install/MsiInstallerBase.cs b/src/Cli/dotnet/Commands/Workload/Install/MsiInstallerBase.cs index 289e37412a9e..55deab8677ed 100644 --- a/src/Cli/dotnet/Commands/Workload/Install/MsiInstallerBase.cs +++ b/src/Cli/dotnet/Commands/Workload/Install/MsiInstallerBase.cs @@ -500,7 +500,7 @@ protected void ReportOnce(string message) /// The action to perform on the provider key. /// The provider key to update. /// The dependent to add or remove. - protected void UpdateDependent(InstallRequestType requestType, string providerKeyName, string dependent) + protected virtual void UpdateDependent(InstallRequestType requestType, string providerKeyName, string dependent) { DependencyProvider provider = new(providerKeyName, allUsers: true); diff --git a/src/Cli/dotnet/Commands/Workload/Install/NetSdkMsiInstallerClient.cs b/src/Cli/dotnet/Commands/Workload/Install/NetSdkMsiInstallerClient.cs index da5f7cc84e71..8ca77b01a6c4 100644 --- a/src/Cli/dotnet/Commands/Workload/Install/NetSdkMsiInstallerClient.cs +++ b/src/Cli/dotnet/Commands/Workload/Install/NetSdkMsiInstallerClient.cs @@ -126,8 +126,13 @@ private class SetupLogReporter(ISetupLogger setupLogger) : IReporter /// /// Cleans up and removes stale workload packs. /// - public void GarbageCollect(Func getResolverForWorkloadSet, DirectoryPath? offlineCache = null, bool cleanAllPacks = false) + public void GarbageCollect( + Func getResolverForWorkloadSet, + CancellationToken cancellationToken, + DirectoryPath? offlineCache = null, + bool cleanAllPacks = false) { + cancellationToken.ThrowIfCancellationRequested(); try { ReportPendingReboot(); @@ -189,7 +194,7 @@ public void GarbageCollect(Func getResolverForWorkloa } } - RemoveWorkloadSets(workloadSetsToRemove, offlineCache); + RemoveWorkloadSets(workloadSetsToRemove, cancellationToken, offlineCache); List manifestsToRemove = []; var installedWorkloadManifests = GetWorkloadManifestRecords(); @@ -239,7 +244,7 @@ public void GarbageCollect(Func getResolverForWorkloa } - RemoveWorkloadManifests(manifestsToRemove, offlineCache); + RemoveWorkloadManifests(manifestsToRemove, cancellationToken, offlineCache); // If aliased, the pack records here are the resolved pack from the alias IEnumerable installedWorkloadPacks = GetWorkloadPackRecords(); @@ -299,7 +304,7 @@ public void GarbageCollect(Func getResolverForWorkloa } } - RemoveWorkloadPacks(packsToRemove, offlineCache); + RemoveWorkloadPacks(packsToRemove, cancellationToken, offlineCache); if (cleanAllPacks) { @@ -313,11 +318,19 @@ public void GarbageCollect(Func getResolverForWorkloa } } - public WorkloadSet InstallWorkloadSet(ITransactionContext context, string workloadSetVersion, DirectoryPath? offlineCache) + public WorkloadSet InstallWorkloadSet( + ITransactionContext context, + string workloadSetVersion, + CancellationToken cancellationToken, + DirectoryPath? offlineCache) { + cancellationToken.ThrowIfCancellationRequested(); ReportPendingReboot(); - var (msi, msiPackageId, installationFolder) = GetWorkloadSetPayload(workloadSetVersion, offlineCache); + var (msi, msiPackageId, installationFolder) = GetWorkloadSetPayload( + workloadSetVersion, + cancellationToken, + offlineCache); context.Run( action: () => @@ -354,7 +367,10 @@ public WorkloadSet InstallWorkloadSet(ITransactionContext context, string worklo return WorkloadSet.FromWorkloadSetFolder(installationFolder, workloadSetVersion, _sdkFeatureBand); } - (MsiPayload msi, string msiPackageId, string installationFolder) GetWorkloadSetPayload(string workloadSetVersion, DirectoryPath? offlineCache) + (MsiPayload msi, string msiPackageId, string installationFolder) GetWorkloadSetPayload( + string workloadSetVersion, + CancellationToken cancellationToken, + DirectoryPath? offlineCache) { var workloadSetFeatureBand = SdkFeatureBand.FromWorkloadSetVersion(workloadSetVersion, out var msiPackageVersion); string msiPackageId = GetManifestPackageId(new ManifestId("Microsoft.NET.Workloads"), workloadSetFeatureBand).ToString(); @@ -365,7 +381,7 @@ public WorkloadSet InstallWorkloadSet(ITransactionContext context, string worklo MsiPayload msi; try { - msi = GetCachedMsiPayload(msiPackageId, msiPackageVersion, offlineCache); + msi = GetCachedMsiPayload(msiPackageId, msiPackageVersion, cancellationToken, offlineCache); } // Unwrap AggregateException caused by switch from async to sync catch (Exception ex) when (ex is NuGetPackageNotFoundException || ex.InnerException is NuGetPackageNotFoundException) @@ -430,15 +446,19 @@ private void UpdateDependentReferenceCounts( } } - private void RemoveWorkloadSets(List workloadSetsToRemove, DirectoryPath? offlineCache) + private void RemoveWorkloadSets( + List workloadSetsToRemove, + CancellationToken cancellationToken, + DirectoryPath? offlineCache) { foreach (WorkloadSetRecord record in workloadSetsToRemove) { + cancellationToken.ThrowIfCancellationRequested(); DetectState state = DetectPackage(record.ProductCode, out Version _); if (state == DetectState.Present) { string msiNuGetPackageId = $"Microsoft.NET.Workloads.{record.WorkloadSetFeatureBand}.Msi.{HostArchitecture}"; - MsiPayload msi = GetCachedMsiPayload(msiNuGetPackageId, record.WorkloadSetPackageVersion, offlineCache); + MsiPayload msi = GetCachedMsiPayload(msiNuGetPackageId, record.WorkloadSetPackageVersion, cancellationToken, offlineCache); if (!string.Equals(record.ProductCode, msi.ProductCode, StringComparison.OrdinalIgnoreCase)) { @@ -456,15 +476,19 @@ private void RemoveWorkloadSets(List workloadSetsToRemove, Di } } - private void RemoveWorkloadManifests(List manifestToRemove, DirectoryPath? offlineCache) + private void RemoveWorkloadManifests( + List manifestToRemove, + CancellationToken cancellationToken, + DirectoryPath? offlineCache) { foreach (WorkloadManifestRecord record in manifestToRemove) { + cancellationToken.ThrowIfCancellationRequested(); DetectState state = DetectPackage(record.ProductCode, out Version _); if (state == DetectState.Present) { string msiNuGetPackageId = $"{record.ManifestId}.Manifest-{record.ManifestFeatureBand}.Msi.{HostArchitecture}"; - MsiPayload msi = GetCachedMsiPayload(msiNuGetPackageId, record.ManifestVersion, offlineCache); + MsiPayload msi = GetCachedMsiPayload(msiNuGetPackageId, record.ManifestVersion, cancellationToken, offlineCache); if (!string.Equals(record.ProductCode, msi.ProductCode, StringComparison.OrdinalIgnoreCase)) { @@ -482,10 +506,14 @@ private void RemoveWorkloadManifests(List manifestToRemo } } - private void RemoveWorkloadPacks(List packsToRemove, DirectoryPath? offlineCache) + private void RemoveWorkloadPacks( + List packsToRemove, + CancellationToken cancellationToken, + DirectoryPath? offlineCache) { foreach (WorkloadPackRecord record in packsToRemove) { + cancellationToken.ThrowIfCancellationRequested(); // We need to make sure the product is actually installed and that we're not dealing with an orphaned record, e.g. // if a previous removal was interrupted. We can't safely clean up orphaned records because it's too expensive // to query all installed components and determine the product codes associated with the component that @@ -496,7 +524,7 @@ private void RemoveWorkloadPacks(List packsToRemove, Directo { // Manually construct the MSI payload package details string id = $"{record.MsiId}.Msi.{HostArchitecture}"; - MsiPayload msi = GetCachedMsiPayload(id, record.MsiNuGetVersion.ToString(), offlineCache); + MsiPayload msi = GetCachedMsiPayload(id, record.MsiNuGetVersion.ToString(), cancellationToken, offlineCache); // Make sure the package we have in the cache matches with the record. If it doesn't, we'll do the uninstall // the hard way @@ -544,18 +572,35 @@ private void DeleteAllWorkloadInstallationRecords() public IWorkloadInstallationRecordRepository GetWorkloadInstallationRecordRepository() => RecordRepository; - public void InstallWorkloadManifest(ManifestVersionUpdate manifestUpdate, ITransactionContext transactionContext, DirectoryPath? offlineCache = null) + public void InstallWorkloadManifest( + ManifestVersionUpdate manifestUpdate, + ITransactionContext transactionContext, + CancellationToken cancellationToken, + DirectoryPath? offlineCache = null) { + bool shouldRollBackManifest = false; try { transactionContext.Run( action: () => { - InstallWorkloadManifestImplementation(manifestUpdate, offlineCache); + InstallWorkloadManifestImplementation(manifestUpdate, cancellationToken, offlineCache, + onInstallAttempt: () => shouldRollBackManifest = true); }, rollback: () => { - InstallWorkloadManifestImplementation(manifestUpdate, offlineCache: null, action: InstallAction.Uninstall); + if (!shouldRollBackManifest) + { + return; + } + + // Rollback has its own lifetime, independent of the cancelled forward operation. + using CancellationTokenSource rollbackCancellation = new(); + InstallWorkloadManifestImplementation( + manifestUpdate, + rollbackCancellation.Token, + offlineCache: null, + action: InstallAction.Uninstall); }); } catch (Exception e) @@ -565,8 +610,14 @@ public void InstallWorkloadManifest(ManifestVersionUpdate manifestUpdate, ITrans } } - void InstallWorkloadManifestImplementation(ManifestVersionUpdate manifestUpdate, DirectoryPath? offlineCache = null, InstallAction action = InstallAction.Install) + void InstallWorkloadManifestImplementation( + ManifestVersionUpdate manifestUpdate, + CancellationToken cancellationToken, + DirectoryPath? offlineCache = null, + InstallAction action = InstallAction.Install, + Action onInstallAttempt = null) { + cancellationToken.ThrowIfCancellationRequested(); ReportPendingReboot(); // Rolling back a manifest update after a successful install is essentially a downgrade, which is blocked so we have to @@ -581,27 +632,38 @@ void InstallWorkloadManifestImplementation(ManifestVersionUpdate manifestUpdate, Log?.LogMessage($"Resolving {manifestUpdate.ManifestId} ({manifestUpdate.NewVersion}) to {msiPackageId} ({msiPackageVersion})."); // Retrieve the payload from the MSI package cache. - MsiPayload msi = GetCachedMsiPayload(msiPackageId, msiPackageVersion, offlineCache); + MsiPayload msi = GetCachedMsiPayload(msiPackageId, msiPackageVersion, cancellationToken, offlineCache); ValidateMsiDatabase(msi); DetectState state = DetectPackage(msi.ProductCode, out Version installedVersion); InstallAction plannedAction = PlanPackage(msi, state, action, installedVersion); + if (plannedAction == InstallAction.Install) + { + onInstallAttempt?.Invoke(); + } + ExecutePackage(msi, plannedAction, msiPackageId); // Update the reference count against the MSI. UpdateDependent(InstallRequestType.AddDependent, msi.Manifest.ProviderKeyName, _dependent); } - public void RepairWorkloads(IEnumerable workloadIds, SdkFeatureBand sdkFeatureBand, DirectoryPath? offlineCache = null) + public void RepairWorkloads( + IEnumerable workloadIds, + SdkFeatureBand sdkFeatureBand, + CancellationToken cancellationToken, + DirectoryPath? offlineCache = null) { + cancellationToken.ThrowIfCancellationRequested(); try { ReportPendingReboot(); foreach (var aquirableMsi in GetMsisForWorkloads(workloadIds)) { + cancellationToken.ThrowIfCancellationRequested(); // Retrieve the payload from the MSI package cache. - MsiPayload msi = GetCachedMsiPayload(aquirableMsi.NuGetPackageId, aquirableMsi.NuGetPackageVersion, offlineCache); + MsiPayload msi = GetCachedMsiPayload(aquirableMsi.NuGetPackageId, aquirableMsi.NuGetPackageVersion, cancellationToken, offlineCache); ValidateMsiDatabase(msi); DetectState state = DetectPackage(msi, out Version installedVersion); InstallAction plannedAction = PlanPackage(msi, state, InstallAction.Repair, installedVersion); @@ -618,14 +680,21 @@ public void RepairWorkloads(IEnumerable workloadIds, SdkFeatureBand } } - public void InstallWorkloads(IEnumerable workloadIds, SdkFeatureBand sdkFeatureBand, ITransactionContext transactionContext, DirectoryPath? offlineCache = null) + public void InstallWorkloads( + IEnumerable workloadIds, + SdkFeatureBand sdkFeatureBand, + ITransactionContext transactionContext, + CancellationToken cancellationToken, + DirectoryPath? offlineCache = null) { + cancellationToken.ThrowIfCancellationRequested(); ReportPendingReboot(); var msisToInstall = GetMsisForWorkloads(workloadIds); foreach (var msiToInstall in msisToInstall) { + cancellationToken.ThrowIfCancellationRequested(); bool shouldRollBackPack = false; transactionContext.Run(action: () => @@ -633,7 +702,7 @@ public void InstallWorkloads(IEnumerable workloadIds, SdkFeatureBand try { // Retrieve the payload from the MSI package cache. - MsiPayload msi = GetCachedMsiPayload(msiToInstall.NuGetPackageId, msiToInstall.NuGetPackageVersion, offlineCache); + MsiPayload msi = GetCachedMsiPayload(msiToInstall.NuGetPackageId, msiToInstall.NuGetPackageVersion, cancellationToken, offlineCache); ValidateMsiDatabase(msi); DetectState state = DetectPackage(msi, out Version installedVersion); InstallAction plannedAction = PlanPackage(msi, state, InstallAction.Install, installedVersion); @@ -656,7 +725,9 @@ public void InstallWorkloads(IEnumerable workloadIds, SdkFeatureBand { if (shouldRollBackPack) { - RollBackMsiInstall(msiToInstall); + // Rollback has its own lifetime, independent of the cancelled forward operation. + using CancellationTokenSource rollbackCancellation = new(); + RollBackMsiInstall(msiToInstall, rollbackCancellation.Token); } }); } @@ -671,7 +742,10 @@ public void WriteWorkloadInstallRecords(IEnumerable workloadsToWrite } } - void RollBackMsiInstall(WorkloadDownload msiToRollback, DirectoryPath? offlineCache = null) + void RollBackMsiInstall( + WorkloadDownload msiToRollback, + CancellationToken cancellationToken, + DirectoryPath? offlineCache = null) { try { @@ -679,7 +753,7 @@ void RollBackMsiInstall(WorkloadDownload msiToRollback, DirectoryPath? offlineCa Log?.LogMessage($"Rolling back workload pack installation for {msiToRollback.NuGetPackageId}."); // Retrieve the payload from the MSI package cache. - MsiPayload msi = GetCachedMsiPayload(msiToRollback.NuGetPackageId, msiToRollback.NuGetPackageVersion, offlineCache); + MsiPayload msi = GetCachedMsiPayload(msiToRollback.NuGetPackageId, msiToRollback.NuGetPackageVersion, cancellationToken, offlineCache); ValidateMsiDatabase(msi); // Check the provider key first in case we were installed and we only need to remove @@ -741,8 +815,11 @@ public void Shutdown() public PackageId GetManifestPackageId(ManifestId manifestId, SdkFeatureBand featureBand) => _manifestInstaller.GetManifestPackageId(manifestId, featureBand); - public Task ExtractManifestAsync(string nupkgPath, string targetPath) - => _manifestInstaller.ExtractManifestAsync(nupkgPath, targetPath); + public Task ExtractManifestAsync( + string nupkgPath, + string targetPath, + CancellationToken cancellationToken) + => _manifestInstaller.ExtractManifestAsync(nupkgPath, targetPath, cancellationToken); private void LogPackInfo(PackInfo packInfo) { @@ -755,7 +832,7 @@ private void LogPackInfo(PackInfo packInfo) /// The product code of the MSI to detect. /// If detected, contains the version of the installed MSI. /// The detect state of the specified MSI. - private DetectState DetectPackage(string productCode, out Version installedVersion) + protected virtual DetectState DetectPackage(string productCode, out Version installedVersion) { installedVersion = default; uint error = WindowsInstaller.GetProductInfo(productCode, InstallProperty.VERSIONSTRING, out string versionValue); @@ -854,15 +931,22 @@ private static string GetMsiPackageId(PackInfo packInfo) /// is downloaded. /// The directory where the package was extracted. /// - private string ExtractPackage(string packageId, string packageVersion, DirectoryPath? offlineCache) + private string ExtractPackage( + string packageId, + string packageVersion, + CancellationToken cancellationToken, + DirectoryPath? offlineCache) { string packagePath; if (offlineCache == null || !offlineCache.HasValue) { Reporter.WriteLine($"Downloading {packageId} ({packageVersion})"); - packagePath = _nugetPackageDownloader.DownloadPackageAsync(new PackageId(packageId), new NuGetVersion(packageVersion), - _packageSourceLocation).Result; + packagePath = _nugetPackageDownloader.DownloadPackageAsync( + new PackageId(packageId), + cancellationToken, + new NuGetVersion(packageVersion), + _packageSourceLocation).GetAwaiter().GetResult(); Log?.LogMessage($"Downloaded {packageId} ({packageVersion}) to '{packagePath}"); } else @@ -881,7 +965,10 @@ private string ExtractPackage(string packageId, string packageVersion, Directory string extractionDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(extractionDirectory); Log?.LogMessage($"Extracting '{packageId}' to '{extractionDirectory}'"); - _ = _nugetPackageDownloader.ExtractPackageAsync(packagePath, new DirectoryPath(extractionDirectory)).Result; + _ = _nugetPackageDownloader.ExtractPackageAsync( + packagePath, + new DirectoryPath(extractionDirectory), + cancellationToken).GetAwaiter().GetResult(); return extractionDirectory; } @@ -917,13 +1004,18 @@ private static IEnumerable GetInstalledFeatureBands(ISetupLogger /// The path to the offline cache. When , packages are downloaded using the /// existing package feeds. /// The MSI payload or if unsuccessful. - private MsiPayload GetCachedMsiPayload(string packageId, string packageVersion, DirectoryPath? offlineCache) + protected virtual MsiPayload GetCachedMsiPayload( + string packageId, + string packageVersion, + CancellationToken cancellationToken, + DirectoryPath? offlineCache) { + cancellationToken.ThrowIfCancellationRequested(); if (!Cache.TryGetPayloadFromCache(packageId, packageVersion, out MsiPayload msiPayload)) { // If it's not fully cached, download or copy if from the local cache and extract the payload package into a // temporary location and try to cache it again in the MSI cache. We DO NOT trust partially cached packages. - string extractedPackageRootPath = ExtractPackage(packageId, packageVersion, offlineCache); + string extractedPackageRootPath = ExtractPackage(packageId, packageVersion, cancellationToken, offlineCache); string manifestPath = Path.Combine(extractedPackageRootPath, "data", "msi.json"); Cache.CachePayload(packageId, packageVersion, manifestPath); Directory.Delete(extractedPackageRootPath, recursive: true); @@ -944,8 +1036,11 @@ private MsiPayload GetCachedMsiPayload(string packageId, string packageVersion, /// The action to perform. /// A friendly name to display to the user when reporting progress. If no value is provided, the MSI /// filename will be used. - private void ExecutePackage(MsiPayload msi, InstallAction action, string displayName = null) + protected virtual void ExecutePackage(MsiPayload msi, InstallAction action, string displayName = null) { + using IDisposable softCancellationTimeout = + ProcessLifecycle.OverrideSoftCancellationTimeout(Timeout.InfiniteTimeSpan); + uint error = Error.SUCCESS; string logFile = GetMsiLogName(msi, action); string name = string.IsNullOrWhiteSpace(displayName) ? msi.Payload : displayName; @@ -1024,7 +1119,7 @@ private uint ExecuteWithProgress(string progressLabel, Func installDelegat /// when retrieving payloads from the cache. /// /// The payload to validate. - private void ValidateMsiDatabase(MsiPayload msiPayload) + protected virtual void ValidateMsiDatabase(MsiPayload msiPayload) { uint error = WindowsInstaller.VerifyPackage(msiPayload.MsiPath); ExitOnError(error, $"Failed to verify package: {msiPayload.MsiPath}."); @@ -1128,5 +1223,6 @@ void IInstaller.UpdateInstallMode(SdkFeatureBand sdkFeatureBand, bool? newMode) // This method should never be called for this kind of installer. It is challenging to get this information from an MSI // and totally unnecessary as the information is identical from a file-based installer. It was added to IInstaller only // to facilitate testing. As a consequence, it does not need to be implemented. - public WorkloadSet GetWorkloadSetContents(string workloadVersion) => throw new NotImplementedException(); + public WorkloadSet GetWorkloadSetContents(string workloadVersion, CancellationToken cancellationToken) + => throw new NotImplementedException(); } diff --git a/src/Cli/dotnet/Commands/Workload/Install/WindowsMsiManifestInstaller.cs b/src/Cli/dotnet/Commands/Workload/Install/WindowsMsiManifestInstaller.cs index 02f36d9fe35d..e9a0b2c9808e 100644 --- a/src/Cli/dotnet/Commands/Workload/Install/WindowsMsiManifestInstaller.cs +++ b/src/Cli/dotnet/Commands/Workload/Install/WindowsMsiManifestInstaller.cs @@ -82,7 +82,10 @@ public PackageId GetManifestPackageId(ManifestId manifestId, SdkFeatureBand feat } } - public async Task ExtractManifestAsync(string nupkgPath, string targetPath) + public async Task ExtractManifestAsync( + string nupkgPath, + string targetPath, + CancellationToken cancellationToken) { log?.LogMessage($"ExtractManifestAsync: Extracting '{nupkgPath}' to '{targetPath}'"); string extractionPath = TemporaryDirectory.CreateSubdirectory(); @@ -90,7 +93,10 @@ public async Task ExtractManifestAsync(string nupkgPath, string targetPath) try { log?.LogMessage($"ExtractManifestAsync: Temporary extraction path: '{extractionPath}'"); - await nugetPackageDownloader.ExtractPackageAsync(nupkgPath, new DirectoryPath(extractionPath)); + await nugetPackageDownloader.ExtractPackageAsync( + nupkgPath, + new DirectoryPath(extractionPath), + cancellationToken); if (Directory.Exists(targetPath)) { Directory.Delete(targetPath, true); diff --git a/src/Cli/dotnet/Commands/Workload/Install/WorkloadAdvertisingManifestUpdater.cs b/src/Cli/dotnet/Commands/Workload/Install/WorkloadAdvertisingManifestUpdater.cs index 692fcebf05b5..12e0f7e7a908 100644 --- a/src/Cli/dotnet/Commands/Workload/Install/WorkloadAdvertisingManifestUpdater.cs +++ b/src/Cli/dotnet/Commands/Workload/Install/WorkloadAdvertisingManifestUpdater.cs @@ -61,28 +61,33 @@ internal class WorkloadAdvertisingManifestUpdater( private readonly IWorkloadManifestInstaller _workloadManifestInstaller = workloadManifestInstaller; private readonly bool _displayManifestUpdates = displayManifestUpdates; - public async Task UpdateAdvertisingManifestsAsync(bool includePreviews, bool useWorkloadSets = false, DirectoryPath? offlineCache = null) + public async Task UpdateAdvertisingManifestsAsync( + CancellationToken cancellationToken, + bool includePreviews, + bool useWorkloadSets = false, + DirectoryPath? offlineCache = null) { if (useWorkloadSets) { - await UpdateManifestWithVersionAsync(WorkloadManifestUpdater.WorkloadSetManifestId, includePreviews, _sdkFeatureBand, null, offlineCache); + await UpdateManifestWithVersionAsync(cancellationToken, WorkloadManifestUpdater.WorkloadSetManifestId, includePreviews, _sdkFeatureBand, null, offlineCache); } else { // this updates all the manifests var manifests = _workloadResolver.GetInstalledManifests(); - await Task.WhenAll(manifests.Select(manifest => UpdateAdvertisingManifestAsync(manifest, includePreviews, offlineCache))).ConfigureAwait(false); + await Task.WhenAll(manifests.Select(manifest => UpdateAdvertisingManifestAsync(cancellationToken, manifest, includePreviews, offlineCache))).ConfigureAwait(false); WriteUpdatableWorkloadsFile(); } } - public async Task BackgroundUpdateAdvertisingManifestsWhenRequiredAsync() + public async Task BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(CancellationToken cancellationToken) { if (!BackgroundUpdatesAreDisabled() && AdManifestSentinelIsDueForUpdate() && - await UpdatedAdManifestPackagesExistAsync().ConfigureAwait(false)) + await UpdatedAdManifestPackagesExistAsync(cancellationToken).ConfigureAwait(false)) { await UpdateAdvertisingManifestsAsync( + cancellationToken, false, ShouldUseWorkloadSetMode(_sdkFeatureBand, _userProfileDir)).ConfigureAwait(false); var sentinelPath = GetAdvertisingManifestSentinelPath(_sdkFeatureBand); @@ -183,6 +188,7 @@ public IEnumerable GetUpdatableWorkloadsToAdvertise(IEnumerable GetInstalledManifestIds() => _workloadResolver.GetInstalledManifests().Select(manifest => new ManifestId(manifest.Id)); private async Task UpdateManifestWithVersionAsync( + CancellationToken cancellationToken, string id, bool includePreviews, SdkFeatureBand band, @@ -204,7 +210,12 @@ private async Task UpdateManifestWithVersionAsync( Path.GetFileName(path).StartsWith(manifestPackageId.ToString(), StringComparison.OrdinalIgnoreCase) && (packageVersion == null || path.Contains(packageVersion.ToString()))) .Max() : - await _nugetPackageDownloader.DownloadPackageAsync(manifestPackageId, packageVersion: packageVersion, packageSourceLocation: _packageSourceLocation, includePreview: includePreviews); + await _nugetPackageDownloader.DownloadPackageAsync( + manifestPackageId, + cancellationToken, + packageVersion: packageVersion, + packageSourceLocation: _packageSourceLocation, + includePreview: includePreviews); } catch (NuGetPackageNotFoundException) { @@ -216,7 +227,7 @@ private async Task UpdateManifestWithVersionAsync( } var adManifestPath = GetAdvertisingManifestPath(_sdkFeatureBand, manifestId); - await _workloadManifestInstaller.ExtractManifestAsync(packagePath, adManifestPath); + await _workloadManifestInstaller.ExtractManifestAsync(packagePath, adManifestPath, cancellationToken); // add file that contains the advertised manifest feature band so GetAdvertisingManifestVersionAndWorkloads will use correct feature band, regardless of if rollback occurred or not File.WriteAllText(Path.Combine(adManifestPath, "AdvertisedManifestFeatureBand.txt"), band.ToString()); @@ -242,7 +253,7 @@ private async Task UpdateManifestWithVersionAsync( return true; } - catch (Exception e) + catch (Exception e) when (e is not OperationCanceledException) { _reporter.WriteLine(CliCommandStrings.FailedAdManifestUpdate, manifestId, e.Message); return false; @@ -270,14 +281,18 @@ private async Task UpdateManifestWithVersionAsync( } } - private async Task UpdateAdvertisingManifestAsync(WorkloadManifestInfo manifest, bool includePreviews, DirectoryPath? offlineCache = null) + private async Task UpdateAdvertisingManifestAsync( + CancellationToken cancellationToken, + WorkloadManifestInfo manifest, + bool includePreviews, + DirectoryPath? offlineCache = null) { var fallbackFeatureBand = new SdkFeatureBand(manifest.ManifestFeatureBand); // The bands should be checked in the order defined here. SdkFeatureBand[] bands = [_sdkFeatureBand, fallbackFeatureBand]; foreach (var band in bands.Distinct()) { - if (await UpdateManifestWithVersionAsync(manifest.Id, includePreviews, band, null, offlineCache)) + if (await UpdateManifestWithVersionAsync(cancellationToken, manifest.Id, includePreviews, band, null, offlineCache)) { return; } @@ -338,23 +353,25 @@ private bool AdManifestSentinelIsDueForUpdate() return true; } - private async Task UpdatedAdManifestPackagesExistAsync() + private async Task UpdatedAdManifestPackagesExistAsync(CancellationToken cancellationToken) { var manifests = GetInstalledManifestIds(); // TODO: This doesn't seem to account for differing feature bands - var availableUpdates = await Task.WhenAll(manifests.Select(manifest => NewerManifestPackageExists(manifest))).ConfigureAwait(false); + var availableUpdates = await Task.WhenAll(manifests.Select(manifest => NewerManifestPackageExists(manifest, cancellationToken))).ConfigureAwait(false); return availableUpdates.Any(); } - private async Task NewerManifestPackageExists(ManifestId manifest) + private async Task NewerManifestPackageExists(ManifestId manifest, CancellationToken cancellationToken) { try { var currentVersion = NuGetVersion.Parse(_workloadResolver.GetManifestVersion(manifest.ToString())); - var latestVersion = await _nugetPackageDownloader.GetLatestPackageVersion(_workloadManifestInstaller.GetManifestPackageId(manifest, _sdkFeatureBand)); + var latestVersion = await _nugetPackageDownloader.GetLatestPackageVersion( + _workloadManifestInstaller.GetManifestPackageId(manifest, _sdkFeatureBand), + cancellationToken); return latestVersion > currentVersion; } - catch (Exception) + catch (Exception ex) when (ex is not OperationCanceledException) { return false; } diff --git a/src/Cli/dotnet/Commands/Workload/Install/WorkloadInstallCommand.cs b/src/Cli/dotnet/Commands/Workload/Install/WorkloadInstallCommand.cs index 9a5fd88871aa..0485d16eb8e6 100644 --- a/src/Cli/dotnet/Commands/Workload/Install/WorkloadInstallCommand.cs +++ b/src/Cli/dotnet/Commands/Workload/Install/WorkloadInstallCommand.cs @@ -121,7 +121,7 @@ private void ValidateWorkloadIdsInput(IReadOnlyCollection filteredWorklo } } - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { bool usedRollback = !string.IsNullOrWhiteSpace(_fromRollbackDefinition); var filteredWorkloadIds = GetValidWorkloadIds(); @@ -141,7 +141,13 @@ public override int Execute() var existingWorkloads = GetInstalledWorkloads(false); var workloadsToDownload = existingWorkloads.Union(filteredWorkloadIds.Select(id => new WorkloadId(id))).ToList(); - var packageUrls = GetPackageDownloadUrlsAsync(workloadsToDownload, _skipManifestUpdate, _includePreviews, NullReporter.Instance, packageDownloader).GetAwaiter().GetResult(); + var packageUrls = GetPackageDownloadUrlsAsync( + workloadsToDownload, + cancellationToken, + _skipManifestUpdate, + _includePreviews, + NullReporter.Instance, + packageDownloader).GetAwaiter().GetResult(); Reporter.WriteLine(JsonSerializer.Serialize(packageUrls, WorkloadInstallJsonSerializerContext.Default.IEnumerableString)); } @@ -157,9 +163,14 @@ public override int Execute() var existingWorkloads = GetInstalledWorkloads(false); var workloadsToDownload = existingWorkloads.Union(filteredWorkloadIds.Select(id => new WorkloadId(id))).ToList(); - DownloadToOfflineCacheAsync(workloadsToDownload, new DirectoryPath(_downloadToCacheOption), _skipManifestUpdate, _includePreviews).Wait(); + DownloadToOfflineCacheAsync( + workloadsToDownload, + new DirectoryPath(_downloadToCacheOption), + cancellationToken, + _skipManifestUpdate, + _includePreviews).GetAwaiter().GetResult(); } - catch (Exception e) + catch (Exception e) when (e is not OperationCanceledException) { throw new GracefulException(string.Format(CliCommandStrings.WorkloadInstallWorkloadCacheDownloadFailed, e.Message), e, isUserError: false); } @@ -194,15 +205,15 @@ public override int Execute() recorder.Run(() => { - InstallWorkloads(recorder, filteredWorkloadIds); + InstallWorkloads(recorder, filteredWorkloadIds, cancellationToken); }); } else { - InstallWorkloads(null, filteredWorkloadIds); + InstallWorkloads(null, filteredWorkloadIds, cancellationToken); } } - catch (Exception e) + catch (Exception e) when (e is not OperationCanceledException) { if (_shouldShutdownInstaller) { @@ -222,7 +233,10 @@ public override int Execute() return _workloadInstaller.ExitCode; } - private void InstallWorkloads(WorkloadHistoryRecorder recorder, IReadOnlyCollection filteredWorkloadIds) + private void InstallWorkloads( + WorkloadHistoryRecorder recorder, + IReadOnlyCollection filteredWorkloadIds, + CancellationToken cancellationToken) { // Normally we want to validate that the workload IDs specified were valid. However, if there is a global.json file with a workload // set version specified, and we might install that workload version, then we don't do that check here, because we might not have the right @@ -259,7 +273,7 @@ private void InstallWorkloads(WorkloadHistoryRecorder recorder, IReadOnlyCollect { Reporter.WriteLine(CliCommandStrings.CheckForUpdatedWorkloadManifests); } - UpdateWorkloadManifests(recorder, context, offlineCache); + UpdateWorkloadManifests(recorder, context, cancellationToken, offlineCache); } // Exit early if no valid workloads to install (e.g., only aspire was requested) @@ -278,7 +292,7 @@ private void InstallWorkloads(WorkloadHistoryRecorder recorder, IReadOnlyCollect workloadIds = workloadIds.Concat(installedWorkloads).Distinct(); workloadIds = WriteSDKInstallRecordsForVSWorkloads(workloadIds); - _workloadInstaller.InstallWorkloads(workloadIds, _sdkFeatureBand, context, offlineCache); + _workloadInstaller.InstallWorkloads(workloadIds, _sdkFeatureBand, context, cancellationToken, offlineCache); // Write workload installation records var recordRepo = _workloadInstaller.GetWorkloadInstallationRecordRepository(); @@ -299,7 +313,13 @@ private void InstallWorkloads(WorkloadHistoryRecorder recorder, IReadOnlyCollect } }); - TryRunGarbageCollection(_workloadInstaller, Reporter, Verbosity, workloadSetVersion => _workloadResolverFactory.CreateForWorkloadSet(_dotnetPath, _sdkVersion.ToString(), _userProfileDir, workloadSetVersion), offlineCache); + TryRunGarbageCollection( + _workloadInstaller, + Reporter, + Verbosity, + workloadSetVersion => _workloadResolverFactory.CreateForWorkloadSet(_dotnetPath, _sdkVersion.ToString(), _userProfileDir, workloadSetVersion), + cancellationToken, + offlineCache); Reporter.WriteLine(); Reporter.WriteLine(string.Format(CliCommandStrings.WorkloadInstallInstallationSucceeded, string.Join(" ", newWorkloadInstallRecords))); @@ -308,13 +328,19 @@ private void InstallWorkloads(WorkloadHistoryRecorder recorder, IReadOnlyCollect }); } - internal static void TryRunGarbageCollection(IInstaller workloadInstaller, IReporter reporter, VerbosityOptions verbosity, Func getResolverForWorkloadSet, DirectoryPath? offlineCache = null) + internal static void TryRunGarbageCollection( + IInstaller workloadInstaller, + IReporter reporter, + VerbosityOptions verbosity, + Func getResolverForWorkloadSet, + CancellationToken cancellationToken, + DirectoryPath? offlineCache = null) { try { - workloadInstaller.GarbageCollect(getResolverForWorkloadSet, offlineCache); + workloadInstaller.GarbageCollect(getResolverForWorkloadSet, cancellationToken, offlineCache); } - catch (Exception e) + catch (Exception e) when (e is not OperationCanceledException) { // Garbage collection failed, warn user reporter.WriteLine(string.Format(CliCommandStrings.GarbageCollectionFailed, @@ -322,25 +348,38 @@ internal static void TryRunGarbageCollection(IInstaller workloadInstaller, IRepo } } - private async Task> GetPackageDownloadUrlsAsync(IEnumerable workloadIds, bool skipManifestUpdate, bool includePreview, + private async Task> GetPackageDownloadUrlsAsync( + IEnumerable workloadIds, + CancellationToken cancellationToken, + bool skipManifestUpdate, + bool includePreview, IReporter reporter = null, INuGetPackageDownloader packageDownloader = null) { reporter ??= Reporter; packageDownloader ??= PackageDownloader; - var downloads = await GetDownloads(workloadIds, skipManifestUpdate, includePreview, reporter: reporter, packageDownloader: packageDownloader); + var downloads = await GetDownloads(workloadIds, cancellationToken, skipManifestUpdate, includePreview, reporter: reporter, packageDownloader: packageDownloader); var urls = new List(); foreach (var download in downloads) { - urls.Add(await packageDownloader.GetPackageUrl(new PackageId(download.NuGetPackageId), new NuGetVersion(download.NuGetPackageVersion), _packageSourceLocation)); + urls.Add(await packageDownloader.GetPackageUrl( + new PackageId(download.NuGetPackageId), + cancellationToken, + new NuGetVersion(download.NuGetPackageVersion), + _packageSourceLocation)); } return urls; } - private Task DownloadToOfflineCacheAsync(IEnumerable workloadIds, DirectoryPath offlineCache, bool skipManifestUpdate, bool includePreviews) + private Task DownloadToOfflineCacheAsync( + IEnumerable workloadIds, + DirectoryPath offlineCache, + CancellationToken cancellationToken, + bool skipManifestUpdate, + bool includePreviews) { - return GetDownloads(workloadIds, skipManifestUpdate, includePreviews, offlineCache.Value); + return GetDownloads(workloadIds, cancellationToken, skipManifestUpdate, includePreviews, offlineCache.Value); } private void RunInNewTransaction(Action a) diff --git a/src/Cli/dotnet/Commands/Workload/Install/WorkloadManifestUpdater.Managed.cs b/src/Cli/dotnet/Commands/Workload/Install/WorkloadManifestUpdater.Managed.cs index f1fe7bf820e8..63386c4028d4 100644 --- a/src/Cli/dotnet/Commands/Workload/Install/WorkloadManifestUpdater.Managed.cs +++ b/src/Cli/dotnet/Commands/Workload/Install/WorkloadManifestUpdater.Managed.cs @@ -54,13 +54,14 @@ public WorkloadManifestUpdater( } public Task UpdateAdvertisingManifestsAsync( + CancellationToken cancellationToken, bool includePreviews, bool useWorkloadSets = false, DirectoryPath? offlineCache = null) - => _advertisingUpdater.UpdateAdvertisingManifestsAsync(includePreviews, useWorkloadSets, offlineCache); + => _advertisingUpdater.UpdateAdvertisingManifestsAsync(cancellationToken, includePreviews, useWorkloadSets, offlineCache); - public Task BackgroundUpdateAdvertisingManifestsWhenRequiredAsync() - => _advertisingUpdater.BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(); + public Task BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(CancellationToken cancellationToken) + => _advertisingUpdater.BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(cancellationToken); public void DeleteUpdatableWorkloadsFile() => _advertisingUpdater.DeleteUpdatableWorkloadsFile(); @@ -112,6 +113,7 @@ private static IEnumerable CalculateManifestRollbacks( } public async Task> GetManifestPackageDownloadsAsync( + CancellationToken cancellationToken, bool includePreviews, SdkFeatureBand providedSdkFeatureBand, SdkFeatureBand installedSdkFeatureBand) @@ -135,6 +137,7 @@ public async Task> GetManifestPackageDownloadsAsyn { var latestVersion = await _nugetPackageDownloader.GetLatestPackageVersion( packageId, + cancellationToken, _packageSourceLocation, includePreviews); success = true; @@ -151,7 +154,7 @@ public async Task> GetManifestPackageDownloadsAsyn _reporter.WriteLine(CliCommandStrings.ManifestPackageUrlNotResolved, providedPackageId); } } - catch + catch (Exception ex) when (ex is not OperationCanceledException) { _reporter.WriteLine(CliCommandStrings.ManifestPackageUrlNotResolved, manifest.Id); } diff --git a/src/Cli/dotnet/Commands/Workload/Install/WorkloadManifestUpdater.cs b/src/Cli/dotnet/Commands/Workload/Install/WorkloadManifestUpdater.cs index d68eba557268..4d309f082b2e 100644 --- a/src/Cli/dotnet/Commands/Workload/Install/WorkloadManifestUpdater.cs +++ b/src/Cli/dotnet/Commands/Workload/Install/WorkloadManifestUpdater.cs @@ -74,14 +74,17 @@ private static WorkloadAdvertisingManifestUpdater GetAdvertisingUpdaterInstance( return new WorkloadAdvertisingManifestUpdater(reporter, workloadResolver, nugetPackageDownloader, userProfileDir, workloadRecordRepo, manifestInstaller, sdkFeatureBand: sdkFeatureBand); } - public static async Task BackgroundUpdateAdvertisingManifestsAsync(string userProfileDir, string workingDirectory = null) + public static async Task BackgroundUpdateAdvertisingManifestsAsync( + string userProfileDir, + string workingDirectory, + CancellationToken cancellationToken) { try { var advertisingUpdater = GetAdvertisingUpdaterInstance(userProfileDir, workingDirectory ?? Directory.GetCurrentDirectory()); - await advertisingUpdater.BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(); + await advertisingUpdater.BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(cancellationToken); } - catch (Exception) + catch (Exception ex) when (ex is not OperationCanceledException) { // Never surface messages on background updates } diff --git a/src/Cli/dotnet/Commands/Workload/InstallingWorkloadCommand.cs b/src/Cli/dotnet/Commands/Workload/InstallingWorkloadCommand.cs index 6223a6d16ebc..9e83b47505bd 100644 --- a/src/Cli/dotnet/Commands/Workload/InstallingWorkloadCommand.cs +++ b/src/Cli/dotnet/Commands/Workload/InstallingWorkloadCommand.cs @@ -190,7 +190,11 @@ InstallStateContents GetCurrentInstallState() return InstallStateContents.FromPath(path); } - protected void UpdateWorkloadManifests(WorkloadHistoryRecorder recorder, ITransactionContext context, DirectoryPath? offlineCache) + protected void UpdateWorkloadManifests( + WorkloadHistoryRecorder recorder, + ITransactionContext context, + CancellationToken cancellationToken, + DirectoryPath? offlineCache) { var shouldUseWorkloadSetsPerInstallState = WorkloadManifestUpdater.ShouldUseWorkloadSetMode(_sdkFeatureBand, _workloadRootDir); var updateToLatestWorkloadSet = _shouldUseWorkloadSets ?? shouldUseWorkloadSetsPerInstallState && !SpecifiedWorkloadSetVersionInGlobalJson; @@ -239,7 +243,8 @@ protected void UpdateWorkloadManifests(WorkloadHistoryRecorder recorder, ITransa PackageDownloader, _workloadSetVersionFromCommandLine, _workloadResolver, - numberOfWorkloadSetsToTake: 1); + numberOfWorkloadSetsToTake: 1, + cancellationToken); if (versions is null) { @@ -263,7 +268,11 @@ protected void UpdateWorkloadManifests(WorkloadHistoryRecorder recorder, ITransa if (string.IsNullOrWhiteSpace(resolvedWorkloadSetVersion) && !UseRollback && !FromHistory) { - _workloadManifestUpdater.UpdateAdvertisingManifestsAsync(_includePreviews, updateToLatestWorkloadSet, offlineCache).Wait(); + _workloadManifestUpdater.UpdateAdvertisingManifestsAsync( + cancellationToken, + _includePreviews, + updateToLatestWorkloadSet, + offlineCache).GetAwaiter().GetResult(); if (updateToLatestWorkloadSet) { resolvedWorkloadSetVersion = _workloadManifestUpdater.GetAdvertisedWorkloadSetVersion(); @@ -289,7 +298,7 @@ protected void UpdateWorkloadManifests(WorkloadHistoryRecorder recorder, ITransa } IEnumerable manifestsToUpdate = - resolvedWorkloadSetVersion != null ? InstallWorkloadSet(context, resolvedWorkloadSetVersion) : + resolvedWorkloadSetVersion != null ? InstallWorkloadSet(context, resolvedWorkloadSetVersion, cancellationToken) : UseRollback ? _workloadManifestUpdater.CalculateManifestRollbacks(_fromRollbackDefinition, recorder) : FromHistory ? _workloadManifestUpdater.CalculateManifestUpdatesFromHistory(_WorkloadHistoryRecord) : _workloadManifestUpdater.CalculateManifestUpdates().Select(m => m.ManifestUpdate); @@ -301,7 +310,7 @@ protected void UpdateWorkloadManifests(WorkloadHistoryRecorder recorder, ITransa { foreach (var manifestUpdate in manifestsToUpdate) { - _workloadInstaller.InstallWorkloadManifest(manifestUpdate, context, offlineCache); + _workloadInstaller.InstallWorkloadManifest(manifestUpdate, context, cancellationToken, offlineCache); } if (!SpecifiedWorkloadSetVersionInGlobalJson) @@ -360,15 +369,23 @@ protected void UpdateWorkloadManifests(WorkloadHistoryRecorder recorder, ITransa }); } - private IEnumerable InstallWorkloadSet(ITransactionContext context, string workloadSetVersion) + private IEnumerable InstallWorkloadSet( + ITransactionContext context, + string workloadSetVersion, + CancellationToken cancellationToken) { Reporter.WriteLine(string.Format(CliCommandStrings.NewWorkloadSet, workloadSetVersion)); - var workloadSet = _workloadInstaller.InstallWorkloadSet(context, workloadSetVersion); + var workloadSet = _workloadInstaller.InstallWorkloadSet(context, workloadSetVersion, cancellationToken); return workloadSet is null ? [] : _workloadManifestUpdater.CalculateManifestUpdatesForWorkloadSet(workloadSet); } - protected async Task> GetDownloads(IEnumerable workloadIds, bool skipManifestUpdate, bool includePreview, string downloadFolder = null, + protected async Task> GetDownloads( + IEnumerable workloadIds, + CancellationToken cancellationToken, + bool skipManifestUpdate, + bool includePreview, + string downloadFolder = null, IReporter reporter = null, INuGetPackageDownloader packageDownloader = null) { reporter ??= Reporter; @@ -393,7 +410,11 @@ protected async Task> GetDownloads(IEnumerable> GetDownloads(IEnumerable> GetDownloads(IEnumerable installedList = _workloadListHelper.InstalledSdkWorkloadIds; @@ -69,7 +69,7 @@ public override int Execute() { _workloadListHelper.CheckTargetSdkVersionIsValid(); - var updateAvailable = GetUpdateAvailable(installedList); + var updateAvailable = GetUpdateAvailable(installedList, cancellationToken); var installed = installedList.Select(id => id.ToString()).ToArray(); ListOutput listOutput = new(installed, [.. updateAvailable]); @@ -136,10 +136,14 @@ public override int Execute() return 0; } - internal IEnumerable GetUpdateAvailable(IEnumerable installedList) + internal IEnumerable GetUpdateAvailable( + IEnumerable installedList, + CancellationToken cancellationToken) { // This was an internal partner ask, and they do not need to support workload sets. - _workloadManifestUpdater.UpdateAdvertisingManifestsAsync(_includePreviews).Wait(); + _workloadManifestUpdater.UpdateAdvertisingManifestsAsync( + cancellationToken, + _includePreviews).GetAwaiter().GetResult(); var manifestsToUpdate = _workloadManifestUpdater.CalculateManifestUpdates(); foreach ((ManifestVersionUpdate manifestUpdate, WorkloadCollection workloads) in manifestsToUpdate) diff --git a/src/Cli/dotnet/Commands/Workload/Repair/WorkloadRepairCommand.cs b/src/Cli/dotnet/Commands/Workload/Repair/WorkloadRepairCommand.cs index 4e523eafb594..805a61e1b571 100644 --- a/src/Cli/dotnet/Commands/Workload/Repair/WorkloadRepairCommand.cs +++ b/src/Cli/dotnet/Commands/Workload/Repair/WorkloadRepairCommand.cs @@ -62,7 +62,7 @@ public WorkloadRepairCommand( _recorder.HistoryRecord.CommandName = "repair"; } - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { try { @@ -81,16 +81,21 @@ public override int Execute() Reporter.WriteLine(string.Format(CliCommandStrings.RepairingWorkloads, string.Join(" ", workloadIds))); - ReinstallWorkloadsBasedOnCurrentManifests(workloadIds, sdkFeatureBand); + ReinstallWorkloadsBasedOnCurrentManifests(workloadIds, sdkFeatureBand, cancellationToken); - WorkloadInstallCommand.TryRunGarbageCollection(_workloadInstaller, Reporter, Verbosity, workloadSetVersion => _workloadResolverFactory.CreateForWorkloadSet(_dotnetPath, _sdkVersion.ToString(), _userProfileDir, workloadSetVersion)); + WorkloadInstallCommand.TryRunGarbageCollection( + _workloadInstaller, + Reporter, + Verbosity, + workloadSetVersion => _workloadResolverFactory.CreateForWorkloadSet(_dotnetPath, _sdkVersion.ToString(), _userProfileDir, workloadSetVersion), + cancellationToken); Reporter.WriteLine(); Reporter.WriteLine(string.Format(CliCommandStrings.RepairSucceeded, string.Join(" ", workloadIds))); Reporter.WriteLine(); }); } - catch (Exception e) + catch (Exception e) when (e is not OperationCanceledException) { // Don't show entire stack trace throw new GracefulException(string.Format(CliCommandStrings.WorkloadRepairFailed, e.Message), e, isUserError: false); @@ -103,9 +108,12 @@ public override int Execute() return _workloadInstaller.ExitCode; } - private void ReinstallWorkloadsBasedOnCurrentManifests(IEnumerable workloadIds, SdkFeatureBand sdkFeatureBand) + private void ReinstallWorkloadsBasedOnCurrentManifests( + IEnumerable workloadIds, + SdkFeatureBand sdkFeatureBand, + CancellationToken cancellationToken) { - _workloadInstaller.RepairWorkloads(workloadIds, sdkFeatureBand); + _workloadInstaller.RepairWorkloads(workloadIds, sdkFeatureBand, cancellationToken); } } diff --git a/src/Cli/dotnet/Commands/Workload/Restore/WorkloadRestoreCommand.cs b/src/Cli/dotnet/Commands/Workload/Restore/WorkloadRestoreCommand.cs index 969d6a8e0938..db7f0d46e86e 100644 --- a/src/Cli/dotnet/Commands/Workload/Restore/WorkloadRestoreCommand.cs +++ b/src/Cli/dotnet/Commands/Workload/Restore/WorkloadRestoreCommand.cs @@ -26,7 +26,7 @@ public WorkloadRestoreCommand(ParseResult result, IReporter reporter = null) _slnOrProjectArgument = result.GetValue(Definition.SlnOrProjectArgument); } - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { var workloadResolverFactory = new WorkloadResolverFactory(); var creationResult = workloadResolverFactory.Create(); @@ -46,10 +46,13 @@ public override int Execute() recorder.Run(() => { // First discover projects. This may return an error if no projects are found, and we shouldn't delay until after Update if that's the case. - var allProjects = DiscoverAllProjects(Directory.GetCurrentDirectory(), _slnOrProjectArgument).Distinct(); + var allProjects = DiscoverAllProjects( + Directory.GetCurrentDirectory(), + cancellationToken, + _slnOrProjectArgument).Distinct(); // Then update manifests and install a workload set as necessary - new WorkloadUpdateCommand(_result, recorder: recorder, isRestoring: true).Execute(); + new WorkloadUpdateCommand(_result, recorder: recorder, isRestoring: true).Execute(cancellationToken); List allWorkloadId = RunTargetToGetWorkloadIds(allProjects); Reporter.WriteLine(string.Format(CliCommandStrings.InstallingWorkloads, string.Join(" ", allWorkloadId))); @@ -59,7 +62,7 @@ public override int Execute() skipWorkloadManifestUpdate: true) { IsRunningRestore = true - }.Execute(); + }.Execute(cancellationToken); }); workloadInstaller.Shutdown(); @@ -111,7 +114,9 @@ private List RunTargetToGetWorkloadIds(IEnumerable allProjec } - internal static List DiscoverAllProjects(string currentDirectory, + internal static List DiscoverAllProjects( + string currentDirectory, + CancellationToken cancellationToken, IEnumerable slnOrProjectArgument = null) { var slnFiles = new List(); @@ -133,7 +138,7 @@ internal static List DiscoverAllProjects(string currentDirectory, foreach (string solutionFilePath in slnFiles) { - var solutionFile = SlnFileFactory.CreateFromFileOrDirectory(solutionFilePath); + var solutionFile = SlnFileFactory.CreateFromFileOrDirectory(solutionFilePath, cancellationToken); projectFiles.AddRange(solutionFile.SolutionProjects.Select( p => Path.GetFullPath(p.FilePath, Path.GetDirectoryName(solutionFilePath)))); } diff --git a/src/Cli/dotnet/Commands/Workload/Search/WorkloadSearchCommand.cs b/src/Cli/dotnet/Commands/Workload/Search/WorkloadSearchCommand.cs index ba681404ffbf..5924f119fe33 100644 --- a/src/Cli/dotnet/Commands/Workload/Search/WorkloadSearchCommand.cs +++ b/src/Cli/dotnet/Commands/Workload/Search/WorkloadSearchCommand.cs @@ -34,7 +34,7 @@ public WorkloadSearchCommand( _workloadResolver = creationResult.WorkloadResolver; } - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { IEnumerable availableWorkloads = _workloadResolver.GetAvailableWorkloads() .OrderBy(workload => workload.Id); diff --git a/src/Cli/dotnet/Commands/Workload/Search/WorkloadSearchVersionsCommand.cs b/src/Cli/dotnet/Commands/Workload/Search/WorkloadSearchVersionsCommand.cs index 2204cafac5a7..05195c30d375 100644 --- a/src/Cli/dotnet/Commands/Workload/Search/WorkloadSearchVersionsCommand.cs +++ b/src/Cli/dotnet/Commands/Workload/Search/WorkloadSearchVersionsCommand.cs @@ -81,14 +81,14 @@ private static IInstaller GenerateInstaller(IReporter reporter, SdkFeatureBand s ); } - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { if (_workloadVersion.Count() == 0) { List versions; try { - versions = GetVersions(_numberOfWorkloadSetsToTake); + versions = GetVersions(_numberOfWorkloadSetsToTake, cancellationToken); } catch (NuGetPackageNotFoundException) { @@ -110,7 +110,7 @@ public override int Execute() } else if (_workloadVersion.Any(v => v.Contains('@'))) { - var versions = FindBestWorkloadSetsFromComponents()?.Take(_numberOfWorkloadSetsToTake); + var versions = FindBestWorkloadSetsFromComponents(cancellationToken)?.Take(_numberOfWorkloadSetsToTake); if (versions is null) { return 0; @@ -131,7 +131,7 @@ public override int Execute() } else { - var workloadSet = _installer.GetWorkloadSetContents(_workloadVersion.Single()); + var workloadSet = _installer.GetWorkloadSetContents(_workloadVersion.Single(), cancellationToken); if (_workloadSetOutputFormat?.Equals("json", StringComparison.OrdinalIgnoreCase) == true) { var set = new WorkloadSet() { ManifestVersions = workloadSet.ManifestVersions }; @@ -153,34 +153,66 @@ public override int Execute() return 0; } - private List GetVersions(int numberOfWorkloadSetsToTake) + private List GetVersions( + int numberOfWorkloadSetsToTake, + CancellationToken cancellationToken) { - return GetVersions(numberOfWorkloadSetsToTake, new SdkFeatureBand(_sdkVersion), _installer, _includePreviews, PackageDownloader, _resolver); + return GetVersions( + numberOfWorkloadSetsToTake, + new SdkFeatureBand(_sdkVersion), + _installer, + _includePreviews, + PackageDownloader, + _resolver, + cancellationToken); } - private static List GetVersions(int numberOfWorkloadSetsToTake, SdkFeatureBand featureBand, IInstaller installer, bool includePreviews, INuGetPackageDownloader packageDownloader, IWorkloadResolver resolver) + private static List GetVersions( + int numberOfWorkloadSetsToTake, + SdkFeatureBand featureBand, + IInstaller installer, + bool includePreviews, + INuGetPackageDownloader packageDownloader, + IWorkloadResolver resolver, + CancellationToken cancellationToken) { installer ??= GenerateInstaller(Utils.Reporter.NullReporter, featureBand, resolver, VerbosityOptions.d, interactive: false); var packageId = installer.GetManifestPackageId(new ManifestId("Microsoft.NET.Workloads"), featureBand); - return [.. packageDownloader.GetLatestPackageVersions(packageId, numberOfWorkloadSetsToTake, packageSourceLocation: null, includePreview: includePreviews) + return [.. packageDownloader.GetLatestPackageVersions(packageId, numberOfWorkloadSetsToTake, cancellationToken, packageSourceLocation: null, includePreview: includePreviews) .GetAwaiter().GetResult() .Select(version => featureBand.GetWorkloadSetPackageVersion(version.ToString()))]; } - private IEnumerable FindBestWorkloadSetsFromComponents() + private IEnumerable FindBestWorkloadSetsFromComponents(CancellationToken cancellationToken) { - return FindBestWorkloadSetsFromComponents(new SdkFeatureBand(_sdkVersion), _installer, _includePreviews, PackageDownloader, _workloadVersion, _resolver, _numberOfWorkloadSetsToTake); + return FindBestWorkloadSetsFromComponents( + new SdkFeatureBand(_sdkVersion), + _installer, + _includePreviews, + PackageDownloader, + _workloadVersion, + _resolver, + _numberOfWorkloadSetsToTake, + cancellationToken); } - public static IEnumerable FindBestWorkloadSetsFromComponents(SdkFeatureBand featureBand, IInstaller installer, bool includePreviews, INuGetPackageDownloader packageDownloader, IEnumerable workloadVersions, IWorkloadResolver resolver, int numberOfWorkloadSetsToTake) + public static IEnumerable FindBestWorkloadSetsFromComponents( + SdkFeatureBand featureBand, + IInstaller installer, + bool includePreviews, + INuGetPackageDownloader packageDownloader, + IEnumerable workloadVersions, + IWorkloadResolver resolver, + int numberOfWorkloadSetsToTake, + CancellationToken cancellationToken) { installer ??= GenerateInstaller(Utils.Reporter.NullReporter, featureBand, resolver, VerbosityOptions.d, interactive: false); List versions; try { // 0 indicates 'give all versions'. Not all will match, so we don't know how many we will need - versions = GetVersions(0, featureBand, installer, includePreviews, packageDownloader, resolver); + versions = GetVersions(0, featureBand, installer, includePreviews, packageDownloader, resolver, cancellationToken); } catch (NuGetPackageNotFoundException) { @@ -197,7 +229,7 @@ public static IEnumerable FindBestWorkloadSetsFromComponents(SdkFeatureB // Since these are ordered by version (descending), the first is the highest version return versions.Where(version => { - var manifestVersions = installer.GetWorkloadSetContents(version).ManifestVersions; + var manifestVersions = installer.GetWorkloadSetContents(version, cancellationToken).ManifestVersions; return manifestIdsAndVersions.All(tuple => manifestVersions.ContainsKey(tuple.Item1) && manifestVersions[tuple.Item1].Version.Equals(tuple.Item2)); }).Take(numberOfWorkloadSetsToTake); } diff --git a/src/Cli/dotnet/Commands/Workload/Uninstall/WorkloadUninstallCommand.cs b/src/Cli/dotnet/Commands/Workload/Uninstall/WorkloadUninstallCommand.cs index d2106a923a6d..1ca6d02d1e70 100644 --- a/src/Cli/dotnet/Commands/Workload/Uninstall/WorkloadUninstallCommand.cs +++ b/src/Cli/dotnet/Commands/Workload/Uninstall/WorkloadUninstallCommand.cs @@ -26,7 +26,8 @@ public WorkloadUninstallCommand( ParseResult parseResult, IReporter reporter = null, IWorkloadResolverFactory workloadResolverFactory = null, - INuGetPackageDownloader nugetPackageDownloader = null) + INuGetPackageDownloader nugetPackageDownloader = null, + IInstaller workloadInstaller = null) : base(parseResult, reporter: reporter, nugetPackageDownloader: nugetPackageDownloader) { _workloadIds = parseResult.GetValue(Definition.WorkloadIdArgument) @@ -46,12 +47,12 @@ public WorkloadUninstallCommand( _userProfileDir = creationResult.UserProfileDir; var sdkFeatureBand = new SdkFeatureBand(_sdkVersion); - _workloadInstaller = WorkloadInstallerFactory.GetWorkloadInstaller(Reporter, sdkFeatureBand, creationResult.WorkloadResolver, Verbosity, creationResult.UserProfileDir, VerifySignatures, PackageDownloader, creationResult.DotnetPath); + _workloadInstaller = workloadInstaller ?? WorkloadInstallerFactory.GetWorkloadInstaller(Reporter, sdkFeatureBand, creationResult.WorkloadResolver, Verbosity, creationResult.UserProfileDir, VerifySignatures, PackageDownloader, creationResult.DotnetPath); _recorder = new(_workloadResolverFactory.Create().WorkloadResolver, _workloadInstaller, () => _workloadResolverFactory.CreateForWorkloadSet(_dotnetPath, _sdkVersion.ToString(), _userProfileDir, null)); _recorder.HistoryRecord.CommandName = "uninstall"; } - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { try { @@ -74,13 +75,20 @@ public override int Execute() .DeleteWorkloadInstallationRecord(workloadId, featureBand); } - _workloadInstaller.GarbageCollect(workloadSetVersion => _workloadResolverFactory.CreateForWorkloadSet(_dotnetPath, _sdkVersion.ToString(), _userProfileDir, workloadSetVersion)); + _workloadInstaller.GarbageCollect( + workloadSetVersion => _workloadResolverFactory.CreateForWorkloadSet(_dotnetPath, _sdkVersion.ToString(), _userProfileDir, workloadSetVersion), + cancellationToken); Reporter.WriteLine(); Reporter.WriteLine(string.Format(CliCommandStrings.WorkloadUninstallUninstallSucceeded, string.Join(" ", _workloadIds))); Reporter.WriteLine(); }); } + catch (OperationCanceledException) + { + _workloadInstaller.Shutdown(); + throw; + } catch (Exception e) { _workloadInstaller.Shutdown(); diff --git a/src/Cli/dotnet/Commands/Workload/Update/WorkloadUpdateCommand.cs b/src/Cli/dotnet/Commands/Workload/Update/WorkloadUpdateCommand.cs index 298fb23de979..4d68444a34b4 100644 --- a/src/Cli/dotnet/Commands/Workload/Update/WorkloadUpdateCommand.cs +++ b/src/Cli/dotnet/Commands/Workload/Update/WorkloadUpdateCommand.cs @@ -75,15 +75,18 @@ public WorkloadUpdateCommand( _isRestoring = isRestoring; } - public override int Execute() + public override int Execute(CancellationToken cancellationToken) { if (!string.IsNullOrWhiteSpace(_downloadToCacheOption)) { try { - DownloadToOfflineCacheAsync(new DirectoryPath(_downloadToCacheOption), _includePreviews).Wait(); + DownloadToOfflineCacheAsync( + new DirectoryPath(_downloadToCacheOption), + _includePreviews, + cancellationToken).GetAwaiter().GetResult(); } - catch (Exception e) + catch (Exception e) when (e is not OperationCanceledException) { throw new GracefulException(string.Format(CliCommandStrings.WorkloadUpdateWorkloadCacheDownloadFailed, e.Message), e, isUserError: false); } @@ -95,19 +98,24 @@ public override int Execute() VerifySignatures, restoreActionConfig: RestoreActionConfiguration); - var packageUrls = GetUpdatablePackageUrlsAsync(_includePreviews, NullReporter.Instance, packageDownloader).GetAwaiter().GetResult(); + var packageUrls = GetUpdatablePackageUrlsAsync( + _includePreviews, + cancellationToken, + NullReporter.Instance, + packageDownloader).GetAwaiter().GetResult(); Reporter.WriteLine(JsonSerializer.Serialize(packageUrls, WorkloadInstallJsonSerializerContext.Default.IEnumerableString)); } else if (_adManifestOnlyOption) { bool? shouldUseWorkloadSetsPerGlobalJson = _shouldUseWorkloadSets ?? (SpecifiedWorkloadSetVersionInGlobalJson ? true : null); _workloadManifestUpdater.UpdateAdvertisingManifestsAsync( + cancellationToken, _includePreviews, shouldUseWorkloadSetsPerGlobalJson ?? WorkloadManifestUpdater.ShouldUseWorkloadSetMode(_sdkFeatureBand, _workloadRootDir), string.IsNullOrWhiteSpace(_fromCacheOption) ? null : new DirectoryPath(_fromCacheOption)) - .Wait(); + .GetAwaiter().GetResult(); Reporter.WriteLine(); Reporter.WriteLine(CliCommandStrings.WorkloadUpdateAdManifestsSucceeded); } @@ -125,15 +133,15 @@ public override int Execute() { _recorder.Run(() => { - UpdateWorkloads(); + UpdateWorkloads(cancellationToken); }); } else { - UpdateWorkloads(); + UpdateWorkloads(cancellationToken); } } - catch (Exception e) + catch (Exception e) when (e is not OperationCanceledException) { // Don't show entire stack trace throw new GracefulException(string.Format(CliCommandStrings.WorkloadUpdateFailed, e.Message), e, isUserError: false); @@ -147,13 +155,13 @@ public override int Execute() return _workloadInstaller.ExitCode; } - private void UpdateWorkloads() + private void UpdateWorkloads(CancellationToken cancellationToken) { DirectoryPath? offlineCache = string.IsNullOrWhiteSpace(_fromCacheOption) ? null : new DirectoryPath(_fromCacheOption); var workloadIds = Enumerable.Empty(); RunInNewTransaction(context => { - UpdateWorkloadManifests(_recorder, context, offlineCache); + UpdateWorkloadManifests(_recorder, context, cancellationToken, offlineCache); // This depends on getting the available workloads, so it needs to run after manifests have potentially been installed workloadIds = WriteSDKInstallRecordsForVSWorkloads(GetUpdatableWorkloads()); @@ -162,16 +170,22 @@ private void UpdateWorkloads() { if (!_historyManifestOnlyOption) { - UpdateInstalledWorkloadsFromHistory(context, offlineCache); + UpdateInstalledWorkloadsFromHistory(context, cancellationToken, offlineCache); } } else { - _workloadInstaller.InstallWorkloads(workloadIds, _sdkFeatureBand, context, offlineCache); + _workloadInstaller.InstallWorkloads(workloadIds, _sdkFeatureBand, context, cancellationToken, offlineCache); } }); - WorkloadInstallCommand.TryRunGarbageCollection(_workloadInstaller, Reporter, Verbosity, workloadSetVersion => _workloadResolverFactory.CreateForWorkloadSet(_dotnetPath, _sdkVersion.ToString(), _userProfileDir, workloadSetVersion), offlineCache); + WorkloadInstallCommand.TryRunGarbageCollection( + _workloadInstaller, + Reporter, + Verbosity, + workloadSetVersion => _workloadResolverFactory.CreateForWorkloadSet(_dotnetPath, _sdkVersion.ToString(), _userProfileDir, workloadSetVersion), + cancellationToken, + offlineCache); // TODO: potentially only do this in some cases (ie not if global.json specifies workload set) _workloadManifestUpdater.DeleteUpdatableWorkloadsFile(); @@ -181,7 +195,10 @@ private void UpdateWorkloads() Reporter.WriteLine(); } - private void UpdateInstalledWorkloadsFromHistory(ITransactionContext context, DirectoryPath? offlineCache) + private void UpdateInstalledWorkloadsFromHistory( + ITransactionContext context, + CancellationToken cancellationToken, + DirectoryPath? offlineCache) { if (FromHistory) { @@ -192,7 +209,7 @@ private void UpdateInstalledWorkloadsFromHistory(ITransactionContext context, Di var workloadsToInstall = desiredWorkloads.Except(installedWorkloads).ToList(); var workloadsToUninstall = installedWorkloads.Except(desiredWorkloads).ToList(); - _workloadInstaller.InstallWorkloads(workloadsToInstall, _sdkFeatureBand, context, offlineCache); + _workloadInstaller.InstallWorkloads(workloadsToInstall, _sdkFeatureBand, context, cancellationToken, offlineCache); foreach (var id in workloadsToUninstall) { @@ -202,21 +219,32 @@ private void UpdateInstalledWorkloadsFromHistory(ITransactionContext context, Di } } - private async Task DownloadToOfflineCacheAsync(DirectoryPath offlineCache, bool includePreviews) + private async Task DownloadToOfflineCacheAsync( + DirectoryPath offlineCache, + bool includePreviews, + CancellationToken cancellationToken) { - await GetDownloads(GetUpdatableWorkloads(), skipManifestUpdate: false, includePreviews, offlineCache.Value); + await GetDownloads(GetUpdatableWorkloads(), cancellationToken, skipManifestUpdate: false, includePreviews, offlineCache.Value); } - private async Task> GetUpdatablePackageUrlsAsync(bool includePreview, IReporter reporter = null, INuGetPackageDownloader packageDownloader = null) + private async Task> GetUpdatablePackageUrlsAsync( + bool includePreview, + CancellationToken cancellationToken, + IReporter reporter = null, + INuGetPackageDownloader packageDownloader = null) { reporter ??= Reporter; packageDownloader ??= PackageDownloader; - var downloads = await GetDownloads(GetUpdatableWorkloads(reporter), skipManifestUpdate: false, includePreview, reporter: reporter, packageDownloader: packageDownloader); + var downloads = await GetDownloads(GetUpdatableWorkloads(reporter), cancellationToken, skipManifestUpdate: false, includePreview, reporter: reporter, packageDownloader: packageDownloader); var urls = new List(); foreach (var download in downloads) { - urls.Add(await packageDownloader.GetPackageUrl(new PackageId(download.NuGetPackageId), new NuGetVersion(download.NuGetPackageVersion), _packageSourceLocation)); + urls.Add(await packageDownloader.GetPackageUrl( + new PackageId(download.NuGetPackageId), + cancellationToken, + new NuGetVersion(download.NuGetPackageVersion), + _packageSourceLocation)); } return urls; diff --git a/src/Cli/dotnet/Commands/Workload/WorkloadCommandParser.cs b/src/Cli/dotnet/Commands/Workload/WorkloadCommandParser.cs index 91bc0921d6f8..fa4bc8b9bdd5 100644 --- a/src/Cli/dotnet/Commands/Workload/WorkloadCommandParser.cs +++ b/src/Cli/dotnet/Commands/Workload/WorkloadCommandParser.cs @@ -3,6 +3,7 @@ using System.CommandLine; using System.CommandLine.Invocation; +using Microsoft.DotNet.Cli.CommandLine; using Microsoft.DotNet.Cli.Commands.Workload.Clean; using Microsoft.DotNet.Cli.Commands.Workload.Config; using Microsoft.DotNet.Cli.Commands.Workload.Elevate; @@ -29,18 +30,18 @@ public static void ConfigureCommand(WorkloadCommandDefinition def) def.InfoOption.Action = new ShowWorkloadsInfoAction(); def.VersionOption.Action = new ShowWorkloadsVersionOption(); - def.InstallCommand.SetAction(parseResult => new WorkloadInstallCommand(parseResult).Execute()); - def.UpdateCommand.SetAction(parseResult => new WorkloadUpdateCommand(parseResult).Execute()); - def.ListCommand.SetAction(parseResult => new WorkloadListCommand(parseResult).Execute()); - def.SearchCommand.SetAction(parseResult => new WorkloadSearchCommand(parseResult).Execute()); - def.SearchCommand.VersionCommand.SetAction(parseResult => new WorkloadSearchVersionsCommand(parseResult).Execute()); - def.UninstallCommand.SetAction(parseResult => new WorkloadUninstallCommand(parseResult).Execute()); - def.RepairCommand.SetAction(parseResult => new WorkloadRepairCommand(parseResult).Execute()); - def.RestoreCommand.SetAction(parseResult => new WorkloadRestoreCommand(parseResult).Execute()); - def.CleanCommand.SetAction(parseResult => new WorkloadCleanCommand(parseResult).Execute()); - def.ElevateCommand.SetAction(parseResult => new WorkloadElevateCommand(parseResult).Execute()); - def.ConfigCommand.SetAction(parseResult => new WorkloadConfigCommand(parseResult).Execute()); - def.HistoryCommand.SetAction(parseResult => new WorkloadHistoryCommand(parseResult).Execute()); + def.InstallCommand.SetAction((parseResult, cancellationToken) => new WorkloadInstallCommand(parseResult).Execute(cancellationToken)); + def.UpdateCommand.SetAction((parseResult, cancellationToken) => new WorkloadUpdateCommand(parseResult).Execute(cancellationToken)); + def.ListCommand.SetAction((parseResult, cancellationToken) => new WorkloadListCommand(parseResult).Execute(cancellationToken)); + def.SearchCommand.SetAction((parseResult, cancellationToken) => new WorkloadSearchCommand(parseResult).Execute(cancellationToken)); + def.SearchCommand.VersionCommand.SetAction((parseResult, cancellationToken) => new WorkloadSearchVersionsCommand(parseResult).Execute(cancellationToken)); + def.UninstallCommand.SetAction((parseResult, cancellationToken) => new WorkloadUninstallCommand(parseResult).Execute(cancellationToken)); + def.RepairCommand.SetAction((parseResult, cancellationToken) => new WorkloadRepairCommand(parseResult).Execute(cancellationToken)); + def.RestoreCommand.SetAction((parseResult, cancellationToken) => new WorkloadRestoreCommand(parseResult).Execute(cancellationToken)); + def.CleanCommand.SetAction((parseResult, cancellationToken) => new WorkloadCleanCommand(parseResult).Execute(cancellationToken)); + def.ElevateCommand.SetAction((parseResult, cancellationToken) => new WorkloadElevateCommand(parseResult).Execute(cancellationToken)); + def.ConfigCommand.SetAction((parseResult, cancellationToken) => new WorkloadConfigCommand(parseResult).Execute(cancellationToken)); + def.HistoryCommand.SetAction((parseResult, cancellationToken) => new WorkloadHistoryCommand(parseResult).Execute(cancellationToken)); } public static RestoreActionConfig ToRestoreActionConfig(this NuGetRestoreOptions options, ParseResult parseResult) diff --git a/src/Cli/dotnet/Commands/Workload/WorkloadIntegrityChecker.cs b/src/Cli/dotnet/Commands/Workload/WorkloadIntegrityChecker.cs index 7002d4c02aaa..dd82f5fd9a5e 100644 --- a/src/Cli/dotnet/Commands/Workload/WorkloadIntegrityChecker.cs +++ b/src/Cli/dotnet/Commands/Workload/WorkloadIntegrityChecker.cs @@ -38,7 +38,11 @@ public static void RunFirstUseCheck(IReporter reporter) if (installedWorkloads.Any()) { reporter.WriteLine(CliCommandStrings.WorkloadIntegrityCheck); - CliTransaction.RunNew(context => installer.InstallWorkloads(installedWorkloads, sdkFeatureBand, context)); + CliTransaction.RunNew(context => installer.InstallWorkloads( + installedWorkloads, + sdkFeatureBand, + context, + ProcessLifecycle.CancellationToken)); reporter.WriteLine("----------------"); } } diff --git a/src/Cli/dotnet/Commands/Workload/WorkloadManifestCorruptionRepairer.cs b/src/Cli/dotnet/Commands/Workload/WorkloadManifestCorruptionRepairer.cs index 28bfe766a5f0..124f6279f6ba 100644 --- a/src/Cli/dotnet/Commands/Workload/WorkloadManifestCorruptionRepairer.cs +++ b/src/Cli/dotnet/Commands/Workload/WorkloadManifestCorruptionRepairer.cs @@ -93,7 +93,10 @@ private void RepairCorruptWorkloadSet(ITransactionContext context, WorkloadSet w foreach (var manifestUpdate in manifestUpdates) { - _workloadInstaller.InstallWorkloadManifest(manifestUpdate, context); + _workloadInstaller.InstallWorkloadManifest( + manifestUpdate, + context, + ProcessLifecycle.CancellationToken); } } diff --git a/src/Cli/dotnet/FilePermissionSetter.cs b/src/Cli/dotnet/FilePermissionSetter.cs index 4b1ee8216b23..fc271612dd93 100644 --- a/src/Cli/dotnet/FilePermissionSetter.cs +++ b/src/Cli/dotnet/FilePermissionSetter.cs @@ -9,9 +9,9 @@ namespace Microsoft.DotNet.Cli; internal class FilePermissionSetter : IFilePermissionSetter { - public void SetUserExecutionPermission(string path) + public void SetUserExecutionPermission(string path, CancellationToken cancellationToken) { - RunCommand(path, "u+x"); + RunCommand(path, "u+x", cancellationToken); } /// @@ -19,12 +19,12 @@ public void SetUserExecutionPermission(string path) /// (G)roup can read, can't write and can execute. /// (O)thers can read, can't write and can execute. /// - public void SetPermission(string path, string chmodArgument) + public void SetPermission(string path, string chmodArgument, CancellationToken cancellationToken) { - RunCommand(path, chmodArgument.ToString()); + RunCommand(path, chmodArgument.ToString(), cancellationToken); } - private static void RunCommand(string path, string chmodArgument) + private static void RunCommand(string path, string chmodArgument, CancellationToken cancellationToken) { if (OperatingSystem.IsWindows()) { @@ -35,7 +35,7 @@ private static void RunCommand(string path, string chmodArgument) .Create("chmod", [chmodArgument, path]) .CaptureStdOut() .CaptureStdErr() - .Execute(); + .Execute(cancellationToken); if (result.ExitCode != 0) { diff --git a/src/Cli/dotnet/FirstRunExperience.cs b/src/Cli/dotnet/FirstRunExperience.cs index 25044b7b4126..2ae6bd9d098d 100644 --- a/src/Cli/dotnet/FirstRunExperience.cs +++ b/src/Cli/dotnet/FirstRunExperience.cs @@ -152,7 +152,7 @@ public static bool Setup(ParseResult parseResult) { WorkloadIntegrityChecker.RunFirstUseCheck(reporter); } - catch (Exception) + catch (Exception ex) when (ex is not OperationCanceledException) { // If the workload check fails for any reason, we want to eat the failure and continue running the command. reporter.WriteLine(CliStrings.WorkloadIntegrityCheckError.Yellow()); diff --git a/src/Cli/dotnet/ForwardingApp.cs b/src/Cli/dotnet/ForwardingApp.cs index e0382f781d35..2daabcad4a82 100644 --- a/src/Cli/dotnet/ForwardingApp.cs +++ b/src/Cli/dotnet/ForwardingApp.cs @@ -35,8 +35,8 @@ public ForwardingApp WithEnvironmentVariable(string name, string value) return this; } - public int Execute() + public int Execute(CancellationToken cancellationToken) { - return _implementation.Execute(); + return _implementation.Execute(cancellationToken); } } diff --git a/src/Cli/dotnet/ICommandRunner.cs b/src/Cli/dotnet/ICommandRunner.cs index 1f88b750a8ba..65d9b82c7fcb 100644 --- a/src/Cli/dotnet/ICommandRunner.cs +++ b/src/Cli/dotnet/ICommandRunner.cs @@ -7,5 +7,5 @@ namespace Microsoft.DotNet.Cli; public interface ICommandRunner { - int Run(string[] commandArgs); + int Run(string[] commandArgs, CancellationToken cancellationToken); } diff --git a/src/Cli/dotnet/IFilePermissionSetter.cs b/src/Cli/dotnet/IFilePermissionSetter.cs index 17909ffc54de..55a985e6b893 100644 --- a/src/Cli/dotnet/IFilePermissionSetter.cs +++ b/src/Cli/dotnet/IFilePermissionSetter.cs @@ -7,6 +7,6 @@ namespace Microsoft.DotNet.Cli; internal interface IFilePermissionSetter { - void SetUserExecutionPermission(string path); - void SetPermission(string path, string chmodArgument); + void SetUserExecutionPermission(string path, CancellationToken cancellationToken); + void SetPermission(string path, string chmodArgument, CancellationToken cancellationToken); } diff --git a/src/Cli/dotnet/NuGetForwardingApp.cs b/src/Cli/dotnet/NuGetForwardingApp.cs index a3aeae4d6da5..08de64342476 100644 --- a/src/Cli/dotnet/NuGetForwardingApp.cs +++ b/src/Cli/dotnet/NuGetForwardingApp.cs @@ -21,13 +21,13 @@ public NuGetForwardingApp(IEnumerable argsToForward) NuGetSignatureVerificationEnabler.ConditionallyEnable(_forwardingApp); } - public int Execute() + public int Execute(CancellationToken cancellationToken) { // Ignore Ctrl-C for the remainder of the command's execution // Forwarding commands will just spawn the child process and exit Console.CancelKeyPress += (sender, e) => { e.Cancel = true; }; - return _forwardingApp.Execute(); + return _forwardingApp.Execute(cancellationToken); } public NuGetForwardingApp WithEnvironmentVariable(string name, string value) diff --git a/src/Cli/dotnet/NugetPackageDownloader/FirstPartyNuGetPackageSigningVerifier.cs b/src/Cli/dotnet/NugetPackageDownloader/FirstPartyNuGetPackageSigningVerifier.cs index 5f75683b4e80..54b88ef0886d 100644 --- a/src/Cli/dotnet/NugetPackageDownloader/FirstPartyNuGetPackageSigningVerifier.cs +++ b/src/Cli/dotnet/NugetPackageDownloader/FirstPartyNuGetPackageSigningVerifier.cs @@ -75,9 +75,10 @@ public FirstPartyNuGetPackageSigningVerifier() /// Path to the .nupkg file. /// Diagnostic output from the NuGet verify command. /// if the package is validly signed by Microsoft. - public bool Verify(FilePath nupkgToVerify, out string commandOutput) + public bool Verify(FilePath nupkgToVerify, CancellationToken cancellationToken, out string commandOutput) { - return NuGetVerify(nupkgToVerify, out commandOutput) && IsFirstParty(nupkgToVerify); + return NuGetVerify(nupkgToVerify, cancellationToken, out commandOutput) && + IsFirstParty(nupkgToVerify, cancellationToken); } /// @@ -93,13 +94,13 @@ public bool Verify(FilePath nupkgToVerify, out string commandOutput) /// This does NOT validate the signature itself — only the identity of the signer. /// Call first for signature validation. /// - internal bool IsFirstParty(FilePath nupkgToVerify) + internal bool IsFirstParty(FilePath nupkgToVerify, CancellationToken cancellationToken) { try { using (var packageReader = new PackageArchiveReader(nupkgToVerify.Value)) { - PrimarySignature primarySignature = packageReader.GetPrimarySignatureAsync(CancellationToken.None).GetAwaiter().GetResult(); + PrimarySignature primarySignature = packageReader.GetPrimarySignatureAsync(cancellationToken).GetAwaiter().GetResult(); using (IX509CertificateChain certificateChain = SignatureUtility.GetCertificateChain(primarySignature)) { if (certificateChain.Count < 2) @@ -143,13 +144,17 @@ internal bool IsFirstParty(FilePath nupkgToVerify) /// Combined stdout + stderr from the verify command. /// Working directory for NuGet config resolution (optional). /// if the package signature is valid. - public static bool NuGetVerify(FilePath nupkgToVerify, out string commandOutput, string currentWorkingDirectory = null) + public static bool NuGetVerify( + FilePath nupkgToVerify, + CancellationToken cancellationToken, + out string commandOutput, + string currentWorkingDirectory = null) { var args = new[] { "verify", "--all", nupkgToVerify.Value }; var command = new DotNetCommandFactory(alwaysRunOutOfProc: true, currentWorkingDirectory) .Create("nuget", args); - var commandResult = command.CaptureStdOut().Execute(); + var commandResult = command.CaptureStdOut().Execute(cancellationToken); commandOutput = commandResult.StdOut + Environment.NewLine + commandResult.StdErr; return commandResult.ExitCode == 0; } diff --git a/src/Cli/dotnet/NugetPackageDownloader/IFirstPartyNuGetPackageSigningVerifier.cs b/src/Cli/dotnet/NugetPackageDownloader/IFirstPartyNuGetPackageSigningVerifier.cs index 70a068ee810f..07f93ad21d6b 100644 --- a/src/Cli/dotnet/NugetPackageDownloader/IFirstPartyNuGetPackageSigningVerifier.cs +++ b/src/Cli/dotnet/NugetPackageDownloader/IFirstPartyNuGetPackageSigningVerifier.cs @@ -9,5 +9,5 @@ namespace Microsoft.DotNet.Cli.NuGetPackageDownloader; public interface IFirstPartyNuGetPackageSigningVerifier { - bool Verify(FilePath nupkgToVerify, out string commandOutput); + bool Verify(FilePath nupkgToVerify, CancellationToken cancellationToken, out string commandOutput); } diff --git a/src/Cli/dotnet/NugetPackageDownloader/INuGetPackageDownloader.cs b/src/Cli/dotnet/NugetPackageDownloader/INuGetPackageDownloader.cs index e77d302a74df..830dada6b20f 100644 --- a/src/Cli/dotnet/NugetPackageDownloader/INuGetPackageDownloader.cs +++ b/src/Cli/dotnet/NugetPackageDownloader/INuGetPackageDownloader.cs @@ -13,6 +13,7 @@ namespace Microsoft.DotNet.Cli.NuGetPackageDownloader; internal interface INuGetPackageDownloader { Task DownloadPackageAsync(PackageId packageId, + CancellationToken cancellationToken, NuGetVersion packageVersion = null, PackageSourceLocation packageSourceLocation = null, bool includePreview = false, @@ -21,27 +22,31 @@ Task DownloadPackageAsync(PackageId packageId, PackageSourceMapping packageSourceMapping = null); Task GetPackageUrl(PackageId packageId, + CancellationToken cancellationToken, NuGetVersion packageVersion = null, PackageSourceLocation packageSourceLocation = null, bool includePreview = false); - Task> ExtractPackageAsync(string packagePath, DirectoryPath targetFolder); + Task> ExtractPackageAsync(string packagePath, DirectoryPath targetFolder, CancellationToken cancellationToken); Task GetLatestPackageVersion(PackageId packageId, + CancellationToken cancellationToken, PackageSourceLocation packageSourceLocation = null, bool includePreview = false); Task> GetLatestPackageVersions(PackageId packageId, int numberOfResults, + CancellationToken cancellationToken, PackageSourceLocation packageSourceLocation = null, bool includePreview = false); Task GetBestPackageVersionAsync(PackageId packageId, VersionRange versionRange, + CancellationToken cancellationToken, PackageSourceLocation packageSourceLocation = null); Task<(NuGetVersion version, PackageSource source)> GetBestPackageVersionAndSourceAsync(PackageId packageId, VersionRange versionRange, - PackageSourceLocation packageSourceLocation = null, - CancellationToken cancellationToken = default); + CancellationToken cancellationToken, + PackageSourceLocation packageSourceLocation = null); } diff --git a/src/Cli/dotnet/NugetPackageDownloader/NuGetPackageDownloader.cs b/src/Cli/dotnet/NugetPackageDownloader/NuGetPackageDownloader.cs index baba57170c17..7256d048c349 100644 --- a/src/Cli/dotnet/NugetPackageDownloader/NuGetPackageDownloader.cs +++ b/src/Cli/dotnet/NugetPackageDownloader/NuGetPackageDownloader.cs @@ -158,6 +158,7 @@ public static NuGetPackageDownloader CreateForWorkloads( } public async Task DownloadPackageAsync(PackageId packageId, + CancellationToken cancellationToken, NuGetVersion packageVersion = null, PackageSourceLocation packageSourceLocation = null, bool includePreview = false, @@ -165,10 +166,14 @@ public async Task DownloadPackageAsync(PackageId packageId, DirectoryPath? downloadFolder = null, PackageSourceMapping packageSourceMapping = null) { - CancellationToken cancellationToken = CancellationToken.None; - - (var source, var resolvedPackageVersion) = await GetPackageSourceAndVersion(packageId, packageVersion, - packageSourceLocation, includePreview, includeUnlisted ?? packageVersion is not null, packageSourceMapping).ConfigureAwait(false); + (var source, var resolvedPackageVersion) = await GetPackageSourceAndVersion( + packageId, + cancellationToken, + packageVersion, + packageSourceLocation, + includePreview, + includeUnlisted ?? packageVersion is not null, + packageSourceMapping).ConfigureAwait(false); FindPackageByIdResource resource = null; SourceRepository repository = GetSourceRepository(source); @@ -199,7 +204,9 @@ public async Task DownloadPackageAsync(PackageId packageId, destinationStream, _cacheSettings, _verboseLogger, - cancellationToken)); + cancellationToken), + cancellationToken, + timer: _retryTimer ?? (() => ExponentialRetry.Timer(ExponentialRetry.Intervals, cancellationToken))); destinationStream.Close(); if (!success) @@ -212,7 +219,7 @@ public async Task DownloadPackageAsync(PackageId packageId, // Delete file if verification fails try { - await VerifySigning(nupkgPath, repository); + await VerifySigning(nupkgPath, repository, cancellationToken); } catch (NuGetPackageInstallerException) { @@ -252,7 +259,7 @@ private bool VerbosityGreaterThanMinimal() => /// /// Full path to the downloaded .nupkg file. /// The NuGet source repository the package was downloaded from. - private async Task VerifySigning(string nupkgPath, SourceRepository repository) + private async Task VerifySigning(string nupkgPath, SourceRepository repository, CancellationToken cancellationToken) { if (!_verifySignatures && !_validationMessagesDisplayed) { @@ -269,7 +276,7 @@ private async Task VerifySigning(string nupkgPath, SourceRepository repository) } if (repository is not null && - await repository.GetResourceAsync().ConfigureAwait(false) is RepositorySignatureResource resource && + await repository.GetResourceAsync(cancellationToken).ConfigureAwait(false) is RepositorySignatureResource resource && resource.AllRepositorySigned) { string commandOutput; @@ -281,8 +288,8 @@ await repository.GetResourceAsync().ConfigureAwait( // // With source mapping: NuGetVerify() = valid NuGet signature (any trusted signer) // -> Package source mapping already constrains feeds, so first-party requirement is relaxed. - if ((!_shouldUsePackageSourceMapping && !_firstPartyNuGetPackageSigningVerifier.Verify(new FilePath(nupkgPath), out commandOutput)) || - (_shouldUsePackageSourceMapping && !FirstPartyNuGetPackageSigningVerifier.NuGetVerify(new FilePath(nupkgPath), out commandOutput, _currentWorkingDirectory))) + if ((!_shouldUsePackageSourceMapping && !_firstPartyNuGetPackageSigningVerifier.Verify(new FilePath(nupkgPath), cancellationToken, out commandOutput)) || + (_shouldUsePackageSourceMapping && !FirstPartyNuGetPackageSigningVerifier.NuGetVerify(new FilePath(nupkgPath), cancellationToken, out commandOutput, _currentWorkingDirectory))) { throw new NuGetPackageInstallerException(string.Format(CliStrings.FailedToValidatePackageSigning, commandOutput)); } @@ -300,11 +307,12 @@ await repository.GetResourceAsync().ConfigureAwait( } public async Task GetPackageUrl(PackageId packageId, + CancellationToken cancellationToken, NuGetVersion packageVersion = null, PackageSourceLocation packageSourceLocation = null, bool includePreview = false) { - (var source, var resolvedPackageVersion) = await GetPackageSourceAndVersion(packageId, packageVersion, packageSourceLocation, includePreview).ConfigureAwait(false); + (var source, var resolvedPackageVersion) = await GetPackageSourceAndVersion(packageId, cancellationToken, packageVersion, packageSourceLocation, includePreview).ConfigureAwait(false); SourceRepository repository = GetSourceRepository(source); if (repository.PackageSource.IsLocal) @@ -315,14 +323,17 @@ public async Task GetPackageUrl(PackageId packageId, ); } - ServiceIndexResourceV3 serviceIndexResource = repository.GetResourceAsync().Result; + ServiceIndexResourceV3 serviceIndexResource = await repository.GetResourceAsync(cancellationToken).ConfigureAwait(false); IReadOnlyList packageBaseAddress = serviceIndexResource?.GetServiceEntryUris(ServiceTypes.PackageBaseAddress); return GetNupkgUrl(packageBaseAddress[0].ToString(), packageId, resolvedPackageVersion); } - public async Task> ExtractPackageAsync(string packagePath, DirectoryPath targetFolder) + public async Task> ExtractPackageAsync( + string packagePath, + DirectoryPath targetFolder, + CancellationToken cancellationToken) { await using FileStream packageStream = File.OpenRead(packagePath); PackageFolderReader packageReader = new(targetFolder.Value); @@ -332,8 +343,6 @@ public async Task> ExtractPackageAsync(string packagePath, D null, _verboseLogger); NuGetPackagePathResolver packagePathResolver = new(targetFolder.Value); - CancellationToken cancellationToken = CancellationToken.None; - var allFilesInPackage = await PackageExtractor.ExtractPackageAsync( targetFolder.Value, packageStream, @@ -362,7 +371,8 @@ public async Task> ExtractPackageAsync(string packagePath, D _filePermissionSetter .SetPermission( fullPath, - fileAndPermission.Permission); + fileAndPermission.Permission, + cancellationToken); } } } @@ -370,21 +380,24 @@ public async Task> ExtractPackageAsync(string packagePath, D return allFilesInPackage; } - public async Task> GetLatestVersionsOfPackage(string packageId, bool includePreview, int numberOfResults) + public async Task> GetLatestVersionsOfPackage( + string packageId, + bool includePreview, + int numberOfResults, + CancellationToken cancellationToken) { IEnumerable packageSources = LoadNuGetSources(new PackageId(packageId), null, null); - return (await GetLatestVersionsInternalAsync(packageId, packageSources, includePreview, CancellationToken.None, numberOfResults)).Select(result => result.Item2); + return (await GetLatestVersionsInternalAsync(packageId, packageSources, includePreview, cancellationToken, numberOfResults)).Select(result => result.Item2); } private async Task<(PackageSource, NuGetVersion)> GetPackageSourceAndVersion(PackageId packageId, + CancellationToken cancellationToken, NuGetVersion packageVersion = null, PackageSourceLocation packageSourceLocation = null, bool includePreview = false, bool includeUnlisted = false, PackageSourceMapping packageSourceMapping = null) { - CancellationToken cancellationToken = CancellationToken.None; - IPackageSearchMetadata packageMetadata; IEnumerable packagesSources = LoadNuGetSources(packageId, packageSourceLocation, packageSourceMapping); @@ -794,6 +807,7 @@ private static IEnumerable TakeRequestedResults(IEnumerable results, in public async Task GetBestPackageVersionAsync(PackageId packageId, VersionRange versionRange, + CancellationToken cancellationToken, PackageSourceLocation packageSourceLocation = null) { if (versionRange.MinVersion != null && versionRange.MaxVersion != null && versionRange.MinVersion == versionRange.MaxVersion) @@ -801,15 +815,15 @@ public async Task GetBestPackageVersionAsync(PackageId packageId, return versionRange.MinVersion; } - return (await GetBestPackageVersionAndSourceAsync(packageId, versionRange, packageSourceLocation) + return (await GetBestPackageVersionAndSourceAsync(packageId, versionRange, cancellationToken, packageSourceLocation) .ConfigureAwait(false)) .version; } public async Task<(NuGetVersion version, PackageSource source)> GetBestPackageVersionAndSourceAsync(PackageId packageId, VersionRange versionRange, - PackageSourceLocation packageSourceLocation = null, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken, + PackageSourceLocation packageSourceLocation = null) { IPackageSearchMetadata packageMetadata; @@ -946,15 +960,20 @@ bool TryGetPackageMetadata( } public async Task GetLatestPackageVersion(PackageId packageId, + CancellationToken cancellationToken, PackageSourceLocation packageSourceLocation = null, bool includePreview = false) { - return (await GetLatestPackageVersions(packageId, numberOfResults: 1, packageSourceLocation, includePreview)).First(); + return (await GetLatestPackageVersions(packageId, numberOfResults: 1, cancellationToken, packageSourceLocation, includePreview)).First(); } - public async Task> GetLatestPackageVersions(PackageId packageId, int numberOfResults, PackageSourceLocation packageSourceLocation = null, bool includePreview = false) + public async Task> GetLatestPackageVersions( + PackageId packageId, + int numberOfResults, + CancellationToken cancellationToken, + PackageSourceLocation packageSourceLocation = null, + bool includePreview = false) { - CancellationToken cancellationToken = CancellationToken.None; IEnumerable packagesSources = LoadNuGetSources(packageId, packageSourceLocation); return (await GetLatestVersionsInternalAsync(packageId.ToString(), packagesSources, diff --git a/src/Cli/dotnet/NugetSearch/INugetToolSearchApiRequest.cs b/src/Cli/dotnet/NugetSearch/INugetToolSearchApiRequest.cs index b099d3888554..dfe5f3228d02 100644 --- a/src/Cli/dotnet/NugetSearch/INugetToolSearchApiRequest.cs +++ b/src/Cli/dotnet/NugetSearch/INugetToolSearchApiRequest.cs @@ -7,5 +7,5 @@ namespace Microsoft.DotNet.Cli.NugetSearch; internal interface INugetToolSearchApiRequest { - Task GetResult(NugetSearchApiParameter nugetSearchApiParameter); + Task GetResult(NugetSearchApiParameter nugetSearchApiParameter, CancellationToken cancellationToken); } diff --git a/src/Cli/dotnet/NugetSearch/NugetToolSearchApiRequest.cs b/src/Cli/dotnet/NugetSearch/NugetToolSearchApiRequest.cs index 2849927a0e53..c612651e5e8b 100644 --- a/src/Cli/dotnet/NugetSearch/NugetToolSearchApiRequest.cs +++ b/src/Cli/dotnet/NugetSearch/NugetToolSearchApiRequest.cs @@ -17,17 +17,29 @@ namespace Microsoft.DotNet.Cli.NugetSearch; internal class NugetToolSearchApiRequest : INugetToolSearchApiRequest { - public async Task GetResult(NugetSearchApiParameter nugetSearchApiParameter) + private const string ServiceIndexUrl = "https://api.nuget.org/v3/index.json"; + private static readonly TimeSpan RequestTimeout = TimeSpan.FromSeconds(10); + + public async Task GetResult( + NugetSearchApiParameter nugetSearchApiParameter, + CancellationToken cancellationToken) + => await ExecuteRequest( + token => ConstructUrl( + nugetSearchApiParameter.SearchTerm, + nugetSearchApiParameter.Skip, + nugetSearchApiParameter.Take, + nugetSearchApiParameter.Prerelease, + token), + GetResultCore, + cancellationToken, + RequestTimeout); + + private static async Task GetResultCore( + Uri queryUrl, + CancellationToken cancellationToken) { - var queryUrl = await ConstructUrl( - nugetSearchApiParameter.SearchTerm, - nugetSearchApiParameter.Skip, - nugetSearchApiParameter.Take, - nugetSearchApiParameter.Prerelease); - - var httpClient = new HttpClient(); - using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(10)); - HttpResponseMessage response = await httpClient.GetAsync(queryUrl, cancellation.Token); + using var httpClient = new HttpClient(); + using HttpResponseMessage response = await httpClient.GetAsync(queryUrl, cancellationToken); if (!response.IsSuccessStatusCode) { if ((int)response.StatusCode >= 500 && (int)response.StatusCode < 600) @@ -44,13 +56,53 @@ public async Task GetResult(NugetSearchApiParameter nugetSearchApiParame queryUrl.AbsoluteUri, response.ReasonPhrase, response.StatusCode)); } - return await response.Content.ReadAsStringAsync(cancellation.Token); + return await response.Content.ReadAsStringAsync(cancellationToken); + } + + internal static async Task ExecuteRequest( + Func> constructUrl, + Func> executeQuery, + CancellationToken cancellationToken, + TimeSpan timeout) + { + Uri queryUrl = await constructUrl(cancellationToken); + return await ExecuteWithTimeout( + token => executeQuery(queryUrl, token), + cancellationToken, + timeout, + queryUrl.AbsoluteUri); + } + + internal static async Task ExecuteWithTimeout( + Func> operation, + CancellationToken cancellationToken, + TimeSpan timeout, + string requestUrl = ServiceIndexUrl) + { + using var timeoutCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeoutCancellation.CancelAfter(timeout); + + try + { + return await operation(timeoutCancellation.Token); + } + catch (OperationCanceledException e) when ( + timeoutCancellation.IsCancellationRequested && + !cancellationToken.IsCancellationRequested) + { + throw new NugetSearchApiRequestException( + string.Format( + CliStrings.RetriableNugetSearchFailure, + requestUrl, + e.Message, + "N/A")); + } } internal static async Task ConstructUrl(string searchTerm = null, int? skip = null, int? take = null, - bool prerelease = false, Uri domainAndPathOverride = null) + bool prerelease = false, CancellationToken cancellationToken = default, Uri domainAndPathOverride = null) { - var uriBuilder = new UriBuilder(domainAndPathOverride ?? await DomainAndPath()); + var uriBuilder = new UriBuilder(domainAndPathOverride ?? await DomainAndPath(cancellationToken)); NameValueCollection query = HttpUtility.ParseQueryString(uriBuilder.Query); if (!string.IsNullOrWhiteSpace(searchTerm)) { @@ -89,26 +141,29 @@ internal static async Task ConstructUrl(string searchTerm = null, int? skip // service index directly over HTTP and select the SearchQueryService endpoint using // System.Text.Json source generation. Failures are translated into NugetSearchApiRequestException // (a GracefulException) with the same retriable/non-retriable messaging as GetResult. - private static async Task DomainAndPath() + private static async Task DomainAndPath(CancellationToken cancellationToken) + => await ExecuteWithTimeout( + DomainAndPathCore, + cancellationToken, + RequestTimeout); + + private static async Task DomainAndPathCore(CancellationToken cancellationToken) { - const string serviceIndexUrl = "https://api.nuget.org/v3/index.json"; const string searchQueryServiceType = "SearchQueryService/3.5.0"; using var httpClient = new HttpClient(); - using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(10)); - HttpResponseMessage response; try { - response = await httpClient.GetAsync(serviceIndexUrl, cancellation.Token); + response = await httpClient.GetAsync(ServiceIndexUrl, cancellationToken); } - catch (Exception e) when (e is HttpRequestException or OperationCanceledException) + catch (HttpRequestException e) { // Transient network failures (DNS, connection refused, timeout) are retriable. throw new NugetSearchApiRequestException( string.Format( CliStrings.RetriableNugetSearchFailure, - serviceIndexUrl, e.Message, "N/A")); + ServiceIndexUrl, e.Message, "N/A")); } using (response) @@ -120,16 +175,16 @@ private static async Task DomainAndPath() throw new NugetSearchApiRequestException( string.Format( CliStrings.RetriableNugetSearchFailure, - serviceIndexUrl, response.ReasonPhrase, response.StatusCode)); + ServiceIndexUrl, response.ReasonPhrase, response.StatusCode)); } throw new NugetSearchApiRequestException( string.Format( CliStrings.NonRetriableNugetSearchFailure, - serviceIndexUrl, response.ReasonPhrase, response.StatusCode)); + ServiceIndexUrl, response.ReasonPhrase, response.StatusCode)); } - var indexJson = await response.Content.ReadAsStringAsync(cancellation.Token); + var indexJson = await response.Content.ReadAsStringAsync(cancellationToken); NugetServiceIndex index; try @@ -141,14 +196,14 @@ private static async Task DomainAndPath() throw new NugetSearchApiRequestException( string.Format( CliStrings.NonRetriableNugetSearchFailure, - serviceIndexUrl, e.Message, response.StatusCode)); + ServiceIndexUrl, e.Message, response.StatusCode)); } var resource = index?.Resources?.FirstOrDefault(r => r.Type == searchQueryServiceType) ?? throw new NugetSearchApiRequestException( string.Format( CliStrings.NonRetriableNugetSearchFailure, - serviceIndexUrl, $"{searchQueryServiceType} not found in service index", response.StatusCode)); + ServiceIndexUrl, $"{searchQueryServiceType} not found in service index", response.StatusCode)); // The service index is server-supplied, so don't trust the URL to be well-formed. try @@ -160,15 +215,15 @@ private static async Task DomainAndPath() throw new NugetSearchApiRequestException( string.Format( CliStrings.NonRetriableNugetSearchFailure, - serviceIndexUrl, $"{searchQueryServiceType} returned a malformed URL: {e.Message}", response.StatusCode)); + ServiceIndexUrl, $"{searchQueryServiceType} returned a malformed URL: {e.Message}", response.StatusCode)); } } } #else - private static async Task DomainAndPath() + private static async Task DomainAndPath(CancellationToken cancellationToken) { var repository = Repository.Factory.GetCoreV3("https://api.nuget.org/v3/index.json"); - var resource = await repository.GetResourceAsync(); + var resource = await repository.GetResourceAsync(cancellationToken); var uris = resource.GetServiceEntryUris("SearchQueryService/3.5.0"); return uris[0]; } diff --git a/src/Cli/dotnet/Parser.cs b/src/Cli/dotnet/Parser.cs index 85f3e61d5f08..3e4e27412353 100644 --- a/src/Cli/dotnet/Parser.cs +++ b/src/Cli/dotnet/Parser.cs @@ -349,6 +349,11 @@ public static bool TokenPerLine(string tokenToReplace, out IReadOnlyList public static InvocationConfiguration InvocationConfiguration { get; } = new() { EnableDefaultExceptionHandler = false, + // ProcessLifecycle owns Ctrl+C, SIGTERM, and process-exit cancellation, while + // ProcessReaper owns forwarding Ctrl+C to child processes. Avoid a second + // System.CommandLine signal handler that would cancel an action while its child is + // handling Ctrl+C. + ProcessTerminationTimeout = null, }; /// @@ -468,26 +473,26 @@ public override void Write(HelpContext context) if (IsInNuGetCommandTree(command)) { - NuGetCommand.Run(context.ParseResult); + NuGetCommand.Run(context.ParseResult, ProcessLifecycle.CancellationToken); } else if (command is MSBuildCommandDefinition) { - new MSBuildForwardingApp(MSBuildArgs.ForHelp).Execute(); + new MSBuildForwardingApp(MSBuildArgs.ForHelp).Execute(ProcessLifecycle.CancellationToken); context.Output.WriteLine(); additionalOption(context); } else if (command is VSTestCommandDefinition) { - new VSTestForwardingApp(["--help"], useArtifactsDirectory: false).Execute(); + new VSTestForwardingApp(["--help"], useArtifactsDirectory: false).Execute(ProcessLifecycle.CancellationToken); } else if (command is FormatCommandDefinition format) { var arguments = context.ParseResult.GetValue(format.Arguments) ?? []; - new FormatForwardingApp([.. arguments, "--help"]).Execute(); + new FormatForwardingApp([.. arguments, "--help"]).Execute(ProcessLifecycle.CancellationToken); } else if (command is FsiCommandDefinition) { - new FsiForwardingApp(["--help"]).Execute(); + new FsiForwardingApp(["--help"]).Execute(ProcessLifecycle.CancellationToken); } else if (command is ICustomHelp helpCommand) { diff --git a/src/Cli/dotnet/Program.cs b/src/Cli/dotnet/Program.cs index 8e4f979f176b..e393ec0a0f83 100644 --- a/src/Cli/dotnet/Program.cs +++ b/src/Cli/dotnet/Program.cs @@ -20,9 +20,7 @@ namespace Microsoft.DotNet.Cli; public class Program { private static readonly Activity? s_mainActivity; - private static readonly PosixSignalRegistration s_sigIntRegistration; private static readonly PosixSignalRegistration s_sigQuitRegistration; - private static readonly PosixSignalRegistration s_sigTermRegistration; private static readonly string? s_globalJsonState; public static ITelemetryClient TelemetryInstance { get; private set; } @@ -30,9 +28,7 @@ public class Program static Program() { var preTelemetry = DateTime.UtcNow; - s_sigIntRegistration = PosixSignalRegistration.Create(PosixSignal.SIGINT, Shutdown); s_sigQuitRegistration = PosixSignalRegistration.Create(PosixSignal.SIGQUIT, Shutdown); - s_sigTermRegistration = PosixSignalRegistration.Create(PosixSignal.SIGTERM, Shutdown); // Note: This TelemetryClient instance needs to be created prior to calculating ActivityKind and ParentActivityContext, // used in the main activity creation below. @@ -75,11 +71,8 @@ static Program() public static int Main(string[] args) { - // Register a handler for SIGTERM to allow graceful shutdown of the application on Unix. - // See https://github.com/dotnet/docs/issues/46226. - using var termSignalRegistration = PosixSignalRegistration.Create(PosixSignal.SIGTERM, _ => Environment.Exit(0)); - - using AutomaticEncodingRestorer _ = new(); + using IDisposable processLifecycle = ProcessLifecycle.Initialize(); + using AutomaticEncodingRestorer encodingRestorer = new(); if (Env.GetEnvironmentVariable(EnvironmentVariableNames.DOTNET_CLI_CONSOLE_USE_DEFAULT_ENCODING) != "1" // Setting output encoding is not available on those platforms @@ -101,6 +94,13 @@ public static int Main(string[] args) s_mainActivity?.AddTag("process.exit.code", exitCode)?.SetStatus(ActivityStatusCode.Ok); return exitCode; } + catch (OperationCanceledException) when ( + ProcessLifecycle.TryGetSignalExitCode(ProcessLifecycle.CancellationToken, out int signalExitCode)) + { + exitCode = signalExitCode; + s_mainActivity?.AddTag("process.exit.code", exitCode)?.SetStatus(ActivityStatusCode.Ok); + return exitCode; + } catch (Exception e) when (e.ShouldBeDisplayedAsError()) { Reporter.Error.WriteLine(CommandLoggingContext.IsVerbose @@ -124,7 +124,7 @@ public static int Main(string[] args) finally { TelemetryInstance.TrackEvent("command/finish", new Dictionary { { "exitCode", exitCode.ToString() } }); - Shutdown(null, exitCode); + Shutdown(ProcessLifecycle.IsSignalTerminationRequested, exitCode); TelemetryClient.WriteLogIfNecessary(); } } @@ -140,12 +140,12 @@ internal static int ProcessArgsAndExecute(string[] args) TelemetryEventEntry.SendFiltered(new ParseResultWithGlobalJsonState(parseResult, s_globalJsonState)); if (parseResult.CanBeInvoked()) { - return CommandInvocation.ExecuteInternalCommand(parseResult); + return CommandInvocation.ExecuteInternalCommand(parseResult, ProcessLifecycle.CancellationToken); } try { - return ExecuteExternalCommand(args, parseResult); + return ExecuteExternalCommand(args, parseResult, ProcessLifecycle.CancellationToken); } catch (CommandUnknownException e) { @@ -171,7 +171,10 @@ static ParseResult ParseArgs(string[] args) } } - private static int ExecuteExternalCommand(string[] args, ParseResult parseResult) + internal static int ExecuteExternalCommand( + string[] args, + ParseResult parseResult, + CancellationToken cancellationToken) { string commandName = "dotnet-" + parseResult.GetValue(Parser.RootCommand.DotnetSubCommand); CommandSpec? resolvedCommandSpec = null; @@ -192,7 +195,7 @@ private static int ExecuteExternalCommand(string[] args, ParseResult parseResult var resolvedCommand = CommandFactoryUsingResolver.CreateOrThrow(commandName, resolvedCommandSpec); using var __ = Activities.Source.StartActivity("execute-extensible-command"); - return resolvedCommand.Execute().ExitCode; + return resolvedCommand.Execute(cancellationToken).ExitCode; } private static int? TryRunFileBasedApp(ParseResult parseResult) @@ -201,26 +204,23 @@ private static int ExecuteExternalCommand(string[] args, ParseResult parseResult // parse as `dotnet run file.cs ..rest_of_args` instead. if (parseResult.TryParseFileBasedAppAsRun() is { } runParseResult) { - return CommandInvocation.ExecuteInternalCommand(runParseResult); + return CommandInvocation.ExecuteInternalCommand(runParseResult, ProcessLifecycle.CancellationToken); } return null; } - public static void Shutdown(PosixSignalContext? context) - => Shutdown(context, 0); + public static void Shutdown(PosixSignalContext? context) => Shutdown(context is not null, 0); - private static void Shutdown(PosixSignalContext? context, int exitCode) + private static void Shutdown(bool signalTerminationRequested, int exitCode) { s_mainActivity?.SetEndTime(DateTime.UtcNow); - s_sigIntRegistration.Dispose(); s_sigQuitRegistration.Dispose(); - s_sigTermRegistration.Dispose(); if (TelemetryInstance is TelemetryClient telemetryClient) { telemetryClient.WaitForPendingEvents(); } - if (context is null) + if (!signalTerminationRequested) { TelemetryClient.WaitForInternalMicrosoftDetection(); } diff --git a/src/Cli/dotnet/ReleasePropertyProjectLocator.cs b/src/Cli/dotnet/ReleasePropertyProjectLocator.cs index ae958c427568..3bc9110614c0 100644 --- a/src/Cli/dotnet/ReleasePropertyProjectLocator.cs +++ b/src/Cli/dotnet/ReleasePropertyProjectLocator.cs @@ -25,7 +25,8 @@ namespace Microsoft.DotNet.Cli; internal sealed class ReleasePropertyProjectLocator( ReadOnlyDictionary? userSpecifiedExplicitMSBuildProperties, string propertyToCheck, - ReleasePropertyProjectLocator.DependentCommandOptions commandOptions) + ReleasePropertyProjectLocator.DependentCommandOptions commandOptions, + CancellationToken cancellationToken) { public readonly struct DependentCommandOptions(IEnumerable? slnOrProjectArgs, string? configOption = null, string? frameworkOption = null) { @@ -148,7 +149,11 @@ public readonly struct DependentCommandOptions(IEnumerable? slnOrProject SolutionModel sln; try { - sln = SlnFileFactory.CreateFromFileOrDirectory(slnFullPath, false, false); + sln = SlnFileFactory.CreateFromFileOrDirectory( + slnFullPath, + cancellationToken, + includeSolutionFilterFiles: false, + includeSolutionXmlFiles: false); } catch (GracefulException) { diff --git a/src/Cli/dotnet/ShellShim/AppHostShimMaker.cs b/src/Cli/dotnet/ShellShim/AppHostShimMaker.cs index f1518763c440..304946535e12 100644 --- a/src/Cli/dotnet/ShellShim/AppHostShimMaker.cs +++ b/src/Cli/dotnet/ShellShim/AppHostShimMaker.cs @@ -17,7 +17,7 @@ internal class AppHostShellShimMaker(string appHostSourceDirectory, IFilePermiss ?? new FilePermissionSetter(); private const ushort WindowsGUISubsystem = 0x2; - public void CreateApphostShellShim(FilePath entryPoint, FilePath shimPath) + public void CreateApphostShellShim(FilePath entryPoint, FilePath shimPath, CancellationToken cancellationToken) { string appHostSourcePath; if (OperatingSystem.IsWindows()) @@ -43,6 +43,6 @@ public void CreateApphostShellShim(FilePath entryPoint, FilePath shimPath) assemblyToCopyResourcesFrom: entryPointFullPath, enableMacOSCodeSign: OperatingSystem.IsMacOS()); - _filePermissionSetter.SetUserExecutionPermission(appHostDestinationFilePath); + _filePermissionSetter.SetUserExecutionPermission(appHostDestinationFilePath, cancellationToken); } } diff --git a/src/Cli/dotnet/ShellShim/IApphostShellShimMaker.cs b/src/Cli/dotnet/ShellShim/IApphostShellShimMaker.cs index 5f66c3d1c1e3..7013e0db5531 100644 --- a/src/Cli/dotnet/ShellShim/IApphostShellShimMaker.cs +++ b/src/Cli/dotnet/ShellShim/IApphostShellShimMaker.cs @@ -9,5 +9,5 @@ namespace Microsoft.DotNet.Cli.ShellShim; internal interface IAppHostShellShimMaker { - void CreateApphostShellShim(FilePath entryPoint, FilePath shimPath); + void CreateApphostShellShim(FilePath entryPoint, FilePath shimPath, CancellationToken cancellationToken); } diff --git a/src/Cli/dotnet/ShellShim/IShellShimRepository.cs b/src/Cli/dotnet/ShellShim/IShellShimRepository.cs index 9d8c41545e5e..571b145b2beb 100644 --- a/src/Cli/dotnet/ShellShim/IShellShimRepository.cs +++ b/src/Cli/dotnet/ShellShim/IShellShimRepository.cs @@ -11,7 +11,7 @@ namespace Microsoft.DotNet.Cli.ShellShim; internal interface IShellShimRepository { - void CreateShim(ToolCommand toolCommand, IReadOnlyList packagedShims = null); + void CreateShim(ToolCommand toolCommand, CancellationToken cancellationToken, IReadOnlyList packagedShims = null); void RemoveShim(ToolCommand toolCommand); } diff --git a/src/Cli/dotnet/ShellShim/ShellShimRepository.cs b/src/Cli/dotnet/ShellShim/ShellShimRepository.cs index cdc1b8ed8b31..d1c1fede37cc 100644 --- a/src/Cli/dotnet/ShellShim/ShellShimRepository.cs +++ b/src/Cli/dotnet/ShellShim/ShellShimRepository.cs @@ -21,7 +21,10 @@ internal class ShellShimRepository( private readonly IAppHostShellShimMaker _appHostShellShimMaker = appHostShellShimMaker ?? new AppHostShellShimMaker(appHostSourceDirectory: appHostSourceDirectory); private readonly IFilePermissionSetter _filePermissionSetter = filePermissionSetter ?? new FilePermissionSetter(); - public void CreateShim(ToolCommand toolCommand, IReadOnlyList packagedShims = null) + public void CreateShim( + ToolCommand toolCommand, + CancellationToken cancellationToken, + IReadOnlyList packagedShims = null) { if (string.IsNullOrEmpty(toolCommand.Executable.Value)) { @@ -51,13 +54,14 @@ public void CreateShim(ToolCommand toolCommand, IReadOnlyList packaged if (TryGetPackagedShim(packagedShims, toolCommand, out FilePath? packagedShim)) { _fileSystem.File.Copy(packagedShim.Value.Value, GetShimPath(toolCommand).Value); - _filePermissionSetter.SetUserExecutionPermission(GetShimPath(toolCommand).Value); + _filePermissionSetter.SetUserExecutionPermission(GetShimPath(toolCommand).Value, cancellationToken); } else { _appHostShellShimMaker.CreateApphostShellShim( toolCommand.Executable, - GetShimPath(toolCommand)); + GetShimPath(toolCommand), + cancellationToken); } } else if (toolCommand.Runner == "executable") @@ -76,7 +80,7 @@ public void CreateShim(ToolCommand toolCommand, IReadOnlyList packaged else { File.CreateSymbolicLink(shimPath, relativePathToExe); - _filePermissionSetter.SetUserExecutionPermission(shimPath); + _filePermissionSetter.SetUserExecutionPermission(shimPath, cancellationToken); } } else diff --git a/src/Cli/dotnet/ShellShim/ShellShimTemplateFinder.cs b/src/Cli/dotnet/ShellShim/ShellShimTemplateFinder.cs index c416292bca02..bb0eddcc1e04 100644 --- a/src/Cli/dotnet/ShellShim/ShellShimTemplateFinder.cs +++ b/src/Cli/dotnet/ShellShim/ShellShimTemplateFinder.cs @@ -21,7 +21,11 @@ internal class ShellShimTemplateFinder( private readonly INuGetPackageDownloader _nugetPackageDownloader = nugetPackageDownloader; private readonly PackageSourceLocation _packageSourceLocation = packageSourceLocation; - public async Task ResolveAppHostSourceDirectoryAsync(string archOption, NuGetFramework targetFramework, Architecture arch) + public async Task ResolveAppHostSourceDirectoryAsync( + string archOption, + NuGetFramework targetFramework, + Architecture arch, + CancellationToken cancellationToken) { string rid; var validRids = new string[] { "win-x64", "win-arm64", "osx-x64", "osx-arm64" }; @@ -52,8 +56,12 @@ public async Task ResolveAppHostSourceDirectoryAsync(string archOption, var packageId = new PackageId($"microsoft.netcore.app.host.{rid}"); NuGetVersion packageVersion = null; - var packagePath = await _nugetPackageDownloader.DownloadPackageAsync(packageId, packageVersion, packageSourceLocation: _packageSourceLocation); - _ = await _nugetPackageDownloader.ExtractPackageAsync(packagePath, _tempDir); + var packagePath = await _nugetPackageDownloader.DownloadPackageAsync( + packageId, + cancellationToken, + packageVersion, + packageSourceLocation: _packageSourceLocation); + _ = await _nugetPackageDownloader.ExtractPackageAsync(packagePath, _tempDir, cancellationToken); return Path.Combine(_tempDir.Value, "runtimes", rid, "native"); } diff --git a/src/Cli/dotnet/SlnFileFactory.cs b/src/Cli/dotnet/SlnFileFactory.cs index 497fa536e6a6..9e4bf85b3106 100644 --- a/src/Cli/dotnet/SlnFileFactory.cs +++ b/src/Cli/dotnet/SlnFileFactory.cs @@ -62,20 +62,24 @@ .. Directory.GetFiles(directory, "*.sln", SearchOption.TopDirectoryOnly), ]; } - public static SolutionModel CreateFromFileOrDirectory(string fileOrDirectory, bool includeSolutionFilterFiles = false, bool includeSolutionXmlFiles = true) + public static SolutionModel CreateFromFileOrDirectory( + string fileOrDirectory, + CancellationToken cancellationToken, + bool includeSolutionFilterFiles = false, + bool includeSolutionXmlFiles = true) { string solutionPath = GetSolutionFileFullPath(fileOrDirectory, includeSolutionFilterFiles, includeSolutionXmlFiles); if (solutionPath.HasExtension(".slnf")) { - return CreateFromFilteredSolutionFile(solutionPath); + return CreateFromFilteredSolutionFile(solutionPath, cancellationToken); } try { ISolutionSerializer serializer = SolutionSerializers.GetSerializerByMoniker(solutionPath)!; - return serializer.OpenAsync(solutionPath, CancellationToken.None).Result; + return serializer.OpenAsync(solutionPath, cancellationToken).GetAwaiter().GetResult(); } - catch (Exception ex) + catch (Exception ex) when (ex is not OperationCanceledException) { throw new GracefulException( CliStrings.InvalidSolutionFormatString, @@ -83,19 +87,23 @@ public static SolutionModel CreateFromFileOrDirectory(string fileOrDirectory, bo } } - public static SolutionModel CreateFromFilteredSolutionFile(string filteredSolutionPath) + public static SolutionModel CreateFromFilteredSolutionFile( + string filteredSolutionPath, + CancellationToken cancellationToken) { string originalSolutionPath; string originalSolutionPathAbsolute; IEnumerable filteredSolutionProjectPaths; try { + cancellationToken.ThrowIfCancellationRequested(); var options = new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip }; string fileContent = File.ReadAllText(filteredSolutionPath); + cancellationToken.ThrowIfCancellationRequested(); // Fix unescaped backslashes for backward compatibility with .slnf files that contain // Windows-style path separators without proper JSON escaping (e.g. "..\foo" instead of "..\\foo" or "../foo"). fileContent = FixInvalidJsonBackslashes(fileContent); @@ -106,7 +114,7 @@ public static SolutionModel CreateFromFilteredSolutionFile(string filteredSoluti filteredSolutionProjectPaths = [.. root.GetProperty("solution").GetProperty("projects").EnumerateArray().Select(p => p.GetString())]; originalSolutionPathAbsolute = Path.GetFullPath(originalSolutionPath, Path.GetDirectoryName(filteredSolutionPath)); } - catch (Exception ex) + catch (Exception ex) when (ex is not OperationCanceledException) { throw new GracefulException( CliStrings.InvalidSolutionFormatString, @@ -114,7 +122,7 @@ public static SolutionModel CreateFromFilteredSolutionFile(string filteredSoluti } SolutionModel filteredSolution = new(); - SolutionModel originalSolution = CreateFromFileOrDirectory(originalSolutionPathAbsolute); + SolutionModel originalSolution = CreateFromFileOrDirectory(originalSolutionPathAbsolute, cancellationToken); // Store the original solution path in the description field of the filtered solution filteredSolution.Description = originalSolutionPathAbsolute; diff --git a/src/Cli/dotnet/ToolPackage/IProjectRestorer.cs b/src/Cli/dotnet/ToolPackage/IProjectRestorer.cs index 757d234ae47d..0ecb5560d751 100644 --- a/src/Cli/dotnet/ToolPackage/IProjectRestorer.cs +++ b/src/Cli/dotnet/ToolPackage/IProjectRestorer.cs @@ -11,5 +11,6 @@ internal interface IProjectRestorer { void Restore(FilePath project, PackageLocation packageLocation, + CancellationToken cancellationToken, string verbosity = null); } diff --git a/src/Cli/dotnet/ToolPackage/IToolPackageDownloader.cs b/src/Cli/dotnet/ToolPackage/IToolPackageDownloader.cs index b7ba984c50d1..b584792dbbb3 100644 --- a/src/Cli/dotnet/ToolPackage/IToolPackageDownloader.cs +++ b/src/Cli/dotnet/ToolPackage/IToolPackageDownloader.cs @@ -13,6 +13,7 @@ internal interface IToolPackageDownloader { IToolPackage InstallPackage(PackageLocation packageLocation, PackageId packageId, + CancellationToken cancellationToken, VerbosityOptions verbosity, VersionRange? versionRange = null, string? targetFramework = null, diff --git a/src/Cli/dotnet/ToolPackage/ToolPackageDownloader.cs b/src/Cli/dotnet/ToolPackage/ToolPackageDownloader.cs index d7e73e0c1936..e8de1108f13a 100644 --- a/src/Cli/dotnet/ToolPackage/ToolPackageDownloader.cs +++ b/src/Cli/dotnet/ToolPackage/ToolPackageDownloader.cs @@ -56,6 +56,7 @@ protected override NuGetVersion DownloadAndExtractPackage( INuGetPackageDownloader nugetPackageDownloader, string packagesRootPath, NuGetVersion packageVersion, + CancellationToken cancellationToken, PackageSourceLocation packageSourceLocation, VerbosityOptions verbosity, bool includeUnlisted = false @@ -80,7 +81,7 @@ protected override NuGetVersion DownloadAndExtractPackage( string packageHash = File.ReadAllText(hashPath); using FileStream packageStream = File.OpenRead(targetNupkgPath); using PackageArchiveReader reader = new(packageStream); - string contentHash = reader.GetContentHash(CancellationToken.None, () => packageHash); + string contentHash = reader.GetContentHash(cancellationToken, () => packageHash); PublishPackageMetadata(metadataPath, contentHash); return; } @@ -91,6 +92,7 @@ protected override NuGetVersion DownloadAndExtractPackage( _downloadActivity?.DisplayName = $"Downloading tool {packageId}@{packageVersion}"; string packagePath = nugetPackageDownloader.DownloadPackageAsync( packageId, + cancellationToken, packageVersion, packageSourceLocation, includeUnlisted: includeUnlisted, @@ -111,7 +113,7 @@ protected override NuGetVersion DownloadAndExtractPackage( $"The downloaded package identity '{actualIdentity}' does not match the requested package identity '{expectedIdentity}'."); } - contentHash = reader.GetContentHash(CancellationToken.None, () => packageHash); + contentHash = reader.GetContentHash(cancellationToken, () => packageHash); } if (verbosity.IsDetailedOrDiagnostic()) @@ -120,7 +122,7 @@ protected override NuGetVersion DownloadAndExtractPackage( } var _extractActivity = Activities.Source.StartActivity("extract-tool"); - nugetPackageDownloader.ExtractPackageAsync(packagePath, new DirectoryPath(packageDirectory)).ConfigureAwait(false).GetAwaiter().GetResult(); + nugetPackageDownloader.ExtractPackageAsync(packagePath, new DirectoryPath(packageDirectory), cancellationToken).ConfigureAwait(false).GetAwaiter().GetResult(); _extractActivity?.Stop(); // NuGet readers treat these files as completion markers, so publish them only after extraction succeeds. diff --git a/src/Cli/dotnet/ToolPackage/ToolPackageDownloaderBase.cs b/src/Cli/dotnet/ToolPackage/ToolPackageDownloaderBase.cs index 480a690cf4f3..600fae1ab121 100644 --- a/src/Cli/dotnet/ToolPackage/ToolPackageDownloaderBase.cs +++ b/src/Cli/dotnet/ToolPackage/ToolPackageDownloaderBase.cs @@ -80,6 +80,7 @@ protected abstract NuGetVersion DownloadAndExtractPackage( INuGetPackageDownloader nugetPackageDownloader, string packagesRootPath, NuGetVersion packageVersion, + CancellationToken cancellationToken, PackageSourceLocation packageSourceLocation, VerbosityOptions verbosity, bool includeUnlisted = false @@ -104,6 +105,7 @@ protected abstract ToolConfiguration GetToolConfiguration(PackageId id, DirectoryPath assetsJsonParentDirectory); public IToolPackage InstallPackage(PackageLocation packageLocation, PackageId packageId, + CancellationToken cancellationToken, VerbosityOptions verbosity = VerbosityOptions.normal, VersionRange? versionRange = null, string? targetFramework = null, @@ -125,7 +127,11 @@ public IToolPackage InstallPackage(PackageLocation packageLocation, PackageId pa var packageSourceLocation = new PackageSourceLocation(packageLocation.NugetConfig, packageLocation.RootConfigDirectory, packageLocation.SourceFeedOverrides, packageLocation.AdditionalFeeds, _currentWorkingDirectory, packageLocation.PackageSourceOverrides); - NuGetVersion packageVersion = nugetPackageDownloader.GetBestPackageVersionAsync(packageId, versionRange, packageSourceLocation).GetAwaiter().GetResult(); + NuGetVersion packageVersion = nugetPackageDownloader.GetBestPackageVersionAsync( + packageId, + versionRange, + cancellationToken, + packageSourceLocation).GetAwaiter().GetResult(); bool givenSpecificVersion = false; if (versionRange.MinVersion != null && versionRange.MaxVersion != null && versionRange.MinVersion == versionRange.MaxVersion) @@ -140,6 +146,7 @@ public IToolPackage InstallPackage(PackageLocation packageLocation, PackageId pa nugetPackageDownloader, packageId, packageVersion, + cancellationToken, givenSpecificVersion, targetFramework, isGlobalToolRollForward, @@ -152,6 +159,7 @@ public IToolPackage InstallPackage(PackageLocation packageLocation, PackageId pa nugetPackageDownloader, packageId, packageVersion, + cancellationToken, givenSpecificVersion, targetFramework, verbosity: verbosity); @@ -163,6 +171,7 @@ protected IToolPackage InstallGlobalToolPackageInternal( INuGetPackageDownloader nugetPackageDownloader, PackageId packageId, NuGetVersion packageVersion, + CancellationToken cancellationToken, bool givenSpecificVersion, string? targetFramework, bool isGlobalToolRollForward, @@ -190,6 +199,7 @@ protected IToolPackage InstallGlobalToolPackageInternal( packageDownloadDir: _globalToolStageDir, packageId, packageVersion, + cancellationToken, nugetPackageDownloader, packageSourceLocation, givenSpecificVersion, @@ -425,6 +435,7 @@ protected IToolPackage InstallLocalToolPackageInternal( INuGetPackageDownloader nugetPackageDownloader, PackageId packageId, NuGetVersion packageVersion, + CancellationToken cancellationToken, bool givenSpecificVersion, string? targetFramework, VerbosityOptions verbosity) @@ -436,6 +447,7 @@ protected IToolPackage InstallLocalToolPackageInternal( packageDownloadDir: _localToolDownloadDir, packageId, packageVersion, + cancellationToken, nugetPackageDownloader, packageSourceLocation, givenSpecificVersion, @@ -458,6 +470,7 @@ protected void DownloadTool( DirectoryPath packageDownloadDir, PackageId packageId, NuGetVersion packageVersion, + CancellationToken cancellationToken, INuGetPackageDownloader nugetPackageDownloader, PackageSourceLocation packageSourceLocation, bool givenSpecificVersion, @@ -470,6 +483,7 @@ protected void DownloadTool( packageDownloadDir, packageId, packageVersion, + cancellationToken, nugetPackageDownloader, packageSourceLocation, includeUnlisted: givenSpecificVersion, @@ -485,6 +499,7 @@ protected void DownloadTool( packageDownloadDir, ridSpecificPackage, packageVersion, + cancellationToken, nugetPackageDownloader, packageSourceLocation, includeUnlisted: true, @@ -503,6 +518,7 @@ private void EnsurePackageInstalled( DirectoryPath packageDownloadDir, PackageId packageId, NuGetVersion packageVersion, + CancellationToken cancellationToken, INuGetPackageDownloader nugetPackageDownloader, PackageSourceLocation packageSourceLocation, bool includeUnlisted, @@ -521,6 +537,7 @@ private void EnsurePackageInstalled( nugetPackageDownloader, packageDownloadDir.Value, packageVersion, + cancellationToken, packageSourceLocation, verbosity, includeUnlisted); @@ -535,6 +552,7 @@ private void EnsurePackageInstalled( nugetPackageDownloader, packageDownloadDir.Value, packageVersion, + cancellationToken, packageSourceLocation, verbosity, includeUnlisted); @@ -700,8 +718,8 @@ ToolPackageInstance toolPackageInstance .GetBestPackageVersionAndSourceAsync( packageId, versionRange, - packageSourceLocation, - cancellationToken) + cancellationToken, + packageSourceLocation) .ConfigureAwait(false); } } diff --git a/src/Cli/dotnet/TransactionalAction.cs b/src/Cli/dotnet/TransactionalAction.cs index 3d680706e139..843f6b3fab0b 100644 --- a/src/Cli/dotnet/TransactionalAction.cs +++ b/src/Cli/dotnet/TransactionalAction.cs @@ -43,6 +43,9 @@ public void Prepare(PreparingEnlistment enlistment) public void Rollback(Enlistment enlistment) { + using IDisposable softCancellationTimeout = + ProcessLifecycle.OverrideSoftCancellationTimeout(Timeout.InfiniteTimeSpan); + if (_rollback != null) { _rollback(); diff --git a/src/Cli/dotnet/dotnet.csproj b/src/Cli/dotnet/dotnet.csproj index bc9c518d2363..5bb22ee2f269 100644 --- a/src/Cli/dotnet/dotnet.csproj +++ b/src/Cli/dotnet/dotnet.csproj @@ -117,6 +117,8 @@ + + diff --git a/src/Containers/AGENTS.md b/src/Containers/AGENTS.md index 46cf25d60dda..e9355106fa93 100644 --- a/src/Containers/AGENTS.md +++ b/src/Containers/AGENTS.md @@ -20,6 +20,9 @@ feature (`Microsoft.NET.Build.Containers`). also carry a legacy `SDK_CONTAINER_*` alias; newer ones (e.g. the push/pull credentials, `DOTNET_CONTAINER_INSECURE_REGISTRIES`) are `DOTNET_CONTAINER_*`-only. Check the existing constant before assuming an alias exists. +- **Runtime probes and foreground process operations require the task cancellation token.** + Propagate `OperationCanceledException`; do not convert cancellation into an unavailable + runtime, an insecure-registry result, or another fallback value. ## Tests diff --git a/src/Containers/Microsoft.NET.Build.Containers/ContainerHelpers.cs b/src/Containers/Microsoft.NET.Build.Containers/ContainerHelpers.cs index 6814ceb13fe5..f43398d3a8df 100644 --- a/src/Containers/Microsoft.NET.Build.Containers/ContainerHelpers.cs +++ b/src/Containers/Microsoft.NET.Build.Containers/ContainerHelpers.cs @@ -183,11 +183,12 @@ internal static bool IsValidEnvironmentVariable(string envVar) internal static string GetManifestMediaType( string defaultManifestMediaType, KnownImageFormats? imageFormat, - DestinationImageReference destinationImageReference) + DestinationImageReference destinationImageReference, + CancellationToken cancellationToken) { if (destinationImageReference.LocalRegistry is ContainerRuntime runtime) { - return runtime.GetManifestMediaType(defaultManifestMediaType, imageFormat); + return runtime.GetManifestMediaType(defaultManifestMediaType, imageFormat, cancellationToken); } return ContainerRuntimeBase.GetDefaultManifestMediaType(defaultManifestMediaType, imageFormat); diff --git a/src/Containers/Microsoft.NET.Build.Containers/DestinationImageReference.cs b/src/Containers/Microsoft.NET.Build.Containers/DestinationImageReference.cs index a6c92d93dd80..ac1f10622c85 100644 --- a/src/Containers/Microsoft.NET.Build.Containers/DestinationImageReference.cs +++ b/src/Containers/Microsoft.NET.Build.Containers/DestinationImageReference.cs @@ -66,7 +66,8 @@ public static DestinationImageReference CreateFromSettings( ILoggerFactory loggerFactory, string? archiveOutputPath, string? outputRegistry, - string? localRegistryCommand) + string? localRegistryCommand, + CancellationToken cancellationToken) { DestinationImageReference destinationImageReference; if (!string.IsNullOrEmpty(archiveOutputPath)) @@ -76,7 +77,7 @@ public static DestinationImageReference CreateFromSettings( else if (!string.IsNullOrEmpty(outputRegistry)) { destinationImageReference = new DestinationImageReference( - new Registry(outputRegistry, loggerFactory.CreateLogger(), RegistryMode.Push), + new Registry(outputRegistry, loggerFactory.CreateLogger(), RegistryMode.Push, cancellationToken), repository, imageTags); } diff --git a/src/Containers/Microsoft.NET.Build.Containers/LocalDaemons/ArchiveFileRegistry.cs b/src/Containers/Microsoft.NET.Build.Containers/LocalDaemons/ArchiveFileRegistry.cs index 975b434c9c0c..7b2bfc0c4771 100644 --- a/src/Containers/Microsoft.NET.Build.Containers/LocalDaemons/ArchiveFileRegistry.cs +++ b/src/Containers/Microsoft.NET.Build.Containers/LocalDaemons/ArchiveFileRegistry.cs @@ -68,9 +68,6 @@ public async Task LoadAsync(MultiArchImage multiArchImage, SourceImageReference /// public Task IsAvailableAsync(CancellationToken cancellationToken) => Task.FromResult(true); - /// - public bool IsAvailable() => true; - public override string ToString() { return string.Format(Strings.ArchiveRegistry_PushInfo, ArchiveOutputPath); diff --git a/src/Containers/Microsoft.NET.Build.Containers/LocalDaemons/ContainerRuntime.cs b/src/Containers/Microsoft.NET.Build.Containers/LocalDaemons/ContainerRuntime.cs index cd69f7c126ac..f089a1918607 100644 --- a/src/Containers/Microsoft.NET.Build.Containers/LocalDaemons/ContainerRuntime.cs +++ b/src/Containers/Microsoft.NET.Build.Containers/LocalDaemons/ContainerRuntime.cs @@ -24,7 +24,7 @@ internal sealed class ContainerRuntime : ILocalRegistry private readonly ILogger _logger; private readonly ContainerRuntimeOperations _operations; - private readonly Func _isPodmanAlias; + private readonly Func _isPodmanAlias; private readonly bool _isWindows; private readonly bool _isMacOS; private readonly TimeSpan _probeTimeout; @@ -58,7 +58,7 @@ internal ContainerRuntime( string? command, ILoggerFactory loggerFactory, Func> tryRunCommand, - Func isPodmanAlias, + Func isPodmanAlias, bool isWindows, bool isMacOS, TimeSpan? probeTimeout = null) @@ -115,7 +115,7 @@ public async Task IsAvailableAsync(CancellationToken cancellationToken) { return await runtime.IsAvailableAsync(cancellationToken).ConfigureAwait(false); } - catch (Exception ex) + catch (Exception ex) when (ex is not OperationCanceledException) { _logger.LogInformation(Strings.LocalDocker_FailedToGetConfig, ex.Message); _logger.LogTrace("Full information: {0}", ex); @@ -123,15 +123,14 @@ public async Task IsAvailableAsync(CancellationToken cancellationToken) } } - /// - public bool IsAvailable() - => IsAvailableAsync(default).GetAwaiter().GetResult(); - - internal ContainerRuntimeKind GetTelemetryValue() - => GetRuntimeAsync(default).GetAwaiter().GetResult()?.GetTelemetryValue() ?? ContainerRuntimeKind.Unknown; + internal ContainerRuntimeKind GetTelemetryValue(CancellationToken cancellationToken) + => GetRuntimeAsync(cancellationToken).GetAwaiter().GetResult()?.GetTelemetryValue() ?? ContainerRuntimeKind.Unknown; - internal string GetManifestMediaType(string defaultManifestMediaType, KnownImageFormats? imageFormat) - => GetRuntimeAsync(default).GetAwaiter().GetResult()?.GetManifestMediaType(defaultManifestMediaType, imageFormat) + internal string GetManifestMediaType( + string defaultManifestMediaType, + KnownImageFormats? imageFormat, + CancellationToken cancellationToken) + => GetRuntimeAsync(cancellationToken).GetAwaiter().GetResult()?.GetManifestMediaType(defaultManifestMediaType, imageFormat) ?? ContainerRuntimeBase.GetDefaultManifestMediaType(defaultManifestMediaType, imageFormat); public override string ToString() @@ -172,7 +171,7 @@ await ProbeAsync(platformNativeRuntime, cancellationToken).ConfigureAwait(false) await Task.WhenAll(podmanAvailable, dockerAvailable).ConfigureAwait(false); - if (dockerAvailable.Result && podmanAvailable.Result && _isPodmanAlias()) + if (dockerAvailable.Result && podmanAvailable.Result && _isPodmanAlias(cancellationToken)) { _runtime = podmanRuntime; } diff --git a/src/Containers/Microsoft.NET.Build.Containers/LocalDaemons/ContainerRuntimes.cs b/src/Containers/Microsoft.NET.Build.Containers/LocalDaemons/ContainerRuntimes.cs index a7d12b50a7fd..e90d381b42d6 100644 --- a/src/Containers/Microsoft.NET.Build.Containers/LocalDaemons/ContainerRuntimes.cs +++ b/src/Containers/Microsoft.NET.Build.Containers/LocalDaemons/ContainerRuntimes.cs @@ -78,7 +78,7 @@ internal sealed class DockerContainerRuntime(ContainerRuntimeOperations operatio /// public override Task IsAvailableAsync(CancellationToken cancellationToken) { - JsonDocument config = GetDockerConfig(); + JsonDocument config = GetDockerConfig(cancellationToken); if (!config.RootElement.TryGetProperty("ServerErrors", out JsonElement errorProperty) || errorProperty.ValueKind == JsonValueKind.Array && errorProperty.GetArrayLength() == 0) { @@ -100,7 +100,7 @@ public override Task LoadAsync( DestinationImageReference destinationReference, CancellationToken cancellationToken) { - if (!IsContainerdStoreEnabled()) + if (!IsContainerdStoreEnabled(cancellationToken)) { throw new DockerLoadException(Strings.ImageLoadFailed_ContainerdStoreDisabled); } @@ -115,11 +115,11 @@ public override Task LoadAsync( cancellationToken); } - internal static bool IsPodmanAlias() + internal static bool IsPodmanAlias(CancellationToken cancellationToken) { try { - JsonElement dockerInfo = GetDockerConfig().RootElement; + JsonElement dockerInfo = GetDockerConfig(cancellationToken).RootElement; bool hasDockerProperty = dockerInfo.TryGetProperty("DockerRootDir", out JsonElement dockerRootDir) && dockerRootDir.GetString() is not null; @@ -129,13 +129,13 @@ internal static bool IsPodmanAlias() buildahVersion.GetString() is not null; return !hasDockerProperty && hasPodmanProperty; } - catch + catch (Exception e) when (e is not OperationCanceledException) { return false; } } - internal static JsonDocument GetDockerConfig() + internal static JsonDocument GetDockerConfig(CancellationToken cancellationToken) { string dockerPath = ContainerRuntimeOperations.FindFullPathFromPath(ContainerRuntime.DockerCommand); Process process = new() @@ -148,7 +148,7 @@ internal static JsonDocument GetDockerConfig() Command dockerCommand = new(process); dockerCommand.CaptureStdOut(); dockerCommand.CaptureStdErr(); - CommandResult result = dockerCommand.Execute(); + CommandResult result = dockerCommand.Execute(cancellationToken); if (result.ExitCode != 0) { throw new DockerLoadException(Resource.FormatString( @@ -160,17 +160,17 @@ internal static JsonDocument GetDockerConfig() return JsonDocument.Parse(result.StdOut ?? string.Empty); } - catch (Exception e) when (e is not DockerLoadException) + catch (Exception e) when (e is not DockerLoadException and not OperationCanceledException) { throw new DockerLoadException(Resource.FormatString(nameof(Strings.DockerInfoFailed_Ex), e.Message)); } } - internal static bool IsInsecureRegistry(string registryDomain) + internal static bool IsInsecureRegistry(string registryDomain, CancellationToken cancellationToken) { try { - JsonElement rootElement = GetDockerConfig().RootElement; + JsonElement rootElement = GetDockerConfig(cancellationToken).RootElement; if (rootElement.TryGetProperty("RegistryConfig", out JsonElement registryConfig) && registryConfig.ValueKind == JsonValueKind.Object && registryConfig.TryGetProperty("IndexConfigs", out JsonElement indexConfigs) && @@ -210,11 +210,11 @@ internal static bool IsInsecureRegistry(string registryDomain) } } - internal static bool IsContainerdStoreEnabled() + internal static bool IsContainerdStoreEnabled(CancellationToken cancellationToken) { try { - if (!GetDockerConfig().RootElement.TryGetProperty("DriverStatus", out JsonElement driverStatus) || + if (!GetDockerConfig(cancellationToken).RootElement.TryGetProperty("DriverStatus", out JsonElement driverStatus) || driverStatus.ValueKind != JsonValueKind.Array) { return false; @@ -236,7 +236,7 @@ internal static bool IsContainerdStoreEnabled() } return false; } - catch + catch (Exception e) when (e is not OperationCanceledException) { return false; } diff --git a/src/Containers/Microsoft.NET.Build.Containers/LocalDaemons/DockerCli.cs b/src/Containers/Microsoft.NET.Build.Containers/LocalDaemons/DockerCli.cs index 05c41f9de150..2a5dfd38baed 100644 --- a/src/Containers/Microsoft.NET.Build.Containers/LocalDaemons/DockerCli.cs +++ b/src/Containers/Microsoft.NET.Build.Containers/LocalDaemons/DockerCli.cs @@ -94,7 +94,7 @@ private async Task LoadAsync( { cancellationToken.ThrowIfCancellationRequested(); - if (checkContainerdStore && !IsContainerdStoreEnabledForDocker()) + if (checkContainerdStore && !IsContainerdStoreEnabledForDocker(cancellationToken)) { throw new DockerLoadException(Strings.ImageLoadFailed_ContainerdStoreDisabled); } @@ -153,7 +153,7 @@ public async Task IsAvailableAsync(CancellationToken cancellationToken) { case DockerCommand: { - JsonDocument config = GetDockerConfig(); + JsonDocument config = GetDockerConfig(cancellationToken); if (!config.RootElement.TryGetProperty("ServerErrors", out JsonElement errorProperty)) { @@ -177,7 +177,7 @@ public async Task IsAvailableAsync(CancellationToken cancellationToken) throw new NotImplementedException($"{command} is an unknown command."); } } - catch (Exception ex) + catch (Exception ex) when (ex is not OperationCanceledException) { _logger.LogInformation(Strings.LocalDocker_FailedToGetConfig, ex.Message); _logger.LogTrace("Full information: {0}", ex); @@ -185,19 +185,12 @@ public async Task IsAvailableAsync(CancellationToken cancellationToken) } } - /// - public bool IsAvailable() - => IsAvailableAsync(default).GetAwaiter().GetResult(); - - public string? GetCommand() - => GetCommandAsync(default).GetAwaiter().GetResult(); - /// /// Gets docker configuration. /// /// when , the method is executed synchronously. /// when failed to retrieve docker configuration. - internal static JsonDocument GetDockerConfig() + internal static JsonDocument GetDockerConfig(CancellationToken cancellationToken) { string dockerPath = FindFullPathFromPath("docker"); Process proc = new() @@ -210,7 +203,7 @@ internal static JsonDocument GetDockerConfig() Command dockerCommand = new(proc); dockerCommand.CaptureStdOut(); dockerCommand.CaptureStdErr(); - CommandResult dockerCommandResult = dockerCommand.Execute(); + CommandResult dockerCommandResult = dockerCommand.Execute(cancellationToken); if (dockerCommandResult.ExitCode != 0) { @@ -223,7 +216,7 @@ internal static JsonDocument GetDockerConfig() return JsonDocument.Parse(dockerCommandResult.StdOut ?? string.Empty); } - catch (Exception e) when (e is not DockerLoadException) + catch (Exception e) when (e is not DockerLoadException and not OperationCanceledException) { throw new DockerLoadException(Resource.FormatString(nameof(Strings.DockerInfoFailed_Ex), e.Message)); } @@ -233,12 +226,12 @@ internal static JsonDocument GetDockerConfig() /// /// /// - public static bool IsInsecureRegistry(string registryDomain) + public static bool IsInsecureRegistry(string registryDomain, CancellationToken cancellationToken) { try { //check the docker config to see if the registry is marked as insecure - var rootElement = GetDockerConfig().RootElement; + var rootElement = GetDockerConfig(cancellationToken).RootElement; //for docker if (rootElement.TryGetProperty("RegistryConfig", out var registryConfig) && registryConfig.ValueKind == JsonValueKind.Object) @@ -589,7 +582,7 @@ await Task.WhenAll( ).ConfigureAwait(false); // be explicit with this check so that we don't do the link target check unless it might actually be a solution. - if (dockerCommand.Result && podmanCommand.Result && IsPodmanAlias()) + if (dockerCommand.Result && podmanCommand.Result && IsPodmanAlias(cancellationToken)) { _command = PodmanCommand; } @@ -605,13 +598,13 @@ await Task.WhenAll( return _command; } - private static bool IsPodmanAlias() + private static bool IsPodmanAlias(CancellationToken cancellationToken) { // If both exist we need to check and see if the docker command is actually docker, // or if it is a podman script in a trenchcoat. try { - var dockerinfo = GetDockerConfig().RootElement; + var dockerinfo = GetDockerConfig(cancellationToken).RootElement; // Docker's info output has a 'DockerRootDir' top-level property string that is a good marker, // while Podman has a 'host' top-level property object with a 'buildahVersion' subproperty var hasdockerProperty = @@ -619,18 +612,18 @@ private static bool IsPodmanAlias() var hasPodmanProperty = dockerinfo.TryGetProperty("host", out var host) && host.TryGetProperty("buildahVersion", out var buildahVersion) && buildahVersion.GetString() is not null; return !hasdockerProperty && hasPodmanProperty; } - catch + catch (Exception e) when (e is not OperationCanceledException) { return false; } } - internal static bool IsContainerdStoreEnabledForDocker() + internal static bool IsContainerdStoreEnabledForDocker(CancellationToken cancellationToken) { try { // We don't need to check if this is docker, because there is no "DriverStatus" for podman - if (!GetDockerConfig().RootElement.TryGetProperty("DriverStatus", out var driverStatus) || driverStatus.ValueKind != JsonValueKind.Array) + if (!GetDockerConfig(cancellationToken).RootElement.TryGetProperty("DriverStatus", out var driverStatus) || driverStatus.ValueKind != JsonValueKind.Array) { return false; } @@ -649,7 +642,7 @@ internal static bool IsContainerdStoreEnabledForDocker() return false; } - catch + catch (Exception e) when (e is not OperationCanceledException) { return false; } diff --git a/src/Containers/Microsoft.NET.Build.Containers/LocalDaemons/ILocalRegistry.cs b/src/Containers/Microsoft.NET.Build.Containers/LocalDaemons/ILocalRegistry.cs index 6422a77b3fe6..2497940892a3 100644 --- a/src/Containers/Microsoft.NET.Build.Containers/LocalDaemons/ILocalRegistry.cs +++ b/src/Containers/Microsoft.NET.Build.Containers/LocalDaemons/ILocalRegistry.cs @@ -26,9 +26,4 @@ internal interface ILocalRegistry /// when the destination is available; otherwise, . public Task IsAvailableAsync(CancellationToken cancellationToken); - /// - /// Determines synchronously whether the destination is ready to receive images. - /// - /// when the destination is available; otherwise, . - public bool IsAvailable(); } diff --git a/src/Containers/Microsoft.NET.Build.Containers/Registry/Registry.cs b/src/Containers/Microsoft.NET.Build.Containers/Registry/Registry.cs index 385220b8195d..0792692c77c3 100644 --- a/src/Containers/Microsoft.NET.Build.Containers/Registry/Registry.cs +++ b/src/Containers/Microsoft.NET.Build.Containers/Registry/Registry.cs @@ -90,24 +90,24 @@ internal sealed class Registry /// public string RegistryName { get; } - internal Registry(string registryName, ILogger logger, IRegistryAPI registryAPI, RegistrySettings? settings = null, Func? retryDelayProvider = null) : - this(new Uri($"https://{registryName}"), logger, registryAPI, settings, retryDelayProvider) + internal Registry(string registryName, ILogger logger, IRegistryAPI registryAPI, CancellationToken cancellationToken, RegistrySettings? settings = null, Func? retryDelayProvider = null) : + this(new Uri($"https://{registryName}"), logger, registryAPI, cancellationToken, settings, retryDelayProvider) { } - internal Registry(string registryName, ILogger logger, RegistryMode mode, RegistrySettings? settings = null) : - this(new Uri($"https://{registryName}"), logger, new RegistryApiFactory(mode), settings) + internal Registry(string registryName, ILogger logger, RegistryMode mode, CancellationToken cancellationToken, RegistrySettings? settings = null) : + this(new Uri($"https://{registryName}"), logger, new RegistryApiFactory(mode), cancellationToken, settings) { } - internal Registry(Uri baseUri, ILogger logger, IRegistryAPI registryAPI, RegistrySettings? settings = null, Func? retryDelayProvider = null) : - this(baseUri, logger, new RegistryApiFactory(registryAPI), settings, retryDelayProvider) + internal Registry(Uri baseUri, ILogger logger, IRegistryAPI registryAPI, CancellationToken cancellationToken, RegistrySettings? settings = null, Func? retryDelayProvider = null) : + this(baseUri, logger, new RegistryApiFactory(registryAPI), cancellationToken, settings, retryDelayProvider) { } - internal Registry(Uri baseUri, ILogger logger, RegistryMode mode, RegistrySettings? settings = null) : - this(baseUri, logger, new RegistryApiFactory(mode), settings) + internal Registry(Uri baseUri, ILogger logger, RegistryMode mode, CancellationToken cancellationToken, RegistrySettings? settings = null) : + this(baseUri, logger, new RegistryApiFactory(mode), cancellationToken, settings) { } - private Registry(Uri baseUri, ILogger logger, RegistryApiFactory factory, RegistrySettings? settings = null, Func? retryDelayProvider = null) + private Registry(Uri baseUri, ILogger logger, RegistryApiFactory factory, CancellationToken cancellationToken, RegistrySettings? settings = null, Func? retryDelayProvider = null) { RegistryName = DeriveRegistryName(baseUri); @@ -119,7 +119,7 @@ private Registry(Uri baseUri, ILogger logger, RegistryApiFactory factory, Regist BaseUri = baseUri; _logger = logger; - _settings = settings ?? new RegistrySettings(RegistryName); + _settings = settings ?? new RegistrySettings(cancellationToken, RegistryName); _registryAPI = factory.Create(RegistryName, BaseUri, logger, _settings.IsInsecure); _retryDelayProvider = retryDelayProvider ?? (() => TimeSpan.FromSeconds(1)); diff --git a/src/Containers/Microsoft.NET.Build.Containers/Registry/RegistrySettings.cs b/src/Containers/Microsoft.NET.Build.Containers/Registry/RegistrySettings.cs index 7bd411935d34..65e38750cc29 100644 --- a/src/Containers/Microsoft.NET.Build.Containers/Registry/RegistrySettings.cs +++ b/src/Containers/Microsoft.NET.Build.Containers/Registry/RegistrySettings.cs @@ -7,7 +7,10 @@ namespace Microsoft.NET.Build.Containers; internal class RegistrySettings { - public RegistrySettings(string? registryName = null, IEnvironmentProvider? environment = null) + public RegistrySettings( + CancellationToken cancellationToken, + string? registryName = null, + IEnvironmentProvider? environment = null) { environment ??= new EnvironmentProvider(); @@ -22,7 +25,7 @@ public RegistrySettings(string? registryName = null, IEnvironmentProvider? envir if (registryName is not null) { - IsInsecure = IsInsecureRegistry(environment, registryName); + IsInsecure = IsInsecureRegistry(environment, registryName, cancellationToken); } } @@ -68,7 +71,10 @@ internal struct EnvVariables internal const string InsecureRegistries = "DOTNET_CONTAINER_INSECURE_REGISTRIES"; } - private static bool IsInsecureRegistry(IEnvironmentProvider environment, string registryName) + private static bool IsInsecureRegistry( + IEnvironmentProvider environment, + string registryName, + CancellationToken cancellationToken) { // Always allow insecure access to 'localhost'. if (registryName.StartsWith("localhost:", StringComparison.OrdinalIgnoreCase) || @@ -88,6 +94,6 @@ private static bool IsInsecureRegistry(IEnvironmentProvider environment, string } } - return DockerContainerRuntime.IsInsecureRegistry(registryName); + return DockerContainerRuntime.IsInsecureRegistry(registryName, cancellationToken); } } diff --git a/src/Containers/Microsoft.NET.Build.Containers/Tasks/CreateImageIndex.cs b/src/Containers/Microsoft.NET.Build.Containers/Tasks/CreateImageIndex.cs index 8046790069b7..217bebf709cc 100644 --- a/src/Containers/Microsoft.NET.Build.Containers/Tasks/CreateImageIndex.cs +++ b/src/Containers/Microsoft.NET.Build.Containers/Tasks/CreateImageIndex.cs @@ -51,7 +51,7 @@ internal async Task ExecuteAsync(CancellationToken cancellationToken) ILogger logger = msbuildLoggerFactory.CreateLogger(); RegistryMode sourceRegistryMode = BaseRegistry.Equals(OutputRegistry, StringComparison.InvariantCultureIgnoreCase) ? RegistryMode.PullFromOutput : RegistryMode.Pull; - Registry? sourceRegistry = IsLocalPull ? null : new Registry(BaseRegistry, logger, sourceRegistryMode); + Registry? sourceRegistry = IsLocalPull ? null : new Registry(BaseRegistry, logger, sourceRegistryMode, cancellationToken); SourceImageReference sourceImageReference = new(sourceRegistry, BaseImageName, BaseImageTag, BaseImageDigest); DestinationImageReference destinationImageReference = DestinationImageReference.CreateFromSettings( @@ -60,7 +60,8 @@ internal async Task ExecuteAsync(CancellationToken cancellationToken) msbuildLoggerFactory, ArchiveOutputPath, OutputRegistry, - LocalRegistry); + LocalRegistry, + cancellationToken); var images = ParseImages(destinationImageReference.Kind); if (Log.HasLoggedErrors) @@ -75,7 +76,7 @@ internal async Task ExecuteAsync(CancellationToken cancellationToken) logger.LogInformation(Strings.BuildingImageIndex, destinationImageReference, string.Join(", ", images.Select(i => i.ManifestDigest))); - var telemetry = new Telemetry(sourceImageReference, destinationImageReference, Log); + var telemetry = new Telemetry(sourceImageReference, destinationImageReference, Log, cancellationToken); await ImagePublisher.PublishImageAsync(multiArchImage, sourceImageReference, destinationImageReference, Log, telemetry, cancellationToken) .ConfigureAwait(false); diff --git a/src/Containers/Microsoft.NET.Build.Containers/Tasks/CreateNewImage.cs b/src/Containers/Microsoft.NET.Build.Containers/Tasks/CreateNewImage.cs index 68a2f9d9a044..8d654fb82ba4 100644 --- a/src/Containers/Microsoft.NET.Build.Containers/Tasks/CreateNewImage.cs +++ b/src/Containers/Microsoft.NET.Build.Containers/Tasks/CreateNewImage.cs @@ -99,7 +99,7 @@ internal async Task ExecuteAsync(CancellationToken cancellationToken) private async Task ExecuteAsyncCore(ILogger logger, ILoggerFactory msbuildLoggerFactory, CancellationToken cancellationToken) { RegistryMode sourceRegistryMode = BaseRegistry.Equals(OutputRegistry, StringComparison.InvariantCultureIgnoreCase) ? RegistryMode.PullFromOutput : RegistryMode.Pull; - Registry? sourceRegistry = IsLocalPull ? null : new Registry(BaseRegistry, logger, sourceRegistryMode); + Registry? sourceRegistry = IsLocalPull ? null : new Registry(BaseRegistry, logger, sourceRegistryMode, cancellationToken); SourceImageReference sourceImageReference = new(sourceRegistry, BaseImageName, BaseImageTag, BaseImageDigest); DestinationImageReference destinationImageReference = DestinationImageReference.CreateFromSettings( @@ -108,9 +108,10 @@ private async Task ExecuteAsyncCore(ILogger logger, ILoggerFactory msbuild msbuildLoggerFactory, ArchiveOutputPath, OutputRegistry, - LocalRegistry); + LocalRegistry, + cancellationToken); - var telemetry = new Telemetry(sourceImageReference, destinationImageReference, Log); + var telemetry = new Telemetry(sourceImageReference, destinationImageReference, Log, cancellationToken); ImageBuilder? imageBuilder; if (sourceRegistry is { } registry) @@ -180,7 +181,8 @@ private async Task ExecuteAsyncCore(ILogger logger, ILoggerFactory msbuild imageBuilder.ManifestMediaType = ContainerHelpers.GetManifestMediaType( imageBuilder.ManifestMediaType, requestedImageFormat, - destinationImageReference); + destinationImageReference, + cancellationToken); DateTime createdAt = ParseSourceDateEpoch(SourceDateEpoch) ?? DateTime.UtcNow; var userId = imageBuilder.IsWindows ? null : ContainerHelpers.TryParseUserId(ContainerUser); Layer newLayer = Layer.FromDirectory( diff --git a/src/Containers/Microsoft.NET.Build.Containers/Telemetry.cs b/src/Containers/Microsoft.NET.Build.Containers/Telemetry.cs index 8331a7f17edd..47ebaeed75d4 100644 --- a/src/Containers/Microsoft.NET.Build.Containers/Telemetry.cs +++ b/src/Containers/Microsoft.NET.Build.Containers/Telemetry.cs @@ -25,14 +25,15 @@ private enum LocalStorageType { Docker, Podman, Wslc, MacOSContainer, Tarball, U internal Telemetry( SourceImageReference source, DestinationImageReference destination, - Microsoft.Build.Utilities.TaskLoggingHelper Log) + Microsoft.Build.Utilities.TaskLoggingHelper Log, + CancellationToken cancellationToken) { this.Log = Log; Context = new PublishTelemetryContext( source.Registry is not null ? GetRegistryType(source.Registry) : null, null, // we don't support local pull yet, but we may in the future destination.RemoteRegistry is not null ? GetRegistryType(destination.RemoteRegistry) : null, - destination.LocalRegistry is not null ? GetLocalStorageType(destination.LocalRegistry) : null); + destination.LocalRegistry is not null ? GetLocalStorageType(destination.LocalRegistry, cancellationToken) : null); } private RegistryType GetRegistryType(Registry r) @@ -46,12 +47,12 @@ private RegistryType GetRegistryType(Registry r) return RegistryType.Other; } - private LocalStorageType GetLocalStorageType(ILocalRegistry r) + private LocalStorageType GetLocalStorageType(ILocalRegistry r, CancellationToken cancellationToken) { if (r is ArchiveFileRegistry) return LocalStorageType.Tarball; var runtime = r as ContainerRuntime; System.Diagnostics.Debug.Assert(runtime != null, "Unknown local registry type"); - return runtime.GetTelemetryValue() switch + return runtime.GetTelemetryValue(cancellationToken) switch { ContainerRuntimeKind.Docker => LocalStorageType.Docker, ContainerRuntimeKind.Podman => LocalStorageType.Podman, diff --git a/src/TemplateEngine/Tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/Commands/CommandRunner.cs b/src/TemplateEngine/Tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/Commands/CommandRunner.cs index 1b820148f220..241da0ca83ea 100644 --- a/src/TemplateEngine/Tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/Commands/CommandRunner.cs +++ b/src/TemplateEngine/Tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/Commands/CommandRunner.cs @@ -7,9 +7,9 @@ namespace Microsoft.TemplateEngine.Authoring.TemplateVerifier.Commands { internal class CommandRunner : ICommandRunner { - public CommandResultData RunCommand(TestCommand testCommand) + public CommandResultData RunCommand(TestCommand testCommand, CancellationToken cancellationToken) { - return new CommandResultData(testCommand.Execute()); + return new CommandResultData(testCommand.Execute(cancellationToken)); } } } diff --git a/src/TemplateEngine/Tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/Commands/ICommandRunner.cs b/src/TemplateEngine/Tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/Commands/ICommandRunner.cs index 1787064fded4..a5e3b28b72bd 100644 --- a/src/TemplateEngine/Tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/Commands/ICommandRunner.cs +++ b/src/TemplateEngine/Tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/Commands/ICommandRunner.cs @@ -7,6 +7,6 @@ namespace Microsoft.TemplateEngine.Authoring.TemplateVerifier.Commands { internal interface ICommandRunner { - CommandResultData RunCommand(TestCommand testCommand); + CommandResultData RunCommand(TestCommand testCommand, CancellationToken cancellationToken); } } diff --git a/src/TemplateEngine/Tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/VerificationEngine.cs b/src/TemplateEngine/Tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/VerificationEngine.cs index 9b85861db6cc..8a61e89349aa 100644 --- a/src/TemplateEngine/Tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/VerificationEngine.cs +++ b/src/TemplateEngine/Tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/VerificationEngine.cs @@ -104,7 +104,12 @@ public async Task Execute( RunInstantiation instantiate = options.CustomInstatiation ?? - (verifierOptions => Task.FromResult(RunDotnetNewCommand(verifierOptions, _commandRunner, _loggerFactory, _logger))); + (verifierOptions => Task.FromResult(RunDotnetNewCommand( + verifierOptions, + _commandRunner, + _loggerFactory, + _logger, + cancellationToken))); IInstantiationResult commandResult = await instantiate(options).ConfigureAwait(false); @@ -327,7 +332,12 @@ private static string EncodeArgsAsPath(IEnumerable? args) return r.Replace(string.Join('#', args), string.Empty); } - private static IInstantiationResult RunDotnetNewCommand(TemplateVerifierOptions options, ICommandRunner commandRunner, ILoggerFactory? loggerFactory, ILogger logger) + private static IInstantiationResult RunDotnetNewCommand( + TemplateVerifierOptions options, + ICommandRunner commandRunner, + ILoggerFactory? loggerFactory, + ILogger logger, + CancellationToken cancellationToken) { // Create temp folder and instantiate there string workingDir = options.OutputDirectory ?? Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); @@ -350,7 +360,7 @@ private static IInstantiationResult RunDotnetNewCommand(TemplateVerifierOptions .WithEnvironmentVariables(options.Environment) .WithWorkingDirectory(workingDir); - CommandResultData installCommandResult = commandRunner.RunCommand(installCommand); + CommandResultData installCommandResult = commandRunner.RunCommand(installCommand, cancellationToken); if (installCommandResult.ExitCode != 0) { @@ -400,7 +410,7 @@ private static IInstantiationResult RunDotnetNewCommand(TemplateVerifierOptions .WithWorkingDirectory(workingDir) .WithNoUpdateCheck(); - var result = commandRunner.RunCommand(command); + var result = commandRunner.RunCommand(command, cancellationToken); // Cleanup, unless the settings dir was externally passed if (!string.IsNullOrEmpty(customHiveLocation) && string.IsNullOrEmpty(options.SettingsDirectory)) { diff --git a/src/TemplateEngine/Tools/Microsoft.TemplateSearch.TemplateDiscovery/TemplateDiscoveryCommand.cs b/src/TemplateEngine/Tools/Microsoft.TemplateSearch.TemplateDiscovery/TemplateDiscoveryCommand.cs index c3741b35f9ad..7b4ba9d4528d 100644 --- a/src/TemplateEngine/Tools/Microsoft.TemplateSearch.TemplateDiscovery/TemplateDiscoveryCommand.cs +++ b/src/TemplateEngine/Tools/Microsoft.TemplateSearch.TemplateDiscovery/TemplateDiscoveryCommand.cs @@ -139,7 +139,7 @@ private static async Task ExecuteAsync(CommandArgs config, CancellationToken can (string metadataPath, string legacyMetadataPath) = PackCheckResultReportWriter.WriteResults(config.OutputPath, checkResults); if (config.TestEnabled) { - CacheFileTests.RunTests(metadataPath, legacyMetadataPath); + CacheFileTests.RunTests(metadataPath, legacyMetadataPath, cancellationToken); } } } diff --git a/src/TemplateEngine/Tools/Microsoft.TemplateSearch.TemplateDiscovery/Test/CacheFileTests.cs b/src/TemplateEngine/Tools/Microsoft.TemplateSearch.TemplateDiscovery/Test/CacheFileTests.cs index d2e2759385c7..4a6da178230a 100644 --- a/src/TemplateEngine/Tools/Microsoft.TemplateSearch.TemplateDiscovery/Test/CacheFileTests.cs +++ b/src/TemplateEngine/Tools/Microsoft.TemplateSearch.TemplateDiscovery/Test/CacheFileTests.cs @@ -9,61 +9,64 @@ namespace Microsoft.TemplateSearch.TemplateDiscovery.Test { internal static class CacheFileTests { - internal static void RunTests(string metadataPath, string legacyMetadataPath) + internal static void RunTests( + string metadataPath, + string legacyMetadataPath, + CancellationToken cancellationToken) { //6.0.100 string sdkVersion = "6.0.100"; string workingDirectory = TestUtils.CreateTemporaryFolder(sdkVersion); - UseSdkVersion(workingDirectory, requestedSdkVersion: sdkVersion, resolvedVersionPattern: "6.0.1", rollForward: "latestPatch"); + UseSdkVersion(workingDirectory, cancellationToken, requestedSdkVersion: sdkVersion, resolvedVersionPattern: "6.0.1", rollForward: "latestPatch"); Console.WriteLine($"Running tests on .NET {sdkVersion} for: {legacyMetadataPath}."); - CanSearch(workingDirectory, legacyMetadataPath); + CanSearch(workingDirectory, legacyMetadataPath, cancellationToken); Console.WriteLine($"Running tests on .NET {sdkVersion} for: {metadataPath}."); - CanSearch(workingDirectory, metadataPath); + CanSearch(workingDirectory, metadataPath, cancellationToken); //6.0.300 sdkVersion = "6.0.300"; workingDirectory = TestUtils.CreateTemporaryFolder(sdkVersion); - UseSdkVersion(workingDirectory, requestedSdkVersion: sdkVersion, resolvedVersionPattern: "6.0.3", rollForward: "latestPatch"); + UseSdkVersion(workingDirectory, cancellationToken, requestedSdkVersion: sdkVersion, resolvedVersionPattern: "6.0.3", rollForward: "latestPatch"); Console.WriteLine($"Running tests on .NET {sdkVersion} for: {legacyMetadataPath}."); - CanSearch(workingDirectory, legacyMetadataPath); + CanSearch(workingDirectory, legacyMetadataPath, cancellationToken); Console.WriteLine($"Running tests on .NET {sdkVersion} for: {metadataPath}."); - CanSearch(workingDirectory, metadataPath); + CanSearch(workingDirectory, metadataPath, cancellationToken); //6.0.400 sdkVersion = "6.0.400"; workingDirectory = TestUtils.CreateTemporaryFolder(sdkVersion); - UseSdkVersion(workingDirectory, requestedSdkVersion: sdkVersion, resolvedVersionPattern: "6.0.4", rollForward: "latestPatch"); + UseSdkVersion(workingDirectory, cancellationToken, requestedSdkVersion: sdkVersion, resolvedVersionPattern: "6.0.4", rollForward: "latestPatch"); Console.WriteLine($"Running tests on .NET {sdkVersion} for: {legacyMetadataPath}."); - CanSearch(workingDirectory, legacyMetadataPath); + CanSearch(workingDirectory, legacyMetadataPath, cancellationToken); Console.WriteLine($"Running tests on .NET {sdkVersion} for: {metadataPath}."); - CanSearch(workingDirectory, metadataPath); + CanSearch(workingDirectory, metadataPath, cancellationToken); //7.0.100 sdkVersion = "7.0.100"; workingDirectory = TestUtils.CreateTemporaryFolder(sdkVersion); - UseSdkVersion(workingDirectory, requestedSdkVersion: sdkVersion, resolvedVersionPattern: "7.0.1", rollForward: "latestPatch"); + UseSdkVersion(workingDirectory, cancellationToken, requestedSdkVersion: sdkVersion, resolvedVersionPattern: "7.0.1", rollForward: "latestPatch"); Console.WriteLine($"Running tests on .NET {sdkVersion} for: {legacyMetadataPath}."); - CanSearch(workingDirectory, legacyMetadataPath); + CanSearch(workingDirectory, legacyMetadataPath, cancellationToken); Console.WriteLine($"Running tests on .NET {sdkVersion} for: {metadataPath}."); - CanSearch(workingDirectory, metadataPath); + CanSearch(workingDirectory, metadataPath, cancellationToken); //7.0.200 sdkVersion = "7.0.200"; workingDirectory = TestUtils.CreateTemporaryFolder(sdkVersion); - UseSdkVersion(workingDirectory, requestedSdkVersion: sdkVersion, resolvedVersionPattern: "7.0.2", rollForward: "latestPatch"); + UseSdkVersion(workingDirectory, cancellationToken, requestedSdkVersion: sdkVersion, resolvedVersionPattern: "7.0.2", rollForward: "latestPatch"); Console.WriteLine($"Running tests on .NET {sdkVersion} for: {legacyMetadataPath}."); - CanSearch(workingDirectory, legacyMetadataPath); + CanSearch(workingDirectory, legacyMetadataPath, cancellationToken); Console.WriteLine($"Running tests on .NET {sdkVersion} for: {metadataPath}."); - CanSearch(workingDirectory, metadataPath); + CanSearch(workingDirectory, metadataPath, cancellationToken); //7.0.300 sdkVersion = "7.0.300"; workingDirectory = TestUtils.CreateTemporaryFolder(sdkVersion); - UseSdkVersion(workingDirectory, requestedSdkVersion: sdkVersion, resolvedVersionPattern: "7.0.3", rollForward: "latestPatch"); + UseSdkVersion(workingDirectory, cancellationToken, requestedSdkVersion: sdkVersion, resolvedVersionPattern: "7.0.3", rollForward: "latestPatch"); Console.WriteLine($"Running tests on .NET {sdkVersion} for: {legacyMetadataPath}."); - CanSearch(workingDirectory, legacyMetadataPath); + CanSearch(workingDirectory, legacyMetadataPath, cancellationToken); Console.WriteLine($"Running tests on .NET {sdkVersion} for: {metadataPath}."); - CanSearch(workingDirectory, metadataPath); + CanSearch(workingDirectory, metadataPath, cancellationToken); //latest workingDirectory = TestUtils.CreateTemporaryFolder("latest"); @@ -71,23 +74,29 @@ internal static void RunTests(string metadataPath, string legacyMetadataPath) new DotnetCommand(TestOutputLogger.Instance, "--version") .WithoutTelemetry() .WithWorkingDirectory(workingDirectory) - .Execute() + .Execute(cancellationToken) .Should() .ExitWith(0); Console.WriteLine($"Running tests on latest .NET for: {legacyMetadataPath}."); - CanSearch(workingDirectory, legacyMetadataPath); + CanSearch(workingDirectory, legacyMetadataPath, cancellationToken); Console.WriteLine($"Running tests on latest .NET for: {metadataPath}."); - CanSearch(workingDirectory, metadataPath); + CanSearch(workingDirectory, metadataPath, cancellationToken); } - private static void UseSdkVersion(string workingDirectory, string requestedSdkVersion, string resolvedVersionPattern, string rollForward = "latestMinor", bool allowPrerelease = false) + private static void UseSdkVersion( + string workingDirectory, + CancellationToken cancellationToken, + string requestedSdkVersion, + string resolvedVersionPattern, + string rollForward = "latestMinor", + bool allowPrerelease = false) { CreateGlobalJson(workingDirectory, requestedSdkVersion, rollForward, allowPrerelease); new DotnetCommand(TestOutputLogger.Instance, "--version") .WithoutTelemetry() .WithWorkingDirectory(workingDirectory) - .Execute() + .Execute(cancellationToken) .Should() .ExitWith(0) .And @@ -95,7 +104,10 @@ private static void UseSdkVersion(string workingDirectory, string requestedSdkVe .And.HaveStdOutContaining(resolvedVersionPattern); } - private static void CanSearchWhileInstantiating(string workingDirectory, string cacheFilePath) + private static void CanSearchWhileInstantiating( + string workingDirectory, + string cacheFilePath, + CancellationToken cancellationToken) { var settingsPath = TestUtils.CreateTemporaryFolder(); new DotnetNewCommand(TestOutputLogger.Instance, "func") @@ -103,14 +115,17 @@ private static void CanSearchWhileInstantiating(string workingDirectory, string .WithoutTelemetry() .WithWorkingDirectory(workingDirectory) .WithEnvironmentVariable("DOTNET_NEW_SEARCH_FILE_OVERRIDE", cacheFilePath) - .Execute() + .Execute(cancellationToken) .Should() .ExitWith(0) .And.HaveStdOutContaining("Couldn't find an installed template that matches the input, searching online for one that does...") .And.HaveStdOutContaining("Template name \"Azure Functions\" (func) from author \"Microsoft\" in pack Microsoft.Azure.WebJobs.ProjectTemplates"); } - private static void CanCheckUpdates(string workingDirectory, string cacheFilePath) + private static void CanCheckUpdates( + string workingDirectory, + string cacheFilePath, + CancellationToken cancellationToken) { var settingsPath = TestUtils.CreateTemporaryFolder(); new DotnetNewCommand(TestOutputLogger.Instance, "--install", "Microsoft.Azure.WebJobs.ItemTemplates::2.1.1785") @@ -118,7 +133,7 @@ private static void CanCheckUpdates(string workingDirectory, string cacheFilePat .WithoutTelemetry() .WithWorkingDirectory(workingDirectory) .WithEnvironmentVariable("DOTNET_NEW_SEARCH_FILE_OVERRIDE", cacheFilePath) - .Execute() + .Execute(cancellationToken) .Should() .ExitWith(0) .And.NotHaveStdErr(); @@ -128,7 +143,7 @@ private static void CanCheckUpdates(string workingDirectory, string cacheFilePat .WithoutTelemetry() .WithWorkingDirectory(workingDirectory) .WithEnvironmentVariable("DOTNET_NEW_SEARCH_FILE_OVERRIDE", cacheFilePath) - .Execute() + .Execute(cancellationToken) .Should() .ExitWith(0) .And.NotHaveStdErr() @@ -137,7 +152,10 @@ private static void CanCheckUpdates(string workingDirectory, string cacheFilePat .And.HaveStdOutContaining("Microsoft.Azure.WebJobs.ItemTemplates::2.1.1785"); } - private static void CanUpdate(string workingDirectory, string cacheFilePath) + private static void CanUpdate( + string workingDirectory, + string cacheFilePath, + CancellationToken cancellationToken) { var settingsPath = TestUtils.CreateTemporaryFolder(); new DotnetNewCommand(TestOutputLogger.Instance, "--install", "Microsoft.Azure.WebJobs.ItemTemplates::2.1.1785") @@ -145,7 +163,7 @@ private static void CanUpdate(string workingDirectory, string cacheFilePath) .WithoutTelemetry() .WithWorkingDirectory(workingDirectory) .WithEnvironmentVariable("DOTNET_NEW_SEARCH_FILE_OVERRIDE", cacheFilePath) - .Execute() + .Execute(cancellationToken) .Should() .ExitWith(0) .And.NotHaveStdErr(); @@ -155,7 +173,7 @@ private static void CanUpdate(string workingDirectory, string cacheFilePath) .WithoutTelemetry() .WithWorkingDirectory(workingDirectory) .WithEnvironmentVariable("DOTNET_NEW_SEARCH_FILE_OVERRIDE", cacheFilePath) - .Execute() + .Execute(cancellationToken) .Should() .ExitWith(0) .And.NotHaveStdErr() @@ -164,7 +182,10 @@ private static void CanUpdate(string workingDirectory, string cacheFilePath) .And.HaveStdOutContaining("Microsoft.Azure.WebJobs.ItemTemplates::2.1.1785"); } - private static void CanSearch(string workingDirectory, string cacheFilePath) + private static void CanSearch( + string workingDirectory, + string cacheFilePath, + CancellationToken cancellationToken) { var settingsPath = TestUtils.CreateTemporaryFolder(); new DotnetNewCommand(TestOutputLogger.Instance, "func", "--search") @@ -172,7 +193,7 @@ private static void CanSearch(string workingDirectory, string cacheFilePath) .WithoutTelemetry() .WithWorkingDirectory(workingDirectory) .WithEnvironmentVariable("DOTNET_NEW_SEARCH_FILE_OVERRIDE", cacheFilePath) - .Execute() + .Execute(cancellationToken) .Should() .ExitWith(0) .And.NotHaveStdErr() diff --git a/src/TemplateEngine/Tools/Shared/Microsoft.TemplateEngine.CommandUtils/Command.cs b/src/TemplateEngine/Tools/Shared/Microsoft.TemplateEngine.CommandUtils/Command.cs index 89b343244688..6548cef38a93 100644 --- a/src/TemplateEngine/Tools/Shared/Microsoft.TemplateEngine.CommandUtils/Command.cs +++ b/src/TemplateEngine/Tools/Shared/Microsoft.TemplateEngine.CommandUtils/Command.cs @@ -26,13 +26,14 @@ public Command(Process process, bool trimtrailingNewlines = false) public string CommandArgs => _process.StartInfo.Arguments; - public CommandResult Execute() + public CommandResult Execute(CancellationToken cancellationToken) { - return Execute(_ => { }); + return Execute(processStarted: null, cancellationToken); } - public CommandResult Execute(Action? processStarted) + public CommandResult Execute(Action? processStarted, CancellationToken cancellationToken) { + cancellationToken.ThrowIfCancellationRequested(); Console.WriteLine($"Running {_process.StartInfo.FileName} {_process.StartInfo.Arguments}"); ThrowIfRunning(); @@ -55,10 +56,17 @@ public CommandResult Execute(Action? processStarted) var taskOut = _stdOut?.BeginRead(_process.StandardOutput); var taskErr = _stdErr?.BeginRead(_process.StandardError); - _process.WaitForExit(); - - taskOut?.Wait(); - taskErr?.Wait(); + while (!_process.WaitForExit(milliseconds: 100)) + { + if (cancellationToken.IsCancellationRequested) + { + TerminateProcess(_process); + cancellationToken.ThrowIfCancellationRequested(); + } + } + + taskOut?.GetAwaiter().GetResult(); + taskErr?.GetAwaiter().GetResult(); } var exitCode = _process.ExitCode; @@ -82,6 +90,24 @@ public CommandResult Execute(Action? processStarted) _stdErr?.CapturedOutput); } + private static void TerminateProcess(Process process) + { + try + { + process.Kill(entireProcessTree: true); + } + 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 Command WorkingDirectory(string projectDirectory) { _process.StartInfo.WorkingDirectory = projectDirectory; diff --git a/src/TemplateEngine/Tools/Shared/Microsoft.TemplateEngine.CommandUtils/TestCommand.cs b/src/TemplateEngine/Tools/Shared/Microsoft.TemplateEngine.CommandUtils/TestCommand.cs index 905221e07d40..9a015e2f4334 100644 --- a/src/TemplateEngine/Tools/Shared/Microsoft.TemplateEngine.CommandUtils/TestCommand.cs +++ b/src/TemplateEngine/Tools/Shared/Microsoft.TemplateEngine.CommandUtils/TestCommand.cs @@ -70,13 +70,13 @@ internal ProcessStartInfo GetProcessStartInfo(params string[] args) return psi; } - internal CommandResult Execute(params string[] args) + internal CommandResult Execute(CancellationToken cancellationToken, params string[] args) { IEnumerable enumerableArgs = args; - return Execute(enumerableArgs); + return Execute(enumerableArgs, cancellationToken); } - internal virtual CommandResult Execute(IEnumerable args) + internal virtual CommandResult Execute(IEnumerable args, CancellationToken cancellationToken) { Command command = CreateCommandSpec(args) .ToCommand() @@ -88,7 +88,7 @@ internal virtual CommandResult Execute(IEnumerable args) command.OnOutputLine(CommandOutputHandler); } - var result = command.Execute(ProcessStartedHandler); + var result = command.Execute(ProcessStartedHandler, cancellationToken); _loggerWrapper.WriteLine($"> {result.StartInfo.FileName} {result.StartInfo.Arguments}"); _loggerWrapper.WriteLine(result.StdOut); diff --git a/test/ArgumentForwarding.Tests/ArgumentForwardingTests.cs b/test/ArgumentForwarding.Tests/ArgumentForwardingTests.cs index 3fa25efd2a78..aa8692581bbb 100644 --- a/test/ArgumentForwarding.Tests/ArgumentForwardingTests.cs +++ b/test/ArgumentForwarding.Tests/ArgumentForwardingTests.cs @@ -172,7 +172,7 @@ private string[] EscapeAndEvaluateArgumentString(string[] rawEvaluatedArgument) var commandResult = CommandFactoryUsingResolver.Create("dotnet", new[] { ReflectorPath }.Concat(rawEvaluatedArgument)) .CaptureStdErr() .CaptureStdOut() - .Execute(); + .Execute(TestContext.CancellationToken); Console.WriteLine($"STDOUT: {commandResult.StdOut}"); @@ -197,7 +197,7 @@ private string[] EscapeAndEvaluateArgumentStringCmd(string[] rawEvaluatedArgumen var commandResult = cmd .CaptureStdErr() .CaptureStdOut() - .Execute(); + .Execute(TestContext.CancellationToken); Console.WriteLine(commandResult.StdOut); Console.WriteLine(commandResult.StdErr); diff --git a/test/Microsoft.DotNet.Cli.Utils.ProcessLifecycle.TestApp/Microsoft.DotNet.Cli.Utils.ProcessLifecycle.TestApp.csproj b/test/Microsoft.DotNet.Cli.Utils.ProcessLifecycle.TestApp/Microsoft.DotNet.Cli.Utils.ProcessLifecycle.TestApp.csproj new file mode 100644 index 000000000000..eae43fec35a0 --- /dev/null +++ b/test/Microsoft.DotNet.Cli.Utils.ProcessLifecycle.TestApp/Microsoft.DotNet.Cli.Utils.ProcessLifecycle.TestApp.csproj @@ -0,0 +1,17 @@ + + + + Exe + $(SdkTargetFramework) + MicrosoftAspNetCore + false + false + true + + + + + + + + diff --git a/test/Microsoft.DotNet.Cli.Utils.ProcessLifecycle.TestApp/ProcessLifecycleTestApp.cs b/test/Microsoft.DotNet.Cli.Utils.ProcessLifecycle.TestApp/ProcessLifecycleTestApp.cs new file mode 100644 index 000000000000..b2f7c939579c --- /dev/null +++ b/test/Microsoft.DotNet.Cli.Utils.ProcessLifecycle.TestApp/ProcessLifecycleTestApp.cs @@ -0,0 +1,300 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.InteropServices; +using Microsoft.DotNet.Cli.Commands.MSBuild; +using Microsoft.DotNet.Cli.Commands.Test; +using Microsoft.DotNet.Cli.Utils; + +namespace Microsoft.DotNet.Cli.Utils.TestApp; + +public static partial class ProcessLifecycleTestApp +{ + public static int Main(string[] args) + { + if (Environment.GetEnvironmentVariable("PROCESS_LIFECYCLE_TEST_FAKE_MSBUILD") == "1") + { + File.WriteAllText(Environment.GetEnvironmentVariable("TEST_MARKER_PATH")!, "ready"); + Thread.Sleep(Timeout.Infinite); + return 0; + } + + string childMode = args[0]; + string markerPath = args[1]; + + if (childMode == "lifecycle-reaper-parent") + { + using IDisposable lifecycle = ProcessLifecycle.Initialize(); + RunReaperParent(args, markerPath, childMode); + return 0; + } + + if (childMode is "reaper-parent" or "uncooperative-reaper-parent") + { + RunReaperParent(args, markerPath, childMode); + return 0; + } + + if (childMode == "signal-child") + { + RunSignalChild(markerPath); + return 0; + } + + if (childMode == "ignoring-signal-child") + { + RunIgnoringSignalChild(markerPath); + return 0; + } + + if (childMode == "ignoring-cancellation-child") + { + RunIgnoringCancellationChild(markerPath); + return 0; + } + + if (OperatingSystem.IsWindows()) + { + // A private console prevents test signals from reaching MTP or other processes. + if (!FreeConsole() || !AllocConsole()) + { + throw new Win32Exception(Marshal.GetLastPInvokeError()); + } + + new Thread(() => + { + for (int signal = 1; ; signal++) + { + WaitForFile(markerPath + $".signal-{signal}"); + if (!GenerateConsoleCtrlEvent(0, 0)) + { + throw new Win32Exception(Marshal.GetLastPInvokeError()); + } + } + }) { IsBackground = true }.Start(); + } + + using IDisposable processLifecycle = ProcessLifecycle.Initialize(); + CancellationToken cancellationToken = ProcessLifecycle.CancellationToken; + if (childMode is "mtp-lifecycle" or "mtp-sigterm-lifecycle") + { + using IDisposable cancellationTimeout = + ProcessLifecycle.OverrideSoftCancellationTimeout(Timeout.InfiniteTimeSpan); + using var ctrlC = new CtrlCCancellationManager( + onFirstCtrlC: () => WriteMarker(markerPath, "signal-cancelled"), + subscribeToConsole: false, + cooperativeCancellationToken: cancellationToken, + forcefulCancellationToken: ProcessLifecycle.ForcefulCancellationToken); + using Process testApplication = CreateChildProcess( + args, + childMode == "mtp-sigterm-lifecycle" + ? "signal-child" + : "ignoring-cancellation-child"); + if (ctrlC.StartAndRegister(() => + { + testApplication.Start(); + return testApplication; + }) is null) + { + return ExitCode.TestSessionAborted; + } + + WaitForMarker(markerPath, "grandchild-ready"); + File.WriteAllText(markerPath + ".pid", testApplication.Id.ToString()); + WriteMarker(markerPath, "ready"); + Thread.Sleep(Timeout.Infinite); + } + + if (childMode == "msbuild-external") + { + var forwardingApp = new MSBuildForwardingApp([], args[6]); + forwardingApp.EnvironmentVariable("TEST_MARKER_PATH", markerPath); + forwardingApp.EnvironmentVariable("PROCESS_LIFECYCLE_TEST_FAKE_MSBUILD", "1"); + try + { + return forwardingApp.Execute(cancellationToken); + } + catch (OperationCanceledException) when ( + ProcessLifecycle.TryGetSignalExitCode(cancellationToken, out int exitCode)) + { + return exitCode; + } + } + + using CancellationTokenRegistration registration = childMode is "uncooperative" or "repeated" + ? cancellationToken.Register(() => WriteMarker(markerPath, "signal-cancelled")) + : default; + + WriteMarker(markerPath, "ready"); + + if (childMode == "repeated") + { + using IDisposable softCancellationTimeout = + ProcessLifecycle.OverrideSoftCancellationTimeout(Timeout.InfiniteTimeSpan); + Thread.Sleep(Timeout.Infinite); + } + + if (childMode == "uncooperative") + { + Thread.Sleep(Timeout.Infinite); + } + + if (childMode == "forceful-cooperative") + { + ProcessLifecycle.ForcefulCancellationToken.WaitHandle.WaitOne(); + WriteMarker(markerPath, "forceful-cancelled"); + return GetSignalExitCode(cancellationToken); + } + + if (childMode == "extended-grace") + { + cancellationToken.WaitHandle.WaitOne(); + using IDisposable softCancellationTimeout = + ProcessLifecycle.OverrideSoftCancellationTimeout(Timeout.InfiniteTimeSpan); + WriteMarker(markerPath, "signal-cancelled"); + Thread.Sleep(TimeSpan.FromMilliseconds(750)); + WriteMarker(markerPath, "override-completed"); + return GetSignalExitCode(cancellationToken); + } + + cancellationToken.WaitHandle.WaitOne(); + WriteMarker( + markerPath, + ProcessLifecycle.IsSignalTerminationRequested ? "signal-cancelled" : "cancelled"); + return GetSignalExitCode(cancellationToken); + } + + private static void WriteMarker(string path, string value) + { + using FileStream stream = new(path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); + using StreamWriter writer = new(stream); + writer.Write(value); + } + + private static void RunReaperParent(string[] args, string markerPath, string childMode) + { + using Process signalChild = CreateChildProcess( + args, + childMode is "reaper-parent" or "lifecycle-reaper-parent" + ? "signal-child" + : "ignoring-signal-child"); + using ProcessReaper reaper = ProcessReaper.Create(signalChild); + + signalChild.Start(); + reaper.NotifyProcessStarted(); + WaitForMarker(markerPath, "grandchild-ready"); + File.WriteAllText(markerPath, "reaper-ready"); + Thread.Sleep(Timeout.Infinite); + } + + private static Process CreateChildProcess(string[] args, string childMode) + { + ProcessStartInfo startInfo = new(args[2]) + { + UseShellExecute = false, + CreateNoWindow = true, + }; + + startInfo.ArgumentList.Add("exec"); + startInfo.ArgumentList.Add("--runtimeconfig"); + startInfo.ArgumentList.Add(args[4]); + startInfo.ArgumentList.Add("--depsfile"); + startInfo.ArgumentList.Add(args[5]); + startInfo.ArgumentList.Add(args[3]); + startInfo.ArgumentList.Add(childMode); + startInfo.ArgumentList.Add(args[1]); + startInfo.ArgumentList.Add(args[2]); + startInfo.ArgumentList.Add(args[3]); + startInfo.ArgumentList.Add(args[4]); + startInfo.ArgumentList.Add(args[5]); + + return new Process { StartInfo = startInfo }; + } + + private static void RunIgnoringSignalChild(string markerPath) + { + using PosixSignalRegistration registration = PosixSignalRegistration.Create( + PosixSignal.SIGTERM, + context => context.Cancel = true); + + File.WriteAllText(markerPath, "grandchild-ready"); + Thread.Sleep(Timeout.Infinite); + } + + private static void RunIgnoringCancellationChild(string markerPath) + { + Console.CancelKeyPress += (_, eventArgs) => eventArgs.Cancel = true; + WriteMarker(markerPath, "grandchild-ready"); + Thread.Sleep(Timeout.Infinite); + } + + private static void RunSignalChild(string markerPath) + { + using PosixSignalRegistration registration = PosixSignalRegistration.Create( + PosixSignal.SIGTERM, + context => + { + context.Cancel = true; + WriteMarker(markerPath, "forwarded"); + Environment.Exit(43); + }); + + WriteMarker(markerPath, "grandchild-ready"); + Thread.Sleep(Timeout.Infinite); + } + + private static void WaitForMarker(string markerPath, string expectedValue) + { + if (!SpinWait.SpinUntil( + () => ReadMarker(markerPath) == expectedValue, + TimeSpan.FromSeconds(30))) + { + throw new TimeoutException($"Timed out waiting for marker '{expectedValue}'."); + } + } + + private static string? ReadMarker(string path) + { + if (!File.Exists(path)) + { + return null; + } + + try + { + using StreamReader reader = new(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)); + return reader.ReadToEnd(); + } + catch (IOException) + { + return null; + } + } + + private static void WaitForFile(string path) + { + if (!SpinWait.SpinUntil(() => File.Exists(path), TimeSpan.FromSeconds(30))) + { + throw new TimeoutException($"Timed out waiting for '{path}'."); + } + } + + private static int GetSignalExitCode(CancellationToken cancellationToken) + => ProcessLifecycle.TryGetSignalExitCode(cancellationToken, out int exitCode) + ? exitCode + : 0; + + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool AllocConsole(); + + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool FreeConsole(); + + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool GenerateConsoleCtrlEvent(uint ctrlEvent, uint processGroupId); +} diff --git a/test/Microsoft.DotNet.Cli.Utils.Tests/BuiltInCommandTests.cs b/test/Microsoft.DotNet.Cli.Utils.Tests/BuiltInCommandTests.cs index db5002f0c924..7984f5e3e1dd 100644 --- a/test/Microsoft.DotNet.Cli.Utils.Tests/BuiltInCommandTests.cs +++ b/test/Microsoft.DotNet.Cli.Utils.Tests/BuiltInCommandTests.cs @@ -8,6 +8,8 @@ namespace Microsoft.DotNet.Cli.Utils [TestClass] public class BuiltInCommandTests { + public TestContext TestContext { get; set; } + /// /// Tests that BuiltInCommand.Execute returns the correct exit code and a /// valid StartInfo FileName and Arguments. @@ -19,13 +21,51 @@ public void TestExecute() string[] testCommandArgs = new[] { "1", "2" }; var builtInCommand = new BuiltInCommand("fakeCommand", testCommandArgs, testCommand, new TestBuiltInCommandEnvironment()); - CommandResult result = builtInCommand.Execute(); + CommandResult result = builtInCommand.Execute(TestContext.CancellationToken); Assert.AreEqual(testCommandArgs.Length, result.ExitCode); Assert.AreEqual(new Muxer().MuxerPath, result.StartInfo.FileName); Assert.AreEqual("fakeCommand 1 2", result.StartInfo.Arguments); } + [TestMethod] + public void ExecuteWithCanceledTokenDoesNotInvokeCommand() + { + bool invoked = false; + var builtInCommand = new BuiltInCommand( + "fakeCommand", + [], + _ => + { + invoked = true; + return 0; + }, + new TestBuiltInCommandEnvironment()); + + Assert.ThrowsExactly( + () => builtInCommand.Execute(new CancellationToken(canceled: true))); + Assert.IsFalse(invoked); + } + + [TestMethod] + public void ExecuteReturnsCompletedResultWhenCancellationLosesTheRace() + { + using var cancellationSource = CancellationTokenSource.CreateLinkedTokenSource(TestContext.CancellationToken); + var builtInCommand = new BuiltInCommand( + "fakeCommand", + [], + _ => + { + cancellationSource.Cancel(); + return 42; + }, + new TestBuiltInCommandEnvironment()); + + CommandResult result = builtInCommand.Execute(cancellationSource.Token); + + Assert.AreEqual(42, result.ExitCode); + } + /// /// Tests that BuiltInCommand.Execute raises the OnOutputLine and OnErrorLine /// the correct number of times and with the correct content. @@ -81,7 +121,7 @@ public void TestOnOutputLines() Assert.AreEqual($"fifth", line); } }) - .Execute(); + .Execute(TestContext.CancellationToken); Assert.AreEqual(exitCode, result.ExitCode); Assert.AreEqual(2, onOutputLineCallCount); diff --git a/test/Microsoft.DotNet.Cli.Utils.Tests/CommandTests.cs b/test/Microsoft.DotNet.Cli.Utils.Tests/CommandTests.cs new file mode 100644 index 000000000000..42a919e416a8 --- /dev/null +++ b/test/Microsoft.DotNet.Cli.Utils.Tests/CommandTests.cs @@ -0,0 +1,103 @@ +// 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; + +namespace Microsoft.DotNet.Cli.Utils; + +[TestClass] +[DoNotParallelize] +public class CommandTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public async Task ExecuteWithCanceledTokenTerminatesProcess() + { + ProcessStartInfo startInfo = new() + { + FileName = OperatingSystem.IsWindows() ? "ping.exe" : "/bin/sleep", + Arguments = OperatingSystem.IsWindows() + ? "-n 600 -w 1000 127.0.0.1" + : "600", + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + CreateNoWindow = true, + }; + using Process process = new() { StartInfo = startInfo }; + using var cancellationSource = CancellationTokenSource.CreateLinkedTokenSource(TestContext.CancellationToken); + var command = new Command(process); + + Task execution = Task.Run(() => command.Execute(cancellationSource.Token)); + try + { + Assert.IsTrue( + SpinWait.SpinUntil( + () => + { + try + { + return process.Id > 0; + } + catch (InvalidOperationException) + { + return false; + } + }, + TimeSpan.FromSeconds(10)), + "The helper process did not start."); + await cancellationSource.CancelAsync(); + + await Assert.ThrowsExactlyAsync( + () => execution.WaitAsync(TestContext.CancellationToken)); + Assert.IsTrue(process.HasExited); + } + finally + { + await cancellationSource.CancelAsync(); + } + } + + [TestMethod] + public void ExecuteReturnsCompletedResultWhenCancellationLosesTheRace() + { + ProcessStartInfo startInfo = new() + { + FileName = OperatingSystem.IsWindows() ? "cmd.exe" : "/bin/sh", + Arguments = OperatingSystem.IsWindows() + ? "/c \"echo done & exit /b 42\"" + : "-c \"echo done; exit 42\"", + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + CreateNoWindow = true, + }; + using Process process = new() { StartInfo = startInfo }; + using var cancellationSource = CancellationTokenSource.CreateLinkedTokenSource(TestContext.CancellationToken); + var command = new Command(process); + command.OnOutputLine(_ => + { + process.WaitForExit(); + cancellationSource.Cancel(); + }); + + CommandResult result = command.Execute(cancellationSource.Token); + + Assert.IsTrue(cancellationSource.IsCancellationRequested); + Assert.AreEqual(42, result.ExitCode); + } + + [TestMethod] + public void ProcessTerminationUsesForcefulTokenForLinkedLifecycleCancellation() + { + using IDisposable processLifecycle = ProcessLifecycle.Initialize(); + using var linkedSource = + CancellationTokenSource.CreateLinkedTokenSource(ProcessLifecycle.CancellationToken); + + CancellationToken processTerminationToken = + ProcessLifecycle.GetProcessTerminationToken(linkedSource.Token); + + Assert.AreEqual(ProcessLifecycle.ForcefulCancellationToken, processTerminationToken); + } +} diff --git a/test/Microsoft.DotNet.Cli.Utils.Tests/Microsoft.DotNet.Cli.Utils.Tests.csproj b/test/Microsoft.DotNet.Cli.Utils.Tests/Microsoft.DotNet.Cli.Utils.Tests.csproj index 744316f095f5..7d7a5d3f6a7f 100644 --- a/test/Microsoft.DotNet.Cli.Utils.Tests/Microsoft.DotNet.Cli.Utils.Tests.csproj +++ b/test/Microsoft.DotNet.Cli.Utils.Tests/Microsoft.DotNet.Cli.Utils.Tests.csproj @@ -8,6 +8,7 @@ + diff --git a/test/Microsoft.DotNet.Cli.Utils.Tests/ProcessLifecycleTests.cs b/test/Microsoft.DotNet.Cli.Utils.Tests/ProcessLifecycleTests.cs new file mode 100644 index 000000000000..ef2f12112d4f --- /dev/null +++ b/test/Microsoft.DotNet.Cli.Utils.Tests/ProcessLifecycleTests.cs @@ -0,0 +1,558 @@ +// 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 Microsoft.DotNet.Cli.Utils.TestApp; +using Microsoft.Win32.SafeHandles; + +namespace Microsoft.DotNet.Cli.Utils.Tests; + +[TestClass] +public class ProcessLifecycleTests : SdkTest +{ + private static readonly TimeSpan s_waitTimeout = TimeSpan.FromSeconds(30); + + [TestMethod] + [OSCondition(ConditionMode.Exclude, OperatingSystems.Windows)] + public void SigTermForcesTerminationWithoutCooperativeCancellation() + { + var testDirectory = TestAssetsManager.CreateTestDirectory(); + using Process child = StartChild("cooperative", testDirectory.Path); + + WaitForMarker(testDirectory.Path, "ready"); + child.SafeHandle.Signal(PosixSignal.SIGTERM).Should().BeTrue(); + child.WaitForExit(s_waitTimeout).Should().BeTrue(); + child.ExitCode.Should().Be(143); + File.ReadAllText(GetMarkerPath(testDirectory.Path)).Should().Be("ready"); + } + + [TestMethod] + [OSCondition(ConditionMode.Exclude, OperatingSystems.Windows)] + public void SigIntAllowsCooperativeCancellation() + { + var testDirectory = TestAssetsManager.CreateTestDirectory(); + using Process child = StartChild("cooperative", testDirectory.Path); + + WaitForMarker(testDirectory.Path, "ready"); + child.SafeHandle.Signal(PosixSignal.SIGINT).Should().BeTrue(); + WaitForMarker(testDirectory.Path, "signal-cancelled"); + child.WaitForExit(s_waitTimeout).Should().BeTrue(); + child.ExitCode.Should().Be(130); + } + + [TestMethod] + [OSCondition(OperatingSystems.Windows)] + public void ConsoleCtrlCCancelsTokenAndForcesTerminationWhenCancellationIsIgnored() + => VerifyCancellationSignal(PosixSignal.SIGINT, expectedForcedExitCode: 130); + + [TestMethod] + [OSCondition(ConditionMode.Exclude, OperatingSystems.Windows)] + public void RepeatedSigIntTerminatesAnUncooperativeProcess() + => VerifyRepeatedSignal(PosixSignal.SIGINT, expectedExitCode: 130); + + [TestMethod] + [OSCondition(OperatingSystems.Windows)] + public void RepeatedConsoleCtrlCTerminatesAnUncooperativeProcess() + => VerifyRepeatedSignal(PosixSignal.SIGINT, expectedExitCode: 130); + + [TestMethod] + [OSCondition(ConditionMode.Exclude, OperatingSystems.Windows)] + public void SigIntForcesTerminationAfterSoftCancellationTimeout() + { + var testDirectory = TestAssetsManager.CreateTestDirectory(); + using Process child = StartChild("uncooperative", testDirectory.Path); + + WaitForMarker(testDirectory.Path, "ready"); + Stopwatch stopwatch = Stopwatch.StartNew(); + child.SafeHandle.Signal(PosixSignal.SIGINT).Should().BeTrue(); + child.WaitForExit(s_waitTimeout).Should().BeTrue(); + + child.ExitCode.Should().Be(130); + stopwatch.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(1.5)); + } + + [TestMethod] + public void SoftCancellationTimeoutAllowsForcefulCancellationToComplete() + { + var testDirectory = TestAssetsManager.CreateTestDirectory(); + using Process child = StartChild("forceful-cooperative", testDirectory.Path); + + WaitForMarker(testDirectory.Path, "ready"); + SendSignal(child, testDirectory.Path, PosixSignal.SIGINT); + WaitForMarker(testDirectory.Path, "forceful-cancelled"); + child.WaitForExit(s_waitTimeout).Should().BeTrue(); + + child.ExitCode.Should().Be(130); + } + + [TestMethod] + [OSCondition(ConditionMode.Exclude, OperatingSystems.Windows)] + public void SoftCancellationTimeoutCanBeOverridden() + { + var testDirectory = TestAssetsManager.CreateTestDirectory(); + using Process child = StartChild("extended-grace", testDirectory.Path); + + WaitForMarker(testDirectory.Path, "ready"); + child.SafeHandle.Signal(PosixSignal.SIGINT).Should().BeTrue(); + WaitForMarker(testDirectory.Path, "override-completed"); + child.WaitForExit(s_waitTimeout).Should().BeTrue(); + child.ExitCode.Should().Be(130); + } + + [TestMethod] + [OSCondition(ConditionMode.Exclude, OperatingSystems.Windows)] + public void SecondSigIntBypassesSoftCancellationTimeoutOverride() + { + var testDirectory = TestAssetsManager.CreateTestDirectory(); + using Process child = StartChild("extended-grace", testDirectory.Path); + + WaitForMarker(testDirectory.Path, "ready"); + child.SafeHandle.Signal(PosixSignal.SIGINT).Should().BeTrue(); + WaitForMarker(testDirectory.Path, "signal-cancelled"); + Stopwatch stopwatch = Stopwatch.StartNew(); + child.SafeHandle.Signal(PosixSignal.SIGINT).Should().BeTrue(); + child.WaitForExit(s_waitTimeout).Should().BeTrue(); + + child.ExitCode.Should().Be(130); + stopwatch.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(1)); + File.ReadAllText(GetMarkerPath(testDirectory.Path)).Should().Be("signal-cancelled"); + } + + [TestMethod] + [OSCondition(ConditionMode.Exclude, OperatingSystems.Windows)] + public void SigTermBypassesSoftCancellationTimeoutOverride() + { + var testDirectory = TestAssetsManager.CreateTestDirectory(); + using Process child = StartChild("extended-grace", testDirectory.Path); + + WaitForMarker(testDirectory.Path, "ready"); + child.SafeHandle.Signal(PosixSignal.SIGTERM).Should().BeTrue(); + child.WaitForExit(s_waitTimeout).Should().BeTrue(); + + child.ExitCode.Should().Be(143); + File.ReadAllText(GetMarkerPath(testDirectory.Path)).Should().Be("ready"); + } + + [TestMethod] + [OSCondition(ConditionMode.Exclude, OperatingSystems.Windows)] + public void ManagedCliWaitsForSecondSigIntBeforeTerminatingExternalCommand() + { + var testDirectory = TestAssetsManager.CreateTestDirectory(); + string markerPath = GetMarkerPath(testDirectory.Path); + string commandPath = Path.Combine(testDirectory.Path, "dotnet-cancellation-test"); + File.WriteAllText( + commandPath, + $"#!/bin/sh{Environment.NewLine}printf ready > '{markerPath}'{Environment.NewLine}sleep 30{Environment.NewLine}"); + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode( + commandPath, + UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute | + UnixFileMode.GroupRead | UnixFileMode.GroupExecute | + UnixFileMode.OtherRead | UnixFileMode.OtherExecute); + } + + ProcessStartInfo startInfo = new(SdkTestContext.Current.ToolsetUnderTest.DotNetHostPath) + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + WorkingDirectory = testDirectory.Path, + }; + startInfo.ArgumentList.Add("cancellation-test"); + var testEnvironment = new Dictionary(); + SdkTestContext.Current.AddTestEnvironmentVariables(testEnvironment); + foreach ((string name, string? value) in testEnvironment) + { + startInfo.Environment[name] = value; + } + + startInfo.Environment["DOTNET_CLI_ENABLEAOT"] = "0"; + startInfo.Environment["DOTNET_CLI_TELEMETRY_OPTOUT"] = "1"; + startInfo.Environment["DOTNET_GENERATE_ASPNET_CERTIFICATE"] = bool.FalseString; + startInfo.Environment["DOTNET_NOLOGO"] = bool.TrueString; + startInfo.Environment["DOTNET_SKIP_WORKLOAD_INTEGRITY_CHECK"] = bool.TrueString; + startInfo.Environment["PATH"] = + testDirectory.Path + Path.PathSeparator + startInfo.Environment["PATH"]; + + using Process child = new() { StartInfo = startInfo }; + bool childStarted = false; + try + { + child.Start(); + childStarted = true; + Task stdoutTask = child.StandardOutput.ReadToEndAsync(TestContext.CancellationToken); + Task stderrTask = child.StandardError.ReadToEndAsync(TestContext.CancellationToken); + + if (!TryWaitForMarker(testDirectory.Path, "ready")) + { + if (!child.HasExited) + { + child.Kill(entireProcessTree: true); + } + + child.WaitForExit(); + Assert.Fail( + $"The managed CLI did not start the external command.{Environment.NewLine}" + + $"Exit code: {child.ExitCode}{Environment.NewLine}" + + $"Standard output:{Environment.NewLine}{stdoutTask.GetAwaiter().GetResult()}{Environment.NewLine}" + + $"Standard error:{Environment.NewLine}{stderrTask.GetAwaiter().GetResult()}"); + } + + child.SafeHandle.Signal(PosixSignal.SIGINT).Should().BeTrue(); + Thread.Sleep(TimeSpan.FromMilliseconds(750)); + child.HasExited.Should().BeFalse("the first SIGINT should allow the external command to finish"); + + Stopwatch stopwatch = Stopwatch.StartNew(); + child.SafeHandle.Signal(PosixSignal.SIGINT).Should().BeTrue(); + child.WaitForExit(s_waitTimeout).Should().BeTrue(); + + child.ExitCode.Should().Be(130); + stopwatch.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(1)); + string standardError = stderrTask.GetAwaiter().GetResult(); + standardError.Should().NotContain("Unhandled exception"); + standardError.Should().NotContain("The operation was canceled"); + _ = stdoutTask.GetAwaiter().GetResult(); + } + finally + { + if (childStarted && !child.HasExited) + { + child.Kill(entireProcessTree: true); + child.WaitForExit(); + } + } + } + + [TestMethod] + [OSCondition(ConditionMode.Exclude, OperatingSystems.Windows)] + public void ForwardedMSBuildUsesTheBuildSoftCancellationTimeout() + { + var testDirectory = TestAssetsManager.CreateTestDirectory(); + string msbuildPath = typeof(ProcessLifecycleTestApp).Assembly.Location; + + using Process child = StartChild("msbuild-external", testDirectory.Path, msbuildPath); + try + { + WaitForMarker(testDirectory.Path, "ready"); + Stopwatch stopwatch = Stopwatch.StartNew(); + child.SafeHandle.Signal(PosixSignal.SIGINT).Should().BeTrue(); + child.WaitForExit(TimeSpan.FromSeconds(5)).Should().BeTrue(); + + child.ExitCode.Should().Be(130); + stopwatch.Elapsed.Should().BeGreaterThan(TimeSpan.FromSeconds(1.5)); + stopwatch.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(4)); + } + finally + { + StopChild(child); + } + } + + [TestMethod] + public void MtpLifecycleAllowsCooperativeCleanupAndKillsChildrenOnForcefulCancellation() + { + var testDirectory = TestAssetsManager.CreateTestDirectory(); + using Process child = StartChild("mtp-lifecycle", testDirectory.Path); + try + { + WaitForMarker(testDirectory.Path, "ready"); + int testApplicationProcessId = + int.Parse(File.ReadAllText(GetMarkerPath(testDirectory.Path) + ".pid")); + + SendSignal(child, testDirectory.Path, PosixSignal.SIGINT); + WaitForMarker(testDirectory.Path, "signal-cancelled"); + Thread.Sleep(TimeSpan.FromMilliseconds(750)); + child.HasExited.Should().BeFalse( + "the first Ctrl+C should allow MTP test applications to finish reporting"); + Process.GetProcessById(testApplicationProcessId).HasExited.Should().BeFalse( + "cooperative cancellation should not kill the test application"); + + Stopwatch stopwatch = Stopwatch.StartNew(); + SendSignal(child, testDirectory.Path, PosixSignal.SIGINT, sequence: 2); + child.WaitForExit(s_waitTimeout).Should().BeTrue(); + + child.ExitCode.Should().Be(130); + stopwatch.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(1)); + SpinWait.SpinUntil( + () => HasProcessExited(testApplicationProcessId), + TimeSpan.FromSeconds(10)) + .Should().BeTrue("forceful cancellation should kill the test application"); + } + finally + { + StopChild(child); + } + } + + [TestMethod] + [OSCondition(ConditionMode.Exclude, OperatingSystems.Windows)] + public void MtpLifecycleForwardsSigTermToTestApplication() + { + var testDirectory = TestAssetsManager.CreateTestDirectory(); + using Process child = StartChild("mtp-sigterm-lifecycle", testDirectory.Path); + try + { + WaitForMarker(testDirectory.Path, "ready"); + int testApplicationProcessId = + int.Parse(File.ReadAllText(GetMarkerPath(testDirectory.Path) + ".pid")); + + Stopwatch stopwatch = Stopwatch.StartNew(); + child.SafeHandle.Signal(PosixSignal.SIGTERM).Should().BeTrue(); + WaitForMarker(testDirectory.Path, "forwarded"); + child.WaitForExit(s_waitTimeout).Should().BeTrue(); + + child.ExitCode.Should().Be(143); + stopwatch.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(2)); + SpinWait.SpinUntil( + () => HasProcessExited(testApplicationProcessId), + TimeSpan.FromSeconds(10)) + .Should().BeTrue("SIGTERM should let the test application exit before forceful cleanup"); + } + finally + { + StopChild(child); + } + } + + [TestMethod] + [OSCondition(ConditionMode.Exclude, OperatingSystems.Windows)] + public void ForwardSigTermSkipsDisposedProcessesAndTerminatesRemainingProcesses() + { + var testDirectory = TestAssetsManager.CreateTestDirectory(); + using Process child = StartChild("signal-child", testDirectory.Path); + using var disposedProcess = new Process(); + disposedProcess.Dispose(); + + try + { + WaitForMarker(testDirectory.Path, "grandchild-ready"); + + ProcessReaper.ForwardSigTermAndTerminate([disposedProcess, child]); + + WaitForMarker(testDirectory.Path, "forwarded"); + child.WaitForExit(s_waitTimeout).Should().BeTrue(); + child.ExitCode.Should().Be(43); + } + finally + { + StopChild(child); + } + } + + [TestMethod] + [OSCondition(ConditionMode.Exclude, OperatingSystems.Windows)] + public void SigTermIsForwardedToReapedChild() + { + var testDirectory = TestAssetsManager.CreateTestDirectory(); + + using Process reaperParent = StartChild( + "reaper-parent", + testDirectory.Path); + + WaitForMarker(testDirectory.Path, "reaper-ready"); + reaperParent.SafeHandle.Signal(PosixSignal.SIGTERM).Should().BeTrue(); + WaitForMarker(testDirectory.Path, "forwarded"); + reaperParent.WaitForExit(s_waitTimeout).Should().BeTrue(); + reaperParent.ExitCode.Should().Be(43); + + using Process uncooperativeReaperParent = StartChild( + "uncooperative-reaper-parent", + testDirectory.Path); + + WaitForMarker(testDirectory.Path, "reaper-ready"); + Stopwatch stopwatch = Stopwatch.StartNew(); + uncooperativeReaperParent.SafeHandle.Signal(PosixSignal.SIGTERM).Should().BeTrue(); + uncooperativeReaperParent.WaitForExit(s_waitTimeout).Should().BeTrue(); + uncooperativeReaperParent.ExitCode.Should().NotBe(0); + stopwatch.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(2)); + } + + [TestMethod] + [OSCondition(ConditionMode.Exclude, OperatingSystems.Windows)] + public void LifecycleSigTermExitCodeIsNotReplacedByReapedChild() + { + var testDirectory = TestAssetsManager.CreateTestDirectory(); + + using Process reaperParent = StartChild( + "lifecycle-reaper-parent", + testDirectory.Path); + + WaitForMarker(testDirectory.Path, "reaper-ready"); + reaperParent.SafeHandle.Signal(PosixSignal.SIGTERM).Should().BeTrue(); + WaitForMarker(testDirectory.Path, "forwarded"); + reaperParent.WaitForExit(s_waitTimeout).Should().BeTrue(); + reaperParent.ExitCode.Should().Be(143); + } + + private void VerifyCancellationSignal(PosixSignal signal, int expectedForcedExitCode) + { + var testDirectory = TestAssetsManager.CreateTestDirectory(); + + using (Process cooperativeChild = StartChild("cooperative", testDirectory.Path)) + { + try + { + WaitForMarker(testDirectory.Path, "ready"); + SendSignal(cooperativeChild, testDirectory.Path, signal); + WaitForMarker(testDirectory.Path, "signal-cancelled"); + cooperativeChild.WaitForExit(s_waitTimeout).Should().BeTrue(); + cooperativeChild.ExitCode.Should().Be(130); + } + finally + { + StopChild(cooperativeChild); + } + } + + using (Process uncooperativeChild = StartChild("uncooperative", testDirectory.Path)) + { + try + { + WaitForMarker(testDirectory.Path, "ready"); + SendSignal(uncooperativeChild, testDirectory.Path, signal); + uncooperativeChild.WaitForExit(s_waitTimeout).Should().BeTrue(); + uncooperativeChild.ExitCode.Should().Be(expectedForcedExitCode); + } + finally + { + StopChild(uncooperativeChild); + } + } + } + + private void VerifyRepeatedSignal(PosixSignal signal, int expectedExitCode) + { + var testDirectory = TestAssetsManager.CreateTestDirectory(); + using Process child = StartChild("repeated", testDirectory.Path); + try + { + WaitForMarker(testDirectory.Path, "ready"); + SendSignal(child, testDirectory.Path, signal); + WaitForMarker(testDirectory.Path, "signal-cancelled"); + Stopwatch stopwatch = Stopwatch.StartNew(); + SendSignal(child, testDirectory.Path, signal, sequence: 2); + child.WaitForExit(s_waitTimeout).Should().BeTrue(); + child.ExitCode.Should().Be(expectedExitCode); + stopwatch.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(1)); + } + finally + { + StopChild(child); + } + } + + private static Process StartChild(string childMode, string testDirectory, params string[] additionalArguments) + { + string markerPath = GetMarkerPath(testDirectory); + File.Delete(markerPath); + File.Delete(markerPath + ".signal-1"); + File.Delete(markerPath + ".signal-2"); + Process process = CreateChildProcess(childMode, testDirectory, additionalArguments); + process.Start(); + return process; + } + + private static void SendSignal(Process child, string testDirectory, PosixSignal signal, int sequence = 1) + { + if (OperatingSystem.IsWindows()) + { + File.WriteAllText(Path.Combine(testDirectory, $"signal-marker.signal-{sequence}"), ""); + } + else + { + child.SafeHandle.Signal(signal).Should().BeTrue(); + } + } + + private static void StopChild(Process child) + { + if (!child.HasExited) + { + child.Kill(entireProcessTree: true); + child.WaitForExit(s_waitTimeout).Should().BeTrue(); + } + } + + private static Process CreateChildProcess( + string childMode, + string testDirectory, + params string[] additionalArguments) + { + string markerPath = GetMarkerPath(testDirectory); + string testAssemblyPath = typeof(ProcessLifecycleTests).Assembly.Location; + string helperAssemblyPath = typeof(ProcessLifecycleTestApp).Assembly.Location; + ProcessStartInfo startInfo = new(SdkTestContext.Current.ToolsetUnderTest.DotNetHostPath) + { + UseShellExecute = false, + CreateNoWindow = true, + }; + + startInfo.ArgumentList.Add("exec"); + startInfo.ArgumentList.Add("--runtimeconfig"); + startInfo.ArgumentList.Add(Path.ChangeExtension(testAssemblyPath, ".runtimeconfig.json")); + startInfo.ArgumentList.Add("--depsfile"); + startInfo.ArgumentList.Add(Path.ChangeExtension(testAssemblyPath, ".deps.json")); + startInfo.ArgumentList.Add(helperAssemblyPath); + startInfo.ArgumentList.Add(childMode); + startInfo.ArgumentList.Add(markerPath); + startInfo.ArgumentList.Add(startInfo.FileName); + startInfo.ArgumentList.Add(helperAssemblyPath); + startInfo.ArgumentList.Add(Path.ChangeExtension(testAssemblyPath, ".runtimeconfig.json")); + startInfo.ArgumentList.Add(Path.ChangeExtension(testAssemblyPath, ".deps.json")); + foreach (string argument in additionalArguments) + { + startInfo.ArgumentList.Add(argument); + } + + return new Process { StartInfo = startInfo }; + } + + private static void WaitForMarker(string testDirectory, string expectedValue) + { + TryWaitForMarker(testDirectory, expectedValue) + .Should().BeTrue($"the child process should write '{expectedValue}' to the signal marker"); + } + + private static bool TryWaitForMarker(string testDirectory, string expectedValue) + { + string markerPath = GetMarkerPath(testDirectory); + return SpinWait.SpinUntil(() => MarkerHasValue(markerPath, expectedValue), s_waitTimeout); + } + + private static bool MarkerHasValue(string markerPath, string expectedValue) + { + try + { + if (!File.Exists(markerPath)) + { + return false; + } + + using FileStream stream = new(markerPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + using StreamReader reader = new(stream); + return reader.ReadToEnd() == expectedValue; + } + catch (IOException) + { + return false; + } + } + + private static string GetMarkerPath(string testDirectory) + => Path.Combine(testDirectory, "signal-marker"); + + private static bool HasProcessExited(int processId) + { + try + { + using Process process = Process.GetProcessById(processId); + return process.HasExited; + } + catch (ArgumentException) + { + return true; + } + } +} diff --git a/test/Microsoft.DotNet.PackageInstall.Tests/MockFirstPartyNuGetPackageSigningVerifier.cs b/test/Microsoft.DotNet.PackageInstall.Tests/MockFirstPartyNuGetPackageSigningVerifier.cs index 6d73540c1fa1..9af7357fb83b 100644 --- a/test/Microsoft.DotNet.PackageInstall.Tests/MockFirstPartyNuGetPackageSigningVerifier.cs +++ b/test/Microsoft.DotNet.PackageInstall.Tests/MockFirstPartyNuGetPackageSigningVerifier.cs @@ -17,8 +17,9 @@ public MockFirstPartyNuGetPackageSigningVerifier(bool verifyResult = true, strin _commandOutput = commandOutput; } - public bool Verify(FilePath nupkgToVerify, out string commandOutput) + public bool Verify(FilePath nupkgToVerify, CancellationToken cancellationToken, out string commandOutput) { + cancellationToken.ThrowIfCancellationRequested(); commandOutput = _commandOutput; return _verifyResult; } diff --git a/test/Microsoft.DotNet.PackageInstall.Tests/NuGetPackageInstallerExtractTests.cs b/test/Microsoft.DotNet.PackageInstall.Tests/NuGetPackageInstallerExtractTests.cs index 002012963543..49efb3bf292c 100644 --- a/test/Microsoft.DotNet.PackageInstall.Tests/NuGetPackageInstallerExtractTests.cs +++ b/test/Microsoft.DotNet.PackageInstall.Tests/NuGetPackageInstallerExtractTests.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #nullable disable @@ -25,10 +25,10 @@ public async Task ItCanExtractNugetPackage() new(new DirectoryPath(Directory.GetCurrentDirectory()), null, new MockFirstPartyNuGetPackageSigningVerifier(), logger, restoreActionConfig: new RestoreActionConfig(NoCache: true)); string packagePath = - await installer.DownloadPackageAsync(new PackageId(packageId), new NuGetVersion(packageVersion)); + await installer.DownloadPackageAsync(new PackageId(packageId), TestContext.CancellationToken, new NuGetVersion(packageVersion)); string targetPath = Path.Combine(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()), "ExtractedPackage"); - IEnumerable result = await installer.ExtractPackageAsync(packagePath, new DirectoryPath(targetPath)); + IEnumerable result = await installer.ExtractPackageAsync(packagePath, new DirectoryPath(targetPath), TestContext.CancellationToken); Directory.Exists(targetPath).Should().BeTrue(); string[] extractedFiles = Directory.GetFiles(targetPath, "*", SearchOption.AllDirectories); diff --git a/test/Microsoft.DotNet.PackageInstall.Tests/NuGetPackageInstallerTests.cs b/test/Microsoft.DotNet.PackageInstall.Tests/NuGetPackageInstallerTests.cs index 7c2ae6257b2d..090c037dd755 100644 --- a/test/Microsoft.DotNet.PackageInstall.Tests/NuGetPackageInstallerTests.cs +++ b/test/Microsoft.DotNet.PackageInstall.Tests/NuGetPackageInstallerTests.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #nullable disable @@ -39,22 +39,23 @@ public NuGetPackageInstallerTests() _logger = new NuGetTestLogger(); _installer = new NuGetPackageDownloader(_tempDirectory, null, new MockFirstPartyNuGetPackageSigningVerifier(), _logger, - restoreActionConfig: new RestoreActionConfig(NoCache: true), timer: () => ExponentialRetry.Timer(ExponentialRetry.TestingIntervals)); + restoreActionConfig: new RestoreActionConfig(NoCache: true), timer: () => ExponentialRetry.Timer(ExponentialRetry.TestingIntervals, TestContext.CancellationToken)); _toolInstaller = new NuGetPackageDownloader(_tempDirectory, null, new MockFirstPartyNuGetPackageSigningVerifier(), _logger, - restoreActionConfig: new RestoreActionConfig(NoCache: true), timer: () => ExponentialRetry.Timer(ExponentialRetry.TestingIntervals), shouldUsePackageSourceMapping: true); + restoreActionConfig: new RestoreActionConfig(NoCache: true), timer: () => ExponentialRetry.Timer(ExponentialRetry.TestingIntervals, TestContext.CancellationToken), shouldUsePackageSourceMapping: true); } [TestMethod] public async Task GivenNoFeedInstallFailsWithException() => await Assert.ThrowsExactlyAsync(() => - _installer.DownloadPackageAsync(TestPackageId, new NuGetVersion(TestPackageVersion))); + _installer.DownloadPackageAsync(TestPackageId, TestContext.CancellationToken, new NuGetVersion(TestPackageVersion))); [TestMethod] public async Task GivenASourceInstallSucceeds() { string packagePath = await _installer.DownloadPackageAsync( TestPackageId, + TestContext.CancellationToken, new NuGetVersion(TestPackageVersion), new PackageSourceLocation(sourceFeedOverrides: new[] { GetTestLocalFeedPath() })); File.Exists(packagePath).Should().BeTrue(); @@ -70,6 +71,7 @@ public async Task GivenAFailedSourceItShouldError() await Assert.ThrowsExactlyAsync(() => _installer.DownloadPackageAsync( TestPackageId, + TestContext.CancellationToken, new NuGetVersion(TestPackageVersion), new PackageSourceLocation(sourceFeedOverrides: new[] { nonExistFeed.Value }))); } @@ -87,6 +89,7 @@ public async Task GivenAFailedSourceAndIgnoreFailedSourcesItShouldNotThrowFatalP await Assert.ThrowsExactlyAsync(() => installer.DownloadPackageAsync( TestPackageId, + TestContext.CancellationToken, new NuGetVersion(TestPackageVersion), new PackageSourceLocation(sourceFeedOverrides: new[] { @@ -101,6 +104,7 @@ public async Task GivenAFailedSourceItShouldIncludeSourceInError() Func downloadAction = () => _installer.DownloadPackageAsync( TestPackageId, + TestContext.CancellationToken, new NuGetVersion(TestPackageVersion), new PackageSourceLocation(sourceFeedOverrides: new[] { source })); @@ -119,6 +123,7 @@ public async Task GivenNugetConfigInstallSucceeds() string packagePath = await _installer.DownloadPackageAsync( TestPackageId, + TestContext.CancellationToken, new NuGetVersion(TestPackageVersion), new PackageSourceLocation(nugetConfigPath)); File.Exists(packagePath).Should().BeTrue(); @@ -138,6 +143,7 @@ public async Task GivenAValidNugetConfigAndFailedSourceItShouldError() await Assert.ThrowsExactlyAsync(() => _installer.DownloadPackageAsync( TestPackageId, + TestContext.CancellationToken, new NuGetVersion(TestPackageVersion), new PackageSourceLocation(validNugetConfigPath, sourceFeedOverrides: new[] { nonExistFeed.Value }))); @@ -155,6 +161,7 @@ public async Task GivenAConfigFileRootDirectoryPackageInstallSucceedsViaFindingN string packagePath = await _installer.DownloadPackageAsync( TestPackageId, + TestContext.CancellationToken, new NuGetVersion(TestPackageVersion), new PackageSourceLocation(rootConfigDirectory: directoryBelowNugetConfig)); File.Exists(packagePath).Should().BeTrue(); @@ -166,6 +173,7 @@ public async Task GivenNoPackageVersionItCanInstallLatestVersionOfPackage() NuGetVersion packageVersion = null; string packagePath = await _installer.DownloadPackageAsync( TestPackageId, + TestContext.CancellationToken, packageVersion, packageSourceLocation: new PackageSourceLocation(sourceFeedOverrides: new[] {GetTestLocalFeedPath()})); packagePath.Should().Contain("global.tool.console.demo.1.0.4.nupkg", "It can get the latest non preview version"); @@ -183,6 +191,7 @@ public async Task GivenARelativeSourcePathInstallSucceeds() Log.WriteLine("Relative path: " + relativePath); string packagePath = await _installer.DownloadPackageAsync( TestPackageId, + TestContext.CancellationToken, new NuGetVersion(TestPackageVersion), new PackageSourceLocation(sourceFeedOverrides: new[] { relativePath })); File.Exists(packagePath).Should().BeTrue(); @@ -213,6 +222,7 @@ public async Task GivenNoPackageSourceMappingItShouldError() Func downloadAction = () => _toolInstaller.DownloadPackageAsync( TestPackageId, + TestContext.CancellationToken, new NuGetVersion(TestPackageVersion), new PackageSourceLocation(nugetConfig: configPath)); (await downloadAction.Should().ThrowAsync()).And.Message.Should().Contain(string.Format(CliStrings.FailedToFindSourceUnderPackageSourceMapping, TestPackageId)); @@ -242,6 +252,7 @@ public async Task GivenPackageSourceMappingFeedNotFoundItShouldError() Func downloadAction = () => _toolInstaller.DownloadPackageAsync( TestPackageId, + TestContext.CancellationToken, new NuGetVersion(TestPackageVersion), new PackageSourceLocation(nugetConfig: configPath)); (await downloadAction.Should().ThrowAsync()).And.Message.Should().Contain(string.Format(CliStrings.FailedToMapSourceUnderPackageSourceMapping, TestPackageId)); @@ -255,6 +266,7 @@ public async Task WhenPassedIncludePreviewItInstallSucceeds() Log.WriteLine(relativePath); string packagePath = await _installer.DownloadPackageAsync( TestPackageId, + TestContext.CancellationToken, packageSourceLocation: new PackageSourceLocation(sourceFeedOverrides: new[] { relativePath }), includePreview: true); File.Exists(packagePath).Should().BeTrue(); @@ -287,12 +299,14 @@ public async Task GivenANonSignedSdkItShouldPrintMessageOnce() _logger, bufferedReporter, restoreActionConfig: new RestoreActionConfig(NoCache: true)); await nuGetPackageDownloader.DownloadPackageAsync( TestPackageId, + TestContext.CancellationToken, new NuGetVersion(TestPackageVersion), new PackageSourceLocation(sourceFeedOverrides: new[] { GetTestLocalFeedPath() })); // download 2 packages should only print the message once string packagePath = await nuGetPackageDownloader.DownloadPackageAsync( TestPackageId, + TestContext.CancellationToken, new NuGetVersion(TestPackageVersion), new PackageSourceLocation(sourceFeedOverrides: new[] { GetTestLocalFeedPath() })); @@ -312,12 +326,14 @@ public async Task GivenANonSignedSdkItShouldNotPrintMessageInQuiet() _logger, bufferedReporter, restoreActionConfig: new RestoreActionConfig(NoCache: true), verbosityOptions: VerbosityOptions.quiet); await nuGetPackageDownloader.DownloadPackageAsync( TestPackageId, + TestContext.CancellationToken, new NuGetVersion(TestPackageVersion), new PackageSourceLocation(sourceFeedOverrides: new[] { GetTestLocalFeedPath() })); // download 2 packages should only print the message once string packagePath = await nuGetPackageDownloader.DownloadPackageAsync( TestPackageId, + TestContext.CancellationToken, new NuGetVersion(TestPackageVersion), new PackageSourceLocation(sourceFeedOverrides: new[] { GetTestLocalFeedPath() })); @@ -350,7 +366,7 @@ private string DownloadSamplePackage(PackageId packageId) action: DownloadMostRecentSamplePackageFromPublicFeed, shouldStopRetry: result => result != null, maxRetryCount: 3, - timer: () => ExponentialRetry.Timer(ExponentialRetry.Intervals), + timer: () => ExponentialRetry.Timer(ExponentialRetry.Intervals, TestContext.CancellationToken), taskDescription: "Run command while retry transient restore error") .ConfigureAwait(false).GetAwaiter().GetResult(); @@ -359,7 +375,7 @@ string DownloadMostRecentSamplePackageFromPublicFeed() try { return nuGetPackageDownloader.DownloadPackageAsync( - new PackageId("Microsoft.iOS.Ref"), null, includePreview: true, + new PackageId("Microsoft.iOS.Ref"), TestContext.CancellationToken, null, includePreview: true, packageSourceLocation: new PackageSourceLocation( sourceFeedOverrides: new[] { "https://api.nuget.org/v3/index.json" })).GetAwaiter() .GetResult(); @@ -380,9 +396,9 @@ public void GivenFirstPartyPackageItShouldReturnTrue() var mauiSamplePackage = DownloadSamplePackage(new PackageId("Microsoft.NET.Sdk.Maui.Manifest-8.0.100-rc.1.Msi.x64")); var package = new FirstPartyNuGetPackageSigningVerifier(); - package.IsFirstParty(new FilePath(iosSamplePackage)).Should().BeTrue(); - package.IsFirstParty(new FilePath(androidSamplePackage)).Should().BeTrue(); - package.IsFirstParty(new FilePath(mauiSamplePackage)).Should().BeTrue(); + package.IsFirstParty(new FilePath(iosSamplePackage), TestContext.CancellationToken).Should().BeTrue(); + package.IsFirstParty(new FilePath(androidSamplePackage), TestContext.CancellationToken).Should().BeTrue(); + package.IsFirstParty(new FilePath(mauiSamplePackage), TestContext.CancellationToken).Should().BeTrue(); } private string GetShaFromSamplePackage(string samplePackage) @@ -457,6 +473,7 @@ public async Task RejectsAdditionalSourceFeedsWhenMappingActive() var download = () => _toolInstaller.DownloadPackageAsync( TestPackageId, + TestContext.CancellationToken, new NuGetVersion(TestPackageVersion), new PackageSourceLocation(additionalSourceFeeds: new[] { someFeed }), packageSourceMapping: mapping); diff --git a/test/Microsoft.DotNet.PackageInstall.Tests/ToolPackageDownloaderTests.cs b/test/Microsoft.DotNet.PackageInstall.Tests/ToolPackageDownloaderTests.cs index 514de7d2fe47..687b4d5248c0 100644 --- a/test/Microsoft.DotNet.PackageInstall.Tests/ToolPackageDownloaderTests.cs +++ b/test/Microsoft.DotNet.PackageInstall.Tests/ToolPackageDownloaderTests.cs @@ -62,6 +62,7 @@ public void GivenNugetConfigInstallSucceeds(bool testMockBehaviorIsInSync) var package = downloader.InstallPackage(new PackageLocation(nugetConfig: testDir.WithFile("NuGet.config")), packageId: TestPackageId, + cancellationToken: TestContext.CancellationToken, verbosity: TestVerbosity, versionRange: VersionRange.Parse(TestPackageVersion), targetFramework: _testTargetframework, @@ -89,6 +90,7 @@ public void GivenNugetConfigInstallSucceedsInTransaction(bool testMockBehaviorIs { package = downloader.InstallPackage(new PackageLocation(nugetConfig: testDir.WithFile("NuGet.config")), packageId: TestPackageId, + cancellationToken: TestContext.CancellationToken, verbosity: TestVerbosity, versionRange: VersionRange.Parse(TestPackageVersion), targetFramework: _testTargetframework, @@ -114,6 +116,7 @@ public void GivenNugetConfigInstallCreatesAnAssetFile(bool testMockBehaviorIsInS var package = downloader.InstallPackage(new PackageLocation(nugetConfig: testDir.WithFile("NuGet.config")), packageId: TestPackageId, + cancellationToken: TestContext.CancellationToken, verbosity: TestVerbosity, versionRange: VersionRange.Parse(TestPackageVersion), targetFramework: _testTargetframework, @@ -157,6 +160,7 @@ public void GivenAConfigFileRootDirectoryPackageInstallSucceedsViaFindingNugetCo var package = downloader.InstallPackage( new PackageLocation(rootConfigDirectory: subDirectory), packageId: TestPackageId, + cancellationToken: TestContext.CancellationToken, verbosity: TestVerbosity, versionRange: VersionRange.Parse(TestPackageVersion), targetFramework: _testTargetframework, @@ -225,6 +229,7 @@ public void GivenAllButNoPackageVersionItCanInstallThePackage(bool testMockBehav var package = downloader.InstallPackage( new PackageLocation(nugetConfig: testDir.WithFile("NuGet.config")), packageId: TestPackageId, + cancellationToken: TestContext.CancellationToken, verbosity: TestVerbosity, targetFramework: _testTargetframework, isGlobalTool: true, @@ -246,6 +251,7 @@ public void GivenAllButNoTargetFrameworkItCanDownloadThePackage(bool testMockBeh var package = downloader.InstallPackage(new PackageLocation(nugetConfig: testDir.WithFile("NuGet.config")), packageId: TestPackageId, + cancellationToken: TestContext.CancellationToken, verbosity: TestVerbosity, versionRange: VersionRange.Parse(TestPackageVersion), isGlobalTool: true, @@ -269,6 +275,7 @@ public void GivenASourceInstallSucceeds(bool testMockBehaviorIsInSync) var package = downloader.InstallPackage(new PackageLocation(additionalFeeds: new[] { source }), packageId: TestPackageId, + cancellationToken: TestContext.CancellationToken, verbosity: TestVerbosity, versionRange: VersionRange.Parse(TestPackageVersion), targetFramework: _testTargetframework, @@ -303,6 +310,7 @@ public void GivenARelativeSourcePathInstallSucceeds(bool testMockBehaviorIsInSyn var package = downloader.InstallPackage( new PackageLocation(additionalFeeds: new[] {relativePath}), packageId: TestPackageId, + cancellationToken: TestContext.CancellationToken, verbosity: TestVerbosity, versionRange: VersionRange.Parse(TestPackageVersion), targetFramework: _testTargetframework, @@ -330,6 +338,7 @@ public void GivenAUriSourceInstallSucceeds(bool testMockBehaviorIsInSync) var package = downloader.InstallPackage( new PackageLocation(additionalFeeds: new[] { new Uri(source).AbsoluteUri }), packageId: TestPackageId, + cancellationToken: TestContext.CancellationToken, verbosity: TestVerbosity, versionRange: VersionRange.Parse(TestPackageVersion), targetFramework: _testTargetframework, @@ -356,6 +365,7 @@ public void GivenAEmptySourceAndNugetConfigInstallSucceeds(bool testMockBehavior var package = downloader.InstallPackage(new PackageLocation(nugetConfig: testDir.WithFile("NuGet.config"), additionalFeeds: new[] { emptySource }), packageId: TestPackageId, + cancellationToken: TestContext.CancellationToken, verbosity: TestVerbosity, versionRange: VersionRange.Parse(TestPackageVersion), targetFramework: _testTargetframework, @@ -388,6 +398,7 @@ public void GivenFailureAfterRestoreInstallWillRollback(bool testMockBehaviorIsI { downloader.InstallPackage(new PackageLocation(additionalFeeds: new[] { source }), packageId: TestPackageId, + cancellationToken: TestContext.CancellationToken, verbosity: TestVerbosity, versionRange: VersionRange.Parse(TestPackageVersion), targetFramework: _testTargetframework, @@ -423,6 +434,7 @@ public void GivenSecondInstallInATransactionTheFirstInstallShouldRollback(bool t { Action first = () => downloader.InstallPackage(new PackageLocation(additionalFeeds: new[] { source }), packageId: TestPackageId, + cancellationToken: TestContext.CancellationToken, verbosity: TestVerbosity, versionRange: VersionRange.Parse(TestPackageVersion), targetFramework: _testTargetframework, @@ -433,6 +445,7 @@ public void GivenSecondInstallInATransactionTheFirstInstallShouldRollback(bool t downloader.InstallPackage(new PackageLocation(additionalFeeds: new[] { source }), packageId: TestPackageId, + cancellationToken: TestContext.CancellationToken, verbosity: TestVerbosity, versionRange: VersionRange.Parse(TestPackageVersion), targetFramework: _testTargetframework, @@ -482,6 +495,7 @@ public void GivenFailureAfterInstallingLocalToolThePublishedPackageIsNotRolledBa { downloader.InstallPackage(new PackageLocation(additionalFeeds: new[] { source }), packageId: TestPackageId, + cancellationToken: TestContext.CancellationToken, verbosity: TestVerbosity, versionRange: VersionRange.Parse(TestPackageVersion), targetFramework: _testTargetframework, @@ -538,6 +552,7 @@ public void GivenSecondInstallOfLocalToolItShouldNotThrowException(bool testMock { downloader.InstallPackage(new PackageLocation(additionalFeeds: new[] { source }), packageId: TestPackageId, + cancellationToken: TestContext.CancellationToken, verbosity: TestVerbosity, versionRange: VersionRange.Parse(TestPackageVersion), targetFramework: _testTargetframework, @@ -546,6 +561,7 @@ public void GivenSecondInstallOfLocalToolItShouldNotThrowException(bool testMock downloader.InstallPackage(new PackageLocation(additionalFeeds: new[] { source }), packageId: TestPackageId, + cancellationToken: TestContext.CancellationToken, verbosity: TestVerbosity, versionRange: VersionRange.Parse(TestPackageVersion), targetFramework: _testTargetframework, @@ -574,6 +590,7 @@ public void GivenSecondInstallWithoutATransactionTheFirstShouldNotRollback(bool var package = downloader.InstallPackage(new PackageLocation(additionalFeeds: new[] { source }), packageId: TestPackageId, + cancellationToken: TestContext.CancellationToken, verbosity: TestVerbosity, versionRange: VersionRange.Parse(TestPackageVersion), targetFramework: _testTargetframework, @@ -584,6 +601,7 @@ public void GivenSecondInstallWithoutATransactionTheFirstShouldNotRollback(bool Action secondCall = () => downloader.InstallPackage(new PackageLocation(additionalFeeds: new[] { source }), packageId: TestPackageId, + cancellationToken: TestContext.CancellationToken, verbosity: TestVerbosity, versionRange: VersionRange.Parse(TestPackageVersion), targetFramework: _testTargetframework, @@ -628,6 +646,7 @@ public void GivenAnInstalledPackageUninstallRemovesThePackage(bool testMockBehav var package = downloader.InstallPackage(new PackageLocation(additionalFeeds: new[] { source }), packageId: TestPackageId, + cancellationToken: TestContext.CancellationToken, verbosity: TestVerbosity, versionRange: VersionRange.Parse(TestPackageVersion), targetFramework: _testTargetframework, @@ -655,6 +674,7 @@ public void GivenAnInstalledPackageUninstallRollsbackWhenTransactionFails(bool t var package = downloader.InstallPackage( new PackageLocation(additionalFeeds: new[] { source }), packageId: TestPackageId, + cancellationToken: TestContext.CancellationToken, verbosity: TestVerbosity, versionRange: VersionRange.Parse(TestPackageVersion), targetFramework: _testTargetframework, @@ -691,6 +711,7 @@ public void GivenAnInstalledPackageUninstallRemovesThePackageWhenTransactionComm var package = downloader.InstallPackage(new PackageLocation(additionalFeeds: new[] { source }), packageId: TestPackageId, + cancellationToken: TestContext.CancellationToken, verbosity: TestVerbosity, versionRange: VersionRange.Parse(TestPackageVersion), targetFramework: _testTargetframework, @@ -721,6 +742,7 @@ public void GivenAPackageNameWithDifferentCaseItCanInstallThePackage(bool testMo var package = downloader.InstallPackage(new PackageLocation(nugetConfig: testDir.WithFile("NuGet.config")), packageId: new PackageId("GlObAl.TooL.coNsoLe.DemO"), + cancellationToken: TestContext.CancellationToken, verbosity: TestVerbosity, targetFramework: _testTargetframework, isGlobalTool: true, @@ -744,6 +766,7 @@ public async Task GivenConcurrentInstallationsOnlyOneInstallsThePackage() () => downloader.InstallPackage( new PackageLocation(additionalFeeds: [source]), packageId: TestPackageId, + cancellationToken: TestContext.CancellationToken, verbosity: TestVerbosity, versionRange: VersionRange.Parse(TestPackageVersion), targetFramework: _testTargetframework, @@ -797,7 +820,8 @@ public async Task GivenPackageExtractionInProgressThePackageIsNotReportedAsInsta blockingDownloader, packagesRoot.Value, packageVersion, - packageSourceLocation), + packageSourceLocation, + TestContext.CancellationToken), TestContext.CancellationToken); try @@ -842,7 +866,8 @@ public async Task GivenPackageHashPublicationInProgressThePackageIsNotReportedAs downloader.CreatePackageDownloader(), packagesRoot.Value, packageVersion, - packageSourceLocation), + packageSourceLocation, + TestContext.CancellationToken), TestContext.CancellationToken); try @@ -924,7 +949,8 @@ public async Task GivenMetadataPublicationFailsItPreservesThePackageForAnotherIn downloader.CreatePackageDownloader(), packagesRoot.Value, packageVersion, - packageSourceLocation); + packageSourceLocation, + TestContext.CancellationToken); }, TestContext.CancellationToken); Task reuse; @@ -941,7 +967,8 @@ public async Task GivenMetadataPublicationFailsItPreservesThePackageForAnotherIn packageVersion, packagesRoot, packageSourceLocation, - _testTargetframework), TestContext.CancellationToken); + _testTargetframework, + TestContext.CancellationToken), TestContext.CancellationToken); if (metadataPublished) { IToolPackage acceptedPackage = await reuse.WaitAsync(TimeSpan.FromSeconds(30), TestContext.CancellationToken); @@ -973,7 +1000,8 @@ await awaitDownload.Should().ThrowAsync() packageDownloader, packagesRoot.Value, packageVersion, - packageSourceLocation).Should().Be(packageVersion); + packageSourceLocation, + TestContext.CancellationToken).Should().Be(packageVersion); packageDownloader.ExtractCalled.Should().BeFalse(); File.ReadAllText(hashPath).Should().Be(publishedHash); File.Exists(reusedPackage.Command.Executable.Value).Should().BeTrue(); @@ -1022,7 +1050,8 @@ public async Task GivenNuGetsPackageLockToolInstallationWaitsForTheCanonicalWrit blockingDownloader, packagesRoot.Value, packageVersion, - packageSourceLocation), + packageSourceLocation, + TestContext.CancellationToken), TestContext.CancellationToken); Task firstCompleted = await Task.WhenAny( @@ -1080,7 +1109,8 @@ public void GivenADownloadedPackageWithAnotherIdentityItIsRejectedBeforeExtracti packageDownloader, packagesRoot.Value, packageVersion, - new PackageSourceLocation(basePath: root.Path)); + new PackageSourceLocation(basePath: root.Path), + TestContext.CancellationToken); download.Should().Throw() .WithMessage($"*'{actualIdentity}'*'{new PackageIdentity(TestPackageId.ToString(), packageVersion)}'*"); @@ -1112,6 +1142,7 @@ public void GivenACompleteCachedLocalToolInstallationDoesNotCreateALockFile() downloader.InstallPackage( packageLocation, TestPackageId, + TestContext.CancellationToken, TestVerbosity, packageVersion, _testTargetframework, @@ -1137,6 +1168,7 @@ public void GivenACompleteCachedLocalToolInstallationDoesNotCreateALockFile() downloader.InstallPackage( packageLocation, TestPackageId, + TestContext.CancellationToken, TestVerbosity, packageVersion, _testTargetframework, @@ -1182,6 +1214,7 @@ public async Task GivenOneLocalInstallFailsAfterPublicationAnotherInstallCanKeep () => failingDownloader.InstallPackage( packageLocation, TestPackageId, + TestContext.CancellationToken, TestVerbosity, packageVersion, _testTargetframework, @@ -1200,6 +1233,7 @@ public async Task GivenOneLocalInstallFailsAfterPublicationAnotherInstallCanKeep reusedPackage = reusingDownloader.InstallPackage( packageLocation, TestPackageId, + TestContext.CancellationToken, TestVerbosity, packageVersion, _testTargetframework, @@ -1331,6 +1365,7 @@ public void GivenARootWithNonAsciiCharacterInstallSucceeds() var package = downloader.InstallPackage(new PackageLocation(nugetConfig: nugetConfigPath), packageId: TestPackageId, + cancellationToken: TestContext.CancellationToken, verbosity: TestVerbosity, versionRange: VersionRange.Parse(TestPackageVersion), targetFramework: _testTargetframework, @@ -1359,6 +1394,7 @@ public void GivenAComplexVersionRangeInstallSucceeds(bool testMockBehaviorIsInSy var package = downloader.InstallPackage(new PackageLocation(nugetConfig: testDir.WithFile("NuGet.config"), additionalFeeds: new[] { emptySource }), packageId: TestPackageId, + cancellationToken: TestContext.CancellationToken, verbosity: TestVerbosity, versionRange: VersionRange.Parse("1.0.0-rc*"), targetFramework: _testTargetframework, @@ -1398,6 +1434,7 @@ public void GivenAPackageWithCasingAndenUSPOSIXInstallSucceeds(bool testMockBeha nugetConfig: testDir.WithFile("NuGet.config"), additionalFeeds: new[] { emptySource }), packageId: packageId, + cancellationToken: TestContext.CancellationToken, verbosity: TestVerbosity, versionRange: VersionRange.Parse(packageVersion), targetFramework: _testTargetframework, @@ -1600,12 +1637,14 @@ public NuGetVersion DownloadAndExtract( INuGetPackageDownloader packageDownloader, string packagesRootPath, NuGetVersion packageVersion, - PackageSourceLocation packageSourceLocation) => + PackageSourceLocation packageSourceLocation, + CancellationToken cancellationToken) => DownloadAndExtractPackage( packageId, packageDownloader, packagesRootPath, packageVersion, + cancellationToken, packageSourceLocation, TestVerbosity); @@ -1617,12 +1656,14 @@ public IToolPackage InstallFromCache( NuGetVersion packageVersion, DirectoryPath packagesRoot, PackageSourceLocation packageSourceLocation, - string targetFramework) + string targetFramework, + CancellationToken cancellationToken) { DownloadTool( packagesRoot, packageId, packageVersion, + cancellationToken, CreatePackageDownloader(), packageSourceLocation, givenSpecificVersion: true, @@ -1731,15 +1772,16 @@ public BlockingNuGetPackageDownloader(INuGetPackageDownloader inner) public void ContinueExtraction() => _continueExtraction.Set(); - public async Task> ExtractPackageAsync(string packagePath, DirectoryPath targetFolder) + public async Task> ExtractPackageAsync(string packagePath, DirectoryPath targetFolder, CancellationToken cancellationToken) { _extractionStarted.SetResult(); _continueExtraction.Wait(); - return await _inner.ExtractPackageAsync(packagePath, targetFolder); + return await _inner.ExtractPackageAsync(packagePath, targetFolder, cancellationToken); } public Task DownloadPackageAsync( PackageId packageId, + CancellationToken cancellationToken, NuGetVersion packageVersion = null, PackageSourceLocation packageSourceLocation = null, bool includePreview = false, @@ -1748,6 +1790,7 @@ public Task DownloadPackageAsync( PackageSourceMapping packageSourceMapping = null) => _inner.DownloadPackageAsync( packageId, + cancellationToken, packageVersion, packageSourceLocation, includePreview, @@ -1757,40 +1800,44 @@ public Task DownloadPackageAsync( public Task GetPackageUrl( PackageId packageId, + CancellationToken cancellationToken, NuGetVersion packageVersion = null, PackageSourceLocation packageSourceLocation = null, bool includePreview = false) => - _inner.GetPackageUrl(packageId, packageVersion, packageSourceLocation, includePreview); + _inner.GetPackageUrl(packageId, cancellationToken, packageVersion, packageSourceLocation, includePreview); public Task GetLatestPackageVersion( PackageId packageId, + CancellationToken cancellationToken, PackageSourceLocation packageSourceLocation = null, bool includePreview = false) => - _inner.GetLatestPackageVersion(packageId, packageSourceLocation, includePreview); + _inner.GetLatestPackageVersion(packageId, cancellationToken, packageSourceLocation, includePreview); public Task> GetLatestPackageVersions( PackageId packageId, int numberOfResults, + CancellationToken cancellationToken, PackageSourceLocation packageSourceLocation = null, bool includePreview = false) => - _inner.GetLatestPackageVersions(packageId, numberOfResults, packageSourceLocation, includePreview); + _inner.GetLatestPackageVersions(packageId, numberOfResults, cancellationToken, packageSourceLocation, includePreview); public Task GetBestPackageVersionAsync( PackageId packageId, VersionRange versionRange, + CancellationToken cancellationToken, PackageSourceLocation packageSourceLocation = null) => - _inner.GetBestPackageVersionAsync(packageId, versionRange, packageSourceLocation); + _inner.GetBestPackageVersionAsync(packageId, versionRange, cancellationToken, packageSourceLocation); public Task<(NuGetVersion version, PackageSource source)> GetBestPackageVersionAndSourceAsync( PackageId packageId, VersionRange versionRange, - PackageSourceLocation packageSourceLocation = null, - CancellationToken cancellationToken = default) => + CancellationToken cancellationToken, + PackageSourceLocation packageSourceLocation = null) => _inner.GetBestPackageVersionAndSourceAsync( packageId, versionRange, - packageSourceLocation, - cancellationToken); + cancellationToken, + packageSourceLocation); public void Dispose() => _continueExtraction.Dispose(); } @@ -1801,6 +1848,7 @@ private sealed class StaticPackagePathNuGetPackageDownloader(string packagePath) public Task DownloadPackageAsync( PackageId packageId, + CancellationToken cancellationToken, NuGetVersion packageVersion = null, PackageSourceLocation packageSourceLocation = null, bool includePreview = false, @@ -1809,7 +1857,7 @@ public Task DownloadPackageAsync( PackageSourceMapping packageSourceMapping = null) => Task.FromResult(packagePath); - public Task> ExtractPackageAsync(string packagePath, DirectoryPath targetFolder) + public Task> ExtractPackageAsync(string packagePath, DirectoryPath targetFolder, CancellationToken cancellationToken) { ExtractCalled = true; throw new InvalidOperationException("Extraction should not run for a mismatched package identity."); @@ -1817,6 +1865,7 @@ public Task> ExtractPackageAsync(string packagePath, Directo public Task GetPackageUrl( PackageId packageId, + CancellationToken cancellationToken, NuGetVersion packageVersion = null, PackageSourceLocation packageSourceLocation = null, bool includePreview = false) => @@ -1824,6 +1873,7 @@ public Task GetPackageUrl( public Task GetLatestPackageVersion( PackageId packageId, + CancellationToken cancellationToken, PackageSourceLocation packageSourceLocation = null, bool includePreview = false) => throw new NotSupportedException(); @@ -1831,6 +1881,7 @@ public Task GetLatestPackageVersion( public Task> GetLatestPackageVersions( PackageId packageId, int numberOfResults, + CancellationToken cancellationToken, PackageSourceLocation packageSourceLocation = null, bool includePreview = false) => throw new NotSupportedException(); @@ -1838,14 +1889,15 @@ public Task> GetLatestPackageVersions( public Task GetBestPackageVersionAsync( PackageId packageId, VersionRange versionRange, + CancellationToken cancellationToken, PackageSourceLocation packageSourceLocation = null) => throw new NotSupportedException(); public Task<(NuGetVersion version, PackageSource source)> GetBestPackageVersionAndSourceAsync( PackageId packageId, VersionRange versionRange, - PackageSourceLocation packageSourceLocation = null, - CancellationToken cancellationToken = default) => + CancellationToken cancellationToken, + PackageSourceLocation packageSourceLocation = null) => throw new NotSupportedException(); } diff --git a/test/Microsoft.DotNet.PackageInstall.Tests/ToolPackageInstallerNugetCacheTests.cs b/test/Microsoft.DotNet.PackageInstall.Tests/ToolPackageInstallerNugetCacheTests.cs index 13745f356bfc..c4da4c191929 100644 --- a/test/Microsoft.DotNet.PackageInstall.Tests/ToolPackageInstallerNugetCacheTests.cs +++ b/test/Microsoft.DotNet.PackageInstall.Tests/ToolPackageInstallerNugetCacheTests.cs @@ -41,6 +41,7 @@ public void GivenNugetConfigInstallSucceeds(bool testMockBehaviorIsInSync) IToolPackage toolPackage = installer.InstallPackage( packageId: TestPackageId, + cancellationToken: TestContext.CancellationToken, verbosity: TestVerbosity, versionRange: VersionRange.Parse(TestPackageVersion), packageLocation: new PackageLocation(nugetConfig: nugetConfigPath), @@ -81,6 +82,7 @@ public void GivenNugetConfigVersionRangeInstallSucceeds(bool testMockBehaviorIsI IToolPackage toolPackage = installer.InstallPackage( packageId: TestPackageId, + cancellationToken: TestContext.CancellationToken, verbosity: TestVerbosity, versionRange: VersionRange.Parse("1.0.0-*"), packageLocation: new PackageLocation(nugetConfig: nugetConfigPath), diff --git a/test/Microsoft.DotNet.PackageInstall.Tests/ToolPackageUninstallerTests.cs b/test/Microsoft.DotNet.PackageInstall.Tests/ToolPackageUninstallerTests.cs index 53eafb2fc343..22c420d18ce7 100644 --- a/test/Microsoft.DotNet.PackageInstall.Tests/ToolPackageUninstallerTests.cs +++ b/test/Microsoft.DotNet.PackageInstall.Tests/ToolPackageUninstallerTests.cs @@ -33,6 +33,7 @@ public void GivenAnInstalledPackageUninstallRemovesThePackage(bool testMockBehav var package = downloader.InstallPackage(new PackageLocation(additionalFeeds: new[] { source }), packageId: TestPackageId, + cancellationToken: TestContext.CancellationToken, verbosity: TestVerbosity, versionRange: VersionRange.Parse(TestPackageVersion), targetFramework: _testTargetframework, diff --git a/test/Microsoft.DotNet.Tools.Tests.ComponentMocks/AppHostShellShimMakerMock.cs b/test/Microsoft.DotNet.Tools.Tests.ComponentMocks/AppHostShellShimMakerMock.cs index 0c16edad19c1..45ac95de768f 100644 --- a/test/Microsoft.DotNet.Tools.Tests.ComponentMocks/AppHostShellShimMakerMock.cs +++ b/test/Microsoft.DotNet.Tools.Tests.ComponentMocks/AppHostShellShimMakerMock.cs @@ -18,7 +18,10 @@ public AppHostShellShimMakerMock(IFileSystem fileSystem = null) _fileSystem = fileSystem ?? new FileSystemWrapper(); } - public void CreateApphostShellShim(FilePath entryPoint, FilePath shimPath) + public void CreateApphostShellShim( + FilePath entryPoint, + FilePath shimPath, + CancellationToken cancellationToken) { var shim = new FakeShim { diff --git a/test/Microsoft.DotNet.Tools.Tests.ComponentMocks/MockNuGetPackageDownloader.cs b/test/Microsoft.DotNet.Tools.Tests.ComponentMocks/MockNuGetPackageDownloader.cs index a926bdd93dbd..300119561c9a 100644 --- a/test/Microsoft.DotNet.Tools.Tests.ComponentMocks/MockNuGetPackageDownloader.cs +++ b/test/Microsoft.DotNet.Tools.Tests.ComponentMocks/MockNuGetPackageDownloader.cs @@ -55,6 +55,7 @@ bool ShouldFindPackage(PackageId packageId, PackageSourceLocation packageSourceL public Task DownloadPackageAsync(PackageId packageId, + CancellationToken cancellationToken, NuGetVersion packageVersion = null, PackageSourceLocation packageSourceLocation = null, bool includePreview = false, @@ -86,7 +87,7 @@ public Task DownloadPackageAsync(PackageId packageId, return Task.FromResult(path); } - public Task> ExtractPackageAsync(string packagePath, DirectoryPath targetFolder) + public Task> ExtractPackageAsync(string packagePath, DirectoryPath targetFolder, CancellationToken cancellationToken) { ExtractCallParams.Add((packagePath, targetFolder)); if (_manifestDownload) @@ -108,7 +109,12 @@ public Task> ExtractPackageAsync(string packagePath, Directo return Task.FromResult(new List() as IEnumerable); } - public Task> GetLatestPackageVersions(PackageId packageId, int numberOfResults, PackageSourceLocation packageSourceLocation = null, bool includePreview = false) + public Task> GetLatestPackageVersions( + PackageId packageId, + int numberOfResults, + CancellationToken cancellationToken, + PackageSourceLocation packageSourceLocation = null, + bool includePreview = false) { if (!ShouldFindPackage(packageId, packageSourceLocation)) @@ -119,7 +125,11 @@ public Task> GetLatestPackageVersions(PackageId packag return Task.FromResult(_packageVersions ?? Enumerable.Empty()); } - public Task GetLatestPackageVersion(PackageId packageId, PackageSourceLocation packageSourceLocation = null, bool includePreview = false) + public Task GetLatestPackageVersion( + PackageId packageId, + CancellationToken cancellationToken, + PackageSourceLocation packageSourceLocation = null, + bool includePreview = false) { if (!ShouldFindPackage(packageId, packageSourceLocation)) { @@ -129,14 +139,20 @@ public Task GetLatestPackageVersion(PackageId packageId, PackageSo return Task.FromResult(_packageVersions.Max()); } - public async Task GetBestPackageVersionAsync(PackageId packageId, VersionRange versionRange, PackageSourceLocation packageSourceLocation = null) + public async Task GetBestPackageVersionAsync( + PackageId packageId, + VersionRange versionRange, + CancellationToken cancellationToken, + PackageSourceLocation packageSourceLocation = null) { - return (await GetBestPackageVersionAndSourceAsync(packageId, versionRange, packageSourceLocation)).version; + return (await GetBestPackageVersionAndSourceAsync(packageId, versionRange, cancellationToken, packageSourceLocation)).version; } - public Task<(NuGetVersion version, PackageSource source)> GetBestPackageVersionAndSourceAsync(PackageId packageId, - VersionRange versionRange,PackageSourceLocation packageSourceLocation = null, - CancellationToken cancellationToken = default) + public Task<(NuGetVersion version, PackageSource source)> GetBestPackageVersionAndSourceAsync( + PackageId packageId, + VersionRange versionRange, + CancellationToken cancellationToken, + PackageSourceLocation packageSourceLocation = null) { cancellationToken.ThrowIfCancellationRequested(); @@ -159,6 +175,7 @@ public async Task GetBestPackageVersionAsync(PackageId packageId, public Task GetPackageUrl(PackageId packageId, + CancellationToken cancellationToken, NuGetVersion packageVersion, PackageSourceLocation packageSourceLocation = null, bool includePreview = false) diff --git a/test/Microsoft.DotNet.Tools.Tests.ComponentMocks/ToolPackageDownloaderMock.cs b/test/Microsoft.DotNet.Tools.Tests.ComponentMocks/ToolPackageDownloaderMock.cs index c5a1d683d1c1..029824ee53d4 100644 --- a/test/Microsoft.DotNet.Tools.Tests.ComponentMocks/ToolPackageDownloaderMock.cs +++ b/test/Microsoft.DotNet.Tools.Tests.ComponentMocks/ToolPackageDownloaderMock.cs @@ -97,6 +97,7 @@ public ToolPackageDownloaderMock( } public IToolPackage InstallPackage(PackageLocation packageLocation, PackageId packageId, + CancellationToken cancellationToken, VerbosityOptions verbosity, VersionRange? versionRange = null, string? targetFramework = null, @@ -106,6 +107,7 @@ public IToolPackage InstallPackage(PackageLocation packageLocation, PackageId pa RestoreActionConfig? restoreActionConfig = null ) { + cancellationToken.ThrowIfCancellationRequested(); string? rollbackDirectory = null; var packageRootDirectory = _toolPackageStore.GetRootPackageDirectory(packageId); diff --git a/test/Microsoft.DotNet.Tools.Tests.ComponentMocks/ToolPackageDownloaderMock2.cs b/test/Microsoft.DotNet.Tools.Tests.ComponentMocks/ToolPackageDownloaderMock2.cs index 92a49dbf7253..b4e320f41469 100644 --- a/test/Microsoft.DotNet.Tools.Tests.ComponentMocks/ToolPackageDownloaderMock2.cs +++ b/test/Microsoft.DotNet.Tools.Tests.ComponentMocks/ToolPackageDownloaderMock2.cs @@ -112,8 +112,9 @@ protected override INuGetPackageDownloader CreateNuGetPackageDownloader(bool ver } protected override NuGetVersion DownloadAndExtractPackage(PackageId packageId, INuGetPackageDownloader nugetPackageDownloader, string packagesRootPath, - NuGetVersion packageVersion, PackageSourceLocation packageSourceLocation, Cli.Utils.VerbosityOptions verbosity, bool includeUnlisted = false) + NuGetVersion packageVersion, CancellationToken cancellationToken, PackageSourceLocation packageSourceLocation, Cli.Utils.VerbosityOptions verbosity, bool includeUnlisted = false) { + cancellationToken.ThrowIfCancellationRequested(); var package = GetPackage(packageId, packageVersion); if (package == null) diff --git a/test/Microsoft.NET.Build.Containers.IntegrationTests/ContainerCli.cs b/test/Microsoft.NET.Build.Containers.IntegrationTests/ContainerCli.cs index 717b5765718b..b62667a96ea5 100644 --- a/test/Microsoft.NET.Build.Containers.IntegrationTests/ContainerCli.cs +++ b/test/Microsoft.NET.Build.Containers.IntegrationTests/ContainerCli.cs @@ -9,7 +9,8 @@ static class ContainerCli public static bool IsAvailable => DockerCliStatus.IsAvailable; - public static bool IsContainerdStoreEnabledForDocker => DockerContainerRuntime.IsContainerdStoreEnabled(); + public static bool IsContainerdStoreEnabledForDocker => + DockerContainerRuntime.IsContainerdStoreEnabled(CancellationToken.None); public static RunExeCommand PullCommand(ITestOutputHelper log, params string[] args) => CreateCommand(log, "pull", args); diff --git a/test/Microsoft.NET.Build.Containers.IntegrationTests/CreateImageIndexTests.cs b/test/Microsoft.NET.Build.Containers.IntegrationTests/CreateImageIndexTests.cs index 67a4aa8e2f57..4961139c1753 100644 --- a/test/Microsoft.NET.Build.Containers.IntegrationTests/CreateImageIndexTests.cs +++ b/test/Microsoft.NET.Build.Containers.IntegrationTests/CreateImageIndexTests.cs @@ -53,7 +53,7 @@ public async Task CreateImageIndex_Baseline() // Assert that the image index is pushed to the registry var loggerFactory = new TestLoggerFactory(Log); var logger = loggerFactory.CreateLogger(nameof(CreateImageIndex_Baseline)); - Registry registry = new(outputRegistry, logger, RegistryMode.Pull); + Registry registry = new(outputRegistry, logger, RegistryMode.Pull, TestContext.CancellationToken); await AssertThatImageIsReferencedInImageIndex("linux-x64", repository, tags, registry); await AssertThatImageIsReferencedInImageIndex("linux-arm64", repository, tags, registry); diff --git a/test/Microsoft.NET.Build.Containers.IntegrationTests/CreateNewImageTests.cs b/test/Microsoft.NET.Build.Containers.IntegrationTests/CreateNewImageTests.cs index da63e7d2c19f..213e6b429518 100644 --- a/test/Microsoft.NET.Build.Containers.IntegrationTests/CreateNewImageTests.cs +++ b/test/Microsoft.NET.Build.Containers.IntegrationTests/CreateNewImageTests.cs @@ -225,7 +225,7 @@ public async System.Threading.Tasks.Task CreateNewImage_RootlessBaseImage() var logger = loggerFactory.CreateLogger(nameof(CreateNewImage_RootlessBaseImage)); // Build a rootless base runtime image. - Registry registry = new(DockerRegistryManager.LocalRegistry, logger, RegistryMode.Push); + Registry registry = new(DockerRegistryManager.LocalRegistry, logger, RegistryMode.Push, TestContext.CancellationToken); ImageBuilder imageBuilder = await registry.GetImageManifestAsync( DockerRegistryManager.RuntimeBaseImage, diff --git a/test/Microsoft.NET.Build.Containers.IntegrationTests/DockerAvailableUtils.cs b/test/Microsoft.NET.Build.Containers.IntegrationTests/DockerAvailableUtils.cs index 3d4789fa8a81..e86b28bae61a 100644 --- a/test/Microsoft.NET.Build.Containers.IntegrationTests/DockerAvailableUtils.cs +++ b/test/Microsoft.NET.Build.Containers.IntegrationTests/DockerAvailableUtils.cs @@ -75,7 +75,7 @@ public ContainerdStoreUnavailableCondition() public override bool IsConditionMet => DockerCliStatus.IsAvailable && DockerCliStatus.Runtime != ContainerRuntimeKind.Podman - && !DockerContainerRuntime.IsContainerdStoreEnabled(); + && !DockerContainerRuntime.IsContainerdStoreEnabled(CancellationToken.None); } public sealed class DockerSupportsArchCondition : ConditionBaseAttribute @@ -103,7 +103,8 @@ internal static class WslcCliStatus { private static readonly Lazy s_isAvailable = new( () => OperatingSystem.IsWindows() - && new ContainerRuntime(ContainerRuntime.WslcCommand, new Microsoft.NET.TestFramework.TestLoggerFactory()).IsAvailable(), + && new ContainerRuntime(ContainerRuntime.WslcCommand, new Microsoft.NET.TestFramework.TestLoggerFactory()) + .IsAvailableAsync(CancellationToken.None).GetAwaiter().GetResult(), LazyThreadSafetyMode.ExecutionAndPublication); public static bool IsAvailable => s_isAvailable.Value; @@ -113,7 +114,8 @@ internal static class MacOSContainerCliStatus { private static readonly Lazy s_isAvailable = new( () => OperatingSystem.IsMacOS() - && new ContainerRuntime(ContainerRuntime.MacOSContainerCommand, new Microsoft.NET.TestFramework.TestLoggerFactory()).IsAvailable(), + && new ContainerRuntime(ContainerRuntime.MacOSContainerCommand, new Microsoft.NET.TestFramework.TestLoggerFactory()) + .IsAvailableAsync(CancellationToken.None).GetAwaiter().GetResult(), LazyThreadSafetyMode.ExecutionAndPublication); public static bool IsAvailable => s_isAvailable.Value; @@ -124,7 +126,8 @@ internal static class PodmanCliStatus private static readonly Lazy s_isAvailable = new( () => new ContainerRuntime( ContainerRuntime.PodmanCommand, - new Microsoft.NET.TestFramework.TestLoggerFactory()).IsAvailable(), + new Microsoft.NET.TestFramework.TestLoggerFactory()) + .IsAvailableAsync(CancellationToken.None).GetAwaiter().GetResult(), LazyThreadSafetyMode.ExecutionAndPublication); public static bool IsAvailable => s_isAvailable.Value; @@ -148,8 +151,8 @@ public static string LocalRegistry private static (bool IsAvailable, ContainerRuntimeKind Runtime) GetStatus() { ContainerRuntime runtime = new(new Microsoft.NET.TestFramework.TestLoggerFactory(), probePlatformNativeCli: false); - bool isAvailable = runtime.IsAvailable(); - return (isAvailable, runtime.GetTelemetryValue()); + bool isAvailable = runtime.IsAvailableAsync(CancellationToken.None).GetAwaiter().GetResult(); + return (isAvailable, runtime.GetTelemetryValue(CancellationToken.None)); } } @@ -159,7 +162,7 @@ public static IEnumerable AvailableRuntimes() { if (DockerCliStatus.IsAvailable && DockerCliStatus.Runtime == ContainerRuntimeKind.Docker - && DockerContainerRuntime.IsContainerdStoreEnabled()) + && DockerContainerRuntime.IsContainerdStoreEnabled(CancellationToken.None)) { yield return KnownLocalRegistryTypes.Docker; } diff --git a/test/Microsoft.NET.Build.Containers.IntegrationTests/DockerRegistryManager.cs b/test/Microsoft.NET.Build.Containers.IntegrationTests/DockerRegistryManager.cs index c77cb8498e21..a1a063efb9c1 100644 --- a/test/Microsoft.NET.Build.Containers.IntegrationTests/DockerRegistryManager.cs +++ b/test/Microsoft.NET.Build.Containers.IntegrationTests/DockerRegistryManager.cs @@ -46,7 +46,7 @@ public static async Task StartAndPopulateDockerRegistry(ITestOutputHelper testOu { using TestLoggerFactory loggerFactory = new(testOutput); - if (!new ContainerRuntime(loggerFactory).IsAvailable()) + if (!new ContainerRuntime(loggerFactory).IsAvailableAsync(CancellationToken.None).GetAwaiter().GetResult()) { throw new InvalidOperationException("Docker is not available, tests cannot run"); } @@ -57,8 +57,8 @@ public static async Task StartAndPopulateDockerRegistry(ITestOutputHelper testOu int spawnRegistryDelay = 1000; //ms StringBuilder failureReasons = new(); - var pullRegistry = new Registry(BaseImageSource, logger, RegistryMode.Pull); - var pushRegistry = new Registry(LocalRegistry, logger, RegistryMode.Push); + var pullRegistry = new Registry(BaseImageSource, logger, RegistryMode.Pull, CancellationToken.None); + var pushRegistry = new Registry(LocalRegistry, logger, RegistryMode.Push, CancellationToken.None); for (int spawnRegistryAttempt = 1; spawnRegistryAttempt <= spawnRegistryMaxRetry; spawnRegistryAttempt++) { diff --git a/test/Microsoft.NET.Build.Containers.IntegrationTests/DockerRegistryTests.cs b/test/Microsoft.NET.Build.Containers.IntegrationTests/DockerRegistryTests.cs index 452e3bddd2ff..ede5ccda9981 100644 --- a/test/Microsoft.NET.Build.Containers.IntegrationTests/DockerRegistryTests.cs +++ b/test/Microsoft.NET.Build.Containers.IntegrationTests/DockerRegistryTests.cs @@ -16,7 +16,7 @@ public async Task GetFromRegistry() { var loggerFactory = new TestLoggerFactory(Log); var logger = loggerFactory.CreateLogger(nameof(GetFromRegistry)); - Registry registry = new(DockerRegistryManager.LocalRegistry, logger, RegistryMode.Push); + Registry registry = new(DockerRegistryManager.LocalRegistry, logger, RegistryMode.Push, TestContext.CancellationToken); var ridgraphfile = ToolsetUtils.GetRuntimeGraphFilePath(); // Don't need rid graph for local registry image pulls - since we're only pushing single image manifests (not manifest lists) @@ -70,9 +70,18 @@ public async Task WriteToPrivateBasicRegistry() // login to that registry ContainerCli.LoginCommand(Log, "--username", "testuser", "--password", "testpassword", registryName).Execute().Should().Pass(); // push an image to that registry using username/password - Registry localAuthed = new(new Uri($"https://{registryName}"), logger, RegistryMode.Push, settings: new() { ParallelUploadEnabled = false, ForceChunkedUpload = true }); + Registry localAuthed = new( + new Uri($"https://{registryName}"), + logger, + RegistryMode.Push, + TestContext.CancellationToken, + settings: new RegistrySettings(TestContext.CancellationToken) + { + ParallelUploadEnabled = false, + ForceChunkedUpload = true + }); var ridgraphfile = ToolsetUtils.GetRuntimeGraphFilePath(); - Registry mcr = new(DockerRegistryManager.BaseImageSource, logger, RegistryMode.Pull); + Registry mcr = new(DockerRegistryManager.BaseImageSource, logger, RegistryMode.Pull, TestContext.CancellationToken); var sourceImage = new SourceImageReference(mcr, DockerRegistryManager.RuntimeBaseImage, DockerRegistryManager.Net6ImageTag, null); var destinationImage = new DestinationImageReference(localAuthed, DockerRegistryManager.RuntimeBaseImage, new[] { DockerRegistryManager.Net6ImageTag }); diff --git a/test/Microsoft.NET.Build.Containers.IntegrationTests/DockerSupportsArchHelper.cs b/test/Microsoft.NET.Build.Containers.IntegrationTests/DockerSupportsArchHelper.cs index 1c980231a7f4..0b57659a48c6 100644 --- a/test/Microsoft.NET.Build.Containers.IntegrationTests/DockerSupportsArchHelper.cs +++ b/test/Microsoft.NET.Build.Containers.IntegrationTests/DockerSupportsArchHelper.cs @@ -59,7 +59,7 @@ private static bool GetIsWindowsDockerDaemon() } // the config json has an OSType property that is either "linux" or "windows" - // we can't use this for linux arch detection because that isn't enough information. - var config = DockerContainerRuntime.GetDockerConfig(); + var config = DockerContainerRuntime.GetDockerConfig(CancellationToken.None); if (config.RootElement.TryGetProperty("OSType", out JsonElement osTypeProperty)) { return osTypeProperty.GetString() == "windows"; diff --git a/test/Microsoft.NET.Build.Containers.IntegrationTests/EndToEndTests.cs b/test/Microsoft.NET.Build.Containers.IntegrationTests/EndToEndTests.cs index c61bd7165dad..855aa92848e5 100644 --- a/test/Microsoft.NET.Build.Containers.IntegrationTests/EndToEndTests.cs +++ b/test/Microsoft.NET.Build.Containers.IntegrationTests/EndToEndTests.cs @@ -57,7 +57,7 @@ public async Task ApiEndToEndWithRegistryPushAndPull() // Build the image - Registry registry = new(DockerRegistryManager.LocalRegistry, logger, RegistryMode.Push); + Registry registry = new(DockerRegistryManager.LocalRegistry, logger, RegistryMode.Push, TestContext.CancellationToken); ImageBuilder imageBuilder = await registry.GetImageManifestAsync( DockerRegistryManager.RuntimeBaseImage, @@ -105,7 +105,7 @@ public async Task ApiEndToEndWithLocalLoad() // Build the image - Registry registry = new(DockerRegistryManager.LocalRegistry, logger, RegistryMode.Push); + Registry registry = new(DockerRegistryManager.LocalRegistry, logger, RegistryMode.Push, TestContext.CancellationToken); ImageBuilder imageBuilder = await registry.GetImageManifestAsync( DockerRegistryManager.RuntimeBaseImage, @@ -214,7 +214,7 @@ public async Task ApiEndToEndWithArchiveWritingAndLoad() // Build the image - Registry registry = new(DockerRegistryManager.LocalRegistry, logger, RegistryMode.Push); + Registry registry = new(DockerRegistryManager.LocalRegistry, logger, RegistryMode.Push, TestContext.CancellationToken); ImageBuilder imageBuilder = await registry.GetImageManifestAsync( DockerRegistryManager.RuntimeBaseImage, @@ -286,7 +286,7 @@ public async Task TarballsHaveCorrectStructure() private async Task<(BuiltImage image, SourceImageReference sourceReference, DestinationImageReference destinationReference)> BuildDockerImageWithArciveDestinationAsync(string archiveFile, string[] tags, string testName) { ILogger logger = LoggerFactory.CreateLogger(testName); - Registry registry = new(DockerRegistryManager.LocalRegistry, logger, RegistryMode.Push); + Registry registry = new(DockerRegistryManager.LocalRegistry, logger, RegistryMode.Push, TestContext.CancellationToken); ImageBuilder imageBuilder = await registry.GetImageManifestAsync( DockerRegistryManager.RuntimeBaseImage, @@ -1590,7 +1590,7 @@ public async Task CanPackageForAllSupportedContainerRIDs(string dockerPlatform, string publishDirectory = BuildLocalApp(tfm: ToolsetInfo.CurrentTargetFramework, rid: rid); // Build the image - Registry registry = new(DockerRegistryManager.BaseImageSource, logger, RegistryMode.Push); + Registry registry = new(DockerRegistryManager.BaseImageSource, logger, RegistryMode.Push, TestContext.CancellationToken); var isWin = rid.StartsWith("win"); ImageBuilder? imageBuilder = await registry.GetImageManifestAsync( DockerRegistryManager.RuntimeBaseImage, @@ -1644,7 +1644,7 @@ public async Task CheckDownloadErrorMessageWhenSourceRepositoryThrows() string publishDirectory = BuildLocalApp(tfm: ToolsetInfo.CurrentTargetFramework, rid: rid); // Build the image - Registry registry = new(DockerRegistryManager.BaseImageSource, logger, RegistryMode.Push); + Registry registry = new(DockerRegistryManager.BaseImageSource, logger, RegistryMode.Push, TestContext.CancellationToken); ImageBuilder? imageBuilder = await registry.GetImageManifestAsync( DockerRegistryManager.RuntimeBaseImage, DockerRegistryManager.Net8PreviewWindowsSpecificImageTag, @@ -1669,7 +1669,7 @@ public async Task CheckDownloadErrorMessageWhenSourceRepositoryThrows() var destinationReference = new DestinationImageReference(new ArchiveFileRegistry(archivePath), NewImageName(), new[] { rid }); (var taskLog, var errors) = SetupTaskLog(); - var telemetry = new Telemetry(sourceReference, destinationReference, taskLog); + var telemetry = new Telemetry(sourceReference, destinationReference, taskLog, TestContext.CancellationToken); await ImagePublisher.PublishImageAsync(builtImage, sourceReference, destinationReference, false, taskLog, telemetry, CancellationToken.None) .ConfigureAwait(false); diff --git a/test/Microsoft.NET.Build.Containers.IntegrationTests/RegistryTests.cs b/test/Microsoft.NET.Build.Containers.IntegrationTests/RegistryTests.cs index b6bda40a01f1..2bc229c4d1af 100644 --- a/test/Microsoft.NET.Build.Containers.IntegrationTests/RegistryTests.cs +++ b/test/Microsoft.NET.Build.Containers.IntegrationTests/RegistryTests.cs @@ -34,7 +34,7 @@ public async Task CanReadManifestFromRegistry(string fullyQualifiedContainerName containerTag ??= "latest"; ILogger logger = LoggerFactory.CreateLogger(nameof(CanReadManifestFromRegistry)); - Registry registry = new(containerRegistry, logger, RegistryMode.Pull); + Registry registry = new(containerRegistry, logger, RegistryMode.Pull, TestContext.CancellationToken); var ridgraphfile = ToolsetUtils.GetRuntimeGraphFilePath(); diff --git a/test/Microsoft.NET.Build.Containers.UnitTests/DockerAvailableUtils.cs b/test/Microsoft.NET.Build.Containers.UnitTests/DockerAvailableUtils.cs index f11111c754aa..9c0a6b2e17ac 100644 --- a/test/Microsoft.NET.Build.Containers.UnitTests/DockerAvailableUtils.cs +++ b/test/Microsoft.NET.Build.Containers.UnitTests/DockerAvailableUtils.cs @@ -48,7 +48,7 @@ public static string LocalRegistry private static (bool IsAvailable, ContainerRuntimeKind Runtime) GetStatus() { ContainerRuntime runtime = new(new TestLoggerFactory(), probePlatformNativeCli: false); - bool isAvailable = runtime.IsAvailable(); - return (isAvailable, runtime.GetTelemetryValue()); + bool isAvailable = runtime.IsAvailableAsync(CancellationToken.None).GetAwaiter().GetResult(); + return (isAvailable, runtime.GetTelemetryValue(CancellationToken.None)); } } diff --git a/test/Microsoft.NET.Build.Containers.UnitTests/DockerDaemonTests.cs b/test/Microsoft.NET.Build.Containers.UnitTests/DockerDaemonTests.cs index d80da1f00c58..228dcdf73b26 100644 --- a/test/Microsoft.NET.Build.Containers.UnitTests/DockerDaemonTests.cs +++ b/test/Microsoft.NET.Build.Containers.UnitTests/DockerDaemonTests.cs @@ -87,7 +87,7 @@ public void Selects_preferred_available_command( isMacOS, isPodmanAlias); - Assert.AreEqual((ContainerRuntimeKind)expectedRuntime, runtime.GetTelemetryValue()); + Assert.AreEqual((ContainerRuntimeKind)expectedRuntime, runtime.GetTelemetryValue(TestContext.CancellationToken)); } [TestMethod] @@ -102,11 +102,11 @@ public void Stops_probing_after_platform_native_runtime_succeeds() probedCommands.Add(command); return Task.FromResult(true); }, - () => false, + _ => false, isWindows: true, isMacOS: false); - Assert.AreEqual(ContainerRuntimeKind.Wslc, runtime.GetTelemetryValue()); + Assert.AreEqual(ContainerRuntimeKind.Wslc, runtime.GetTelemetryValue(TestContext.CancellationToken)); Assert.AreSequenceEqual(new[] { ContainerRuntime.WslcCommand }, probedCommands); } @@ -121,7 +121,7 @@ public async Task Times_out_runtime_probes() await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken); return true; }, - () => false, + _ => false, isWindows: false, isMacOS: false, probeTimeout: TimeSpan.FromMilliseconds(10)); @@ -129,6 +129,24 @@ public async Task Times_out_runtime_probes() Assert.IsFalse(await runtime.IsAvailableAsync(default)); } + [TestMethod] + public async Task Availability_check_propagates_cancellation() + { + ContainerRuntime runtime = new( + ContainerRuntime.PodmanCommand, + _loggerFactory, + (_, _, cancellationToken) => Task.FromCanceled(cancellationToken), + _ => false, + isWindows: false, + isMacOS: false); + using CancellationTokenSource cancellationSource = + CancellationTokenSource.CreateLinkedTokenSource(TestContext.CancellationToken); + cancellationSource.Cancel(); + + await Assert.ThrowsAsync( + () => runtime.IsAvailableAsync(cancellationSource.Token)); + } + [TestMethod] public void Does_not_probe_wslc_outside_windows() { @@ -141,11 +159,11 @@ public void Does_not_probe_wslc_outside_windows() probedCommands.Add(command); return Task.FromResult(command == ContainerRuntime.WslcCommand); }, - () => false, + _ => false, isWindows: false, isMacOS: false); - Assert.AreEqual(ContainerRuntimeKind.Unknown, runtime.GetTelemetryValue()); + Assert.AreEqual(ContainerRuntimeKind.Unknown, runtime.GetTelemetryValue(TestContext.CancellationToken)); Assert.DoesNotContain(ContainerRuntime.WslcCommand, probedCommands); } @@ -161,11 +179,11 @@ public void Does_not_probe_container_outside_macos() probedCommands.Add(command); return Task.FromResult(command == ContainerRuntime.MacOSContainerCommand); }, - () => false, + _ => false, isWindows: false, isMacOS: false); - Assert.AreEqual(ContainerRuntimeKind.Unknown, runtime.GetTelemetryValue()); + Assert.AreEqual(ContainerRuntimeKind.Unknown, runtime.GetTelemetryValue(TestContext.CancellationToken)); Assert.DoesNotContain(ContainerRuntime.MacOSContainerCommand, probedCommands); } @@ -187,7 +205,7 @@ public async Task Uses_platform_native_specific_commands( probedArguments = arguments; return Task.FromResult(true); }, - () => false, + _ => false, isWindows, isMacOS); @@ -203,7 +221,7 @@ public void Creates_explicit_platform_native_registry(string registryType, int e ILocalRegistry registry = KnownLocalRegistryTypes.CreateLocalRegistry(registryType, _loggerFactory); ContainerRuntime runtime = (ContainerRuntime)registry; - Assert.AreEqual((ContainerRuntimeKind)expectedRuntime, runtime.GetTelemetryValue()); + Assert.AreEqual((ContainerRuntimeKind)expectedRuntime, runtime.GetTelemetryValue(TestContext.CancellationToken)); Assert.Contains(registryType, KnownLocalRegistryTypes.SupportedLocalRegistryTypes); } @@ -218,7 +236,8 @@ public void MacOSContainer_registry_preserves_requested_image_format() ContainerHelpers.GetManifestMediaType( SchemaTypes.OciManifestV1, KnownImageFormats.Docker, - destination)); + destination, + TestContext.CancellationToken)); } [TestMethod] @@ -241,7 +260,7 @@ private ContainerRuntime CreateRuntime(Func isAvailable, bool isWi command: null, _loggerFactory, (command, _, _) => Task.FromResult(isAvailable(command)), - () => isPodmanAlias, + _ => isPodmanAlias, isWindows, isMacOS); } diff --git a/test/Microsoft.NET.Build.Containers.UnitTests/RegistryTests.cs b/test/Microsoft.NET.Build.Containers.UnitTests/RegistryTests.cs index c81e657e4d61..aef11ac1df7d 100644 --- a/test/Microsoft.NET.Build.Containers.UnitTests/RegistryTests.cs +++ b/test/Microsoft.NET.Build.Containers.UnitTests/RegistryTests.cs @@ -38,7 +38,7 @@ public void Dispose() public void CheckIfGoogleArtifactRegistry(string registryName, bool expectedIsGoogleArtifactRegistry) { ILogger logger = _loggerFactory.CreateLogger(nameof(CheckIfGoogleArtifactRegistry)); - Registry registry = new(registryName, logger, RegistryMode.Push); + Registry registry = new(registryName, logger, RegistryMode.Push, TestContext.CancellationToken); Assert.AreEqual(expectedIsGoogleArtifactRegistry, registry.IsGoogleArtifactRegistry); } @@ -46,7 +46,7 @@ public void CheckIfGoogleArtifactRegistry(string registryName, bool expectedIsGo public void DockerIoAlias() { ILogger logger = _loggerFactory.CreateLogger(nameof(DockerIoAlias)); - Registry registry = new("docker.io", logger, RegistryMode.Push); + Registry registry = new("docker.io", logger, RegistryMode.Push, TestContext.CancellationToken); Assert.IsTrue(registry.IsDockerHub); Assert.AreEqual("docker.io", registry.RegistryName); Assert.AreEqual("registry-1.docker.io", registry.BaseUri.Host); @@ -110,7 +110,7 @@ public async Task PushAsync_SkipsBlobUploadsByDefaultWhenManifestAlreadyExists() Mock api = new(MockBehavior.Strict); api.SetupGet(a => a.Manifest).Returns(manifestOperations.Object); - Registry registry = new("example.com", logger, api.Object); + Registry registry = new("example.com", logger, api.Object, TestContext.CancellationToken); BuiltImage image = new() { Config = "{}", @@ -154,7 +154,7 @@ public async Task PushAsync_DoesNotCheckManifestWhenNoCacheIsEnabled() api.SetupGet(a => a.Blob).Returns(blobOperations.Object); api.SetupGet(a => a.Manifest).Returns(manifestOperations.Object); - Registry registry = new("example.com", logger, api.Object); + Registry registry = new("example.com", logger, api.Object, TestContext.CancellationToken); BuiltImage image = new() { Config = "{}", @@ -194,7 +194,7 @@ public async Task RegistriesThatProvideNoUploadSizeAttemptFullUpload() api.Setup(api => api.Blob.Upload.StartAsync(repoName, It.IsAny())).Returns(Task.FromResult(new StartUploadInformation(uploadPath))); api.Setup(api => api.Blob.Upload.UploadAtomicallyAsync(uploadPath, It.IsAny(), It.IsAny())).Returns(Task.FromResult(new FinalizeUploadInformation(uploadPath))); - Registry registry = new("public.ecr.aws", logger, api.Object); + Registry registry = new("public.ecr.aws", logger, api.Object, TestContext.CancellationToken); await registry.PushLayerAsync(mockLayer.Object, repoName, CancellationToken.None); api.Verify(api => api.Blob.Upload.UploadChunkAsync(uploadPath, It.IsAny(), It.IsAny()), Times.Never()); @@ -228,7 +228,7 @@ public async Task RegistriesThatProvideUploadSizePrefersFullUploadWhenChunkSizeI return Task.FromResult(ChunkUploadSuccessful(absoluteUploadUri, uploadPath, uploadedCount)); }); - Registry registry = new(registryUri, logger, api.Object); + Registry registry = new(registryUri, logger, api.Object, TestContext.CancellationToken); await registry.PushLayerAsync(mockLayer.Object, repoName, CancellationToken.None); api.Verify(api => api.Blob.Upload.UploadAtomicallyAsync(It.IsIn(absoluteUploadUri, uploadPath), It.IsAny(), It.IsAny()), Times.Exactly(1)); @@ -263,7 +263,7 @@ public async Task RegistriesThatFailAtomicUploadFallbackToChunked() return Task.FromResult(ChunkUploadSuccessful(absoluteUploadUri, uploadPath, uploadedCount)); }); - Registry registry = new(registryUri, logger, api.Object); + Registry registry = new(registryUri, logger, api.Object, TestContext.CancellationToken); await registry.PushLayerAsync(mockLayer.Object, repoName, CancellationToken.None); api.Verify(api => api.Blob.Upload.UploadAtomicallyAsync(It.IsIn(absoluteUploadUri, uploadPath), It.IsAny(), It.IsAny()), Times.Once()); @@ -298,14 +298,14 @@ public async Task ChunkedUploadCalculatesChunksCorrectly() return Task.FromResult(ChunkUploadSuccessful(absoluteUploadUri, uploadPath, uploadedCount)); }); - RegistrySettings settings = new() + RegistrySettings settings = new(TestContext.CancellationToken) { ParallelUploadEnabled = false, ForceChunkedUpload = false, ChunkedUploadSizeBytes = chunkSize, }; - Registry registry = new(registryUri, logger, api.Object, settings); + Registry registry = new(registryUri, logger, api.Object, TestContext.CancellationToken, settings); await registry.PushLayerAsync(mockLayer.Object, repoName, CancellationToken.None); api.Verify(api => api.Blob.Upload.UploadAtomicallyAsync(It.IsIn(absoluteUploadUri, uploadPath), It.IsAny(), It.IsAny()), Times.Once()); @@ -334,7 +334,7 @@ public async Task PushAsync_Logging() api.Setup(api => api.Blob.Upload.StartAsync(repoName, It.IsAny())).Returns(Task.FromResult(new StartUploadInformation(uploadPath))); api.Setup(api => api.Blob.Upload.UploadAtomicallyAsync(uploadPath, It.IsAny(), It.IsAny())).Returns(Task.FromResult(new FinalizeUploadInformation(uploadPath))); - Registry registry = new("public.ecr.aws", logger, api.Object); + Registry registry = new("public.ecr.aws", logger, api.Object, TestContext.CancellationToken); await registry.PushLayerAsync(mockLayer.Object, repoName, CancellationToken.None); Assert.IsNotEmpty(loggedMessages); @@ -372,14 +372,14 @@ public async Task PushAsync_ForceChunkedUpload() return Task.FromResult(ChunkUploadSuccessful(absoluteUploadUri, uploadPath, uploadedCount)); }); - RegistrySettings settings = new() + RegistrySettings settings = new(TestContext.CancellationToken) { ParallelUploadEnabled = false, ForceChunkedUpload = true, ChunkedUploadSizeBytes = chunkSize, }; - Registry registry = new(registryUri, logger, api.Object, settings); + Registry registry = new(registryUri, logger, api.Object, TestContext.CancellationToken, settings); await registry.PushLayerAsync(mockLayer.Object, repoName, CancellationToken.None); api.Verify(api => api.Blob.Upload.UploadAtomicallyAsync(It.IsIn(absoluteUploadUri, uploadPath), It.IsAny(), It.IsAny()), Times.Never()); @@ -472,14 +472,14 @@ public async Task UploadBlobChunkedAsync_NormalFlow() return Task.FromResult(ChunkUploadSuccessful(absoluteUploadUri, uploadPath, uploadedCount)); }); - RegistrySettings settings = new() + RegistrySettings settings = new(TestContext.CancellationToken) { ParallelUploadEnabled = false, ForceChunkedUpload = false, ChunkedUploadSizeBytes = chunkSize, }; - Registry registry = new(registryUri, logger, api.Object, settings); + Registry registry = new(registryUri, logger, api.Object, TestContext.CancellationToken, settings); await registry.UploadBlobChunkedAsync(testStream, new StartUploadInformation(absoluteUploadUri), CancellationToken.None); api.Verify(api => api.Blob.Upload.UploadChunkAsync(It.IsIn(absoluteUploadUri, uploadPath), It.IsAny(), It.IsAny()), Times.Exactly(5)); @@ -507,14 +507,14 @@ public async Task UploadBlobChunkedAsync_Failure() throw preparedException; }); - RegistrySettings settings = new() + RegistrySettings settings = new(TestContext.CancellationToken) { ParallelUploadEnabled = false, ForceChunkedUpload = false, ChunkedUploadSizeBytes = chunkSize, }; - Registry registry = new(registryUri, logger, api.Object, settings); + Registry registry = new(registryUri, logger, api.Object, TestContext.CancellationToken, settings); ApplicationException receivedException = await Assert.ThrowsExactlyAsync(() => registry.UploadBlobChunkedAsync(testStream, new StartUploadInformation(absoluteUploadUri), CancellationToken.None)); Assert.AreEqual(preparedException, receivedException); @@ -586,11 +586,11 @@ public async Task InsecureRegistry(bool isInsecureRegistry, bool serverIsHttps, } }, TestContext.CancellationToken); - RegistrySettings settings = new() + RegistrySettings settings = new(TestContext.CancellationToken) { IsInsecure = isInsecureRegistry }; - Registry registry = new(registryUri, logger, RegistryMode.Pull, settings: settings); + Registry registry = new(registryUri, logger, RegistryMode.Pull, TestContext.CancellationToken, settings); // Make a request. Task getManifest = registry.GetImageManifestAsync(repositoryName: "dotnet/runtime", reference: "latest", runtimeIdentifier: "linux-x64", manifestPicker: null!, cancellationToken: default!); @@ -667,7 +667,10 @@ public void IsRegistryInsecure(string registryName, string? insecureRegistriesEn environment["DOTNET_CONTAINER_INSECURE_REGISTRIES"] = insecureRegistriesEnvvar; } - var registrySettings = new RegistrySettings(registryName, new MockEnvironmentProvider(environment)); + var registrySettings = new RegistrySettings( + TestContext.CancellationToken, + registryName, + new MockEnvironmentProvider(environment)); Assert.AreEqual(expectedInsecure, registrySettings.IsInsecure); } @@ -692,7 +695,7 @@ public async Task DownloadBlobAsync_RetriesOnFailure() .ThrowsAsync(new Exception("Simulated failure 2")) // Second attempt fails .ReturnsAsync(new MemoryStream(responseBytes)); // Third attempt succeeds - Registry registry = new(repoName, logger, mockRegistryAPI.Object, null, () => TimeSpan.Zero); + Registry registry = new(repoName, logger, mockRegistryAPI.Object, cancellationToken, null, () => TimeSpan.Zero); string? result = null; try @@ -735,7 +738,7 @@ public async Task DownloadBlobAsync_ThrowsAfterMaxRetries() .ThrowsAsync(new Exception("Simulated failure 4")) .ThrowsAsync(new Exception("Simulated failure 5")); - Registry registry = new(repoName, logger, mockRegistryAPI.Object, null, () => TimeSpan.Zero); + Registry registry = new(repoName, logger, mockRegistryAPI.Object, cancellationToken, null, () => TimeSpan.Zero); // Act & Assert await Assert.ThrowsExactlyAsync(async () => diff --git a/test/Microsoft.NET.Build.Tests/AspNetCoreOnFullFramework.cs b/test/Microsoft.NET.Build.Tests/AspNetCoreOnFullFramework.cs index d0421fc9480c..69e5f62ae7b2 100644 --- a/test/Microsoft.NET.Build.Tests/AspNetCoreOnFullFramework.cs +++ b/test/Microsoft.NET.Build.Tests/AspNetCoreOnFullFramework.cs @@ -90,7 +90,7 @@ class Class1 ICommand toolCommand = toolCommandSpec.ToCommand().CaptureStdOut(); - var toolResult = toolCommand.Execute(); + var toolResult = toolCommand.Execute(TestContext.CancellationToken); toolResult.Should().Pass(); } diff --git a/test/Microsoft.NET.Build.Tests/GivenThatWeWantToGenerateADepsFileForATool.cs b/test/Microsoft.NET.Build.Tests/GivenThatWeWantToGenerateADepsFileForATool.cs index 41fb1b149d07..94d3704f9a29 100644 --- a/test/Microsoft.NET.Build.Tests/GivenThatWeWantToGenerateADepsFileForATool.cs +++ b/test/Microsoft.NET.Build.Tests/GivenThatWeWantToGenerateADepsFileForATool.cs @@ -224,7 +224,7 @@ private CommandResult GenerateDepsAndRunTool(TestProject toolProject, [CallerMem ICommand toolCommand = toolCommandSpec.ToCommand().CaptureStdOut(); - var toolResult = toolCommand.Execute(); + var toolResult = toolCommand.Execute(TestContext.CancellationToken); return toolResult; } diff --git a/test/Microsoft.NET.Publish.Tests/GivenThatWeWantToPublishTrimmedWindowsFormsAndWPFApps.cs b/test/Microsoft.NET.Publish.Tests/GivenThatWeWantToPublishTrimmedWindowsFormsAndWPFApps.cs index 85fac8166aa2..05d12a299f91 100644 --- a/test/Microsoft.NET.Publish.Tests/GivenThatWeWantToPublishTrimmedWindowsFormsAndWPFApps.cs +++ b/test/Microsoft.NET.Publish.Tests/GivenThatWeWantToPublishTrimmedWindowsFormsAndWPFApps.cs @@ -179,7 +179,7 @@ public void It_publishes_and_runs_windows_forms_app_with_no_wpf() var result = runAppCommand.ToCommand() .CaptureStdErr() .CaptureStdOut() - .Execute(); + .Execute(TestContext.CancellationToken); result.ExitCode.Should().Be(0); } @@ -253,7 +253,7 @@ public void It_publishes_and_runs_wpf_app_with_no_winforms() var result = runAppCommand.ToCommand() .CaptureStdErr() .CaptureStdOut() - .Execute(); + .Execute(TestContext.CancellationToken); result.ExitCode.Should().Be(42); } diff --git a/test/Microsoft.NET.Publish.Tests/PublishWebApp.cs b/test/Microsoft.NET.Publish.Tests/PublishWebApp.cs index 87363dbad974..ee1d84c243d5 100644 --- a/test/Microsoft.NET.Publish.Tests/PublishWebApp.cs +++ b/test/Microsoft.NET.Publish.Tests/PublishWebApp.cs @@ -53,7 +53,7 @@ public void It_publishes_and_runs_self_contained_web_app() var result = runAppCommand.ToCommand() .CaptureStdErr() .CaptureStdOut() - .Execute(); + .Execute(TestContext.CancellationToken); result .Should() diff --git a/test/Microsoft.NET.Publish.Tests/PublishWpfApp.cs b/test/Microsoft.NET.Publish.Tests/PublishWpfApp.cs index ee6ad84b8808..c366be31fade 100644 --- a/test/Microsoft.NET.Publish.Tests/PublishWpfApp.cs +++ b/test/Microsoft.NET.Publish.Tests/PublishWpfApp.cs @@ -63,7 +63,7 @@ public void It_publishes_and_runs_self_contained_wpf_app() var result = runAppCommand.ToCommand() .CaptureStdErr() .CaptureStdOut() - .Execute(); + .Execute(TestContext.CancellationToken); result.ExitCode.Should().Be(42); } diff --git a/test/Microsoft.NET.TestFramework/Commands/TestCommand.cs b/test/Microsoft.NET.TestFramework/Commands/TestCommand.cs index ff5401650c53..800eaebe8d73 100644 --- a/test/Microsoft.NET.TestFramework/Commands/TestCommand.cs +++ b/test/Microsoft.NET.TestFramework/Commands/TestCommand.cs @@ -157,7 +157,7 @@ public CommandResult Execute(params string[] args) action: () => Execute(enumerableArgs), shouldStopRetry: ShouldStopRetry, maxRetryCount: 3, - timer: () => Timer(Intervals), + timer: () => Timer(Intervals, ProcessLifecycle.CancellationToken), taskDescription: "Run command while retrying transient errors") .ConfigureAwait(false).GetAwaiter().GetResult(); } @@ -235,7 +235,7 @@ public virtual CommandResult Execute(IEnumerable args) var display = $"{fileToShow} {string.Join(" ", spec.Arguments)}"; Log.WriteLine($"Executing '{display}':"); - var result = command.Execute(ProcessStartedHandler); + var result = command.Execute(ProcessStartedHandler, ProcessLifecycle.CancellationToken); Log.WriteLine($"Command '{display}' exited with exit code {result.ExitCode}."); // On failure, dump the already-captured output so the cause is visible in test logs. diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/PostActionDispatcherTests.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/PostActionDispatcherTests.cs index afc9a31d3a58..f9b46aebacd2 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/PostActionDispatcherTests.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/PostActionDispatcherTests.cs @@ -13,6 +13,8 @@ namespace Microsoft.TemplateEngine.Cli.UnitTests [TestClass] public class PostActionDispatcherTests { + public TestContext TestContext { get; set; } = null!; + // MSTest has no IClassFixture equivalent; a lazily-initialized static helper // mirrors the per-class lifetime that xUnit's IClassFixture provides. private static readonly Lazy s_environmentSettingsHelper = @@ -56,7 +58,7 @@ public void CanProcessSuccessPostAction() engineEnvironmentSettings, () => string.Empty); - var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Prompt); + var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Prompt, TestContext.CancellationToken); Assert.AreEqual(PostActionExecutionStatus.Success, result); Assert.HasCount(1, postActionProcessor.Calls); Assert.AreEqual(engineEnvironmentSettings, postActionProcessor.Calls.Single().EngineEnvironmentSettings); @@ -87,7 +89,7 @@ public void CanDryRunSuccessPostAction() engineEnvironmentSettings, () => string.Empty); - var result = dispatcher.Process(templateCreationResult, isDryRun: true, AllowRunScripts.Prompt); + var result = dispatcher.Process(templateCreationResult, isDryRun: true, AllowRunScripts.Prompt, TestContext.CancellationToken); Assert.AreEqual(PostActionExecutionStatus.Success, result); Assert.IsEmpty(postActionProcessor.Calls); } @@ -113,7 +115,7 @@ public void CanProcessFailedPostAction() engineEnvironmentSettings, () => string.Empty); - var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Prompt); + var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Prompt, TestContext.CancellationToken); Assert.AreEqual(PostActionExecutionStatus.Failure, result); Assert.AreEqual(engineEnvironmentSettings, postActionProcessor.Calls.Single().EngineEnvironmentSettings); Assert.AreEqual(postAction, postActionProcessor.Calls.Single().PostAction); @@ -144,7 +146,7 @@ public void CanDryRunFailedPostAction() engineEnvironmentSettings, () => string.Empty); - var result = dispatcher.Process(templateCreationResult, isDryRun: true, AllowRunScripts.Prompt); + var result = dispatcher.Process(templateCreationResult, isDryRun: true, AllowRunScripts.Prompt, TestContext.CancellationToken); Assert.AreEqual(PostActionExecutionStatus.Success, result); Assert.IsEmpty(postActionProcessor.Calls); } @@ -174,7 +176,7 @@ public void CanProcessUnknownPostAction() engineEnvironmentSettings, () => string.Empty); - var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Prompt); + var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Prompt, TestContext.CancellationToken); Assert.AreEqual(PostActionExecutionStatus.Failure, result); Assert.IsEmpty(postActionProcessor.Calls); } @@ -200,10 +202,40 @@ public void CanProcessPostActionThrowingException() engineEnvironmentSettings, () => string.Empty); - var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Yes); + var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Yes, TestContext.CancellationToken); Assert.AreEqual(PostActionExecutionStatus.Failure, result); } + [TestMethod] + public void PropagatesCancellationFromPostAction() + { + var engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true); + engineEnvironmentSettings.Components.AddComponent(typeof(IPostActionProcessor), new ThrowCancellationPostAction()); + var postAction = new MockPostAction(default, default, default, default, default!) + { + ContinueOnError = true, + }; + + MockCreationResult creationResult = new(new List() { postAction }); + MockCreationEffects creationEffects = new(); + var templateCreationResult = new TemplateCreationResult( + CreationResultStatus.Success, + "TestTemplate", + null, + creationResult, + "TestPath", + creationEffects); + + PostActionDispatcher dispatcher = new( + engineEnvironmentSettings, + () => string.Empty); + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + Assert.ThrowsExactly( + () => dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Yes, cancellationTokenSource.Token)); + } + [TestMethod] public void CanContinueOnErrorWhenConfigured() { @@ -241,7 +273,7 @@ public void CanContinueOnErrorWhenConfigured() engineEnvironmentSettings, () => string.Empty); - var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Yes); + var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Yes, TestContext.CancellationToken); // in case continue on error is true, success status is returned on failure Assert.AreEqual(PostActionExecutionStatus.Success, result); @@ -289,7 +321,7 @@ public void CannotContinueOnErrorWhenNotConfigured() engineEnvironmentSettings, () => string.Empty); - var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Yes); + var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Yes, TestContext.CancellationToken); Assert.AreEqual(PostActionExecutionStatus.Failure, result); //only first post action was executed @@ -325,7 +357,7 @@ public void CanProcessRunScriptPostAction_WhenRunScriptAllowed() engineEnvironmentSettings, () => string.Empty); - var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Yes); + var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Yes, TestContext.CancellationToken); //expect failure as post action fails Assert.AreEqual(PostActionExecutionStatus.Failure, result); } @@ -357,7 +389,7 @@ public void CanProcessRunScriptPostAction_WhenRunScriptNotAllowed() engineEnvironmentSettings, () => string.Empty); - var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.No); + var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.No, TestContext.CancellationToken); Assert.AreEqual(PostActionExecutionStatus.Cancelled, result); } @@ -388,7 +420,7 @@ public void CanProcessRunScriptPostAction_WhenRunScriptPrompt_Yes() engineEnvironmentSettings, () => "Y"); // the user allows to run post action - var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Prompt); + var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Prompt, TestContext.CancellationToken); //expect failure as post action fails Assert.AreEqual(PostActionExecutionStatus.Failure, result); @@ -421,7 +453,7 @@ public void CanProcessRunScriptPostAction_WhenRunScriptPrompt_No() engineEnvironmentSettings, () => "N"); // the user forbids to run post action - var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Prompt); + var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Prompt, TestContext.CancellationToken); Assert.AreEqual(PostActionExecutionStatus.Cancelled, result); } @@ -453,11 +485,11 @@ public void CanProcessRunScriptPostAction_DryRun() () => "N"); // the user forbids to run post action //run script setting doesn't matter for dry run - var result = dispatcher.Process(templateCreationResult, isDryRun: true, AllowRunScripts.Prompt); + var result = dispatcher.Process(templateCreationResult, isDryRun: true, AllowRunScripts.Prompt, TestContext.CancellationToken); Assert.AreEqual(PostActionExecutionStatus.Success, result); - result = dispatcher.Process(templateCreationResult, isDryRun: true, AllowRunScripts.Yes); + result = dispatcher.Process(templateCreationResult, isDryRun: true, AllowRunScripts.Yes, TestContext.CancellationToken); Assert.AreEqual(PostActionExecutionStatus.Success, result); - result = dispatcher.Process(templateCreationResult, isDryRun: true, AllowRunScripts.No); + result = dispatcher.Process(templateCreationResult, isDryRun: true, AllowRunScripts.No, TestContext.CancellationToken); Assert.AreEqual(PostActionExecutionStatus.Success, result); } @@ -498,7 +530,7 @@ public void CanProcessRunScriptPostActionAndFailedPostAction_WhenRunScriptPrompt engineEnvironmentSettings, () => "N"); // the user forbids to run post action - var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Prompt); + var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Prompt, TestContext.CancellationToken); Assert.AreEqual(PostActionExecutionStatus.Cancelled, result); Assert.HasCount(1, postActionProcessor.Calls); Assert.AreEqual(postAction2, postActionProcessor.Calls.Single().PostAction); @@ -541,7 +573,7 @@ public void CanProcessRunScriptPostActionAndSuccessPostAction_WhenRunScriptPromp engineEnvironmentSettings, () => "N"); // the user forbids to run post action - var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Prompt); + var result = dispatcher.Process(templateCreationResult, isDryRun: false, AllowRunScripts.Prompt, TestContext.CancellationToken); Assert.AreEqual(PostActionExecutionStatus.Cancelled, result); Assert.AreNotEqual(PostActionExecutionStatus.Failure, result); Assert.HasCount(1, postActionProcessor.Calls); @@ -582,7 +614,8 @@ public bool Process( IPostAction action, ICreationEffects creationEffects, ICreationResult templateCreationResult, - string outputBasePath) + string outputBasePath, + CancellationToken cancellationToken = default) { _receivedCalls.Add((environment, action, creationEffects, templateCreationResult, outputBasePath)); return _expectedResult; @@ -598,10 +631,28 @@ public bool Process( IPostAction action, ICreationEffects creationEffects, ICreationResult templateCreationResult, - string outputBasePath) + string outputBasePath, + CancellationToken cancellationToken = default) { throw new Exception("post action exception"); } } + + private class ThrowCancellationPostAction : IPostActionProcessor + { + public Guid Id => Guid.Empty; + + public bool Process( + IEngineEnvironmentSettings environment, + IPostAction action, + ICreationEffects creationEffects, + ICreationResult templateCreationResult, + string outputBasePath, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + return true; + } + } } } diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/PostActionTests/AddJsonPropertyPostActionTests.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/PostActionTests/AddJsonPropertyPostActionTests.cs index fd89c835260e..ac32f979817a 100644 --- a/test/Microsoft.TemplateEngine.Cli.UnitTests/PostActionTests/AddJsonPropertyPostActionTests.cs +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/PostActionTests/AddJsonPropertyPostActionTests.cs @@ -18,6 +18,8 @@ namespace Microsoft.TemplateEngine.Cli.UnitTests.PostActionTests [ResourceLock(nameof(Reporter))] public class AddJsonPropertyPostActionTests { + public TestContext TestContext { get; set; } = null!; + // MSTest has no IClassFixture equivalent; a lazily-initialized static helper // mirrors the per-class lifetime that xUnit's IClassFixture provides. private static readonly Lazy s_environmentSettingsHelper = @@ -85,7 +87,8 @@ public void FailsWhenParentPropertyPathIsInvalid() postAction, new MockCreationEffects(), new MockCreationResult(), - targetBasePath); + targetBasePath, + TestContext.CancellationToken); Assert.IsFalse(result); mockReporter.Verify(r => r.WriteLine(string.Format(LocalizableStrings.PostAction_ModifyJson_Error_ParentPropertyPathInvalid, parentPropertyPath)), Times.Once); @@ -119,7 +122,8 @@ public void FailsWhenPropertyPathCasingIsNotCorrect() postAction, new MockCreationEffects(), new MockCreationResult(), - targetBasePath); + targetBasePath, + TestContext.CancellationToken); Assert.IsFalse(result); @@ -154,7 +158,8 @@ public void FailsWhenMandatoryArgumentsNotConfigured(ModifyJsonPostActionTestCas postAction, new MockCreationEffects(), new MockCreationResult(), - targetBasePath); + targetBasePath, + TestContext.CancellationToken); Assert.IsFalse(result); @@ -186,7 +191,8 @@ public void CanSuccessfullyModifyJsonFile(ModifyJsonPostActionTestCase<(JsonNode postAction, new MockCreationEffects(), new MockCreationResult(), - targetBasePath); + targetBasePath, + TestContext.CancellationToken); Assert.IsTrue(result); @@ -233,7 +239,8 @@ public void PreservesExistingPropertiesWhenOverwriteIsDisabled(string originalJs postAction, new MockCreationEffects(), new MockCreationResult(), - targetBasePath); + targetBasePath, + TestContext.CancellationToken); Assert.AreEqual(expectedResult, result); string actualJsonContent = _engineEnvironmentSettings.Host.FileSystem.ReadAllText(jsonFilePath); @@ -294,7 +301,8 @@ public void ComparesOnlyStringValuesIgnoringCaseWhenRequested(string originalVal postAction, new MockCreationEffects(), new MockCreationResult(), - targetBasePath); + targetBasePath, + TestContext.CancellationToken); Assert.AreEqual(expectedResult, result); string actualJsonContent = _engineEnvironmentSettings.Host.FileSystem.ReadAllText(jsonFilePath); @@ -343,7 +351,8 @@ public void CanOverwriteExistingPropertyByDefaultOrWhenEnabled(string? allowProp postAction, new MockCreationEffects(), new MockCreationResult(), - targetBasePath); + targetBasePath, + TestContext.CancellationToken); Assert.IsTrue(result); JsonNode? modifiedJsonContent = JsonNode.Parse(_engineEnvironmentSettings.Host.FileSystem.ReadAllText(jsonFilePath)); @@ -374,7 +383,8 @@ public void CanSuccessfullyCreateAndModifyJsonFileWhenAllowFileCreationAndPathCr postAction, new MockCreationEffects(), new MockCreationResult(), - targetBasePath); + targetBasePath, + TestContext.CancellationToken); Assert.IsTrue(result); @@ -411,7 +421,8 @@ public void CanSuccessfullyModifyJsonFileWhenPathDoesNotExistAndAllowPathCreatio postAction, new MockCreationEffects(), new MockCreationResult(), - targetBasePath); + targetBasePath, + TestContext.CancellationToken); Assert.IsTrue(result); @@ -451,7 +462,8 @@ public void FailsWhenFileExistsButPathDoesNotExistAndAllowPathCreationIsNotSet() postAction, new MockCreationEffects(), new MockCreationResult(), - targetBasePath); + targetBasePath, + TestContext.CancellationToken); Assert.IsFalse(result); @@ -484,7 +496,8 @@ public void FailsWhenFileDoesNotExistAndAllowFileCreationIsNotSet() postAction, new MockCreationEffects(), new MockCreationResult(), - targetBasePath); + targetBasePath, + TestContext.CancellationToken); Assert.IsFalse(result); @@ -519,7 +532,8 @@ public void FailsWhenFileDoesNotExistAndAllowFileCreationIsSetButAllowPathCreati postAction, new MockCreationEffects(), new MockCreationResult(), - targetBasePath); + targetBasePath, + TestContext.CancellationToken); Assert.IsFalse(result); diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/PostActionTests/ProcessStartPostActionProcessorTests.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/PostActionTests/ProcessStartPostActionProcessorTests.cs new file mode 100644 index 000000000000..b4e2bf853608 --- /dev/null +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/PostActionTests/ProcessStartPostActionProcessorTests.cs @@ -0,0 +1,58 @@ +// 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 Microsoft.DotNet.Cli.Utils; +using Microsoft.TemplateEngine.Abstractions; +using Microsoft.TemplateEngine.Cli.PostActionProcessors; +using Microsoft.TemplateEngine.Mocks; +using Microsoft.TemplateEngine.TestHelper; +using Moq; + +namespace Microsoft.TemplateEngine.Cli.UnitTests.PostActionTests; + +[TestClass] +public class ProcessStartPostActionProcessorTests +{ + [TestMethod] + public void PropagatesCancellationToCommand() + { + using EnvironmentSettingsHelper environmentSettingsHelper = new(); + IEngineEnvironmentSettings environmentSettings = environmentSettingsHelper.CreateEnvironment(virtualize: true); + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + var command = new Mock(MockBehavior.Strict); + command.Setup(c => c.CaptureStdOut()).Returns(command.Object); + command.Setup(c => c.CaptureStdErr()).Returns(command.Object); + command + .Setup(c => c.Execute(cancellationTokenSource.Token)) + .Throws(new OperationCanceledException(cancellationTokenSource.Token)); + ProcessStartInfo? processStartInfo = null; + ProcessStartPostActionProcessor processor = new(process => + { + processStartInfo = process.StartInfo; + return command.Object; + }); + var postAction = new MockPostAction(default, default, default, default, default!) + { + Args = new Dictionary + { + ["executable"] = "test-command", + ["args"] = "--test", + }, + }; + + Assert.ThrowsExactly(() => processor.Process( + environmentSettings, + postAction, + new MockCreationEffects(), + new MockCreationResult(), + environmentSettings.GetTempVirtualizedPath(), + cancellationTokenSource.Token)); + + Assert.IsNotNull(processStartInfo); + Assert.AreEqual("test-command", processStartInfo.FileName); + Assert.AreEqual("--test", processStartInfo.Arguments); + command.VerifyAll(); + } +} diff --git a/test/Microsoft.TemplateEngine.Cli.UnitTests/TemplateInvokerTests.cs b/test/Microsoft.TemplateEngine.Cli.UnitTests/TemplateInvokerTests.cs new file mode 100644 index 000000000000..82266c165459 --- /dev/null +++ b/test/Microsoft.TemplateEngine.Cli.UnitTests/TemplateInvokerTests.cs @@ -0,0 +1,21 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace Microsoft.TemplateEngine.Cli.UnitTests; + +[TestClass] +public class TemplateInvokerTests +{ + [TestMethod] + public async Task PropagatesCancellationAndReportsUnsuccessfulTelemetry() + { + bool? telemetrySuccess = null; + + await Assert.ThrowsExactlyAsync( + () => TemplateInvoker.InvokeTemplateAsync( + () => Task.FromException(new OperationCanceledException()), + success => telemetrySuccess = success)); + + Assert.IsFalse(telemetrySuccess); + } +} diff --git a/test/TemplateEngine/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests/ExportCommandFailureTests.cs b/test/TemplateEngine/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests/ExportCommandFailureTests.cs index da698cebe420..615e6f26a745 100644 --- a/test/TemplateEngine/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests/ExportCommandFailureTests.cs +++ b/test/TemplateEngine/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests/ExportCommandFailureTests.cs @@ -40,7 +40,7 @@ public async Task PostActionsShouldHaveIds() ] }"; (await CreateTemplateAndExport(json)) - .Execute() + .Execute(TestContext.CancellationToken) .Should() .ExitWith(1) .And.HaveStdOutContaining("Generating localization files for a template.json has failed.") @@ -61,7 +61,7 @@ public async Task PostActionIdsAreUnique() ] }"; (await CreateTemplateAndExport(json)) - .Execute() + .Execute(TestContext.CancellationToken) .Should() .ExitWith(1) .And.HaveStdOutContaining("Generating localization files for a template.json has failed.") @@ -84,7 +84,7 @@ public async Task SingleManualInstructionDoesntNeedId() ] }"; (await CreateTemplateAndExport(json)) - .Execute() + .Execute(TestContext.CancellationToken) .Should() .ExitWith(0) .And.HaveStdOutContaining("Localization files were successfully generated"); @@ -109,7 +109,7 @@ public async Task MultipleManualInstructionShouldHaveIds() ] }"; (await CreateTemplateAndExport(json)) - .Execute() + .Execute(TestContext.CancellationToken) .Should() .ExitWith(1) .And.HaveStdOutContaining("Generating localization files for a template.json has failed.") @@ -135,7 +135,7 @@ public async Task ManualInstructionIdsAreUnique() ] }"; (await CreateTemplateAndExport(json)) - .Execute() + .Execute(TestContext.CancellationToken) .Should() .ExitWith(1) .And.HaveStdOutContaining("Generating localization files for a template.json has failed.") diff --git a/test/TemplateEngine/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests/ValidateCommandTests.cs b/test/TemplateEngine/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests/ValidateCommandTests.cs index 25831dd72615..a2810cb66f4e 100644 --- a/test/TemplateEngine/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests/ValidateCommandTests.cs +++ b/test/TemplateEngine/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests/ValidateCommandTests.cs @@ -41,7 +41,7 @@ public Task ValidateCommand_BasicTest() Path.GetFullPath("Microsoft.TemplateEngine.Authoring.CLI.dll"), "validate", Path.Combine(TestTemplatesLocation, "Invalid")) - .Execute(); + .Execute(TestContext.CancellationToken); commandResult .Should() diff --git a/test/TemplateEngine/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests/VerifyCommandTests.cs b/test/TemplateEngine/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests/VerifyCommandTests.cs index 6d99579a1ed9..cba426e8e815 100644 --- a/test/TemplateEngine/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests/VerifyCommandTests.cs +++ b/test/TemplateEngine/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests/VerifyCommandTests.cs @@ -45,7 +45,7 @@ public void VerifyCommandFullDevLoop() "--unique-for", "RuntimeAndVersion"); - cmd.Execute() + cmd.Execute(TestContext.CancellationToken) .Should() .ExitWith((int)TemplateVerificationErrorCode.VerificationFailed) .And.HaveStdOutContaining("Verification Failed."); @@ -109,7 +109,7 @@ public void VerifyCommandFullDevLoop() "--unique-for", "RuntimeAndVersion"); - cmd2.Execute() + cmd2.Execute(TestContext.CancellationToken) .Should() .Pass() .And.HaveStdOutContaining("Running the verification of console.") @@ -150,7 +150,7 @@ public void VerifyCommandFullDevLoopWithNotInstalledTemplate() snapshotsDir, "--disable-diff-tool"); - cmd.Execute() + cmd.Execute(TestContext.CancellationToken) .Should() .ExitWith((int)TemplateVerificationErrorCode.VerificationFailed) .And.HaveStdOutContaining("Verification Failed."); @@ -198,7 +198,7 @@ public void VerifyCommandFullDevLoopWithNotInstalledTemplate() "--snapshots-directory", snapshotsDir); - cmd2.Execute() + cmd2.Execute(TestContext.CancellationToken) .Should() .Pass() .And.HaveStdOutContaining(string.Format("Running the verification of {0}.", templateShortName)) diff --git a/test/TemplateEngine/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/LocalizeTemplateTests.cs b/test/TemplateEngine/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/LocalizeTemplateTests.cs index a3b4f1f72ae5..7c26a6962ca8 100644 --- a/test/TemplateEngine/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/LocalizeTemplateTests.cs +++ b/test/TemplateEngine/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/LocalizeTemplateTests.cs @@ -25,14 +25,14 @@ public void CanRunTask() new DotnetCommand(Log, "add", "TemplatePackage.csproj", "package", "Microsoft.TemplateEngine.Authoring.Tasks", "--prerelease") .WithoutTelemetry() .WithWorkingDirectory(tmpDir) - .Execute() + .Execute(TestContext.CancellationToken) .Should() .Pass(); new DotnetCommand(Log, "build") .WithoutTelemetry() .WithWorkingDirectory(tmpDir) - .Execute() + .Execute(TestContext.CancellationToken) .Should() .Pass(); @@ -55,14 +55,14 @@ public void CanRunTaskSelectedLangs() new DotnetCommand(Log, "add", "TemplatePackage.csproj", "package", "Microsoft.TemplateEngine.Authoring.Tasks", "--prerelease") .WithoutTelemetry() .WithWorkingDirectory(tmpDir) - .Execute() + .Execute(TestContext.CancellationToken) .Should() .Pass(); new DotnetCommand(Log, "build") .WithoutTelemetry() .WithWorkingDirectory(tmpDir) - .Execute() + .Execute(TestContext.CancellationToken) .Should() .Pass(); @@ -86,14 +86,14 @@ public void CanRunTaskSelectedTemplates() new DotnetCommand(Log, "add", "TemplatePackage.csproj", "package", "Microsoft.TemplateEngine.Authoring.Tasks", "--prerelease") .WithoutTelemetry() .WithWorkingDirectory(tmpDir) - .Execute() + .Execute(TestContext.CancellationToken) .Should() .Pass(); new DotnetCommand(Log, "build") .WithoutTelemetry() .WithWorkingDirectory(tmpDir) - .Execute() + .Execute(TestContext.CancellationToken) .Should() .Pass(); @@ -118,14 +118,14 @@ public void CanRunTaskAndDetectError() new DotnetCommand(Log, "add", "TemplatePackage.csproj", "package", "Microsoft.TemplateEngine.Authoring.Tasks", "--prerelease") .WithoutTelemetry() .WithWorkingDirectory(tmpDir) - .Execute() + .Execute(TestContext.CancellationToken) .Should() .Pass(); new DotnetCommand(Log, "build") .WithoutTelemetry() .WithWorkingDirectory(tmpDir) - .Execute() + .Execute(TestContext.CancellationToken) .Should() .Fail() .And.HaveStdOutContaining("Build FAILED.") diff --git a/test/TemplateEngine/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/ValidateTemplatesTests.cs b/test/TemplateEngine/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/ValidateTemplatesTests.cs index 126fc564f9e9..2f82d837e0a2 100644 --- a/test/TemplateEngine/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/ValidateTemplatesTests.cs +++ b/test/TemplateEngine/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/ValidateTemplatesTests.cs @@ -25,14 +25,14 @@ public void CanRunValidateTask_OnError() new DotnetCommand(Log, "add", "TemplatePackage.csproj", "package", "Microsoft.TemplateEngine.Authoring.Tasks", "--prerelease") .WithoutTelemetry() .WithWorkingDirectory(tmpDir) - .Execute() + .Execute(TestContext.CancellationToken) .Should() .Pass(); new DotnetCommand(Log, "build") .WithoutTelemetry() .WithWorkingDirectory(tmpDir) - .Execute() + .Execute(TestContext.CancellationToken) .Should() .Fail() .And.HaveStdOutContaining("Template configuration error MV002: Missing 'name'.") @@ -49,14 +49,14 @@ public void CanRunValidateTask_OnInfo() new DotnetCommand(Log, "add", "TemplatePackage.csproj", "package", "Microsoft.TemplateEngine.Authoring.Tasks", "--prerelease") .WithoutTelemetry() .WithWorkingDirectory(tmpDir) - .Execute() + .Execute(TestContext.CancellationToken) .Should() .Pass(); new DotnetCommand(Log, "build") .WithoutTelemetry() .WithWorkingDirectory(tmpDir) - .Execute() + .Execute(TestContext.CancellationToken) .Should() .Pass() .And.HaveStdOutContaining("Template configuration message MV006: Missing 'author'.") diff --git a/test/TemplateEngine/Microsoft.TemplateEngine.Authoring.TemplateVerifier.UnitTests/VerificationEngineTests.cs b/test/TemplateEngine/Microsoft.TemplateEngine.Authoring.TemplateVerifier.UnitTests/VerificationEngineTests.cs index 110337484153..59fbffee6801 100644 --- a/test/TemplateEngine/Microsoft.TemplateEngine.Authoring.TemplateVerifier.UnitTests/VerificationEngineTests.cs +++ b/test/TemplateEngine/Microsoft.TemplateEngine.Authoring.TemplateVerifier.UnitTests/VerificationEngineTests.cs @@ -137,7 +137,7 @@ public async Task ExecuteFailsOnInstantiationFailure() string snapshotsDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName().Replace(".", string.Empty)); ICommandRunner commandRunner = A.Fake(); - A.CallTo(() => commandRunner.RunCommand(A._)) + A.CallTo(() => commandRunner.RunCommand(A._, A._)) .Returns(new CommandResultData(20, "stdout content", "stderr content", workingDir)); TemplateVerifierOptions options = new TemplateVerifierOptions(templateName: "made-up-template") @@ -164,7 +164,7 @@ public async Task ExecuteSucceedsOnExpectedInstantiationFailure() string workingDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName().Replace(".", string.Empty)); ICommandRunner commandRunner = A.Fake(); - A.CallTo(() => commandRunner.RunCommand(A._)) + A.CallTo(() => commandRunner.RunCommand(A._, A._)) .Returns(new CommandResultData(20, "stdout content", "stderr content", workingDir)); TemplateVerifierOptions options = new TemplateVerifierOptions(templateName: "made-up-template") @@ -187,7 +187,7 @@ public async Task ExecuteSucceedsOnExpectedInstantiationSuccess() string workingDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName().Replace(".", string.Empty)); ICommandRunner commandRunner = A.Fake(); - A.CallTo(() => commandRunner.RunCommand(A._)) + A.CallTo(() => commandRunner.RunCommand(A._, A._)) .Returns(new CommandResultData(0, "different stdout content", "another stderr content", workingDir)); TemplateVerifierOptions options = new TemplateVerifierOptions(templateName: "made-up-template") diff --git a/test/TemplateEngine/Microsoft.TemplateSearch.TemplateDiscovery.IntegrationTests/TemplateDiscoveryTests.cs b/test/TemplateEngine/Microsoft.TemplateSearch.TemplateDiscovery.IntegrationTests/TemplateDiscoveryTests.cs index 385f815f6383..d75b79653c76 100644 --- a/test/TemplateEngine/Microsoft.TemplateSearch.TemplateDiscovery.IntegrationTests/TemplateDiscoveryTests.cs +++ b/test/TemplateEngine/Microsoft.TemplateSearch.TemplateDiscovery.IntegrationTests/TemplateDiscoveryTests.cs @@ -32,7 +32,7 @@ public async Task CanRunDiscoveryTool() "--packagesPath", Path.GetDirectoryName(packageLocation) ?? throw new Exception("Couldn't get package location directory"), "-v") - .Execute() + .Execute(TestContext.CancellationToken) .Should() .ExitWith(0); @@ -51,7 +51,7 @@ public async Task CanRunDiscoveryTool() .WithoutTelemetry() .WithEnvironmentVariable("DOTNET_NEW_SEARCH_FILE_OVERRIDE", cacheFilePath) .WithEnvironmentVariable("DOTNET_CLI_CONTEXT_VERBOSE", "true") - .Execute() + .Execute(TestContext.CancellationToken) .Should() .ExitWith(0) .And.NotHaveStdErr(); @@ -61,7 +61,7 @@ public async Task CanRunDiscoveryTool() .WithoutTelemetry() .WithEnvironmentVariable("DOTNET_NEW_SEARCH_FILE_OVERRIDE", cacheFilePath) .WithEnvironmentVariable("DOTNET_CLI_CONTEXT_VERBOSE", "true") - .Execute() + .Execute(TestContext.CancellationToken) .Should() .ExitWith(0) .And.NotHaveStdErr() @@ -73,7 +73,7 @@ public async Task CanRunDiscoveryTool() .WithoutTelemetry() .WithEnvironmentVariable("DOTNET_NEW_SEARCH_FILE_OVERRIDE", cacheFilePath) .WithEnvironmentVariable("DOTNET_CLI_CONTEXT_VERBOSE", "true") - .Execute() + .Execute(TestContext.CancellationToken) .Should() .ExitWith(0) .And.NotHaveStdErr(); @@ -83,7 +83,7 @@ public async Task CanRunDiscoveryTool() .WithoutTelemetry() .WithEnvironmentVariable("DOTNET_NEW_SEARCH_FILE_OVERRIDE", cacheFilePath) .WithEnvironmentVariable("DOTNET_CLI_CONTEXT_VERBOSE", "true") - .Execute() + .Execute(TestContext.CancellationToken) .Should() .ExitWith(0) .And.NotHaveStdErr() @@ -107,7 +107,7 @@ public void CanReadAuthor() "--packagesPath", Path.GetDirectoryName(packageLocation) ?? throw new Exception("Couldn't get package location directory"), "-v") - .Execute() + .Execute(TestContext.CancellationToken) .Should() .ExitWith(0); @@ -132,7 +132,7 @@ public void CanReadDescription() "--packagesPath", Path.GetDirectoryName(packageLocation) ?? throw new Exception("Couldn't get package location directory"), "-v") - .Execute() + .Execute(TestContext.CancellationToken) .Should() .ExitWith(0); @@ -155,7 +155,7 @@ public void CanReadIconUrl() "--packagesPath", Path.GetDirectoryName(packageLocation) ?? throw new Exception("Couldn't get package location directory"), "-v") - .Execute() + .Execute(TestContext.CancellationToken) .Should() .ExitWith(0); @@ -182,7 +182,7 @@ public async Task CanDetectNewPackagesInDiffMode() "-v", "--diff", "false") - .Execute() + .Execute(TestContext.CancellationToken) .Should() .ExitWith(0) .And.HaveStdOutContaining( @@ -223,7 +223,7 @@ public async Task CanDetectNewPackagesInDiffMode() "true", "--diff-override-cache", cacheV2Path) - .Execute() + .Execute(TestContext.CancellationToken) .Should() .ExitWith(0) .And.HaveStdOutContaining( @@ -270,7 +270,7 @@ public void CanDetectUpdatedPackagesInDiffMode() "-v", "--diff", "false") - .Execute() + .Execute(TestContext.CancellationToken) .Should() .ExitWith(0) .And.HaveStdOutContaining( @@ -309,7 +309,7 @@ public void CanDetectUpdatedPackagesInDiffMode() "true", "--diff-override-cache", cacheV2Path) - .Execute() + .Execute(TestContext.CancellationToken) .Should() .ExitWith(0) .And.HaveStdOutContaining( @@ -357,7 +357,7 @@ public void CanDetectRemovedPackagesInDiffMode() "-v", "--diff", "false") - .Execute() + .Execute(TestContext.CancellationToken) .Should() .ExitWith(0) .And.HaveStdOutContaining( @@ -396,7 +396,7 @@ public void CanDetectRemovedPackagesInDiffMode() "true", "--diff-override-cache", cacheV2Path) - .Execute() + .Execute(TestContext.CancellationToken) .Should() .ExitWith(0) .And.HaveStdOutContaining( @@ -444,7 +444,7 @@ public void CanReadCliData() "--packagesPath", Path.GetDirectoryName(packageLocation) ?? throw new Exception("Couldn't get package location directory"), "-v") - .Execute() + .Execute(TestContext.CancellationToken) .Should() .ExitWith(0); @@ -475,7 +475,7 @@ public void CanReadCliDataFromDiff() "-v", "--diff", "false") - .Execute() + .Execute(TestContext.CancellationToken) .Should() .ExitWith(0); @@ -500,7 +500,7 @@ public void CanReadCliDataFromDiff() "true", "--diff-override-cache", Path.Combine(testDir, "SearchCache", "NuGetTemplateSearchInfoVer2.json")) - .Execute() + .Execute(TestContext.CancellationToken) .Should() .ExitWith(0) .And.HaveStdOutContaining("not changed: 1"); @@ -523,7 +523,7 @@ private void CheckTemplateOptionsSearch(IEnumerable cacheFilePaths, stri .WithoutTelemetry() .WithEnvironmentVariable("DOTNET_NEW_SEARCH_FILE_OVERRIDE", cacheFilePath) .WithEnvironmentVariable("DOTNET_CLI_CONTEXT_VERBOSE", "true") - .Execute() + .Execute(TestContext.CancellationToken) .Should() .ExitWith(0) .And.NotHaveStdErr(); @@ -533,7 +533,7 @@ private void CheckTemplateOptionsSearch(IEnumerable cacheFilePaths, stri .WithoutTelemetry() .WithEnvironmentVariable("DOTNET_NEW_SEARCH_FILE_OVERRIDE", cacheFilePath) .WithEnvironmentVariable("DOTNET_CLI_CONTEXT_VERBOSE", "true") - .Execute() + .Execute(TestContext.CancellationToken) .Should() .ExitWith(0) .And.NotHaveStdErr() @@ -546,7 +546,7 @@ private void CheckTemplateOptionsSearch(IEnumerable cacheFilePaths, stri .WithoutTelemetry() .WithEnvironmentVariable("DOTNET_NEW_SEARCH_FILE_OVERRIDE", cacheFilePath) .WithEnvironmentVariable("DOTNET_CLI_CONTEXT_VERBOSE", "true") - .Execute() + .Execute(TestContext.CancellationToken) .Should() .ExitWith(0) .And.NotHaveStdErr() @@ -559,7 +559,7 @@ private void CheckTemplateOptionsSearch(IEnumerable cacheFilePaths, stri .WithoutTelemetry() .WithEnvironmentVariable("DOTNET_NEW_SEARCH_FILE_OVERRIDE", cacheFilePath) .WithEnvironmentVariable("DOTNET_CLI_CONTEXT_VERBOSE", "true") - .Execute() + .Execute(TestContext.CancellationToken) .Should() .ExitWith(0) .And.NotHaveStdErr() @@ -572,7 +572,7 @@ private void CheckTemplateOptionsSearch(IEnumerable cacheFilePaths, stri .WithoutTelemetry() .WithEnvironmentVariable("DOTNET_NEW_SEARCH_FILE_OVERRIDE", cacheFilePath) .WithEnvironmentVariable("DOTNET_CLI_CONTEXT_VERBOSE", "true") - .Execute() + .Execute(TestContext.CancellationToken) .Should().Fail(); } } diff --git a/test/TestAssets/TestProjects/WinExeApp/Program.cs b/test/TestAssets/TestProjects/WinExeApp/Program.cs index 613bd3a7adf6..86dd5fe0e5d4 100644 --- a/test/TestAssets/TestProjects/WinExeApp/Program.cs +++ b/test/TestAssets/TestProjects/WinExeApp/Program.cs @@ -43,6 +43,11 @@ private void OnShown(object sender, EventArgs e) private void OnFormClosing(object sender, FormClosingEventArgs e) { + if (int.TryParse(Environment.GetEnvironmentVariable("DOTNET_TEST_WINEXE_CLOSE_DELAY_MS"), out int delayMilliseconds)) + { + Thread.Sleep(delayMilliseconds); + } + // Mark that we were closed gracefully (via CloseMainWindow) ClosedGracefully = e.CloseReason == CloseReason.UserClosing || e.CloseReason == CloseReason.WindowsShutDown || diff --git a/test/dotnet-aot.Tests/AotIntegrationTests.cs b/test/dotnet-aot.Tests/AotIntegrationTests.cs index feff2b881301..a1fc2405ac2a 100644 --- a/test/dotnet-aot.Tests/AotIntegrationTests.cs +++ b/test/dotnet-aot.Tests/AotIntegrationTests.cs @@ -714,6 +714,74 @@ public void AotBuild_WithEnableAot_FallsBackToManaged() $"Expected exit code 0 or 1, got {exitCode}. Stderr: {stderr}"); } + [TestMethod] + [OSCondition(ConditionMode.Exclude, OperatingSystems.Windows)] + public void AotExternalCommand_WaitsForSecondSigIntBeforeExitingQuietly() + { + SkipIfDnUnavailable(); + + string testDirectory = Path.Join(Path.GetTempPath(), $"dotnet-aot-cancellation-{Guid.NewGuid():N}"); + Directory.CreateDirectory(testDirectory); + string markerPath = Path.Join(testDirectory, "ready"); + string commandPath = Path.Join(testDirectory, "dotnet-aot-cancellation-test"); + File.WriteAllText( + commandPath, + $"#!/bin/sh{Environment.NewLine}echo ready > '{markerPath}'{Environment.NewLine}sleep 30{Environment.NewLine}"); + File.SetUnixFileMode( + commandPath, + UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute | + UnixFileMode.GroupRead | UnixFileMode.GroupExecute | + UnixFileMode.OtherRead | UnixFileMode.OtherExecute); + + ProcessStartInfo startInfo = new(FindDnPath()!) + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + startInfo.ArgumentList.Add("aot-cancellation-test"); + startInfo.Environment["DOTNET_CLI_ENABLEAOT"] = "true"; + startInfo.Environment["DOTNET_CLI_TELEMETRY_OPTOUT"] = "1"; + startInfo.Environment["DOTNET_SKIP_FIRST_TIME_EXPERIENCE"] = "1"; + startInfo.Environment["PATH"] = + testDirectory + Path.PathSeparator + startInfo.Environment["PATH"]; + + using Process process = new() { StartInfo = startInfo }; + try + { + process.Start(); + Task stdoutTask = process.StandardOutput.ReadToEndAsync(TestContext.CancellationToken); + Task stderrTask = process.StandardError.ReadToEndAsync(TestContext.CancellationToken); + SpinWait.SpinUntil(() => File.Exists(markerPath), TimeSpan.FromSeconds(10)) + .Should().BeTrue("the external command should start"); + + process.SafeHandle.Signal(PosixSignal.SIGINT).Should().BeTrue(); + Thread.Sleep(TimeSpan.FromMilliseconds(750)); + process.HasExited.Should().BeFalse("the first SIGINT should allow the external command to finish"); + + Stopwatch stopwatch = Stopwatch.StartNew(); + process.SafeHandle.Signal(PosixSignal.SIGINT).Should().BeTrue(); + process.WaitForExit(10_000).Should().BeTrue(); + + process.ExitCode.Should().Be(130); + stopwatch.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(1)); + string standardError = stderrTask.GetAwaiter().GetResult(); + standardError.Should().NotContain("Unhandled exception"); + standardError.Should().NotContain("The operation was canceled"); + _ = stdoutTask.GetAwaiter().GetResult(); + } + finally + { + if (!process.HasExited) + { + process.Kill(entireProcessTree: true); + } + + try { Directory.Delete(testDirectory, recursive: true); } catch { } + } + } + [TestMethod] public void Version_WithAotDisabled_StillWorks() { diff --git a/test/dotnet-aot.Tests/AotRunCommandTests.cs b/test/dotnet-aot.Tests/AotRunCommandTests.cs index dd7506c6b04a..701b3ef8b757 100644 --- a/test/dotnet-aot.Tests/AotRunCommandTests.cs +++ b/test/dotnet-aot.Tests/AotRunCommandTests.cs @@ -18,6 +18,43 @@ namespace Microsoft.DotNet.Cli.Tests; [TestClass] public class AotRunCommandTests { + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public void PreCanceledTokenDoesNotCallLauncher() + { + var fixture = CreateFixture(); + try + { + var parseResult = Parser.Parse([ + "run", + "--file", fixture.EntryPointPath, + "--no-build", + "--no-launch-profile", + ]); + using var cancellationSource = new CancellationTokenSource(); + cancellationSource.Cancel(); + bool launcherCalled = false; + + Assert.ThrowsExactly(() => + AotRunCommand.Execute( + parseResult, + _ => + { + launcherCalled = true; + return 0; + }, + cancellationSource.Token, + fixture.TestDirectory)); + + Assert.IsFalse(launcherCalled); + } + finally + { + DeleteFixture(fixture); + } + } + /// Verifies that an explicit no-build invocation reaches the launcher without prevalidating output. [TestMethod] public void EligibleSyntheticNoBuildProducesLaunchInvocation() @@ -59,6 +96,7 @@ public void EligibleSyntheticNoBuildProducesLaunchInvocation() invocation = value; return 17; }, + TestContext.CancellationToken, fixture.TestDirectory); Assert.AreEqual(17, exitCode); @@ -109,6 +147,7 @@ public void EligiblePositionalNoBuildProducesLaunchInvocation() invocation = value; return 17; }, + TestContext.CancellationToken, fixture.TestDirectory); Assert.AreEqual(17, exitCode); @@ -139,6 +178,7 @@ public void StandardInputFallsBackBeforePlanning() AotRunCommand.Execute( parseResult, static _ => throw new InvalidOperationException("Launcher should not be called."), + TestContext.CancellationToken, fixture.TestDirectory)); Assert.AreEqual(oldArtifactsTime, Directory.GetLastWriteTimeUtc(fixture.ArtifactsPath)); @@ -170,6 +210,7 @@ public void PositionalFileWithProjectInCurrentDirectoryFallsBackBeforePlanning() AotRunCommand.Execute( parseResult, static _ => throw new InvalidOperationException("Launcher should not be called."), + TestContext.CancellationToken, fixture.TestDirectory)); Assert.AreEqual(oldArtifactsTime, Directory.GetLastWriteTimeUtc(fixture.ArtifactsPath)); @@ -193,6 +234,7 @@ public void NoProjectOrFileReportsManagedError() AotRunCommand.Execute( parseResult, static _ => throw new InvalidOperationException("Launcher should not be called."), + TestContext.CancellationToken, fixture.TestDirectory)); Assert.AreEqual( @@ -220,6 +262,7 @@ public void MultipleProjectsReportManagedError() AotRunCommand.Execute( parseResult, static _ => throw new InvalidOperationException("Launcher should not be called."), + TestContext.CancellationToken, fixture.TestDirectory)); Assert.AreEqual( @@ -271,6 +314,7 @@ public void ProjectLaunchProfileDecoratesSyntheticLaunch() invocation = value; return 17; }, + TestContext.CancellationToken, fixture.TestDirectory); Assert.AreEqual(17, exitCode); @@ -322,6 +366,7 @@ public void LaunchProfileWithMSBuildPropertiesFallsBackToManaged(string commandN AotRunCommand.Execute( parseResult, static _ => throw new InvalidOperationException("Launcher should not be called."), + TestContext.CancellationToken, fixture.TestDirectory)); } finally @@ -363,6 +408,7 @@ public void LaunchProfileFieldWithMSBuildPropertyFallsBackToManaged(string comma AotRunCommand.Execute( parseResult, static _ => throw new InvalidOperationException("Launcher should not be called."), + TestContext.CancellationToken, fixture.TestDirectory)); } finally @@ -415,6 +461,7 @@ public void ExecutableLaunchProfileBypassesSyntheticCache() invocation = value; return 17; }, + TestContext.CancellationToken, fixture.TestDirectory); Assert.AreEqual(17, exitCode); @@ -461,11 +508,14 @@ public void ChangedSourceWithDirectiveStillLaunchesNoBuildOutput() ]); AotRunInvocation? invocation = null; - int exitCode = AotRunCommand.Execute(parseResult, value => - { - invocation = value; - return 17; - }); + int exitCode = AotRunCommand.Execute( + parseResult, + value => + { + invocation = value; + return 17; + }, + cancellationToken: TestContext.CancellationToken); Assert.AreEqual(17, exitCode); Assert.IsNotNull(invocation); @@ -511,7 +561,10 @@ public void UnsupportedOptionFallsBackBeforePlanning() IReadOnlyList messages = CaptureVerboseMessages(() => Assert.Throws(() => - AotRunCommand.Execute(parseResult, static _ => throw new InvalidOperationException("Launcher should not be called.")))); + AotRunCommand.Execute( + parseResult, + static _ => throw new InvalidOperationException("Launcher should not be called."), + cancellationToken: TestContext.CancellationToken))); Assert.AreEqual(oldArtifactsTime, Directory.GetLastWriteTimeUtc(fixture.ArtifactsPath)); Assert.Contains("--configuration", string.Join(Environment.NewLine, messages)); @@ -543,7 +596,10 @@ public void ExplicitOptionOutsideAllowlistFallsBackBeforePlanning() Assert.IsEmpty(parseResult.Errors); Assert.Throws(() => - AotRunCommand.Execute(parseResult, static _ => throw new InvalidOperationException("Launcher should not be called."))); + AotRunCommand.Execute( + parseResult, + static _ => throw new InvalidOperationException("Launcher should not be called."), + cancellationToken: TestContext.CancellationToken)); Assert.AreEqual(oldArtifactsTime, Directory.GetLastWriteTimeUtc(fixture.ArtifactsPath)); } diff --git a/test/dotnet-aot.Tests/NativeEntryPointTests.cs b/test/dotnet-aot.Tests/NativeEntryPointTests.cs index 61332757d56e..f3cc306ad480 100644 --- a/test/dotnet-aot.Tests/NativeEntryPointTests.cs +++ b/test/dotnet-aot.Tests/NativeEntryPointTests.cs @@ -677,6 +677,62 @@ public void ExecuteCore_AotEnabled_LocalizedFirstRun_StaysOnAotPath(string uiLan }); } + [TestMethod] + public void NativeEntryPoint_AotEnabled_PreCanceledExternalCommandIsNotLaunched() + { + WithEnvRestore(() => + { + Environment.SetEnvironmentVariable("DOTNET_CLI_ENABLEAOT", "true"); + + string toolDir = Path.Combine(Path.GetTempPath(), $"aot-canceled-tool-{Guid.NewGuid():N}"); + Directory.CreateDirectory(toolDir); + string markerPath = Path.Combine(toolDir, "launched"); + string originalPath = Environment.GetEnvironmentVariable("PATH") ?? ""; + + try + { + if (OperatingSystem.IsWindows()) + { + File.WriteAllText( + Path.Combine(toolDir, "dotnet-aotcanceledtool.cmd"), + $"@echo off{Environment.NewLine}echo launched>\"{markerPath}\"{Environment.NewLine}"); + } + else + { + string toolPath = Path.Combine(toolDir, "dotnet-aotcanceledtool"); + File.WriteAllText( + toolPath, + $"#!/bin/sh{Environment.NewLine}touch '{markerPath}'{Environment.NewLine}"); + File.SetUnixFileMode( + toolPath, + UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute | + UnixFileMode.GroupRead | UnixFileMode.GroupExecute | + UnixFileMode.OtherRead | UnixFileMode.OtherExecute); + } + + Environment.SetEnvironmentVariable("PATH", toolDir + Path.PathSeparator + originalPath); + using var cancellationSource = new CancellationTokenSource(); + cancellationSource.Cancel(); + + int exitCode = NativeEntryPoint.ExecuteCoreForNativeEntryPoint( + hostPath: "test-host", + dotnetRoot: "test-root", + sdkDir: AppContext.BaseDirectory, + hostfxrPath: "", + args: ["aotcanceledtool"], + cancellationToken: cancellationSource.Token); + + Assert.AreEqual(1, exitCode); + Assert.IsFalse(File.Exists(markerPath)); + } + finally + { + Environment.SetEnvironmentVariable("PATH", originalPath); + try { Directory.Delete(toolDir, recursive: true); } catch { } + } + }); + } + [TestMethod] public void ExecuteCore_AotEnabled_ResolvableExternalCommand_EmitsParserAndResolutionTelemetry() { diff --git a/test/dotnet-aot.Tests/WorkloadUpdateTests.cs b/test/dotnet-aot.Tests/WorkloadUpdateTests.cs index 24a2506c6ced..e36900bfb26c 100644 --- a/test/dotnet-aot.Tests/WorkloadUpdateTests.cs +++ b/test/dotnet-aot.Tests/WorkloadUpdateTests.cs @@ -20,6 +20,8 @@ public class WorkloadUpdateTests private const string ManifestId = "microsoft.net.sdk.test"; private static readonly SdkFeatureBand s_featureBand = new("11.0.100"); + public TestContext TestContext { get; set; } = null!; + [TestMethod] public async Task DisabledBackgroundUpdateDoesNotQueryNuGet() { @@ -27,7 +29,7 @@ public async Task DisabledBackgroundUpdateDoesNotQueryNuGet() var downloader = CreateUpdater(testDirectory.Path, out WorkloadAdvertisingManifestUpdater updater, name => name == EnvironmentVariableNames.WORKLOAD_UPDATE_NOTIFY_DISABLE ? "true" : null); - await updater.BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(); + await updater.BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(TestContext.CancellationToken); Assert.AreEqual(0, downloader.LatestVersionQueries); Assert.AreEqual(0, downloader.Downloads); @@ -45,7 +47,7 @@ public async Task DueBackgroundUpdateDownloadsManifestAndWritesState() _ => null, userProfileDir); - await updater.BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(); + await updater.BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(TestContext.CancellationToken); Assert.AreEqual(1, downloader.LatestVersionQueries); Assert.AreEqual(1, downloader.Downloads); @@ -80,7 +82,7 @@ public async Task WindowsMsiAdvertisingInstallerExtractsPreExpandedManifest() WindowsMsiManifestInstaller.CreateForAdvertisingManifestUpdates(downloader, out var records); string targetPath = Path.Combine(testDirectory.Path, "target", ManifestId); - await installer.ExtractManifestAsync("manifest.nupkg", targetPath); + await installer.ExtractManifestAsync("manifest.nupkg", targetPath, TestContext.CancellationToken); Assert.IsInstanceOfType(records); Assert.AreEqual( @@ -226,6 +228,7 @@ private sealed class RecordingNuGetPackageDownloader( public Task DownloadPackageAsync( PackageId packageId, + CancellationToken cancellationToken, NuGetVersion? packageVersion = null, PackageSourceLocation? packageSourceLocation = null, bool includePreview = false, @@ -240,7 +243,7 @@ public Task DownloadPackageAsync( return Task.FromResult(path); } - public Task> ExtractPackageAsync(string packagePath, DirectoryPath targetFolder) + public Task> ExtractPackageAsync(string packagePath, DirectoryPath targetFolder, CancellationToken cancellationToken) { Extractions++; string dataDirectory = useMsiLayout @@ -254,6 +257,7 @@ public Task> ExtractPackageAsync(string packagePath, Directo public Task GetLatestPackageVersion( PackageId packageId, + CancellationToken cancellationToken, PackageSourceLocation? packageSourceLocation = null, bool includePreview = false) { @@ -264,6 +268,7 @@ public Task GetLatestPackageVersion( public Task GetPackageUrl( PackageId packageId, + CancellationToken cancellationToken, NuGetVersion? packageVersion = null, PackageSourceLocation? packageSourceLocation = null, bool includePreview = false) => throw new NotSupportedException(); @@ -271,18 +276,20 @@ public Task GetPackageUrl( public Task> GetLatestPackageVersions( PackageId packageId, int numberOfResults, + CancellationToken cancellationToken, PackageSourceLocation? packageSourceLocation = null, bool includePreview = false) => throw new NotSupportedException(); public Task GetBestPackageVersionAsync( PackageId packageId, VersionRange versionRange, + CancellationToken cancellationToken, PackageSourceLocation? packageSourceLocation = null) => throw new NotSupportedException(); public Task<(NuGetVersion version, PackageSource source)> GetBestPackageVersionAndSourceAsync( PackageId packageId, VersionRange versionRange, - PackageSourceLocation? packageSourceLocation = null, - CancellationToken cancellationToken = default) => throw new NotSupportedException(); + CancellationToken cancellationToken, + PackageSourceLocation? packageSourceLocation = null) => throw new NotSupportedException(); } } diff --git a/test/dotnet-new.IntegrationTests/CommonTemplatesTests.cs b/test/dotnet-new.IntegrationTests/CommonTemplatesTests.cs index 6f561a754d16..c9012ddaa883 100644 --- a/test/dotnet-new.IntegrationTests/CommonTemplatesTests.cs +++ b/test/dotnet-new.IntegrationTests/CommonTemplatesTests.cs @@ -165,7 +165,7 @@ public void NuGetConfigPermissions() .WorkingDirectory(workingDir) .CaptureStdOut() .CaptureStdErr() - .Execute() + .Execute(TestContext.CancellationToken) .Should() .ExitWith(0) .And.HaveStdOutMatching("^-rw-------.*nuget.config$", RegexOptions.Multiline); diff --git a/test/dotnet.Tests.TestApp/RunApiTestApp.cs b/test/dotnet.Tests.TestApp/RunApiTestApp.cs new file mode 100644 index 000000000000..6705f47ec2b8 --- /dev/null +++ b/test/dotnet.Tests.TestApp/RunApiTestApp.cs @@ -0,0 +1,69 @@ +// 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.InteropServices; +using Microsoft.DotNet.Cli; +using Microsoft.DotNet.Cli.Commands.Run.Api; + +namespace Microsoft.DotNet.Cli.TestApp; + +public static class RunApiTestApp +{ + public static async Task Main() + { + using CancellationTokenSource cancellation = new(); + Task execution = new RunApiCommand(Parser.Parse(["run-api"])).ExecuteAsync(cancellation.Token); + if (execution.IsCompleted) + { + throw new InvalidOperationException("Run API must be waiting for input before cancellation."); + } + + if (OperatingSystem.IsLinux()) + { + await WaitForBlockedStandardInputRead(); + } + + await cancellation.CancelAsync(); + return await execution; + } + + private static async Task WaitForBlockedStandardInputRead() + { + string readSyscall = RuntimeInformation.ProcessArchitecture switch + { + Architecture.X64 => "0", + Architecture.Arm64 or Architecture.LoongArch64 or Architecture.RiscV64 => "63", + Architecture.X86 or Architecture.Arm or Architecture.S390x or Architecture.Ppc64le => "3", + _ => throw new PlatformNotSupportedException("Unknown Linux read syscall number."), + }; + var timeout = Stopwatch.StartNew(); + while (timeout.Elapsed < TimeSpan.FromSeconds(10)) + { + foreach (string thread in Directory.EnumerateDirectories("/proc/self/task")) + { + try + { + string[] syscall = File.ReadAllText(Path.Combine(thread, "syscall")).Split(' '); + // No input is supplied, so read(fd=0) cannot complete before cancellation. + if (syscall.Length > 1 && syscall[0] == readSyscall && syscall[1] == "0x0") + { + return; + } + } + catch (FileNotFoundException) + { + // A runtime thread can exit between enumeration and inspection. + } + catch (DirectoryNotFoundException) + { + // A runtime thread can exit between enumeration and inspection. + } + } + + await Task.Delay(10); + } + + throw new TimeoutException("No thread entered a blocked read on standard input."); + } +} diff --git a/test/dotnet.Tests.TestApp/dotnet.Tests.TestApp.csproj b/test/dotnet.Tests.TestApp/dotnet.Tests.TestApp.csproj new file mode 100644 index 000000000000..0784c55913b7 --- /dev/null +++ b/test/dotnet.Tests.TestApp/dotnet.Tests.TestApp.csproj @@ -0,0 +1,15 @@ + + + + Exe + $(SdkTargetFramework) + MicrosoftAspNetCore + false + false + + + + + + + diff --git a/test/dotnet.Tests/BuildServerTests/RazorServerTests.cs b/test/dotnet.Tests/BuildServerTests/RazorServerTests.cs index a31ea255bfb0..e4253ea67818 100644 --- a/test/dotnet.Tests/BuildServerTests/RazorServerTests.cs +++ b/test/dotnet.Tests/BuildServerTests/RazorServerTests.cs @@ -17,6 +17,8 @@ namespace Microsoft.DotNet.Tests.BuildServerTests [TestClass] public class RazorServerTests { + public TestContext TestContext { get; set; } = null!; + [TestMethod] public void GivenAFailedShutdownCommandItThrows() { @@ -47,7 +49,7 @@ public void GivenAFailedShutdownCommandItThrows() commandFactory: CreateCommandFactoryMock(serverPath, PipeName, exitCode: 1, stdErr: ErrorMessage).Object, fileSystem: fileSystemMock); - Action a = () => server.Shutdown(); + Action a = () => server.Shutdown(TestContext.CancellationToken); a.Should().Throw().WithMessage( string.Format( @@ -86,7 +88,7 @@ public void GivenASuccessfulShutdownItDoesNotThrow() commandFactory: CreateCommandFactoryMock(serverPath, PipeName).Object, fileSystem: fileSystemMock); - server.Shutdown(); + server.Shutdown(TestContext.CancellationToken); fileSystemMock.File.Exists(pidFilePath).Should().BeFalse(); } @@ -120,7 +122,7 @@ public void GivenANonExistingRazorServerPathItDeletesPidFileAndDoesNotThrow() commandFactory: commandFactoryMock.Object, fileSystem: fileSystemMock); - Action a = () => server.Shutdown(); + Action a = () => server.Shutdown(TestContext.CancellationToken); a.Should().NotThrow(); commandFactoryMock.Verify(c => c.Create(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny()), Times.Never); @@ -133,7 +135,9 @@ private Mock CreateCommandFactoryMock(string serverPath, string var commandMock = new Mock(MockBehavior.Strict); commandMock.Setup(c => c.CaptureStdOut()).Returns(commandMock.Object); commandMock.Setup(c => c.CaptureStdErr()).Returns(commandMock.Object); - commandMock.Setup(c => c.Execute()).Returns(new CommandResult(null, exitCode, "", stdErr)); + commandMock + .Setup(c => c.Execute(It.IsAny())) + .Returns(new CommandResult(null, exitCode, "", stdErr)); var commandFactoryMock = new Mock(MockBehavior.Strict); commandFactoryMock diff --git a/test/dotnet.Tests/BuildServerTests/VBCSCompilerServerTests.cs b/test/dotnet.Tests/BuildServerTests/VBCSCompilerServerTests.cs index 76e3aec69483..09a44f03f76e 100644 --- a/test/dotnet.Tests/BuildServerTests/VBCSCompilerServerTests.cs +++ b/test/dotnet.Tests/BuildServerTests/VBCSCompilerServerTests.cs @@ -15,11 +15,13 @@ namespace Microsoft.DotNet.Tests.BuildServerTests [TestClass] public class VBCSCompilerServerTests { + public TestContext TestContext { get; set; } = null!; + [TestMethod] public void GivenAZeroExitShutdownDoesNotThrow() { var server = new VBCSCompilerServer(CreateCommandFactoryMock().Object); - server.Shutdown(); + server.Shutdown(TestContext.CancellationToken); } [TestMethod] @@ -29,7 +31,7 @@ public void GivenANonZeroExitCodeShutdownThrows() var server = new VBCSCompilerServer(CreateCommandFactoryMock(exitCode: 1, stdErr: ErrorMessage).Object); - Action a = () => server.Shutdown(); + Action a = () => server.Shutdown(TestContext.CancellationToken); a.Should().Throw().WithMessage( string.Format( @@ -42,7 +44,9 @@ private Mock CreateCommandFactoryMock(int exitCode = 0, string var commandMock = new Mock(MockBehavior.Strict); commandMock.Setup(c => c.CaptureStdOut()).Returns(commandMock.Object); commandMock.Setup(c => c.CaptureStdErr()).Returns(commandMock.Object); - commandMock.Setup(c => c.Execute()).Returns(new CommandResult(null, exitCode, "", stdErr)); + commandMock + .Setup(c => c.Execute(It.IsAny())) + .Returns(new CommandResult(null, exitCode, "", stdErr)); var commandFactoryMock = new Mock(MockBehavior.Strict); commandFactoryMock diff --git a/test/dotnet.Tests/CommandTests/BuildServer/Shutdown/BuildServerShutdownCommandTests.cs b/test/dotnet.Tests/CommandTests/BuildServer/Shutdown/BuildServerShutdownCommandTests.cs index c2f403316aae..beb48ca4606a 100644 --- a/test/dotnet.Tests/CommandTests/BuildServer/Shutdown/BuildServerShutdownCommandTests.cs +++ b/test/dotnet.Tests/CommandTests/BuildServer/Shutdown/BuildServerShutdownCommandTests.cs @@ -36,7 +36,7 @@ public void GivenNoOptionsItEnumeratesAllServers() var command = CreateCommand(serverProvider: provider.Object); - command.Execute().Should().Be(0); + command.Execute(TestContext.CancellationToken).Should().Be(0); _reporter.Lines.Should().Equal(CliCommandStrings.NoServersToShutdown.Green()); @@ -54,7 +54,7 @@ public void GivenMSBuildOptionOnlyItEnumeratesOnlyMSBuildServers() var command = CreateCommand(options: ["--msbuild"], serverProvider: provider.Object); - command.Execute().Should().Be(0); + command.Execute(TestContext.CancellationToken).Should().Be(0); _reporter.Lines.Should().Equal(CliCommandStrings.NoServersToShutdown.Green()); @@ -72,7 +72,7 @@ public void GivenVBCSCompilerOptionOnlyItEnumeratesOnlyVBCSCompilers() var command = CreateCommand(options: ["--vbcscompiler"], serverProvider: provider.Object); - command.Execute().Should().Be(0); + command.Execute(TestContext.CancellationToken).Should().Be(0); _reporter.Lines.Should().Equal(CliCommandStrings.NoServersToShutdown.Green()); @@ -90,7 +90,7 @@ public void GivenRazorOptionOnlyItEnumeratesOnlyRazorServers() var command = CreateCommand(options: ["--razor"], serverProvider: provider.Object); - command.Execute().Should().Be(0); + command.Execute(TestContext.CancellationToken).Should().Be(0); _reporter.Lines.Should().Equal(CliCommandStrings.NoServersToShutdown.Green()); @@ -113,7 +113,7 @@ public void GivenSuccessfulShutdownsItPrintsSuccess() var command = CreateCommand(serverProvider: provider.Object); - command.Execute().Should().Be(0); + command.Execute(TestContext.CancellationToken).Should().Be(0); _reporter.Lines.Should().Equal( FormatShuttingDownMessage(mocks[0].Object), @@ -145,7 +145,7 @@ public void GivenAFailingShutdownItPrintsFailureMessage() var command = CreateCommand(serverProvider: provider.Object); - command.Execute().Should().Be(1); + command.Execute(TestContext.CancellationToken).Should().Be(1); _reporter.Lines.Should().Equal( FormatShuttingDownMessage(mocks[0].Object), @@ -158,6 +158,74 @@ public void GivenAFailingShutdownItPrintsFailureMessage() VerifyShutdownCalls(mocks); } + [TestMethod] + public async Task GivenCancellationItCancelsTheServerShutdown() + { + using var cancellationSource = CancellationTokenSource.CreateLinkedTokenSource(TestContext.CancellationToken); + using var shutdownStarted = new ManualResetEventSlim(); + using var shutdownFinished = new ManualResetEventSlim(); + var server = new Mock(MockBehavior.Strict); + server.SetupGet(s => s.ProcessId).Returns(0); + server.SetupGet(s => s.Name).Returns("server"); + server + .Setup(s => s.Shutdown(cancellationSource.Token)) + .Callback(cancellationToken => + { + shutdownStarted.Set(); + try + { + cancellationToken.WaitHandle.WaitOne(); + cancellationToken.ThrowIfCancellationRequested(); + } + finally + { + shutdownFinished.Set(); + } + }); + + var provider = new Mock(MockBehavior.Strict); + provider + .Setup(p => p.EnumerateBuildServers(ServerEnumerationFlags.All)) + .Returns([server.Object]); + + var command = CreateCommand(serverProvider: provider.Object); + Task execution = Task.Run( + () => command.Execute(cancellationSource.Token), + TestContext.CancellationToken); + + shutdownStarted.Wait(TestContext.CancellationToken); + cancellationSource.Cancel(); + + await Assert.ThrowsExactlyAsync(() => execution); + shutdownFinished.Wait(TestContext.CancellationToken); + server.Verify(s => s.Shutdown(cancellationSource.Token), Times.Once); + } + + [TestMethod] + public void GivenServerShutdownThrowsMatchingCancellationItPropagates() + { + using var cancellationSource = CancellationTokenSource.CreateLinkedTokenSource(TestContext.CancellationToken); + var server = new Mock(MockBehavior.Strict); + server.SetupGet(s => s.ProcessId).Returns(0); + server.SetupGet(s => s.Name).Returns("server"); + server + .Setup(s => s.Shutdown(cancellationSource.Token)) + .Throws(new OperationCanceledException(cancellationSource.Token)); + + var provider = new Mock(MockBehavior.Strict); + provider + .Setup(p => p.EnumerateBuildServers(ServerEnumerationFlags.All)) + .Returns([server.Object]); + + var command = CreateCommand(serverProvider: provider.Object); + + var exception = Assert.ThrowsExactly( + () => command.Execute(cancellationSource.Token)); + + exception.CancellationToken.Should().Be(cancellationSource.Token); + server.Verify(s => s.Shutdown(cancellationSource.Token), Times.Once); + } + [TestMethod] [Ignore("https://github.com/dotnet/sdk/issues/3684")] public void GivenARunningRazorServerItShutsDownSuccessfully() @@ -219,11 +287,11 @@ private Mock CreateServerMock(string name, int pid = 0, string exc if (exceptionMessage == null) { - mock.Setup(s => s.Shutdown()); + mock.Setup(s => s.Shutdown(It.IsAny())); } else { - mock.Setup(s => s.Shutdown()).Throws(new Exception(exceptionMessage)); + mock.Setup(s => s.Shutdown(It.IsAny())).Throws(new Exception(exceptionMessage)); } return mock; @@ -233,7 +301,7 @@ private void VerifyShutdownCalls(IEnumerable> mocks) { foreach (var mock in mocks) { - mock.Verify(s => s.Shutdown(), Times.Once); + mock.Verify(s => s.Shutdown(TestContext.CancellationToken), Times.Once); } } diff --git a/test/dotnet.Tests/CommandTests/CommandInvocationTests.cs b/test/dotnet.Tests/CommandTests/CommandInvocationTests.cs new file mode 100644 index 000000000000..9382bb37c500 --- /dev/null +++ b/test/dotnet.Tests/CommandTests/CommandInvocationTests.cs @@ -0,0 +1,40 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Microsoft.DotNet.Cli; + +namespace Microsoft.DotNet.Tests.Commands; + +[TestClass] +[DoNotParallelize] // The test temporarily replaces the process-wide root command action. +public sealed class CommandInvocationTests : SdkTest +{ + [TestMethod] + public void PassesCancellationTokenToCommandAction() + { + using var cancellationTokenSource = new CancellationTokenSource(); + bool cancellationObserved = false; + var originalAction = Parser.RootCommand.Action; + int exitCode; + try + { + Parser.RootCommand.SetAction((_, cancellationToken) => + { + cancellationTokenSource.Cancel(); + cancellationObserved = cancellationToken.IsCancellationRequested; + return Task.FromResult(0); + }); + + exitCode = CommandInvocation.ExecuteInternalCommand( + Parser.Parse([]), + cancellationTokenSource.Token); + } + finally + { + Parser.RootCommand.Action = originalAction; + } + + Assert.AreEqual(0, exitCode); + Assert.IsTrue(cancellationObserved); + } +} diff --git a/test/dotnet.Tests/CommandTests/MSBuild/GivenDotnetPackInvocation.cs b/test/dotnet.Tests/CommandTests/MSBuild/GivenDotnetPackInvocation.cs index fd8994ae3196..cc18999404a4 100644 --- a/test/dotnet.Tests/CommandTests/MSBuild/GivenDotnetPackInvocation.cs +++ b/test/dotnet.Tests/CommandTests/MSBuild/GivenDotnetPackInvocation.cs @@ -44,7 +44,7 @@ public void MsbuildInvocationIsCorrect(string[] args, string[] expectedAdditiona .ToArray(); var msbuildPath = ""; - var command = (PackCommand)PackCommand.FromArgs(args, msbuildPath); + var command = (PackCommand)PackCommand.FromArgs(args, TestContext.CancellationToken, msbuildPath); var expectedPrefix = args.FirstOrDefault() == "--no-build" ? ExpectedNoBuildPrefix : [.. ExpectedPrefix, .. GivenDotnetBuildInvocation.RestoreExpectedPrefixForImplicitRestore]; command.SeparateRestoreCommand.Should().BeNull(); diff --git a/test/dotnet.Tests/CommandTests/MSBuild/GivenDotnetPublishInvocation.cs b/test/dotnet.Tests/CommandTests/MSBuild/GivenDotnetPublishInvocation.cs index e9cdad78b266..e1a6eab07828 100644 --- a/test/dotnet.Tests/CommandTests/MSBuild/GivenDotnetPublishInvocation.cs +++ b/test/dotnet.Tests/CommandTests/MSBuild/GivenDotnetPublishInvocation.cs @@ -45,7 +45,7 @@ public void MsbuildInvocationIsCorrect(string[] args, string[] expectedAdditiona .ToArray(); var msbuildPath = ""; - var command = (PublishCommand)PublishCommand.FromArgs(args, msbuildPath); + var command = (PublishCommand)PublishCommand.FromArgs(args, TestContext.CancellationToken, msbuildPath); command.SeparateRestoreCommand .Should() @@ -62,7 +62,7 @@ public void MsbuildInvocationIsCorrect(string[] args, string[] expectedAdditiona public void MsbuildInvocationIsCorrectForSeparateRestore(string[] args, string[] expectedAdditionalArgs) { var msbuildPath = ""; - var command = (PublishCommand)PublishCommand.FromArgs(args, msbuildPath); + var command = (PublishCommand)PublishCommand.FromArgs(args, TestContext.CancellationToken, msbuildPath); var restoreTokens = command.SeparateRestoreCommand! // for this scenario, we expect a separate restore command @@ -87,7 +87,7 @@ public void MsbuildInvocationIsCorrectForSeparateRestore(string[] args, string[] public void MsbuildInvocationIsCorrectForNoBuild() { var msbuildPath = ""; - var command = (PublishCommand)PublishCommand.FromArgs(new[] { "--no-build" }, msbuildPath); + var command = (PublishCommand)PublishCommand.FromArgs(new[] { "--no-build" }, TestContext.CancellationToken, msbuildPath); command.SeparateRestoreCommand .Should() @@ -102,7 +102,7 @@ public void MsbuildInvocationIsCorrectForNoBuild() public void CommandAcceptsMultipleCustomProperties() { var msbuildPath = ""; - var command = (PublishCommand)PublishCommand.FromArgs(new[] { "/p:Prop1=prop1", "/p:Prop2=prop2" }, msbuildPath); + var command = (PublishCommand)PublishCommand.FromArgs(new[] { "/p:Prop1=prop1", "/p:Prop2=prop2" }, TestContext.CancellationToken, msbuildPath); command.GetArgumentTokensToMSBuild() .Should() diff --git a/test/dotnet.Tests/CommandTests/MSBuild/GivenDotnetVsTestForwardingApp.cs b/test/dotnet.Tests/CommandTests/MSBuild/GivenDotnetVsTestForwardingApp.cs index d1fda86d7d1d..9c3a01047436 100644 --- a/test/dotnet.Tests/CommandTests/MSBuild/GivenDotnetVsTestForwardingApp.cs +++ b/test/dotnet.Tests/CommandTests/MSBuild/GivenDotnetVsTestForwardingApp.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.DotNet.Cli.Commands.Test; +using Microsoft.DotNet.Cli.Commands.VSTest; namespace Microsoft.DotNet.Cli.MSBuild.Tests { @@ -32,6 +33,16 @@ public void ItCanUseEnvironmentVariableToForceCustomPathToVsTestApp() Environment.SetEnvironmentVariable(vsTestConsolePath, null); } } + + [TestMethod] + public void ItDoesNotLaunchVsTestWhenCancellationIsAlreadyRequested() + { + using var cancellationSource = new CancellationTokenSource(); + cancellationSource.Cancel(); + + Assert.ThrowsExactly(() => + VSTestCommand.Run(Parser.Parse(["vstest"]), cancellationSource.Token)); + } } } diff --git a/test/dotnet.Tests/CommandTests/MSBuild/GivenMsbuildForwardingApp.cs b/test/dotnet.Tests/CommandTests/MSBuild/GivenMsbuildForwardingApp.cs index ba21c406136f..355653e44b37 100644 --- a/test/dotnet.Tests/CommandTests/MSBuild/GivenMsbuildForwardingApp.cs +++ b/test/dotnet.Tests/CommandTests/MSBuild/GivenMsbuildForwardingApp.cs @@ -191,5 +191,34 @@ public void ItUsesCliServerSettingUnlessMSBuildServerSettingIsExplicit(string ms Environment.SetEnvironmentVariable("MSBUILDUSESERVER", originalMSBuildUseServer); } } + + [TestMethod] + public void ItDoesNotStartOutOfProcessMSBuildAfterCancellation() + { + using var cancellationTokenSource = new CancellationTokenSource(); + cancellationTokenSource.Cancel(); + + var forwardingApp = new MSBuildForwardingAppWithoutLogging( + MSBuildArgs.FromOtherArgs(), + msbuildPath: "", + forceOutOfProc: true); + + Action execute = () => forwardingApp.Execute(cancellationTokenSource.Token); + + execute.Should().Throw(); + } + + [TestMethod] + public void ItDoesNotStartInProcessMSBuildAfterCancellation() + { + using var cancellationTokenSource = new CancellationTokenSource(); + cancellationTokenSource.Cancel(); + + var forwardingApp = new MSBuildForwardingAppWithoutLogging(MSBuildArgs.FromOtherArgs()); + + Action execute = () => forwardingApp.ExecuteInProc([], cancellationTokenSource.Token); + + execute.Should().Throw(); + } } } diff --git a/test/dotnet.Tests/CommandTests/MSBuild/MSBuildArgumentCommandLineParserTests.cs b/test/dotnet.Tests/CommandTests/MSBuild/MSBuildArgumentCommandLineParserTests.cs index 25d341f5d747..bc2bb5c1336a 100644 --- a/test/dotnet.Tests/CommandTests/MSBuild/MSBuildArgumentCommandLineParserTests.cs +++ b/test/dotnet.Tests/CommandTests/MSBuild/MSBuildArgumentCommandLineParserTests.cs @@ -14,6 +14,7 @@ namespace Microsoft.DotNet.Tests.CommandLineParserTests [TestClass] public class MSBuildArgumentCommandLineParserTests { + public TestContext TestContext { get; set; } = null!; [TestMethod] [DataRow(new string[] { "-property:prop1=true", "-p:prop2=false" }, true)] @@ -28,7 +29,7 @@ public void MSBuildArgumentsAreForwardedCorrectly(string[] arguments, bool build { RestoringCommand command = buildCommand ? (RestoringCommand)BuildCommand.FromArgs(arguments) : - (RestoringCommand)PublishCommand.FromArgs(arguments); + (RestoringCommand)PublishCommand.FromArgs(arguments, TestContext.CancellationToken); var expectedArguments = arguments.Select(a => a.Replace("-property:", "--property:").Replace("-p:", "--property:")); var argString = command.MSBuildArguments; diff --git a/test/dotnet.Tests/CommandTests/New/DotnetAddPostActionTests.cs b/test/dotnet.Tests/CommandTests/New/DotnetAddPostActionTests.cs index 6e3f28e5309f..39dc41389e3c 100644 --- a/test/dotnet.Tests/CommandTests/New/DotnetAddPostActionTests.cs +++ b/test/dotnet.Tests/CommandTests/New/DotnetAddPostActionTests.cs @@ -12,6 +12,8 @@ namespace Microsoft.DotNet.Cli.New.Tests [TestClass] public class DotnetAddPostActionTests { + public TestContext TestContext { get; set; } = null!; + private IEngineEnvironmentSettings _engineEnvironmentSettings = null!; [TestInitialize] @@ -174,7 +176,8 @@ public void AddRefCanHandleProjectFileRenames() postAction, creationEffects, new MockCreationResult(), - targetBasePath); + targetBasePath, + TestContext.CancellationToken); Assert.AreEqual(projFileFullPath, callback.Target); Assert.AreEqual(referencedProjFileFullPath, callback.Reference); @@ -201,7 +204,8 @@ public void AddRefCanHandleProjectFilesWithoutRenames() postAction, creationEffects, new MockCreationResult(), - targetBasePath); + targetBasePath, + TestContext.CancellationToken); Assert.AreEqual(projFileFullPath, callback.Target); Assert.AreEqual(referencedProjFileFullPath, callback.Reference); @@ -244,7 +248,8 @@ public void AddRefCanHandleExistingProjectFiles() postAction, creationEffects, new MockCreationResult(), - targetBasePath); + targetBasePath, + TestContext.CancellationToken); Assert.AreEqual(existingProjectFileFullPath, callback.Target); Assert.AreEqual(referencedProjectFileFullPath, callback.Reference); @@ -270,7 +275,8 @@ public void AddRefCanTargetASingleProjectWithAJsonArray() postAction, creationEffects, new MockCreationResult(), - targetBasePath); + targetBasePath, + TestContext.CancellationToken); Assert.AreEqual(projFileFullPath, callback.Target); Assert.AreEqual("System.Net.Json", callback.Reference); @@ -297,19 +303,55 @@ public void AddRefCanTargetASingleProjectWithTheProjectName() postAction, creationEffects, new MockCreationResult(), - targetBasePath); + targetBasePath, + TestContext.CancellationToken); Assert.AreEqual(projFileFullPath, callback.Target); Assert.AreEqual("System.Net.Json", callback.Reference); } + [TestMethod] + [DataRow("package")] + [DataRow("project")] + public void AddRefPropagatesCancellation(string referenceType) + { + DotnetAddPostActionProcessor actionProcessor = new( + (_, _, _, cancellationToken) => throw new OperationCanceledException(cancellationToken), + (_, _, cancellationToken) => throw new OperationCanceledException(cancellationToken)); + + string targetBasePath = _engineEnvironmentSettings.GetTempVirtualizedPath(); + var args = new Dictionary() + { + { "targetFiles", "[\"MyApp.csproj\"]" }, + { "referenceType", referenceType }, + { "reference", referenceType == "package" ? "System.Net.Json" : "./Reference.csproj" }, + }; + var postAction = new MockPostAction(default, default, default, default, default!) + { + ActionId = DotnetAddPostActionProcessor.ActionProcessorId, + Args = args, + }; + MockCreationEffects creationEffects = new MockCreationEffects() + .WithFileChange(new MockFileChange("./MyApp.csproj", "./MyApp.csproj", ChangeKind.Create)); + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + Assert.ThrowsExactly(() => actionProcessor.Process( + _engineEnvironmentSettings, + postAction, + creationEffects, + new MockCreationResult(), + targetBasePath, + cancellationTokenSource.Token)); + } + private class MockAddProjectReferenceCallback { public string? Target { get; private set; } public string? Reference { get; private set; } - public bool AddProjectReference(string target, string reference) + public bool AddProjectReference(string target, string reference, CancellationToken cancellationToken = default) { if (Target != null) { @@ -322,7 +364,7 @@ public bool AddProjectReference(string target, string reference) return true; } - public bool AddPackageReference(string target, string reference, string? version) + public bool AddPackageReference(string target, string reference, string? version, CancellationToken cancellationToken = default) { if (Target != null) { diff --git a/test/dotnet.Tests/CommandTests/New/DotnetRestorePostActionTests.cs b/test/dotnet.Tests/CommandTests/New/DotnetRestorePostActionTests.cs index 9ec03d064bfc..50f5ce2ec8db 100644 --- a/test/dotnet.Tests/CommandTests/New/DotnetRestorePostActionTests.cs +++ b/test/dotnet.Tests/CommandTests/New/DotnetRestorePostActionTests.cs @@ -12,6 +12,8 @@ namespace Microsoft.DotNet.Cli.New.Tests [TestClass] public class DotnetRestorePostActionTests { + public TestContext TestContext { get; set; } = null!; + private IEngineEnvironmentSettings _engineEnvironmentSettings = null!; [TestInitialize] @@ -40,7 +42,8 @@ public void DotnetRestoreCanTargetASingleProjectWithAJsonArray() postAction, creationEffects, new MockCreationResult(), - targetBasePath); + targetBasePath, + TestContext.CancellationToken); Assert.AreEqual(projFileFullPath, callback.Target); } @@ -65,16 +68,43 @@ public void DotnetRestoreCanTargetASingleProjectWithTheProjectName() postAction, creationEffects, new MockCreationResult(), - targetBasePath); + targetBasePath, + TestContext.CancellationToken); Assert.AreEqual(projFileFullPath, callback.Target); } + [TestMethod] + public void DotnetRestorePropagatesCancellation() + { + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + DotnetRestorePostActionProcessor actionProcessor = new( + (_, cancellationToken) => throw new OperationCanceledException(cancellationToken)); + + string targetBasePath = _engineEnvironmentSettings.GetTempVirtualizedPath(); + var args = new Dictionary() { { "files", "MyApp.csproj" } }; + var postAction = new MockPostAction(default, default, default, default, default!) { ActionId = actionProcessor.Id, Args = args }; + MockCreationEffects creationEffects = new MockCreationEffects() + .WithFileChange(new MockFileChange("./MyApp.csproj", "./MyApp.csproj", ChangeKind.Create)); + + OperationCanceledException exception = Assert.ThrowsExactly( + () => actionProcessor.Process( + _engineEnvironmentSettings, + postAction, + creationEffects, + new MockCreationResult(), + targetBasePath, + cancellationTokenSource.Token)); + + Assert.AreEqual(cancellationTokenSource.Token, exception.CancellationToken); + } + private class MockDotnetRestoreCallback { public string? Target { get; private set; } - public bool RestoreProject(string target) + public bool RestoreProject(string target, CancellationToken cancellationToken = default) { Target = target; return true; diff --git a/test/dotnet.Tests/CommandTests/New/DotnetSlnPostActionTests.cs b/test/dotnet.Tests/CommandTests/New/DotnetSlnPostActionTests.cs index d2c9eded70ca..10124d8a026c 100644 --- a/test/dotnet.Tests/CommandTests/New/DotnetSlnPostActionTests.cs +++ b/test/dotnet.Tests/CommandTests/New/DotnetSlnPostActionTests.cs @@ -11,6 +11,8 @@ namespace Microsoft.DotNet.Cli.New.Tests [TestClass] public class DotnetSlnPostActionTests { + public TestContext TestContext { get; set; } = null!; + private IEngineEnvironmentSettings _engineEnvironmentSettings = null!; [TestInitialize] @@ -240,7 +242,8 @@ public void AddProjectToSolutionCanTargetASingleProjectWithAJsonArray() postAction, creationEffects, new MockCreationResult(), - targetBasePath); + targetBasePath, + TestContext.CancellationToken); Assert.AreSequenceEqual(new[] { projFileFullPath }, callback.Projects); Assert.AreEqual(slnFileFullPath, callback.Solution); @@ -269,7 +272,8 @@ public void AddProjectToSolutionCanTargetASingleProjectWithTheProjectName() postAction, creationEffects, new MockCreationResult(), - targetBasePath); + targetBasePath, + TestContext.CancellationToken); Assert.AreSequenceEqual(new[] { projFileFullPath }, callback.Projects); Assert.AreEqual(slnFileFullPath, callback.Solution); @@ -301,7 +305,8 @@ public void AddProjectToSolutionCanPlaceProjectInSolutionRoot() postAction, creationEffects, new MockCreationResult(), - targetBasePath); + targetBasePath, + TestContext.CancellationToken); Assert.IsTrue(callback.InRoot); Assert.IsNull(callback.TargetFolder); @@ -333,7 +338,8 @@ public void AddProjectToSolutionCanPlaceProjectInSolutionFolder() postAction, creationEffects, new MockCreationResult(), - targetBasePath); + targetBasePath, + TestContext.CancellationToken); Assert.IsNull(callback.InRoot); Assert.AreEqual("src", callback.TargetFolder); @@ -366,7 +372,8 @@ public void AddProjectToSolutionFailsWhenSolutionFolderAndInRootSpecified() postAction, creationEffects, new MockCreationResult(), - targetBasePath); + targetBasePath, + TestContext.CancellationToken); Assert.IsFalse(result); } @@ -395,7 +402,7 @@ private class MockAddProjectToSolutionCallback public bool? InRoot { get; private set; } - public bool AddProjectToSolution(string solution, IReadOnlyList projects, string? targetFolder, bool? inRoot) + public bool AddProjectToSolution(string solution, IReadOnlyList projects, string? targetFolder, bool? inRoot, CancellationToken cancellationToken = default) { Solution = solution; Projects = projects; diff --git a/test/dotnet.Tests/CommandTests/NuGet/GivenANuGetCommand.cs b/test/dotnet.Tests/CommandTests/NuGet/GivenANuGetCommand.cs index 0e0b3e4ec5be..de5b19ea4d48 100644 --- a/test/dotnet.Tests/CommandTests/NuGet/GivenANuGetCommand.cs +++ b/test/dotnet.Tests/CommandTests/NuGet/GivenANuGetCommand.cs @@ -85,20 +85,32 @@ public void ItPassesCommandIfSupported(string[] inputArgs, int result) { // Arrange string[] receivedArgs = null; + using var cancellationTokenSource = new CancellationTokenSource(); var testCommandRunner = new Mock(); testCommandRunner - .Setup(x => x.Run(It.IsAny())) - .Callback(s => receivedArgs = s) + .Setup(x => x.Run(It.IsAny(), cancellationTokenSource.Token)) + .Callback((s, _) => receivedArgs = s) .Returns(0); // Act - var returned = NuGetCommand.Run(inputArgs, testCommandRunner.Object); + var returned = NuGetCommand.Run(inputArgs, testCommandRunner.Object, cancellationTokenSource.Token); // Assert receivedArgs.Should().BeEquivalentTo(inputArgs); returned.Should().Be(result); } + [TestMethod] + public void ItDoesNotRunNuGetAfterCancellation() + { + using var cancellationTokenSource = new CancellationTokenSource(); + cancellationTokenSource.Cancel(); + + Action run = () => NuGetCommand.Run([], cancellationTokenSource.Token, isFileBasedApp: true); + + run.Should().Throw(); + } + [TestMethod] public void ItAcceptsPrefixedOption() { diff --git a/test/dotnet.Tests/CommandTests/Pack/ReleasePropertyProjectLocatorTests.cs b/test/dotnet.Tests/CommandTests/Pack/ReleasePropertyProjectLocatorTests.cs index 0967eb217321..4241aa86db2c 100644 --- a/test/dotnet.Tests/CommandTests/Pack/ReleasePropertyProjectLocatorTests.cs +++ b/test/dotnet.Tests/CommandTests/Pack/ReleasePropertyProjectLocatorTests.cs @@ -114,12 +114,13 @@ public void SolutionDiscoverySkipsSharedProjects(string solutionExtension, bool Assert.AreEqual("true", result[$"_SolutionLevel{propertyName}"]); } - private static IReadOnlyDictionary? DiscoverReleaseProperties(string projectOrSolutionPath, string propertyName) + private IReadOnlyDictionary? DiscoverReleaseProperties(string projectOrSolutionPath, string propertyName) { var locator = new ReleasePropertyProjectLocator( userSpecifiedExplicitMSBuildProperties: null, propertyToCheck: propertyName, - commandOptions: new ReleasePropertyProjectLocator.DependentCommandOptions([projectOrSolutionPath])); + commandOptions: new ReleasePropertyProjectLocator.DependentCommandOptions([projectOrSolutionPath]), + TestContext.CancellationToken); return locator.GetCustomDefaultConfigurationValueIfSpecified(); } diff --git a/test/dotnet.Tests/CommandTests/Package/List/GivenDotnetListPackage.cs b/test/dotnet.Tests/CommandTests/Package/List/GivenDotnetListPackage.cs index 1f26fe6cd95a..aa9bba3b04ee 100644 --- a/test/dotnet.Tests/CommandTests/Package/List/GivenDotnetListPackage.cs +++ b/test/dotnet.Tests/CommandTests/Package/List/GivenDotnetListPackage.cs @@ -221,6 +221,27 @@ public void RestoresAndLists_FileBasedApp() .And.HaveStdOutContaining(packageVersion); } + [TestMethod] + public void RestorePropagatesCancellation() + { + var testDirectory = TestAssetsManager.CreateTestDirectory(); + string projectPath = Path.Combine(testDirectory.Path, "Test.csproj"); + File.WriteAllText(projectPath, """ + + + net10.0 + + + """); + var parseResult = Parser.Parse(["dotnet", "package", "list", "--project", projectPath]); + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + Assert.ThrowsExactly( + () => new Microsoft.DotNet.Cli.Commands.Package.List.PackageListCommand(parseResult) + .Execute(cancellationTokenSource.Token)); + } + [TestMethod] public void ItListsTransitivePackage() { diff --git a/test/dotnet.Tests/CommandTests/Run/GivenDotnetRunIsInterrupted.cs b/test/dotnet.Tests/CommandTests/Run/GivenDotnetRunIsInterrupted.cs index 54eae68903e8..d7a644308654 100644 --- a/test/dotnet.Tests/CommandTests/Run/GivenDotnetRunIsInterrupted.cs +++ b/test/dotnet.Tests/CommandTests/Run/GivenDotnetRunIsInterrupted.cs @@ -27,7 +27,8 @@ public void ItTerminatesWinExeAppWithCloseMainWindow() .WithSource(); var command = new DotnetCommand(Log, "run") - .WithWorkingDirectory(asset.Path); + .WithWorkingDirectory(asset.Path) + .WithEnvironmentVariable("DOTNET_TEST_WINEXE_CLOSE_DELAY_MS", "1000"); // Launch dotnet run in a new process group so that GenerateConsoleCtrlEvent // targets only the child group and does not propagate to the test host. diff --git a/test/dotnet.Tests/CommandTests/Run/RunApiCancellationTests.cs b/test/dotnet.Tests/CommandTests/Run/RunApiCancellationTests.cs new file mode 100644 index 000000000000..15ef0441fee4 --- /dev/null +++ b/test/dotnet.Tests/CommandTests/Run/RunApiCancellationTests.cs @@ -0,0 +1,164 @@ +// 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.Text.Json; +using Microsoft.DotNet.Cli.TestApp; +using Microsoft.DotNet.Cli.Utils; +using Microsoft.Win32.SafeHandles; + +namespace Microsoft.DotNet.Cli.Run.Tests; + +[TestClass] +public class RunApiCancellationTests : SdkTest +{ + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(30); + + [TestMethod] + [OSCondition(ConditionMode.Exclude, OperatingSystems.Linux)] + public async Task CancellationInterruptsAnOpenStandardInputPipe() + => await VerifyStandardInputCancellation(); + + [TestMethod] + [OSCondition(OperatingSystems.Linux)] + public async Task CancellationInterruptsABlockedLinuxStandardInputRead() + => await VerifyStandardInputCancellation(); + + [TestMethod] + [OSCondition(ConditionMode.Exclude, OperatingSystems.Windows)] + public async Task SignalCancellationUsesTheSignalExitCode() + { + using Process child = StartChild(); + Task standardError = child.StandardError.ReadToEndAsync(TestContext.CancellationToken); + try + { + await child.StandardInput.WriteLineAsync("""{"$type":"Unknown"}"""); + await child.StandardInput.FlushAsync(TestContext.CancellationToken); + string? response = await child.StandardOutput.ReadLineAsync(TestContext.CancellationToken) + .AsTask() + .WaitAsync(s_timeout, TestContext.CancellationToken); + response.Should().NotBeNull(); + + child.SafeHandle.Signal(PosixSignal.SIGINT).Should().BeTrue(); + await child.WaitForExitAsync(TestContext.CancellationToken).WaitAsync(s_timeout, TestContext.CancellationToken); + + child.ExitCode.Should().Be(130); + (await standardError).Should().BeEmpty(); + } + finally + { + StopChild(child); + } + } + + private async Task VerifyStandardInputCancellation() + { + using Process child = StartChild(cancelPendingRead: true); + Task standardOutput = child.StandardOutput.ReadToEndAsync(TestContext.CancellationToken); + Task standardError = child.StandardError.ReadToEndAsync(TestContext.CancellationToken); + try + { + await child.WaitForExitAsync(TestContext.CancellationToken).WaitAsync(s_timeout, TestContext.CancellationToken); + child.ExitCode.Should().Be(0); + (await standardOutput).Should().BeEmpty(); + (await standardError).Should().BeEmpty(); + } + finally + { + StopChild(child); + } + } + + [TestMethod] + [DataRow("\n")] + [DataRow("\r\n")] + [DataRow("\r")] + public async Task InputLinesBlankLinesAndEndOfFileRetainTheirResponses(string newline) + { + using Process child = StartChild(); + Task standardOutput = child.StandardOutput.ReadToEndAsync(TestContext.CancellationToken); + Task standardError = child.StandardError.ReadToEndAsync(TestContext.CancellationToken); + try + { + await child.StandardInput.WriteAsync( + $" {newline}{newline}{{\"$type\":\"Unknown1\"}}{newline}{{\"$type\":\"Unknown2\"}}"); + child.StandardInput.Close(); + await child.WaitForExitAsync(TestContext.CancellationToken).WaitAsync(s_timeout, TestContext.CancellationToken); + child.ExitCode.Should().Be(0); + string output = await standardOutput; + string[] responses = output.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries); + responses.Should().HaveCount(2); + for (int i = 0; i < responses.Length; i++) + { + using JsonDocument response = JsonDocument.Parse(responses[i]); + response.RootElement.GetProperty("$type").GetString().Should().Be("Error"); + response.RootElement.GetProperty("Version").GetInt32().Should().Be(1); + response.RootElement.GetProperty("Message").GetString().Should().Contain($"Unknown{i + 1}"); + } + + (await standardError).Should().BeEmpty(); + } + finally + { + StopChild(child); + } + } + + [TestMethod] + public async Task EmptyEndOfFileExitsWithoutAResponse() + { + using Process child = StartChild(); + Task standardOutput = child.StandardOutput.ReadToEndAsync(TestContext.CancellationToken); + Task standardError = child.StandardError.ReadToEndAsync(TestContext.CancellationToken); + try + { + child.StandardInput.Close(); + await child.WaitForExitAsync(TestContext.CancellationToken).WaitAsync(s_timeout, TestContext.CancellationToken); + child.ExitCode.Should().Be(0); + (await standardOutput).Should().BeEmpty(); + (await standardError).Should().BeEmpty(); + } + finally + { + StopChild(child); + } + } + + private static Process StartChild(bool cancelPendingRead = false) + { + string assemblyPath = typeof(RunApiCancellationTests).Assembly.Location; + ProcessStartInfo startInfo = new(SdkTestContext.Current.ToolsetUnderTest.DotNetHostPath) + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardInput = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + if (cancelPendingRead) + { + startInfo.ArgumentList.Add("exec"); + startInfo.ArgumentList.Add("--runtimeconfig"); + startInfo.ArgumentList.Add(Path.ChangeExtension(assemblyPath, ".runtimeconfig.json")); + startInfo.ArgumentList.Add("--depsfile"); + startInfo.ArgumentList.Add(Path.ChangeExtension(assemblyPath, ".deps.json")); + startInfo.ArgumentList.Add(typeof(RunApiTestApp).Assembly.Location); + } + else + { + startInfo.ArgumentList.Add("run-api"); + } + Process child = new() { StartInfo = startInfo }; + child.Start(); + return child; + } + + private static void StopChild(Process child) + { + if (!child.HasExited) + { + child.Kill(entireProcessTree: true); + child.WaitForExit(s_timeout).Should().BeTrue(); + } + } +} diff --git a/test/dotnet.Tests/CommandTests/Run/RunCommandTests.cs b/test/dotnet.Tests/CommandTests/Run/RunCommandTests.cs index 022ec0617c2a..2d66ff3d27af 100644 --- a/test/dotnet.Tests/CommandTests/Run/RunCommandTests.cs +++ b/test/dotnet.Tests/CommandTests/Run/RunCommandTests.cs @@ -3,6 +3,7 @@ using Microsoft.DotNet.Cli.Commands; using Microsoft.DotNet.Cli.Commands.Run; +using Microsoft.DotNet.Cli.MSBuild.Tests; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.ProjectTools; @@ -36,6 +37,21 @@ private static RunCommand CreateRunCommand( readCodeFromStdin: false, environmentVariables: new Dictionary()); + [TestMethod] + public void VirtualProjectBuildRejectsCancellationBeforeStarting() + { + var testDirectory = TestAssetsManager.CreateTestDirectory(); + var sourceFile = Path.Join(testDirectory.Path, "Program.cs"); + File.WriteAllText(sourceFile, "Console.WriteLine();"); + var command = new VirtualProjectBuildingCommand( + sourceFile, + MSBuildArgs.FromOtherArgs([])); + using var cancellationSource = CancellationTokenSource.CreateLinkedTokenSource(TestContext.CancellationToken); + cancellationSource.Cancel(); + + Assert.ThrowsExactly(() => command.Execute(cancellationSource.Token)); + } + [TestMethod] public void EnvironmentVariableExpansion_Project() { diff --git a/test/dotnet.Tests/CommandTests/Sdk/Check/GivenDotnetSdkCheck.cs b/test/dotnet.Tests/CommandTests/Sdk/Check/GivenDotnetSdkCheck.cs index 1f1bce351aa3..585203e0cee4 100644 --- a/test/dotnet.Tests/CommandTests/Sdk/Check/GivenDotnetSdkCheck.cs +++ b/test/dotnet.Tests/CommandTests/Sdk/Check/GivenDotnetSdkCheck.cs @@ -54,7 +54,7 @@ public void WhenNewFeatureBandExistsItIsAdvertised(bool newerBandExists) var oldSdks = GetFakeEnvironmentInfo(new[] { "3.1.100" }, Array.Empty()); var newSdks = GetFakeEnvironmentInfo(new[] { "5.0.100" }, Array.Empty()); - new SdkCheckCommand(parseResult, new MockNETBundleProvider(newerBandExists ? oldSdks : newSdks), new MockProductCollectionProvider(fakeReleasesPath), _reporter).Execute(); + new SdkCheckCommand(parseResult, new MockNETBundleProvider(newerBandExists ? oldSdks : newSdks), new MockProductCollectionProvider(fakeReleasesPath), _reporter).Execute(CancellationToken.None); if (newerBandExists) { @@ -76,7 +76,7 @@ public void ItContainsInfoForAllInstalledBundles() var parseResult = Parser.Parse(new string[] { "dotnet", "sdk", "check" }); var bundles = GetFakeEnvironmentInfo(new[] { "1.0.10", "2.1.809", "3.1.402", "5.0.100" }, new[] { "1.1.4", "2.1.8", "3.1.0", "3.1.3", "5.0.0" }); - new SdkCheckCommand(parseResult, new MockNETBundleProvider(bundles), new MockProductCollectionProvider(fakeReleasesPath), _reporter).Execute(); + new SdkCheckCommand(parseResult, new MockNETBundleProvider(bundles), new MockProductCollectionProvider(fakeReleasesPath), _reporter).Execute(CancellationToken.None); foreach (var version in bundles.SdkInfo.Select(b => b.Version.ToString())) { @@ -110,7 +110,7 @@ public void WhenANewPatchIsAvailableItIsAdvertised(string[] sdkVersions, string[ var parseResult = Parser.Parse(new string[] { "dotnet", "sdk", "check" }); var bundles = GetFakeEnvironmentInfo(sdkVersions, runtimeVersions); - new SdkCheckCommand(parseResult, new MockNETBundleProvider(bundles), new MockProductCollectionProvider(fakeReleasesPath), _reporter).Execute(); + new SdkCheckCommand(parseResult, new MockNETBundleProvider(bundles), new MockProductCollectionProvider(fakeReleasesPath), _reporter).Execute(CancellationToken.None); var commandResult = string.Join(' ', _reporter.Lines); var expectedLines = latestPatchVersions.Select(version => string.Format(CliCommandStrings.NewPatchAvailableMessage, version)); @@ -137,7 +137,7 @@ public void WhenABundleIsOutOfSupportItPrintsWarning(string[] sdkVersions, strin var parseResult = Parser.Parse(new string[] { "dotnet", "sdk", "check" }); var bundles = GetFakeEnvironmentInfo(sdkVersions, runtimeVersions); - new SdkCheckCommand(parseResult, new MockNETBundleProvider(bundles), new MockProductCollectionProvider(fakeReleasesPath), _reporter).Execute(); + new SdkCheckCommand(parseResult, new MockNETBundleProvider(bundles), new MockProductCollectionProvider(fakeReleasesPath), _reporter).Execute(CancellationToken.None); var commandResult = string.Join(' ', _reporter.Lines); var expectedLines = outOfSupportVersions.Select(version => string.Format(CliCommandStrings.OutOfSupportMessage, version.Substring(0, 3))); @@ -171,7 +171,7 @@ public void WhenABundleIsInMaintenanceModeItPrintsWarning(string[] sdkVersions, var parseResult = Parser.Parse(new string[] { "dotnet", "sdk", "check" }); var bundles = GetFakeEnvironmentInfo(sdkVersions, runtimeVersions); - new SdkCheckCommand(parseResult, new MockNETBundleProvider(bundles), new MockProductCollectionProvider(fakeReleasesPath), _reporter).Execute(); + new SdkCheckCommand(parseResult, new MockNETBundleProvider(bundles), new MockProductCollectionProvider(fakeReleasesPath), _reporter).Execute(CancellationToken.None); var commandResult = string.Join('\n', _reporter.Lines); var expectedLines = maintenanceVersions.Select(version => string.Format(CliCommandStrings.MaintenanceMessage, version.Substring(0, 3))); @@ -204,7 +204,7 @@ public void ItUsesConfigFile() Directory.CreateDirectory(Path.GetDirectoryName(configFilePath)); File.WriteAllText(configFilePath, configFileContent); - new SdkCheckCommand(parseResult, new MockNETBundleProvider(bundles), dotnetRoot: dotnetRoot, dotnetVersion: "6.0.100", reporter: _reporter).Execute(); + new SdkCheckCommand(parseResult, new MockNETBundleProvider(bundles), dotnetRoot: dotnetRoot, dotnetVersion: "6.0.100", reporter: _reporter).Execute(CancellationToken.None); _reporter.Lines.Count().Should().Be(3); _reporter.Lines.Should().Contain(replacementString); @@ -218,7 +218,7 @@ public void WhenSdkHasNoReleasesJsonItShowsVersionCheckUnavailable() var bundles = GetFakeEnvironmentInfo(new[] { "3.1.100", "5.0.100", "99.0.100" }, new[] { "3.1.0", "5.0.0" }); // This should not throw even though 99.0 doesn't have releases.json - new SdkCheckCommand(parseResult, new MockNETBundleProvider(bundles), new MockProductCollectionProvider(fakeReleasesPath), _reporter).Execute(); + new SdkCheckCommand(parseResult, new MockNETBundleProvider(bundles), new MockProductCollectionProvider(fakeReleasesPath), _reporter).Execute(CancellationToken.None); // Verify all SDKs are shown foreach (var version in bundles.SdkInfo.Select(b => b.Version.ToString())) diff --git a/test/dotnet.Tests/CommandTests/Sdk/Check/MockProductCollectionProvider.cs b/test/dotnet.Tests/CommandTests/Sdk/Check/MockProductCollectionProvider.cs index f648da23b81b..bd61db65e0d0 100644 --- a/test/dotnet.Tests/CommandTests/Sdk/Check/MockProductCollectionProvider.cs +++ b/test/dotnet.Tests/CommandTests/Sdk/Check/MockProductCollectionProvider.cs @@ -17,14 +17,25 @@ public MockProductCollectionProvider(string path) _path = path; } - public ProductCollection GetProductCollection(Uri uri = null, string filePath = null) + public ProductCollection GetProductCollection( + CancellationToken cancellationToken, + Uri uri = null, + string filePath = null) { - return ProductCollection.GetFromFileAsync(Path.Combine(_path, "releases-index.json"), false).Result; + cancellationToken.ThrowIfCancellationRequested(); + return ProductCollection.GetFromFileAsync(Path.Combine(_path, "releases-index.json"), false) + .GetAwaiter() + .GetResult(); } - public IEnumerable GetProductReleases(Product product) + public IEnumerable GetProductReleases( + Product product, + CancellationToken cancellationToken) { - return product.GetReleasesAsync(Path.Combine(_path, product.ProductVersion, "releases.json"), false).Result; + cancellationToken.ThrowIfCancellationRequested(); + return product.GetReleasesAsync(Path.Combine(_path, product.ProductVersion, "releases.json"), false) + .GetAwaiter() + .GetResult(); } } } diff --git a/test/dotnet.Tests/CommandTests/Solution/List/GivenDotnetSlnList.cs b/test/dotnet.Tests/CommandTests/Solution/List/GivenDotnetSlnList.cs index 71df3e124198..4b60cbac5fda 100644 --- a/test/dotnet.Tests/CommandTests/Solution/List/GivenDotnetSlnList.cs +++ b/test/dotnet.Tests/CommandTests/Solution/List/GivenDotnetSlnList.cs @@ -27,6 +27,22 @@ public GivenDotnetSlnList() { } + [TestMethod] + public void GivenCanceledTokenSolutionLoadingIsCanceled() + { + var projectDirectory = TestAssetsManager + .CopyTestAsset("TestAppWithEmptySln") + .WithSource() + .Path; + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + Assert.ThrowsExactly(() => + SlnFileFactory.CreateFromFileOrDirectory( + Path.Combine(projectDirectory, "App.sln"), + cancellationTokenSource.Token)); + } + [TestMethod] [DataRow("sln", "--help")] [DataRow("sln", "-h")] diff --git a/test/dotnet.Tests/CommandTests/Test/CtrlCCancellationManagerTests.cs b/test/dotnet.Tests/CommandTests/Test/CtrlCCancellationManagerTests.cs index 4b6651496fb5..070a014e182f 100644 --- a/test/dotnet.Tests/CommandTests/Test/CtrlCCancellationManagerTests.cs +++ b/test/dotnet.Tests/CommandTests/Test/CtrlCCancellationManagerTests.cs @@ -13,6 +13,8 @@ namespace dotnet.Tests.CommandTests.Test; [TestClass] public class CtrlCCancellationManagerTests { + public TestContext TestContext { get; set; } = null!; + [TestMethod] public void FirstCtrlC_CancelsTokenAndInvokesUiCallbackExactlyOnce() { @@ -51,6 +53,67 @@ public void SecondCtrlC_InvokesExitActionWithTestSessionAborted() receivedExitCode.Should().Be(ExitCode.TestSessionAborted); } + [TestMethod] + public void CooperativeLifecycleCancellation_CancelsTokenAndInvokesUiCallback() + { + int callbackCount = 0; + using var cooperativeCancellation = new CancellationTokenSource(); + using var manager = new CtrlCCancellationManager( + onFirstCtrlC: () => Interlocked.Increment(ref callbackCount), + exitAction: _ => Assert.Fail("Cooperative cancellation must not exit."), + subscribeToConsole: false, + cooperativeCancellationToken: cooperativeCancellation.Token); + + cooperativeCancellation.Cancel(); + + manager.Token.IsCancellationRequested.Should().BeTrue(); + callbackCount.Should().Be(1); + } + + [TestMethod] + [DataRow(false)] + [DataRow(true)] + public void ForcefulLifecycleCancellation_KillsChildrenWithoutOwningProcessExit( + bool cancelCooperativelyFirst) + { + int exitCount = 0; + using var cooperativeCancellation = new CancellationTokenSource(); + using var forcefulCancellation = new CancellationTokenSource(); + using var manager = new CtrlCCancellationManager( + onFirstCtrlC: () => { }, + exitAction: _ => Interlocked.Increment(ref exitCount), + subscribeToConsole: false, + cooperativeCancellationToken: cooperativeCancellation.Token, + forcefulCancellationToken: forcefulCancellation.Token); + using var process = CreateLongRunningProcess(); + try + { + manager.StartAndRegister(() => + { + process.Start(); + return process; + }).Should().BeSameAs(process); + + if (cancelCooperativelyFirst) + { + cooperativeCancellation.Cancel(); + process.HasExited.Should().BeFalse("cooperative cancellation must leave the child running"); + } + + forcefulCancellation.Cancel(); + + process.WaitForExit(TimeSpan.FromSeconds(10)).Should().BeTrue(); + exitCount.Should().Be(0, "ProcessLifecycle owns the host exit for forceful signals"); + } + finally + { + if (!process.HasExited) + { + try { process.Kill(entireProcessTree: true); } catch { } + } + } + } + [TestMethod] public void ThirdAndSubsequentCtrlC_AreNoOps() { @@ -71,7 +134,7 @@ public void ThirdAndSubsequentCtrlC_AreNoOps() } [TestMethod] - public void Register_AfterForcing_KillsTheProcessImmediately() + public void StartAndRegister_AfterForcing_DoesNotStartTheProcess() { int exitCount = 0; using var manager = new CtrlCCancellationManager( @@ -83,26 +146,20 @@ public void Register_AfterForcing_KillsTheProcessImmediately() manager.SimulateCtrlC(); exitCount.Should().Be(1); - using var process = StartLongRunningProcess(); - try + using var process = CreateLongRunningProcess(); + manager.StartAndRegister(() => { - manager.Register(process); + process.Start(); + return process; + }).Should().BeNull(); - // The manager should have killed the process immediately because we are in the Forcing state. - process.WaitForExit(TimeSpan.FromSeconds(10)).Should().BeTrue("Register after Forcing must kill the registered process"); - process.HasExited.Should().BeTrue(); - } - finally - { - if (!process.HasExited) - { - try { process.Kill(entireProcessTree: true); } catch { } - } - } + Action getProcessId = () => _ = process.Id; + getProcessId.Should().Throw( + "process startup must not race after forceful cancellation begins"); } [TestMethod] - public void Register_BeforeForcing_KillsTheProcessOnSecondCtrlC() + public void StartAndRegister_BeforeForcing_KillsTheProcessOnSecondCtrlC() { int exitCount = 0; using var manager = new CtrlCCancellationManager( @@ -110,10 +167,14 @@ public void Register_BeforeForcing_KillsTheProcessOnSecondCtrlC() exitAction: _ => Interlocked.Increment(ref exitCount), subscribeToConsole: false); - using var process = StartLongRunningProcess(); + using var process = CreateLongRunningProcess(); try { - manager.Register(process); + manager.StartAndRegister(() => + { + process.Start(); + return process; + }).Should().BeSameAs(process); manager.SimulateCtrlC(); process.HasExited.Should().BeFalse("first Ctrl+C must not kill registered processes"); @@ -140,10 +201,14 @@ public void Unregister_RemovesProcessFromForceKillSet() exitAction: _ => Interlocked.Increment(ref exitCount), subscribeToConsole: false); - using var process = StartLongRunningProcess(); + using var process = CreateLongRunningProcess(); try { - manager.Register(process); + manager.StartAndRegister(() => + { + process.Start(); + return process; + }).Should().BeSameAs(process); manager.Unregister(process); manager.SimulateCtrlC(); @@ -164,6 +229,57 @@ public void Unregister_RemovesProcessFromForceKillSet() } } + [TestMethod] + public async Task ForcefulCancellation_WaitsForStartupRegistrationAndKillsTheProcess() + { + int exitCount = 0; + using var manager = new CtrlCCancellationManager( + onFirstCtrlC: () => { }, + exitAction: _ => Interlocked.Increment(ref exitCount), + subscribeToConsole: false); + using var startEntered = new ManualResetEventSlim(); + using var allowStart = new ManualResetEventSlim(); + + Task startTask = Task.Run(() => manager.StartAndRegister(() => + { + startEntered.Set(); + allowStart.Wait(TestContext.CancellationToken); + return StartLongRunningProcess(); + }), TestContext.CancellationToken); + + startEntered.Wait(TestContext.CancellationToken); + Task forceTask = Task.Run(() => + { + manager.SimulateCtrlC(); + manager.SimulateCtrlC(); + }, TestContext.CancellationToken); + + bool forcefulCancellationStarted = SpinWait.SpinUntil( + () => manager.IsForcing, + TimeSpan.FromSeconds(10)); + allowStart.Set(); + forcefulCancellationStarted.Should().BeTrue( + "forceful cancellation should begin while process startup owns the registration lock"); + + Process? startedProcess = await startTask; + startedProcess.Should().NotBeNull(); + using Process process = startedProcess!; + try + { + await forceTask; + process.WaitForExit(TimeSpan.FromSeconds(10)).Should().BeTrue( + "forceful cancellation must include a process that starts during shutdown"); + exitCount.Should().Be(1); + } + finally + { + if (!process.HasExited) + { + try { process.Kill(entireProcessTree: true); } catch { } + } + } + } + [TestMethod] public void Dispose_IsIdempotent() { @@ -223,7 +339,7 @@ public void FirstCtrlC_AfterDispose_DoesNotThrowFromDisposedTokenSource() act.Should().NotThrow("a Ctrl+C arriving after Dispose must not surface as an unhandled exception"); } - private static Process StartLongRunningProcess() + private static Process CreateLongRunningProcess() { // Spawn a platform-appropriate long-running process so we have a real OS process to // register/kill in tests. The actual program is irrelevant — we only need a process tree @@ -246,7 +362,13 @@ private static Process StartLongRunningProcess() CreateNoWindow = true, }; - var process = Process.Start(psi) ?? throw new InvalidOperationException("Failed to start long-running helper process"); + return new Process { StartInfo = psi }; + } + + private static Process StartLongRunningProcess() + { + Process process = CreateLongRunningProcess(); + process.Start(); // Sanity-check that the helper is actually alive before handing it back. If it exited // immediately the assertions on HasExited downstream would silently produce false failures diff --git a/test/dotnet.Tests/CommandTests/Test/TerminalTestReporterTests.cs b/test/dotnet.Tests/CommandTests/Test/TerminalTestReporterTests.cs index 05ba1fb5bbfd..708a44c38aa5 100644 --- a/test/dotnet.Tests/CommandTests/Test/TerminalTestReporterTests.cs +++ b/test/dotnet.Tests/CommandTests/Test/TerminalTestReporterTests.cs @@ -14,6 +14,17 @@ namespace dotnet.Tests.CommandTests.Test; [TestClass] public class TerminalTestReporterTests { + [TestMethod] + [DataRow(TestExitCode.Success, true, TestExitCode.TestSessionAborted)] + [DataRow(TestExitCode.Success, false, TestExitCode.Success)] + [DataRow(TestExitCode.GenericFailure, true, TestExitCode.GenericFailure)] + public void GetExitCodeForReporting_UsesAbortedForCancelledSuccessfulRun( + int exitCode, + bool cancellationRequested, + int expectedExitCode) + => MicrosoftTestingPlatformTestCommand.GetExitCodeForReporting(exitCode, cancellationRequested) + .Should().Be(expectedExitCode); + [TestMethod] public void AnsiTerminal_StopUpdate_WritesStringBuilder() { diff --git a/test/dotnet.Tests/CommandTests/Test/VSTestArtifactDirectoryDiscoveryTests.cs b/test/dotnet.Tests/CommandTests/Test/VSTestArtifactDirectoryDiscoveryTests.cs index ee74ec867370..df29271d56f7 100644 --- a/test/dotnet.Tests/CommandTests/Test/VSTestArtifactDirectoryDiscoveryTests.cs +++ b/test/dotnet.Tests/CommandTests/Test/VSTestArtifactDirectoryDiscoveryTests.cs @@ -99,7 +99,8 @@ public void ItSkipsPostProcessingWithoutStartingVSTestWhenThereAreNoArtifacts() int exitCode = TestCommand.RunArtifactPostProcessingIfNeeded( NewCorrelationId(), diag: null, - FeatureFlag.Instance); + FeatureFlag.Instance, + CancellationToken.None); exitCode.Should().Be(0); } diff --git a/test/dotnet.Tests/CommandTests/Tool/Install/InstallToolParserTests.cs b/test/dotnet.Tests/CommandTests/Tool/Install/InstallToolParserTests.cs index 0e7bcf534acd..8f10b8b83f23 100644 --- a/test/dotnet.Tests/CommandTests/Tool/Install/InstallToolParserTests.cs +++ b/test/dotnet.Tests/CommandTests/Tool/Install/InstallToolParserTests.cs @@ -176,7 +176,7 @@ public void InstallToolWithBothAtVersionAndVersionOptionThrowsError() var toolInstallCommand = new Cli.Commands.Tool.Install.ToolInstallCommand(result); - Action a = () => toolInstallCommand.Execute(); + Action a = () => toolInstallCommand.Execute(CancellationToken.None); a.Should().Throw().And.Message .Should().Contain(Cli.CliStrings.PackageIdentityArgumentVersionOptionConflict); diff --git a/test/dotnet.Tests/CommandTests/Tool/Install/ToolInstallCommandTests.cs b/test/dotnet.Tests/CommandTests/Tool/Install/ToolInstallCommandTests.cs index d9449fb8d6e3..5ed94b69c699 100644 --- a/test/dotnet.Tests/CommandTests/Tool/Install/ToolInstallCommandTests.cs +++ b/test/dotnet.Tests/CommandTests/Tool/Install/ToolInstallCommandTests.cs @@ -26,7 +26,7 @@ public void WhenRunWithBothGlobalAndToolPathShowErrorMessage() var toolInstallCommand = new ToolInstallCommand( parseResult); - Action a = () => toolInstallCommand.Execute(); + Action a = () => toolInstallCommand.Execute(CancellationToken.None); a.Should().Throw().And.Message .Should().Contain(string.Format( @@ -47,14 +47,14 @@ public void WhenRunWithRoot() new DotnetNewCommand(Log, "tool-manifest").WithCustomHive("/tmp/folder").WithWorkingDirectory("/tmp/folder").Execute().Should().Pass(); var parseResult = Parser.Parse("tool install dotnetsay"); - new ToolInstallLocalCommand(parseResult, runtimeJsonPathForTests: ridGraphPath).Execute().Should().Be(0); + new ToolInstallLocalCommand(parseResult, runtimeJsonPathForTests: ridGraphPath).Execute(CancellationToken.None).Should().Be(0); Directory.SetCurrentDirectory("/tmp/folder/sub"); new DotnetNewCommand(Log, "tool-manifest").WithCustomHive("/tmp/folder/sub").WithWorkingDirectory("/tmp/folder/sub").Execute().Should().Pass(); parseResult = Parser.Parse("tool install dotnetsay"); - new ToolInstallLocalCommand(parseResult, runtimeJsonPathForTests: ridGraphPath).Execute().Should().Be(0); + new ToolInstallLocalCommand(parseResult, runtimeJsonPathForTests: ridGraphPath).Execute(CancellationToken.None).Should().Be(0); - new ToolRunCommand(Parser.Parse($"tool run dotnetsay")).Execute().Should().Be(0); + new ToolRunCommand(Parser.Parse($"tool run dotnetsay")).Execute(CancellationToken.None).Should().Be(0); } finally { @@ -71,7 +71,7 @@ public void WhenRunWithBothGlobalAndLocalShowErrorMessage() var toolInstallCommand = new ToolInstallCommand( parseResult); - Action a = () => toolInstallCommand.Execute(); + Action a = () => toolInstallCommand.Execute(CancellationToken.None); a.Should().Throw().And.Message .Should().Contain( @@ -88,7 +88,7 @@ public void WhenRunWithGlobalAndToolManifestShowErrorMessage() var toolInstallCommand = new ToolInstallCommand( parseResult); - Action a = () => toolInstallCommand.Execute(); + Action a = () => toolInstallCommand.Execute(CancellationToken.None); a.Should().Throw().And.Message .Should().Contain(CliCommandStrings.OnlyLocalOptionSupportManifestFileOption); @@ -106,7 +106,7 @@ public void WhenRunWithToolPathAndToolManifestShowErrorMessage() var toolInstallCommand = new ToolInstallCommand( parseResult); - Action a = () => toolInstallCommand.Execute(); + Action a = () => toolInstallCommand.Execute(CancellationToken.None); a.Should().Throw().And.Message .Should().Contain(CliCommandStrings.OnlyLocalOptionSupportManifestFileOption); @@ -124,7 +124,7 @@ public void WhenRunWithLocalAndFrameworkShowErrorMessage() var toolInstallCommand = new ToolInstallCommand( parseResult); - Action a = () => toolInstallCommand.Execute(); + Action a = () => toolInstallCommand.Execute(CancellationToken.None); a.Should().Throw().And.Message .Should().Contain(CliCommandStrings.LocalOptionDoesNotSupportFrameworkOption); diff --git a/test/dotnet.Tests/CommandTests/Tool/Install/ToolInstallGlobalOrToolPathCommandTests.cs b/test/dotnet.Tests/CommandTests/Tool/Install/ToolInstallGlobalOrToolPathCommandTests.cs index 4c5314a920d5..ec2dfb78da43 100644 --- a/test/dotnet.Tests/CommandTests/Tool/Install/ToolInstallGlobalOrToolPathCommandTests.cs +++ b/test/dotnet.Tests/CommandTests/Tool/Install/ToolInstallGlobalOrToolPathCommandTests.cs @@ -106,7 +106,7 @@ public void WhenPassingIgnoreFailedSourcesItShouldNotThrow() new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim, true), _reporter); - toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0); + toolInstallGlobalOrToolPathCommand.Execute(CancellationToken.None).Should().Be(0); _fileSystem.File.Delete(Path.Combine(_temporaryDirectory, "nuget.config")); } @@ -143,7 +143,7 @@ public void WhenRunWithPackageIdItShouldCreateValidShim() _environmentPathInstructionMock, _reporter); - toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0); + toolInstallGlobalOrToolPathCommand.Execute(CancellationToken.None).Should().Be(0); // It is hard to simulate shell behavior. Only Assert shim can point to executable dll _fileSystem.File.Exists(ExpectedCommandPath()).Should().BeTrue(); @@ -167,7 +167,7 @@ public void WhenRunFromToolInstallRedirectCommandWithPackageIdItShouldCreateVali _parseResult, toolInstallGlobalOrToolPathCommand); - toolInstallCommand.Execute().Should().Be(0); + toolInstallCommand.Execute(CancellationToken.None).Should().Be(0); _fileSystem.File.Exists(ExpectedCommandPath()).Should().BeTrue(); } @@ -188,7 +188,7 @@ public void WhenRunWithSourceItShouldFindOnlyTheProvidedSource() _reporter); // Should not find the package because it is in the wrong feed - var ex = Assert.ThrowsExactly(() => toolInstallGlobalOrToolPathCommand.Execute()); + var ex = Assert.ThrowsExactly(() => toolInstallGlobalOrToolPathCommand.Execute(CancellationToken.None)); ex.Message.Should().Contain(PackageId); } @@ -205,7 +205,7 @@ public void WhenRunWithPackageIdWithSourceItShouldCreateValidShim() _environmentPathInstructionMock, _reporter); - toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0); + toolInstallGlobalOrToolPathCommand.Execute(CancellationToken.None).Should().Be(0); // It is hard to simulate shell behavior. Only Assert shim can point to executable dll _fileSystem.File.Exists(ExpectedCommandPath()) @@ -226,7 +226,7 @@ public void WhenRunWithPackageIdItShouldShowPathInstruction() _environmentPathInstructionMock, _reporter); - toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0); + toolInstallGlobalOrToolPathCommand.Execute(CancellationToken.None).Should().Be(0); _reporter.Lines.First().Should().Be(EnvironmentPathInstructionMock.MockInstructionText); } @@ -249,7 +249,7 @@ public void WhenRunWithPackageIdPackageFormatIsNotFullySupportedItShouldShowPath _environmentPathInstructionMock, _reporter); - toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0); + toolInstallGlobalOrToolPathCommand.Execute(CancellationToken.None).Should().Be(0); _reporter.Lines.First().Should().Be(CliStrings.FormatVersionIsHigher.Yellow()); _reporter.Lines.Skip(1).First().Should().Be(EnvironmentPathInstructionMock.MockInstructionText); @@ -269,7 +269,7 @@ public void GivenFailedPackageInstallWhenRunWithPackageIdItShouldFail() _environmentPathInstructionMock, _reporter); - Action a = () => toolInstallGlobalOrToolPathCommand.Execute(); + Action a = () => toolInstallGlobalOrToolPathCommand.Execute(CancellationToken.None); a.Should().Throw().And.Message .Should().Contain(ErrorMessage); @@ -289,7 +289,7 @@ public void GivenCreateShimItShouldHaveNoBrokenFolderOnDisk() _environmentPathInstructionMock, _reporter); - Action a = () => toolInstallGlobalOrToolPathCommand.Execute(); + Action a = () => toolInstallGlobalOrToolPathCommand.Execute(CancellationToken.None); a.Should().Throw().And.Message .Should().Contain(string.Format( @@ -316,9 +316,13 @@ public async Task GivenShimCreationFailureAnotherInstallWaitsForRollbackBeforeRe new EnvironmentPathInstructionMock(new BufferedReporter(), _pathToPlaceShim, true), new BufferedReporter()); - Task firstInstall = Task.Run(firstCommand.Execute, TestContext.CancellationToken); + Task firstInstall = Task.Run( + () => firstCommand.Execute(TestContext.CancellationToken), + TestContext.CancellationToken); await blockingShellShimRepository.CreateStarted; - Task secondInstall = Task.Run(secondCommand.Execute, TestContext.CancellationToken); + Task secondInstall = Task.Run( + () => secondCommand.Execute(TestContext.CancellationToken), + TestContext.CancellationToken); Task firstCompleted = await Task.WhenAny( secondInstall, @@ -348,7 +352,7 @@ public void GivenInCorrectToolConfigurationWhenRunWithPackageIdItShouldFail() _environmentPathInstructionMock, _reporter); - Action a = () => toolInstallGlobalOrToolPathCommand.Execute(); + Action a = () => toolInstallGlobalOrToolPathCommand.Execute(CancellationToken.None); a.Should().Throw().And.Message .Should().Contain( @@ -369,7 +373,7 @@ public void WhenRunWithPackageIdItShouldShowSuccessMessage() new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim, true), _reporter); - toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0); + toolInstallGlobalOrToolPathCommand.Execute(CancellationToken.None).Should().Be(0); _reporter .Lines @@ -392,7 +396,7 @@ public void WhenRunWithPackageIdWithQuietItShouldShowNoSuccessMessage() new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim, true), _reporter); - toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0); + toolInstallGlobalOrToolPathCommand.Execute(CancellationToken.None).Should().Be(0); _reporter .Lines @@ -417,7 +421,7 @@ public void WhenRunWithInvalidVersionItShouldThrow() new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim, true), _reporter); - Action action = () => toolInstallGlobalOrToolPathCommand.Execute(); + Action action = () => toolInstallGlobalOrToolPathCommand.Execute(CancellationToken.None); action .Should().Throw() @@ -438,7 +442,7 @@ public void WhenRunWithExactVersionItShouldSucceed() new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim, true), _reporter); - toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0); + toolInstallGlobalOrToolPathCommand.Execute(CancellationToken.None).Should().Be(0); _reporter .Lines @@ -462,7 +466,7 @@ public void WhenInstallTheSpecificSameVersionTwiceItShouldNoop() new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim, true), _reporter); - toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0); + toolInstallGlobalOrToolPathCommand.Execute(CancellationToken.None).Should().Be(0); _reporter .Lines @@ -474,7 +478,7 @@ public void WhenInstallTheSpecificSameVersionTwiceItShouldNoop() PackageVersion).Green()); _reporter.Clear(); - toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0); + toolInstallGlobalOrToolPathCommand.Execute(CancellationToken.None).Should().Be(0); _reporter.Lines.Should().Equal(string.Format(CliCommandStrings.ToolAlreadyInstalled, PackageId, PackageVersion).Green()); } @@ -490,7 +494,7 @@ public async Task WhenVersionCheckIsCanceledItShouldStop() new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim, true), _reporter); - command.Execute().Should().Be(0); + command.Execute(TestContext.CancellationToken).Should().Be(0); Func execute = () => command.ExecuteAsync(new CancellationToken(canceled: true)); @@ -511,7 +515,7 @@ public void WhenInstallWithHigherVersionItShouldUpdate() new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim, true), _reporter); - toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0); + toolInstallGlobalOrToolPathCommand.Execute(CancellationToken.None).Should().Be(0); _reporter .Lines @@ -532,7 +536,7 @@ public void WhenInstallWithHigherVersionItShouldUpdate() new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim, true), _reporter); - toolInstallGlobalOrToolPathCommand2.Execute().Should().Be(0); + toolInstallGlobalOrToolPathCommand2.Execute(CancellationToken.None).Should().Be(0); _reporter .Lines @@ -558,7 +562,7 @@ public void WhenInstallWithLowerVersionWithAllowDowngradeOptionItShouldDowngrade new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim, true), _reporter); - toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0); + toolInstallGlobalOrToolPathCommand.Execute(CancellationToken.None).Should().Be(0); _reporter .Lines @@ -579,7 +583,7 @@ public void WhenInstallWithLowerVersionWithAllowDowngradeOptionItShouldDowngrade new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim, true), _reporter); - toolInstallGlobalOrToolPathCommand2.Execute().Should().Be(0); + toolInstallGlobalOrToolPathCommand2.Execute(CancellationToken.None).Should().Be(0); _reporter .Lines @@ -605,7 +609,7 @@ public void WhenInstallWithLowerVersionItShouldFail() new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim, true), _reporter); - toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0); + toolInstallGlobalOrToolPathCommand.Execute(CancellationToken.None).Should().Be(0); _reporter .Lines @@ -626,7 +630,7 @@ public void WhenInstallWithLowerVersionItShouldFail() new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim, true), _reporter); - Action a = () => toolInstallGlobalOrToolPathCommand2.Execute(); + Action a = () => toolInstallGlobalOrToolPathCommand2.Execute(CancellationToken.None); a.Should().Throw(); } @@ -642,7 +646,7 @@ public void WhenRunWithValidVersionRangeItShouldSucceed() new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim, true), _reporter); - toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0); + toolInstallGlobalOrToolPathCommand.Execute(CancellationToken.None).Should().Be(0); _reporter .Lines @@ -678,7 +682,7 @@ public void WhenRunWithValidVersionItShouldInterpretAsNuGetExactVersion(string v currentWorkingDirectory: testDir, verifySignatures: false); - toolInstallCommand.Execute().Should().Be(0); + toolInstallCommand.Execute(CancellationToken.None).Should().Be(0); // Uninstall the unlisted package var toolUninstallCommand = new ToolUninstallGlobalOrToolPathCommand(Parser.Parse("dotnet tool uninstall -g " + UnlistedPackageId), @@ -690,7 +694,7 @@ public void WhenRunWithValidVersionItShouldInterpretAsNuGetExactVersion(string v fileSystem: _fileSystem, appHostShellShimMaker: new AppHostShellShimMakerMock(_fileSystem), filePermissionSetter: new NoOpFilePermissionSetter())); - toolUninstallCommand.Execute().Should().Be(0); + toolUninstallCommand.Execute(CancellationToken.None).Should().Be(0); } [TestMethod] @@ -719,7 +723,7 @@ public void WhenRunWithPrereleaseItShouldSucceed() _environmentPathInstructionMock, _reporter); - toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0); + toolInstallGlobalOrToolPathCommand.Execute(CancellationToken.None).Should().Be(0); _reporter .Lines @@ -745,7 +749,7 @@ public void WhenRunWithPrereleaseAndPackageVersionItShouldThrow() _environmentPathInstructionMock, _reporter); - Action a = () => toolInstallGlobalOrToolPathCommand.Execute(); + Action a = () => toolInstallGlobalOrToolPathCommand.Execute(CancellationToken.None); a.Should().Throw(); } @@ -821,7 +825,7 @@ public void WhenRunWithoutAMatchingRangeItShouldFail() new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim, true), _reporter); - Action a = () => toolInstallGlobalOrToolPathCommand.Execute(); + Action a = () => toolInstallGlobalOrToolPathCommand.Execute(CancellationToken.None); a.Should().Throw().And.Message .Should().Contain(string.Format(CliStrings.IsNotFoundInNuGetFeeds, $"Version 5.0 of {PackageId}", "{MockFeeds}")); @@ -841,7 +845,7 @@ public void WhenRunWithValidVersionWildcardItShouldSucceed() new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim, true), _reporter); - toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0); + toolInstallGlobalOrToolPathCommand.Execute(CancellationToken.None).Should().Be(0); _reporter .Lines @@ -865,7 +869,7 @@ public void WhenRunWithPackageIdAndBinPathItShouldNoteHaveEnvironmentPathInstruc new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim), _reporter); - toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0); + toolInstallGlobalOrToolPathCommand.Execute(CancellationToken.None).Should().Be(0); _reporter.Lines.Should().NotContain(l => l.Contains(EnvironmentPathInstructionMock.MockInstructionText)); } @@ -880,7 +884,7 @@ public void WhenInstallItDoesNotSkipNuGetPackageVerfication() environmentPathInstruction: new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim, true), reporter: _reporter); - toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0); + toolInstallGlobalOrToolPathCommand.Execute(CancellationToken.None).Should().Be(0); _reporter.Lines.Should().NotContain(l => l.Contains(CliStrings.NuGetPackageSignatureVerificationSkipped)); } @@ -913,7 +917,7 @@ public void AndPackagedShimIsProvidedWhenRunWithPackageIdItCreateShimUsingPackag new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim), _reporter); - installCommand.Execute().Should().Be(0); + installCommand.Execute(CancellationToken.None).Should().Be(0); _fileSystem.File.ReadAllText(ExpectedCommandPath()).Should().Be(tokenToIdentifyPackagedShim); } @@ -930,7 +934,7 @@ public void WhenRunWithArchOptionItErrorsOnInvalidRids() _environmentPathInstructionMock, _reporter); - var exceptionThrown = Assert.ThrowsExactly(() => toolInstallGlobalOrToolPathCommand.Execute()); + var exceptionThrown = Assert.ThrowsExactly(() => toolInstallGlobalOrToolPathCommand.Execute(CancellationToken.None)); exceptionThrown.Message.Should().Contain("-invalid is invalid"); } @@ -948,7 +952,7 @@ public void WhenRunWithArchOptionItDownloadsAppHostTemplate() _reporter, nugetPackageDownloader); - toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0); + toolInstallGlobalOrToolPathCommand.Execute(CancellationToken.None).Should().Be(0); nugetPackageDownloader.DownloadCallParams.Count.Should().Be(1); nugetPackageDownloader.ExtractCallParams.Count.Should().Be(1); nugetPackageDownloader.DownloadCallParams.First().Item1.Should().Be(new PackageId("microsoft.netcore.app.host.win-arm64")); @@ -1036,11 +1040,11 @@ private string ExpectedCommandPath() internal class NoOpFilePermissionSetter : IFilePermissionSetter { - public void SetUserExecutionPermission(string path) + public void SetUserExecutionPermission(string path, CancellationToken cancellationToken) { } - public void SetPermission(string path, string chmodArgument) + public void SetPermission(string path, string chmodArgument, CancellationToken cancellationToken) { } } @@ -1053,10 +1057,13 @@ private sealed class BlockingFailingShellShimRepository : IShellShimRepository, public Task CreateStarted => _createStarted.Task; - public void CreateShim(ToolCommand toolCommand, IReadOnlyList packagedShims = null) + public void CreateShim( + ToolCommand toolCommand, + CancellationToken cancellationToken, + IReadOnlyList packagedShims = null) { _createStarted.TrySetResult(); - _continue.Wait(); + _continue.Wait(cancellationToken); throw new ShellShimException("Simulated shim creation failure."); } diff --git a/test/dotnet.Tests/CommandTests/Tool/Install/ToolInstallLocalCommandTests.cs b/test/dotnet.Tests/CommandTests/Tool/Install/ToolInstallLocalCommandTests.cs index 67cccc87a6cc..513bcaa5f09a 100644 --- a/test/dotnet.Tests/CommandTests/Tool/Install/ToolInstallLocalCommandTests.cs +++ b/test/dotnet.Tests/CommandTests/Tool/Install/ToolInstallLocalCommandTests.cs @@ -112,7 +112,7 @@ public void WhenPassingIgnoreFailedSourcesItShouldNotThrow() _localToolsResolverCache, _reporter); - toolInstallCommand.Execute().Should().Be(0); + toolInstallCommand.Execute(CancellationToken.None).Should().Be(0); _fileSystem.File.Delete(Path.Combine(_temporaryDirectory, "nuget.config")); } @@ -122,7 +122,7 @@ public void WhenRunWithPackageIdItShouldSaveToCacheAndAddToManifestFile() { var toolInstallLocalCommand = GetDefaultTestToolInstallLocalCommand(); - toolInstallLocalCommand.Execute().Should().Be(0); + toolInstallLocalCommand.Execute(CancellationToken.None).Should().Be(0); AssertDefaultInstallSuccess(); } @@ -143,7 +143,7 @@ public void GivenCreateManifestIfNeededWithoutArgumentTheDefaultIsTrueForLegacyB _localToolsResolverCache, _reporter); - toolInstallLocalCommand.Execute().Should().Be(0); + toolInstallLocalCommand.Execute(CancellationToken.None).Should().Be(0); } [TestMethod] @@ -162,7 +162,7 @@ public void GivenNoManifestFileItShouldThrowAndContainNoManifestGuide() _localToolsResolverCache, _reporter); - Action a = () => toolInstallLocalCommand.Execute(); + Action a = () => toolInstallLocalCommand.Execute(CancellationToken.None); a.Should().Throw() .And.Message.Should() @@ -189,7 +189,7 @@ public void WhenRunWithExplicitManifestFileItShouldAddEntryToExplicitManifestFil _localToolsResolverCache, _reporter); - installLocalCommand.Execute().Should().Be(0); + installLocalCommand.Execute(CancellationToken.None).Should().Be(0); _toolManifestFinder.Find(new FilePath(explicitManifestFilePath)).Should().HaveCount(1); } @@ -208,7 +208,7 @@ public void WhenRunWithRollForwardItShouldRollForwardToTrueInManifestFile() _localToolsResolverCache, _reporter); - installLocalCommand.Execute().Should().Be(0); + installLocalCommand.Execute(CancellationToken.None).Should().Be(0); _fileSystem.File.ReadAllText(_manifestFilePath).Should() .Contain("\"rollForward\": true"); } @@ -228,7 +228,7 @@ public void WhenRunWithoutRollForwardItShouldDefaultRollForwardToFalseInManifest _localToolsResolverCache, _reporter); - installLocalCommand.Execute().Should().Be(0); + installLocalCommand.Execute(CancellationToken.None).Should().Be(0); _fileSystem.File.ReadAllText(_manifestFilePath).Should() .Contain("\"rollForward\": false"); } @@ -242,7 +242,7 @@ public void WhenRunFromToolInstallRedirectCommandWithPackageIdItShouldSaveToCach _parseResult, toolInstallLocalCommand: toolInstallLocalCommand); - toolInstallCommand.Execute().Should().Be(0); + toolInstallCommand.Execute(CancellationToken.None).Should().Be(0); AssertDefaultInstallSuccess(); } @@ -251,7 +251,7 @@ public void WhenRunWithPackageIdItShouldShowSuccessMessage() { var toolInstallLocalCommand = GetDefaultTestToolInstallLocalCommand(); - toolInstallLocalCommand.Execute().Should().Be(0); + toolInstallLocalCommand.Execute(CancellationToken.None).Should().Be(0); _reporter.Lines[0].Should() .Contain( @@ -275,7 +275,7 @@ public void GivenFailedPackageInstallWhenRunWithPackageIdItShouldNotChangeManife _localToolsResolverCache, _reporter); - Action a = () => installLocalCommand.Execute(); + Action a = () => installLocalCommand.Execute(CancellationToken.None); a.Should().Throw() .And.Message.Should() .Contain(CliCommandStrings.ToolInstallationRestoreFailed); @@ -295,7 +295,7 @@ public void GivenManifestFileConflictItShouldNotAddToCache() var toolInstallLocalCommand = GetDefaultTestToolInstallLocalCommand(); - Action a = () => toolInstallLocalCommand.Execute(); + Action a = () => toolInstallLocalCommand.Execute(CancellationToken.None); a.Should().Throw(); _localToolsResolverCache.TryLoad(new RestoredCommandIdentifier( @@ -321,7 +321,7 @@ public void WhenRunWithExistingManifestInConfigDirectoryItShouldAddToExistingMan var toolInstallLocalCommand = GetDefaultTestToolInstallLocalCommand(); - toolInstallLocalCommand.Execute().Should().Be(0); + toolInstallLocalCommand.Execute(CancellationToken.None).Should().Be(0); // Verify the tool was added to the existing .config manifest var manifestPackages = _toolManifestFinder.Find(); @@ -363,7 +363,7 @@ public void WhenRunWithExactVersionItShouldSucceed() _localToolsResolverCache, _reporter); - installLocalCommand.Execute().Should().Be(0); + installLocalCommand.Execute(CancellationToken.None).Should().Be(0); AssertDefaultInstallSuccess(); } @@ -381,7 +381,7 @@ public void WhenRunWithValidVersionRangeItShouldSucceed() _localToolsResolverCache, _reporter); - installLocalCommand.Execute().Should().Be(0); + installLocalCommand.Execute(CancellationToken.None).Should().Be(0); AssertDefaultInstallSuccess(); } @@ -399,7 +399,7 @@ public void WhenRunWithPrereleaseAndPackageVersionItShouldSucceed() _localToolsResolverCache, _reporter); - installLocalCommand.Execute().Should().Be(0); + installLocalCommand.Execute(CancellationToken.None).Should().Be(0); var manifestPackages = _toolManifestFinder.Find(); manifestPackages.Should().HaveCount(1); var addedPackage = manifestPackages.Single(); @@ -435,7 +435,7 @@ public void GivenNoManifestFileAndCreateManifestIfNeededFlagItShouldCreateManife _localToolsResolverCache, _reporter); - installLocalCommand.Execute().Should().Be(0); + installLocalCommand.Execute(CancellationToken.None).Should().Be(0); _fileSystem.File.Exists(Path.Combine(_temporaryDirectory, "dotnet-tools.json")).Should().BeTrue(); } @@ -456,7 +456,7 @@ public void GivenNoManifestFileItUsesCreateManifestIfNeededByDefault() _localToolsResolverCache, _reporter); - installLocalCommand.Execute().Should().Be(0); + installLocalCommand.Execute(CancellationToken.None).Should().Be(0); _fileSystem.File.Exists(Path.Combine(_temporaryDirectory, "dotnet-tools.json")).Should().BeTrue(); } @@ -480,7 +480,7 @@ public void GivenNoManifestFileAndCreateManifestIfNeededFlagItShouldCreateManife _localToolsResolverCache, _reporter); - installLocalCommand.Execute().Should().Be(0); + installLocalCommand.Execute(CancellationToken.None).Should().Be(0); _fileSystem.File.Exists(Path.Combine(_temporaryDirectory, "dotnet-tools.json")).Should().BeTrue(); } @@ -501,7 +501,7 @@ public void GivenNoManifestFileAndCreateManifestIfNeededFlagItShouldCreateManife _localToolsResolverCache, _reporter); - installLocalCommand.Execute().Should().Be(0); + installLocalCommand.Execute(CancellationToken.None).Should().Be(0); _fileSystem.File.Exists(Path.Combine(_temporaryDirectory, "dotnet-tools.json")).Should().BeTrue(); } diff --git a/test/dotnet.Tests/CommandTests/Tool/List/ToolListCommandTests.cs b/test/dotnet.Tests/CommandTests/Tool/List/ToolListCommandTests.cs index 7985c58b5dab..ffb9ca9f9c8c 100644 --- a/test/dotnet.Tests/CommandTests/Tool/List/ToolListCommandTests.cs +++ b/test/dotnet.Tests/CommandTests/Tool/List/ToolListCommandTests.cs @@ -19,7 +19,7 @@ public void WhenRunWithBothGlobalAndToolPathShowErrorMessage() var toolInstallCommand = new ToolListCommand( result); - Action a = () => toolInstallCommand.Execute(); + Action a = () => toolInstallCommand.Execute(CancellationToken.None); a.Should().Throw().And.Message .Should().Contain(string.Format( @@ -35,7 +35,7 @@ public void WhenRunWithBothGlobalAndLocalShowErrorMessage() var toolInstallCommand = new ToolListCommand( result); - Action a = () => toolInstallCommand.Execute(); + Action a = () => toolInstallCommand.Execute(CancellationToken.None); a.Should().Throw().And.Message .Should().Contain( diff --git a/test/dotnet.Tests/CommandTests/Tool/List/ToolListGlobalOrToolPathCommandTests.cs b/test/dotnet.Tests/CommandTests/Tool/List/ToolListGlobalOrToolPathCommandTests.cs index 15e5a328b165..6193bf5810c3 100644 --- a/test/dotnet.Tests/CommandTests/Tool/List/ToolListGlobalOrToolPathCommandTests.cs +++ b/test/dotnet.Tests/CommandTests/Tool/List/ToolListGlobalOrToolPathCommandTests.cs @@ -36,7 +36,7 @@ public void GivenNoInstalledPackagesItPrintsEmptyTable() var command = CreateCommand(store.Object, "-g"); - command.Execute().Should().Be(0); + command.Execute(CancellationToken.None).Should().Be(0); _reporter.Lines.Should().Equal(EnumerateExpectedTableLines(store.Object)); } @@ -52,7 +52,7 @@ public void GivenAnInvalidToolPathItThrowsException() var toolPath = "tool-path-does-not-exist"; var command = CreateCommand(store.Object, $"--tool-path {toolPath}", toolPath); - Action a = () => command.Execute(); + Action a = () => command.Execute(CancellationToken.None); a.Should().Throw() .And @@ -72,7 +72,7 @@ public void GivenAToolPathItPassesToolPathToStoreFactory() var toolPath = Path.GetTempPath(); var command = CreateCommand(store.Object, $"--tool-path {toolPath}", toolPath); - command.Execute().Should().Be(0); + command.Execute(CancellationToken.None).Should().Be(0); _reporter.Lines.Should().Equal(EnumerateExpectedTableLines(store.Object)); } @@ -100,7 +100,7 @@ public void GivenAToolPathItPassesToolPathToStoreFactoryFromRedirectCommand() result, toolListGlobalOrToolPathCommand); - toolListCommand.Execute().Should().Be(0); + toolListCommand.Execute(CancellationToken.None).Should().Be(0); _reporter.Lines.Should().Equal(EnumerateExpectedTableLines(store.Object)); } @@ -121,7 +121,7 @@ public void GivenASingleInstalledPackageItPrintsThePackage() var command = CreateCommand(store.Object, "-g"); - command.Execute().Should().Be(0); + command.Execute(CancellationToken.None).Should().Be(0); _reporter.Lines.Should().Equal(EnumerateExpectedTableLines(store.Object)); } @@ -152,7 +152,7 @@ public void GivenMultipleInstalledPackagesItPrintsThePackages() var command = CreateCommand(store.Object, "-g"); - command.Execute().Should().Be(0); + command.Execute(CancellationToken.None).Should().Be(0); _reporter.Lines.Should().Equal(EnumerateExpectedTableLines(store.Object)); } @@ -179,7 +179,7 @@ public void GivenMultipleInstalledPackagesItPrintsThePackagesForJsonFormat() var command = CreateCommand(store.Object, "-g --format json"); - command.Execute().Should().Be(0); + command.Execute(CancellationToken.None).Should().Be(0); _reporter.Lines.Count.Should().Be(1); @@ -213,7 +213,7 @@ public void GivenAPackageWithMultipleCommandsItListsThem() var command = CreateCommand(store.Object, "-g"); - command.Execute().Should().Be(0); + command.Execute(CancellationToken.None).Should().Be(0); _reporter.Lines.Should().Equal(EnumerateExpectedTableLines(store.Object)); } @@ -240,7 +240,7 @@ public void GivenABrokenPackageItPrintsWarning() var command = CreateCommand(store.Object, "-g"); - command.Execute().Should().Be(0); + command.Execute(CancellationToken.None).Should().Be(0); _reporter.Lines.Should().Equal( EnumerateExpectedTableLines(store.Object).Prepend( @@ -286,7 +286,7 @@ public void GivenPackageIdArgItPrintsThatPackage() var command = CreateCommand(store.Object, "test.tool -g"); - command.Execute().Should().Be(0); + command.Execute(CancellationToken.None).Should().Be(0); _reporter.Lines.Should().Equal(EnumerateExpectedTableLines(store.Object, new PackageId("test.tool"))); } @@ -307,7 +307,7 @@ public void GivenNotInstalledPackageItPrintsEmpty() var command = CreateCommand(store.Object, "not-installed-package -g"); - command.Execute().Should().Be(1); + command.Execute(CancellationToken.None).Should().Be(1); _reporter.Lines.Should().Equal(EnumerateExpectedTableLines(store.Object, new PackageId("not-installed-package"))); } diff --git a/test/dotnet.Tests/CommandTests/Tool/List/ToolListLocalCommandTests.cs b/test/dotnet.Tests/CommandTests/Tool/List/ToolListLocalCommandTests.cs index a454d10d7ff9..756b754037ea 100644 --- a/test/dotnet.Tests/CommandTests/Tool/List/ToolListLocalCommandTests.cs +++ b/test/dotnet.Tests/CommandTests/Tool/List/ToolListLocalCommandTests.cs @@ -58,7 +58,7 @@ public ToolListLocalCommandTests() [TestMethod] public void GivenManifestInspectorItPrintsTheTable() { - _defaultToolListLocalCommand.Execute(); + _defaultToolListLocalCommand.Execute(CancellationToken.None); _reporter.Lines.Count.Should().Be(4); _reporter.Lines.Should().Contain(l => l.Contains("package.id")); _reporter.Lines.Should().Contain(l => l.Contains("2.1.4")); @@ -76,7 +76,7 @@ public void GivenManifestInspectorItPrintsJson() new ToolListLocalCommand( Parser.Parse("dotnet tool list --format json"), _toolManifestInspector, - _reporter).Execute(); + _reporter).Execute(CancellationToken.None); _reporter.Lines.Count.Should().Be(1); var versionedData = JsonSerializer.Deserialize>(_reporter.Lines[0]); @@ -100,7 +100,7 @@ public void GivenManifestInspectorWhenCalledFromRedirectCommandItPrintsTheTable( { var command = new ToolListCommand(result: _parseResult, toolListLocalCommand: _defaultToolListLocalCommand); - _defaultToolListLocalCommand.Execute(); + _defaultToolListLocalCommand.Execute(CancellationToken.None); _reporter.Lines.Count.Should().Be(4); _reporter.Lines.Should().Contain(l => l.Contains("package.id")); _reporter.Lines.Should().Contain(l => l.Contains("2.1.4")); @@ -115,7 +115,7 @@ public void GivenManifestInspectorWhenCalledFromRedirectCommandItPrintsTheTable( [TestMethod] public void GivenPackageIdArgumentItPrintsTheCorrectPackageInfo() { - CreateCommandWithArg("package.id").Execute().Should().Be(0); + CreateCommandWithArg("package.id").Execute(CancellationToken.None).Should().Be(0); _reporter.Lines.Count.Should().Be(3); _reporter.Lines.Should().Contain(l => l.Contains("package.id")); _reporter.Lines.Should().Contain(l => l.Contains("2.1.4")); @@ -126,7 +126,7 @@ public void GivenPackageIdArgumentItPrintsTheCorrectPackageInfo() [TestMethod] public void GivenNotInstalledPackageItPrintsEmpty() { - CreateCommandWithArg("not-installed-package").Execute().Should().Be(1); + CreateCommandWithArg("not-installed-package").Execute(CancellationToken.None).Should().Be(1); _reporter.Lines.Count.Should().Be(2); } diff --git a/test/dotnet.Tests/CommandTests/Tool/Restore/ToolRestoreCommandTests.cs b/test/dotnet.Tests/CommandTests/Tool/Restore/ToolRestoreCommandTests.cs index bf549feff05d..43cfeadca912 100644 --- a/test/dotnet.Tests/CommandTests/Tool/Restore/ToolRestoreCommandTests.cs +++ b/test/dotnet.Tests/CommandTests/Tool/Restore/ToolRestoreCommandTests.cs @@ -133,7 +133,7 @@ public void WhenRunItCanSaveCommandsToCache() _reporter ); - toolRestoreCommand.Execute().Should().Be(0); + toolRestoreCommand.Execute(CancellationToken.None).Should().Be(0); _localToolsResolverCache.TryLoad( new RestoredCommandIdentifier( @@ -172,7 +172,7 @@ public void WhenRunItCanSaveCommandsToCacheAndShowSuccessMessage() _reporter ); - toolRestoreCommand.Execute().Should().Be(0); + toolRestoreCommand.Execute(CancellationToken.None).Should().Be(0); _reporter.Lines.Should().Contain(l => l.Contains(string.Format( CliCommandStrings.RestoreSuccessful, _packageIdA, @@ -236,7 +236,7 @@ public void WhenRestoredCommandHasTheSameCommandNameItThrows() })), }; - Action a = () => toolRestoreCommand.Execute(); + Action a = () => toolRestoreCommand.Execute(CancellationToken.None); a.Should().Throw() .And.Message .Should().BeOneOf(allPossibleErrorMessage, "Run in parallel, no order guarantee"); @@ -266,7 +266,7 @@ public void WhenSomePackageFailedToRestoreItCanRestorePartiallySuccessful() _reporter ); - int executeResult = toolRestoreCommand.Execute(); + int executeResult = toolRestoreCommand.Execute(CancellationToken.None); _reporter.Lines.Should() .Contain(l => l.Contains(string.Format(CliCommandStrings.PackageFailedToRestore, "non-exists", ""))); @@ -307,7 +307,7 @@ public void ItShouldFailWhenPackageCommandNameDoesNotMatchManifestCommands() _reporter ); - toolRestoreCommand.Execute().Should().Be(1); + toolRestoreCommand.Execute(CancellationToken.None).Should().Be(1); _reporter.Lines.Should() .Contain(l => l.Contains( @@ -449,7 +449,7 @@ public void WhenCannotFindManifestFileItPrintsWarning() _reporter ); - toolRestoreCommand.Execute().Should().Be(0); + toolRestoreCommand.Execute(CancellationToken.None).Should().Be(0); _reporter.Lines.Should() .Contain(l => @@ -476,9 +476,9 @@ public void WhenPackageIsRestoredAlreadyItWillNotRestoreItAgain() _reporter ); - toolRestoreCommand.Execute(); + toolRestoreCommand.Execute(CancellationToken.None); var installCallCountBeforeTheSecondRestore = _installCalledCount; - toolRestoreCommand.Execute(); + toolRestoreCommand.Execute(CancellationToken.None); installCallCountBeforeTheSecondRestore.Should().BeGreaterThan(0); _installCalledCount.Should().Be(installCallCountBeforeTheSecondRestore); @@ -504,10 +504,10 @@ public void WhenPackageIsRestoredAlreadyButDllIsRemovedItRestoresAgain() _reporter ); - toolRestoreCommand.Execute(); + toolRestoreCommand.Execute(CancellationToken.None); _fileSystem.Directory.Delete(_nugetGlobalPackagesFolder.Value, true); var installCallCountBeforeTheSecondRestore = _installCalledCount; - toolRestoreCommand.Execute(); + toolRestoreCommand.Execute(CancellationToken.None); installCallCountBeforeTheSecondRestore.Should().BeGreaterThan(0); _installCalledCount.Should().Be(installCallCountBeforeTheSecondRestore + 1); @@ -527,7 +527,7 @@ public void WhenRunWithoutManifestFileItShouldPrintSpecificRestoreErrorMessage() _reporter ); - toolRestoreCommand.Execute().Should().Be(0); + toolRestoreCommand.Execute(CancellationToken.None).Should().Be(0); _reporter.Lines.Should().Contain(l => l.Contains(AnsiExtensions.Yellow(CliCommandStrings.NoToolsWereRestored))); @@ -584,7 +584,7 @@ public void WhenNewerVersionIsAvailableItShowsWarning() _reporter ); - toolRestoreCommand.Execute().Should().Be(0); + toolRestoreCommand.Execute(CancellationToken.None).Should().Be(0); _reporter.Lines.Should().Contain(l => l.Contains(string.Format(CliCommandStrings.RestoreNewVersionAvailable, _packageIdA, newerPackageVersion.ToNormalizedString()))); @@ -640,7 +640,7 @@ public void WhenCurrentVersionIsPrereleaseAndNewerStableIsAvailableItShowsWarnin _reporter ); - toolRestoreCommand.Execute().Should().Be(0); + toolRestoreCommand.Execute(CancellationToken.None).Should().Be(0); _reporter.Lines.Should().Contain(l => l.Contains(string.Format(CliCommandStrings.RestoreNewVersionAvailable, _packageIdA, newerStableVersion.ToNormalizedString()))); @@ -696,7 +696,7 @@ public void WhenCurrentVersionIsStableAndNewerPrereleaseIsAvailableItDoesNotShow _reporter ); - toolRestoreCommand.Execute().Should().Be(0); + toolRestoreCommand.Execute(CancellationToken.None).Should().Be(0); // Should NOT contain warning about the prerelease version _reporter.Lines.Should().NotContain(l => diff --git a/test/dotnet.Tests/CommandTests/Tool/Restore/ToolRestoreCommandWithMultipleNugetConfigTests.cs b/test/dotnet.Tests/CommandTests/Tool/Restore/ToolRestoreCommandWithMultipleNugetConfigTests.cs index 1ec47d83724a..0ebf1d94c91e 100644 --- a/test/dotnet.Tests/CommandTests/Tool/Restore/ToolRestoreCommandWithMultipleNugetConfigTests.cs +++ b/test/dotnet.Tests/CommandTests/Tool/Restore/ToolRestoreCommandWithMultipleNugetConfigTests.cs @@ -134,7 +134,7 @@ public void WhenManifestPackageAreFromDifferentDirectoryItCanFindTheRightNugetCo _reporter ); - toolRestoreCommand.Execute().Should() + toolRestoreCommand.Execute(CancellationToken.None).Should() .Be(0, "if nuget probed from sub dir, it will find only the nuget.config under sub dir. " + "And it does not have the feed to package A. However, since package A is set in " + "manifest file under repository root, nuget should prob from manifest file directory " + diff --git a/test/dotnet.Tests/CommandTests/Tool/Run/ToolRunCommandTests.cs b/test/dotnet.Tests/CommandTests/Tool/Run/ToolRunCommandTests.cs index 07992dda2274..df6f49c364ed 100644 --- a/test/dotnet.Tests/CommandTests/Tool/Run/ToolRunCommandTests.cs +++ b/test/dotnet.Tests/CommandTests/Tool/Run/ToolRunCommandTests.cs @@ -83,6 +83,22 @@ public void WhenRunWithoutRollForwardOptionItShouldNotIncludeRollForwardInNative result.Args.Should().NotContain("--roll-forward", "Major"); } + [TestMethod] + public void PreCanceledTokenDoesNotLaunchTool() + { + (_, LocalToolsCommandResolver localToolsCommandResolver) = DefaultSetup("a"); + using var cancellationSource = new CancellationTokenSource(); + cancellationSource.Cancel(); + + Assert.ThrowsExactly(() => + ToolRunCommand.ExecuteCommand( + localToolsCommandResolver, + "a", + [], + allowRollForward: false, + cancellationSource.Token)); + } + private (FilePath, LocalToolsCommandResolver) DefaultSetup(string toolCommand) { var testDirectoryRoot = TestAssetsManager.CreateTestDirectory(); diff --git a/test/dotnet.Tests/CommandTests/Tool/Search/NugetSearchApiRequestTests.cs b/test/dotnet.Tests/CommandTests/Tool/Search/NugetSearchApiRequestTests.cs index b7c4e2e90fa5..9601f004d7ff 100644 --- a/test/dotnet.Tests/CommandTests/Tool/Search/NugetSearchApiRequestTests.cs +++ b/test/dotnet.Tests/CommandTests/Tool/Search/NugetSearchApiRequestTests.cs @@ -10,10 +10,12 @@ public class NugetSearchApiRequestTests { private readonly Uri _domainAndPathOverride = new("https://azuresearch-usnc.nuget.org/query"); + public TestContext TestContext { get; set; } = null!; + [TestMethod] public async Task WhenPassedInRequestParametersItCanConstructTheUrl() { - (await NugetToolSearchApiRequest.ConstructUrl("mytool", 3, 4, true, _domainAndPathOverride)) + (await NugetToolSearchApiRequest.ConstructUrl("mytool", 3, 4, true, TestContext.CancellationToken, _domainAndPathOverride)) .AbsoluteUri .Should().Be( "https://azuresearch-usnc.nuget.org/query?q=mytool&packageType=dotnettool&semVerLevel=2.0.0&skip=3&take=4&prerelease=true"); @@ -22,10 +24,83 @@ public async Task WhenPassedInRequestParametersItCanConstructTheUrl() [TestMethod] public async Task WhenPassedWithoutParameterItCanConstructTheUrl() { - (await NugetToolSearchApiRequest.ConstructUrl(domainAndPathOverride: _domainAndPathOverride)) + (await NugetToolSearchApiRequest.ConstructUrl( + cancellationToken: TestContext.CancellationToken, + domainAndPathOverride: _domainAndPathOverride)) .AbsoluteUri .Should().Be( "https://azuresearch-usnc.nuget.org/query?packageType=dotnettool&semVerLevel=2.0.0"); } + + [TestMethod] + public async Task InternalTimeoutIsReportedAsRetriableFailure() + { + Func action = async () => await NugetToolSearchApiRequest.ExecuteWithTimeout( + async token => + { + await Task.Delay(Timeout.InfiniteTimeSpan, token); + return 0; + }, + TestContext.CancellationToken, + TimeSpan.FromMilliseconds(10)); + + NugetSearchApiRequestException exception = + await Assert.ThrowsExactlyAsync(action); + + exception.Message.Should().Contain("Retry"); + } + + [TestMethod] + public async Task CallerCancellationIsNotReportedAsTimeout() + { + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + + Func action = async () => await NugetToolSearchApiRequest.ExecuteWithTimeout( + async token => + { + await Task.Delay(Timeout.InfiniteTimeSpan, token); + return 0; + }, + cancellation.Token, + TimeSpan.FromSeconds(1)); + + await Assert.ThrowsExactlyAsync(action); + } + + [TestMethod] + public async Task UnrelatedCancellationIsNotReportedAsTimeout() + { + Func action = async () => await NugetToolSearchApiRequest.ExecuteWithTimeout( + _ => throw new OperationCanceledException(), + TestContext.CancellationToken, + TimeSpan.FromSeconds(1)); + + await Assert.ThrowsExactlyAsync(action); + } + + [TestMethod] + public async Task QueryTimeoutStartsAfterEndpointDiscoveryCompletes() + { + TimeSpan timeout = TimeSpan.FromMilliseconds(50); + + string result = await NugetToolSearchApiRequest.ExecuteRequest( + async _ => + { + await Task.Delay( + timeout + TimeSpan.FromMilliseconds(50), + TestContext.CancellationToken); + return _domainAndPathOverride; + }, + (_, token) => + { + token.ThrowIfCancellationRequested(); + return Task.FromResult("result"); + }, + TestContext.CancellationToken, + timeout); + + result.Should().Be("result"); + } } } diff --git a/test/dotnet.Tests/CommandTests/Tool/Uninstall/ToolUninstallCommandTests.cs b/test/dotnet.Tests/CommandTests/Tool/Uninstall/ToolUninstallCommandTests.cs index d472e1f308e3..6a5d4189242f 100644 --- a/test/dotnet.Tests/CommandTests/Tool/Uninstall/ToolUninstallCommandTests.cs +++ b/test/dotnet.Tests/CommandTests/Tool/Uninstall/ToolUninstallCommandTests.cs @@ -29,7 +29,7 @@ public void WhenRunWithBothGlobalAndToolPathShowErrorMessage() var toolUninstallCommand = new ToolUninstallCommand(result); - Action a = () => toolUninstallCommand.Execute(); + Action a = () => toolUninstallCommand.Execute(CancellationToken.None); a.Should().Throw().And.Message .Should().Contain(string.Format( @@ -44,7 +44,7 @@ public void WhenRunWithBothGlobalAndLocalShowErrorMessage() var toolUninstallCommand = new ToolUninstallCommand(result); - Action a = () => toolUninstallCommand.Execute(); + Action a = () => toolUninstallCommand.Execute(CancellationToken.None); a.Should().Throw().And.Message .Should().Contain( @@ -59,7 +59,7 @@ public void WhenRunWithGlobalAndToolManifestShowErrorMessage() var toolUninstallCommand = new ToolUninstallCommand(result); - Action a = () => toolUninstallCommand.Execute(); + Action a = () => toolUninstallCommand.Execute(CancellationToken.None); a.Should().Throw().And.Message .Should().Contain(CliCommandStrings.OnlyLocalOptionSupportManifestFileOption); @@ -73,7 +73,7 @@ public void WhenRunWithToolPathAndToolManifestShowErrorMessage() var toolUninstallCommand = new ToolUninstallCommand(result); - Action a = () => toolUninstallCommand.Execute(); + Action a = () => toolUninstallCommand.Execute(CancellationToken.None); a.Should().Throw().And.Message .Should().Contain(CliCommandStrings.OnlyLocalOptionSupportManifestFileOption); diff --git a/test/dotnet.Tests/CommandTests/Tool/Uninstall/ToolUninstallGlobalOrToolPathCommandTests.cs b/test/dotnet.Tests/CommandTests/Tool/Uninstall/ToolUninstallGlobalOrToolPathCommandTests.cs index 169bd7f81ba7..6591548a8b54 100644 --- a/test/dotnet.Tests/CommandTests/Tool/Uninstall/ToolUninstallGlobalOrToolPathCommandTests.cs +++ b/test/dotnet.Tests/CommandTests/Tool/Uninstall/ToolUninstallGlobalOrToolPathCommandTests.cs @@ -48,7 +48,7 @@ public void GivenANonExistentPackageItErrors() var packageId = "does.not.exist"; var command = CreateUninstallCommand($"-g {packageId}"); - Action a = () => command.Execute(); + Action a = () => command.Execute(CancellationToken.None); a.Should().Throw() .And @@ -60,7 +60,7 @@ public void GivenANonExistentPackageItErrors() [TestMethod] public void GivenAPackageItUninstalls() { - CreateInstallCommand($"-g {PackageId} --verbosity minimal").Execute().Should().Be(0); + CreateInstallCommand($"-g {PackageId} --verbosity minimal").Execute(CancellationToken.None).Should().Be(0); _reporter .Lines @@ -84,7 +84,7 @@ public void GivenAPackageItUninstalls() _reporter.Lines.Clear(); - CreateUninstallCommand($"-g {PackageId}").Execute().Should().Be(0); + CreateUninstallCommand($"-g {PackageId}").Execute(CancellationToken.None).Should().Be(0); _reporter .Lines @@ -102,7 +102,7 @@ public void GivenAPackageItUninstalls() [TestMethod] public async Task GivenUninstallInProgressAnotherInstallWaitsBeforeReinstalling() { - CreateInstallCommand($"-g {PackageId} --verbosity minimal").Execute().Should().Be(0); + CreateInstallCommand($"-g {PackageId} --verbosity minimal").Execute(TestContext.CancellationToken).Should().Be(0); _reporter.Lines.Clear(); var store = new ToolPackageStoreMock(new DirectoryPath(_toolsDirectory), _fileSystem); @@ -118,10 +118,12 @@ public async Task GivenUninstallInProgressAnotherInstallWaitsBeforeReinstalling( appHostShellShimMaker: new AppHostShellShimMakerMock(_fileSystem)), new BufferedReporter()); - Task uninstall = Task.Run(uninstallCommand.Execute, TestContext.CancellationToken); + Task uninstall = Task.Run( + () => uninstallCommand.Execute(TestContext.CancellationToken), + TestContext.CancellationToken); await blockingUninstaller.UninstallStarted; Task reinstall = Task.Run( - () => CreateInstallCommand($"-g {PackageId} --verbosity minimal").Execute(), + () => CreateInstallCommand($"-g {PackageId} --verbosity minimal").Execute(TestContext.CancellationToken), TestContext.CancellationToken); Task firstCompleted = await Task.WhenAny( @@ -148,7 +150,7 @@ public async Task GivenUninstallInProgressAnotherInstallWaitsBeforeReinstalling( [TestMethod] public async Task GivenPackageMutationInProgressUninstallWaitsBeforeReadingInstalledState() { - CreateInstallCommand($"-g {PackageId} --verbosity minimal").Execute().Should().Be(0); + CreateInstallCommand($"-g {PackageId} --verbosity minimal").Execute(TestContext.CancellationToken).Should().Be(0); var store = new ToolPackageStoreMock(new DirectoryPath(_toolsDirectory), _fileSystem); IToolPackage package = store.EnumeratePackageVersions(new PackageId(PackageId)).Single(); @@ -161,7 +163,7 @@ public async Task GivenPackageMutationInProgressUninstallWaitsBeforeReadingInsta try { Task uninstall = Task.Run( - () => CreateUninstallCommand($"-g {PackageId}").Execute(), + () => CreateUninstallCommand($"-g {PackageId}").Execute(TestContext.CancellationToken), TestContext.CancellationToken); Task firstCompleted = await Task.WhenAny( uninstall, @@ -186,7 +188,7 @@ public async Task GivenPackageMutationInProgressUninstallWaitsBeforeReadingInsta [TestMethod] public void GivenAPackageWhenCallFromUninstallRedirectCommandItUninstalls() { - CreateInstallCommand($"-g {PackageId} --verbosity minimal").Execute().Should().Be(0); + CreateInstallCommand($"-g {PackageId} --verbosity minimal").Execute(CancellationToken.None).Should().Be(0); _reporter .Lines @@ -238,7 +240,7 @@ var uninstallCommand result, toolUninstallGlobalOrToolPathCommand: toolUninstallGlobalOrToolPathCommand); - uninstallCommand.Execute().Should().Be(0); + uninstallCommand.Execute(CancellationToken.None).Should().Be(0); _reporter .Lines @@ -256,7 +258,7 @@ var uninstallCommand [TestMethod] public void GivenAFailureToUninstallItLeavesItInstalled() { - CreateInstallCommand($"-g {PackageId} --verbosity minimal").Execute().Should().Be(0); + CreateInstallCommand($"-g {PackageId} --verbosity minimal").Execute(CancellationToken.None).Should().Be(0); _reporter .Lines @@ -281,7 +283,7 @@ public void GivenAFailureToUninstallItLeavesItInstalled() Action a = () => CreateUninstallCommand( options: $"-g {PackageId}", uninstallCallback: () => throw new IOException("simulated error")) - .Execute(); + .Execute(CancellationToken.None); a.Should().Throw() .And @@ -303,7 +305,7 @@ public void GivenAnInvalidToolPathItThrowsException() var uninstallCommand = CreateUninstallCommand($"--tool-path {toolPath} {PackageId}"); - Action a = () => uninstallCommand.Execute(); + Action a = () => uninstallCommand.Execute(CancellationToken.None); a.Should().Throw() .And diff --git a/test/dotnet.Tests/CommandTests/Tool/Uninstall/ToolUninstallLocalCommandTests.cs b/test/dotnet.Tests/CommandTests/Tool/Uninstall/ToolUninstallLocalCommandTests.cs index 87288eb7d52d..3e0ccc22ae0e 100644 --- a/test/dotnet.Tests/CommandTests/Tool/Uninstall/ToolUninstallLocalCommandTests.cs +++ b/test/dotnet.Tests/CommandTests/Tool/Uninstall/ToolUninstallLocalCommandTests.cs @@ -53,7 +53,7 @@ public ToolUninstallLocalCommandTests() [TestMethod] public void WhenRunWithPackageIdItShouldRemoveFromManifestFile() { - _defaultToolUninstallLocalCommand.Execute().Should().Be(0); + _defaultToolUninstallLocalCommand.Execute(CancellationToken.None).Should().Be(0); _fileSystem.File.ReadAllText(_manifestFilePath).Should().Be(_entryRemovedJsonContent); } @@ -62,7 +62,7 @@ public void WhenRunWithPackageIdItShouldRemoveFromManifestFile() public void GivenNoManifestFileItShouldThrow() { _fileSystem.File.Delete(_manifestFilePath); - Action a = () => _defaultToolUninstallLocalCommand.Execute().Should().Be(0); + Action a = () => _defaultToolUninstallLocalCommand.Execute(CancellationToken.None).Should().Be(0); a.Should().Throw() .And.Message.Should() @@ -79,7 +79,7 @@ public void GivenNoManifestFileContainPackageIdItShouldThrow() _fileSystem.File.Delete(_manifestFilePath); _fileSystem.File.WriteAllText(_manifestFilePath, _jsonContentContainNoPackageId); - Action a = () => _defaultToolUninstallLocalCommand.Execute().Should().Be(0); + Action a = () => _defaultToolUninstallLocalCommand.Execute(CancellationToken.None).Should().Be(0); a.Should().Throw() .And.Message.Should() @@ -103,7 +103,7 @@ var parseResult _toolManifestEditor, _reporter); - toolUninstallLocalCommand.Execute().Should().Be(0); + toolUninstallLocalCommand.Execute(CancellationToken.None).Should().Be(0); _fileSystem.File.ReadAllText(explicitManifestFilePath).Should().Be(_entryRemovedJsonContent); } @@ -120,7 +120,7 @@ public void WhenRunFromToolUninstallRedirectCommandWithPackageIdItShouldRemoveFr parseResult, toolUninstallLocalCommand: toolUninstallLocalCommand); - toolUninstallCommand.Execute().Should().Be(0); + toolUninstallCommand.Execute(CancellationToken.None).Should().Be(0); _fileSystem.File.ReadAllText(_manifestFilePath).Should().Be(_entryRemovedJsonContent); } @@ -128,7 +128,7 @@ public void WhenRunFromToolUninstallRedirectCommandWithPackageIdItShouldRemoveFr [TestMethod] public void WhenRunWithPackageIdItShouldShowSuccessMessage() { - _defaultToolUninstallLocalCommand.Execute(); + _defaultToolUninstallLocalCommand.Execute(CancellationToken.None); _reporter.Lines.Single() .Should().Contain( string.Format( @@ -143,7 +143,7 @@ public void GivenParentDirHasManifestWithSamePackageIdWhenRunWithPackageIdItShou var parentManifestFilePath = Path.Combine(_temporaryDirectoryParent, "dotnet-tools.json"); _fileSystem.File.WriteAllText(parentManifestFilePath, _jsonContent); - _defaultToolUninstallLocalCommand.Execute(); + _defaultToolUninstallLocalCommand.Execute(CancellationToken.None); _fileSystem.File.ReadAllText(_manifestFilePath).Should().Be(_entryRemovedJsonContent, "Change the closest one"); _fileSystem.File.ReadAllText(parentManifestFilePath).Should().Be(_jsonContent, "Do not change the manifest layer above"); @@ -155,8 +155,8 @@ public void GivenParentDirHasManifestWithSamePackageIdWhenRunWithPackageIdItShou var parentManifestFilePath = Path.Combine(_temporaryDirectoryParent, "dotnet-tools.json"); _fileSystem.File.WriteAllText(parentManifestFilePath, _jsonContent); - _defaultToolUninstallLocalCommand.Execute(); - _defaultToolUninstallLocalCommand.Execute(); + _defaultToolUninstallLocalCommand.Execute(CancellationToken.None); + _defaultToolUninstallLocalCommand.Execute(CancellationToken.None); _fileSystem.File.ReadAllText(parentManifestFilePath).Should().Be( _entryRemovedJsonContent, @@ -169,7 +169,7 @@ public void GivenParentDirHasManifestWithSamePackageIdWhenRunWithPackageIdItShou var parentManifestFilePath = Path.Combine(_temporaryDirectoryParent, "dotnet-tools.json"); _fileSystem.File.WriteAllText(parentManifestFilePath, _jsonContent); - _defaultToolUninstallLocalCommand.Execute(); + _defaultToolUninstallLocalCommand.Execute(CancellationToken.None); _reporter.Lines[0].Should().Contain(parentManifestFilePath); _reporter.Lines[0].Should().NotContain(_manifestFilePath); diff --git a/test/dotnet.Tests/CommandTests/Tool/Update/ToolUpdateCommandTests.cs b/test/dotnet.Tests/CommandTests/Tool/Update/ToolUpdateCommandTests.cs index 603cef48d97c..dad871e6807b 100644 --- a/test/dotnet.Tests/CommandTests/Tool/Update/ToolUpdateCommandTests.cs +++ b/test/dotnet.Tests/CommandTests/Tool/Update/ToolUpdateCommandTests.cs @@ -28,7 +28,7 @@ public void WhenRunWithBothGlobalAndToolPathShowErrorMessage() var toolUpdateCommand = new ToolUpdateCommand( result); - Action a = () => toolUpdateCommand.Execute(); + Action a = () => toolUpdateCommand.Execute(CancellationToken.None); a.Should().Throw().And.Message .Should().Contain(string.Format( @@ -44,7 +44,7 @@ public void WhenRunWithBothGlobalAndLocalShowErrorMessage() var toolUpdateCommand = new ToolUpdateCommand( result); - Action a = () => toolUpdateCommand.Execute(); + Action a = () => toolUpdateCommand.Execute(CancellationToken.None); a.Should().Throw().And.Message .Should().Contain( @@ -61,7 +61,7 @@ public void WhenRunWithGlobalAndToolManifestShowErrorMessage() var toolUpdateCommand = new ToolUpdateCommand( result); - Action a = () => toolUpdateCommand.Execute(); + Action a = () => toolUpdateCommand.Execute(CancellationToken.None); a.Should().Throw().And.Message .Should().Contain(CliCommandStrings.OnlyLocalOptionSupportManifestFileOption); @@ -77,7 +77,7 @@ public void WhenRunWithToolPathAndToolManifestShowErrorMessage() var toolUpdateCommand = new ToolUpdateCommand( result); - Action a = () => toolUpdateCommand.Execute(); + Action a = () => toolUpdateCommand.Execute(CancellationToken.None); a.Should().Throw().And.Message .Should().Contain(CliCommandStrings.OnlyLocalOptionSupportManifestFileOption); @@ -93,7 +93,7 @@ public void WhenRunWithAllAndVersionShowErrorMessage() var toolUpdateCommand = new ToolUpdateCommand( result); - Action a = () => toolUpdateCommand.Execute(); + Action a = () => toolUpdateCommand.Execute(CancellationToken.None); a.Should().Throw().And.Message .Should().Contain( @@ -109,7 +109,7 @@ public void WhenRunWithoutAllOrPackageIdShowErrorMessage() var toolUpdateCommand = new ToolUpdateCommand(result); - Action a = () => toolUpdateCommand.Execute(); + Action a = () => toolUpdateCommand.Execute(CancellationToken.None); a.Should().Throw().And.Message .Should().Contain( @@ -124,7 +124,7 @@ public void WhenRunWithBothAllAndPackageIdShowErrorMessage() var toolUpdateCommand = new ToolUpdateCommand(result); - Action a = () => toolUpdateCommand.Execute(); + Action a = () => toolUpdateCommand.Execute(CancellationToken.None); a.Should().Throw().And.Message .Should().Contain( diff --git a/test/dotnet.Tests/CommandTests/Tool/Update/ToolUpdateGlobalOrToolPathCommandTests.cs b/test/dotnet.Tests/CommandTests/Tool/Update/ToolUpdateGlobalOrToolPathCommandTests.cs index 5498e03f3278..6ac2bc6e4f81 100644 --- a/test/dotnet.Tests/CommandTests/Tool/Update/ToolUpdateGlobalOrToolPathCommandTests.cs +++ b/test/dotnet.Tests/CommandTests/Tool/Update/ToolUpdateGlobalOrToolPathCommandTests.cs @@ -119,7 +119,7 @@ public void WhenPassingIgnoreFailedSourcesItShouldNotThrow() var command = CreateUpdateCommand($"-g {_packageId} --ignore-failed-sources"); - command.Execute().Should().Be(0); + command.Execute(CancellationToken.None).Should().Be(0); _fileSystem.File.Delete(Path.Combine(_tempDirectory, "nuget.config")); } @@ -129,7 +129,7 @@ public void GivenANonFeedExistentPackageItErrors() var packageId = "does.not.exist"; var command = CreateUpdateCommand($"-g {packageId}"); - Action a = () => command.Execute(); + Action a = () => command.Execute(CancellationToken.None); a.Should().Throw().And.Message .Should().Contain( @@ -141,7 +141,7 @@ public void GivenANonExistentPackageItInstallTheLatest() { var command = CreateUpdateCommand($"-g {_packageId}"); - command.Execute(); + command.Execute(CancellationToken.None); _store.EnumeratePackageVersions(_packageId).Single().Version.ToFullString().Should() .Be(HigherPackageVersion); @@ -151,11 +151,11 @@ public void GivenANonExistentPackageItInstallTheLatest() [TestMethod] public void GivenAnExistedLowerversionInstallationWhenCallItCanUpdateThePackageVersion() { - CreateInstallCommand($"-g {_packageId} --version {LowerPackageVersion}").Execute(); + CreateInstallCommand($"-g {_packageId} --version {LowerPackageVersion}").Execute(CancellationToken.None); var command = CreateUpdateCommand($"-g {_packageId}"); - command.Execute(); + command.Execute(CancellationToken.None); _store.EnumeratePackageVersions(_packageId).Single().Version.ToFullString().Should() .Be(HigherPackageVersion); @@ -164,10 +164,10 @@ public void GivenAnExistedLowerversionInstallationWhenCallItCanUpdateThePackageV [TestMethod] public void GivenAnExistedLowerVersionInstallationItCanUpdateAllThePackageVersion() { - CreateInstallCommand($"-g {_packageId} --version {LowerPackageVersion}").Execute(); - CreateInstallCommand($"-g {_packageId2} --version {LowerPackageVersion}", _packageId2.ToString()).Execute(); + CreateInstallCommand($"-g {_packageId} --version {LowerPackageVersion}").Execute(CancellationToken.None); + CreateInstallCommand($"-g {_packageId2} --version {LowerPackageVersion}", _packageId2.ToString()).Execute(CancellationToken.None); - CreateUpdateCommand($"--all -g -v:d").Execute(); + CreateUpdateCommand($"--all -g -v:d").Execute(CancellationToken.None); _store.EnumeratePackageVersions(_packageId).Single().Version.ToFullString().Should() .Be(HigherPackageVersion); @@ -178,7 +178,7 @@ public void GivenAnExistedLowerVersionInstallationItCanUpdateAllThePackageVersio [TestMethod] public void GivenAnExistedLowerversionInstallationWhenCallFromRedirectorItCanUpdateThePackageVersion() { - CreateInstallCommand($"-g {_packageId} --version {LowerPackageVersion}").Execute(); + CreateInstallCommand($"-g {_packageId} --version {LowerPackageVersion}").Execute(CancellationToken.None); ParseResult result = Parser.Parse("dotnet tool update " + $"-g {_packageId}"); @@ -194,7 +194,7 @@ public void GivenAnExistedLowerversionInstallationWhenCallFromRedirectorItCanUpd toolUpdateGlobalOrToolPathCommand, new ToolUpdateLocalCommand(result)); - toolUpdateCommand.Execute(); + toolUpdateCommand.Execute(CancellationToken.None); _store.EnumeratePackageVersions(_packageId).Single().Version.ToFullString().Should() .Be(HigherPackageVersion); @@ -203,12 +203,12 @@ public void GivenAnExistedLowerversionInstallationWhenCallFromRedirectorItCanUpd [TestMethod] public void GivenAnExistedLowerversionInstallationWhenCallItCanPrintSuccessMessage() { - CreateInstallCommand($"-g {_packageId} --version {LowerPackageVersion}").Execute(); + CreateInstallCommand($"-g {_packageId} --version {LowerPackageVersion}").Execute(CancellationToken.None); _reporter.Lines.Clear(); var command = CreateUpdateCommand($"-g {_packageId} --verbosity minimal"); - command.Execute(); + command.Execute(CancellationToken.None); _reporter.Lines.First().Should().Contain(string.Format( CliCommandStrings.ToolUpdateUpdateSucceeded, @@ -218,12 +218,12 @@ public void GivenAnExistedLowerversionInstallationWhenCallItCanPrintSuccessMessa [TestMethod] public void GivenAnExistedLowerversionInstallationWhenUpdateAllItCanPrintSuccessMessage() { - CreateInstallCommand($"-g {_packageId} --version {LowerPackageVersion}").Execute(); + CreateInstallCommand($"-g {_packageId} --version {LowerPackageVersion}").Execute(CancellationToken.None); _reporter.Lines.Clear(); var command = CreateUpdateCommand($"-g --all --verbosity minimal"); - command.Execute(); + command.Execute(CancellationToken.None); _reporter.Lines.First().Should().Contain(string.Format( CliCommandStrings.ToolUpdateUpdateSucceeded, @@ -234,11 +234,11 @@ public void GivenAnExistedLowerversionInstallationWhenUpdateAllItCanPrintSuccess public void GivenAnExistedPreviewVersionInstallationWhenUpdateToHigherVersionItSucceeds() { var installCommand = CreateInstallCommand($"-g {_packageId} --version {HigherPreviewPackageVersion} --verbosity minimal"); - installCommand.Execute(); + installCommand.Execute(CancellationToken.None); _reporter.Lines.Clear(); var command = CreateUpdateCommand($"-g {_packageId} --version {HigherPackageVersion} --verbosity minimal"); - command.Execute().Should().Be(0); + command.Execute(CancellationToken.None).Should().Be(0); _reporter.Lines.First().Should().Contain(string.Format( CliCommandStrings.ToolUpdateUpdateSucceeded, @@ -248,12 +248,12 @@ public void GivenAnExistedPreviewVersionInstallationWhenUpdateToHigherVersionItS [TestMethod] public void GivenAnExistedHigherversionInstallationWhenUpdateToLowerVersionItErrors() { - CreateInstallCommand($"-g {_packageId} --version {HigherPackageVersion}").Execute(); + CreateInstallCommand($"-g {_packageId} --version {HigherPackageVersion}").Execute(CancellationToken.None); _reporter.Lines.Clear(); var command = CreateUpdateCommand($"-g {_packageId} --version {LowerPackageVersion} --verbosity minimal"); - Action a = () => command.Execute(); + Action a = () => command.Execute(CancellationToken.None); a.Should().Throw().And.Message .Should().Contain( @@ -263,12 +263,12 @@ public void GivenAnExistedHigherversionInstallationWhenUpdateToLowerVersionItErr [TestMethod] public void GivenAnExistedHigherversionInstallationWithDowngradeFlagWhenUpdateToLowerVersionItSucceeds() { - CreateInstallCommand($"-g {_packageId} --version {HigherPackageVersion}").Execute(); + CreateInstallCommand($"-g {_packageId} --version {HigherPackageVersion}").Execute(CancellationToken.None); _reporter.Lines.Clear(); var command = CreateUpdateCommand($"-g {_packageId} --version {LowerPackageVersion} --verbosity minimal --allow-downgrade"); - command.Execute(); + command.Execute(CancellationToken.None); _reporter.Lines.First().Should().Contain(string.Format( CliCommandStrings.ToolUpdateUpdateSucceeded, @@ -278,12 +278,12 @@ public void GivenAnExistedHigherversionInstallationWithDowngradeFlagWhenUpdateTo [TestMethod] public void GivenAnExistedLowerversionInstallationWhenCallWithWildCardVersionItCanPrintSuccessMessage() { - CreateInstallCommand($"-g {_packageId} --version {LowerPackageVersion}").Execute(); + CreateInstallCommand($"-g {_packageId} --version {LowerPackageVersion}").Execute(CancellationToken.None); _reporter.Lines.Clear(); var command = CreateUpdateCommand($"-g {_packageId} --version 1.0.5-* --verbosity minimal"); - command.Execute(); + command.Execute(CancellationToken.None); _reporter.Lines.First().Should().Contain(string.Format( CliCommandStrings.ToolUpdateUpdateSucceeded, @@ -293,12 +293,12 @@ public void GivenAnExistedLowerversionInstallationWhenCallWithWildCardVersionItC [TestMethod] public void GivenAnExistedLowerversionInstallationWhenCallWithPrereleaseVersionItCanPrintSuccessMessage() { - CreateInstallCommand($"-g {_packageId} --version {LowerPackageVersion}").Execute(); + CreateInstallCommand($"-g {_packageId} --version {LowerPackageVersion}").Execute(CancellationToken.None); _reporter.Lines.Clear(); var command = CreateUpdateCommand($"-g {_packageId} --prerelease --verbosity minimal"); - command.Execute(); + command.Execute(CancellationToken.None); _reporter.Lines.First().Should().Contain(string.Format( CliCommandStrings.ToolUpdateUpdateSucceeded, @@ -308,12 +308,12 @@ public void GivenAnExistedLowerversionInstallationWhenCallWithPrereleaseVersionI [TestMethod] public void GivenAnExistedHigherVersionInstallationWhenCallWithLowerVersionItThrowsAndRollsBack() { - CreateInstallCommand($"-g {_packageId} --version {HigherPackageVersion}").Execute(); + CreateInstallCommand($"-g {_packageId} --version {HigherPackageVersion}").Execute(CancellationToken.None); _reporter.Lines.Clear(); var command = CreateUpdateCommand($"-g {_packageId} --version {LowerPackageVersion}"); - Action a = () => command.Execute(); + Action a = () => command.Execute(CancellationToken.None); a.Should().Throw().And.Message .Should().Contain( @@ -328,12 +328,12 @@ public void GivenAnExistedHigherVersionInstallationWhenCallWithLowerVersionItThr [TestMethod] public void GivenAnExistedSameVersionInstallationWhenCallItCanPrintSuccessMessage() { - CreateInstallCommand($"-g {_packageId} --version {HigherPackageVersion}").Execute(); + CreateInstallCommand($"-g {_packageId} --version {HigherPackageVersion}").Execute(CancellationToken.None); _reporter.Lines.Clear(); var command = CreateUpdateCommand($"-g {_packageId} --verbosity minimal"); - command.Execute(); + command.Execute(CancellationToken.None); _reporter.Lines.First().Should().Contain(string.Format( CliCommandStrings.ToolAlreadyInstalled, @@ -343,12 +343,12 @@ public void GivenAnExistedSameVersionInstallationWhenCallItCanPrintSuccessMessag [TestMethod] public void GivenAnExistedSameVersionInstallationWhenCallWithPrereleaseItUsesAPrereleaseSuccessMessage() { - CreateInstallCommand($"-g {_packageId} --version {HigherPreviewPackageVersion}").Execute(); + CreateInstallCommand($"-g {_packageId} --version {HigherPreviewPackageVersion}").Execute(CancellationToken.None); _reporter.Lines.Clear(); var command = CreateUpdateCommand($"-g {_packageId} --version {HigherPreviewPackageVersion} --verbosity minimal"); - command.Execute(); + command.Execute(CancellationToken.None); _reporter.Lines.First().Should().Contain(string.Format( CliCommandStrings.ToolAlreadyInstalled, @@ -358,7 +358,7 @@ public void GivenAnExistedSameVersionInstallationWhenCallWithPrereleaseItUsesAPr [TestMethod] public void GivenAnExistedLowerversionWhenReinstallThrowsIthasTheFirstLineIndicateUpdateFailure() { - CreateInstallCommand($"-g {_packageId} --version {LowerPackageVersion}").Execute(); + CreateInstallCommand($"-g {_packageId} --version {LowerPackageVersion}").Execute(CancellationToken.None); _reporter.Lines.Clear(); ParseResult result = Parser.Parse("dotnet tool update " + $"-g {_packageId}"); @@ -376,7 +376,7 @@ public void GivenAnExistedLowerversionWhenReinstallThrowsIthasTheFirstLineIndica (_, _) => GetMockedShellShimRepository(), _reporter); - Action a = () => command.Execute(); + Action a = () => command.Execute(CancellationToken.None); a.Should().Throw().And.Message.Should().Contain( string.Format(CliCommandStrings.UpdateToolFailed, _packageId) + Environment.NewLine + string.Format(CliCommandStrings.InvalidToolConfiguration, "Simulated error")); @@ -385,7 +385,7 @@ public void GivenAnExistedLowerversionWhenReinstallThrowsIthasTheFirstLineIndica [TestMethod] public void GivenAnExistedLowerversionWhenReinstallThrowsItRollsBack() { - CreateInstallCommand($"-g {_packageId} --version {LowerPackageVersion}").Execute(); + CreateInstallCommand($"-g {_packageId} --version {LowerPackageVersion}").Execute(CancellationToken.None); _reporter.Lines.Clear(); ParseResult result = Parser.Parse("dotnet tool update " + $"-g {_packageId}"); @@ -403,7 +403,7 @@ public void GivenAnExistedLowerversionWhenReinstallThrowsItRollsBack() (_, _) => GetMockedShellShimRepository(), _reporter); - Action a = () => command.Execute(); + Action a = () => command.Execute(CancellationToken.None); _store.EnumeratePackageVersions(_packageId).Single().Version.ToFullString().Should() .Be(LowerPackageVersion); @@ -422,7 +422,7 @@ public void GivenPackagedShimIsProvidedWhenRunWithPackageIdItCreatesShimUsingPac var mockPackage = _mockFeeds[0].Packages.Single(p => p.PackageId == _packageId.ToString() && p.Version == HigherPackageVersion); mockPackage.AdditionalFiles[$"tools/{ToolPackageDownloaderMock2.DefaultTargetFramework}/any/shims/{toolTargetRuntimeIdentifier}/{mockPackage.ToolCommandName}{extension}"] = tokenToIdentifyPackagedShim; - CreateInstallCommand($"-g {_packageId} --version {LowerPackageVersion}").Execute(); + CreateInstallCommand($"-g {_packageId} --version {LowerPackageVersion}").Execute(CancellationToken.None); _reporter.Lines.Clear(); string options = $"-g {_packageId}"; @@ -434,7 +434,7 @@ public void GivenPackagedShimIsProvidedWhenRunWithPackageIdItCreatesShimUsingPac (_, _) => GetMockedShellShimRepository(), _reporter); - command.Execute(); + command.Execute(CancellationToken.None); _fileSystem.File.ReadAllText(ExpectedCommandPath()).Should().Be(tokenToIdentifyPackagedShim); diff --git a/test/dotnet.Tests/CommandTests/Tool/Update/ToolUpdateLocalCommandTests.cs b/test/dotnet.Tests/CommandTests/Tool/Update/ToolUpdateLocalCommandTests.cs index b265365186a3..7afd54f587a5 100644 --- a/test/dotnet.Tests/CommandTests/Tool/Update/ToolUpdateLocalCommandTests.cs +++ b/test/dotnet.Tests/CommandTests/Tool/Update/ToolUpdateLocalCommandTests.cs @@ -157,7 +157,7 @@ public void WhenPassingIgnoreFailedSourcesItShouldNotThrow() _localToolsResolverCache, _reporter); - updateLocalCommand.Execute().Should().Be(0); + updateLocalCommand.Execute(CancellationToken.None).Should().Be(0); _fileSystem.File.Delete(Path.Combine(_temporaryDirectory, "nuget.config")); } @@ -165,10 +165,10 @@ public void WhenPassingIgnoreFailedSourcesItShouldNotThrow() [TestMethod] public void WhenRunWithPackageIdItShouldUpdateFromManifestFile() { - _toolRestoreCommand.Execute(); + _toolRestoreCommand.Execute(CancellationToken.None); _mockFeed.Packages[0].Version = _packageNewVersionA.ToNormalizedString(); - _defaultToolUpdateLocalCommand.Execute().Should().Be(0); + _defaultToolUpdateLocalCommand.Execute(CancellationToken.None).Should().Be(0); AssertUpdateSuccess(); } @@ -176,7 +176,7 @@ public void WhenRunWithPackageIdItShouldUpdateFromManifestFile() [TestMethod] public void WhenRunWithUpdateAllItShouldUpdateFromManifestFile() { - _toolRestoreCommand.Execute(); + _toolRestoreCommand.Execute(CancellationToken.None); new ToolRestoreCommand( Parser.Parse($"dotnet tool restore"), _toolPackageDownloaderMock, @@ -184,12 +184,12 @@ public void WhenRunWithUpdateAllItShouldUpdateFromManifestFile() _localToolsResolverCache, _fileSystem, _reporter - ).Execute(); + ).Execute(CancellationToken.None); _mockFeed.Packages[0].Version = _packageNewVersionA.ToNormalizedString(); _mockFeed.Packages[1].Version = _packageNewVersionA.ToNormalizedString(); - _toolUpdateAllLocalCommand.Execute().Should().Be(0); + _toolUpdateAllLocalCommand.Execute(CancellationToken.None).Should().Be(0); AssertUpdateSuccess(packageIdExpected: _packageIdA.ToString()); AssertUpdateSuccess(packageIdExpected: _packageIdB.ToString()); @@ -198,7 +198,7 @@ public void WhenRunWithUpdateAllItShouldUpdateFromManifestFile() [TestMethod] public void WhenRunFromDirectorWithPackageIdItShouldUpdateFromManifestFile() { - _toolRestoreCommand.Execute(); + _toolRestoreCommand.Execute(CancellationToken.None); _mockFeed.Packages[0].Version = _packageNewVersionA.ToNormalizedString(); var toolUpdateCommand = new ToolUpdateCommand( @@ -207,7 +207,7 @@ public void WhenRunFromDirectorWithPackageIdItShouldUpdateFromManifestFile() new ToolUpdateGlobalOrToolPathCommand(_parseResultUpdate), _defaultToolUpdateLocalCommand); - toolUpdateCommand.Execute().Should().Be(0); + toolUpdateCommand.Execute(CancellationToken.None).Should().Be(0); AssertUpdateSuccess(); } @@ -217,7 +217,7 @@ public void GivenNoRestoredManifestWhenRunWithPackageIdItShouldUpdateFromManifes { _mockFeed.Packages[0].Version = _packageNewVersionA.ToNormalizedString(); - _defaultToolUpdateLocalCommand.Execute().Should().Be(0); + _defaultToolUpdateLocalCommand.Execute(CancellationToken.None).Should().Be(0); AssertUpdateSuccess(); } @@ -229,7 +229,7 @@ public void GivenManifestDoesNotHavePackageWhenRunWithPackageIdItShouldUpdate() _fileSystem.File.Delete(_manifestFilePath); _fileSystem.File.WriteAllText(Path.Combine(_temporaryDirectory, _manifestFilePath), _jsonEmptyContent); - _defaultToolUpdateLocalCommand.Execute().Should().Be(0); + _defaultToolUpdateLocalCommand.Execute(CancellationToken.None).Should().Be(0); AssertUpdateSuccess(); } @@ -238,7 +238,7 @@ public void GivenManifestDoesNotHavePackageWhenRunWithPackageIdItShouldUpdate() public void GivenNoManifestFileItShouldThrow() { _fileSystem.File.Delete(_manifestFilePath); - Action a = () => _defaultToolUpdateLocalCommand.Execute().Should().Be(0); + Action a = () => _defaultToolUpdateLocalCommand.Execute(CancellationToken.None).Should().Be(0); a.Should().Throw().And.Message.Should() .Contain(string.Format(CliStrings.CannotFindAManifestFile, "")); @@ -256,7 +256,7 @@ ParseResult parseResult = Parser.Parse( $"dotnet tool update {_packageIdA.ToString()} --tool-manifest {explicitManifestFilePath}"); - _toolRestoreCommand.Execute(); + _toolRestoreCommand.Execute(CancellationToken.None); _mockFeed.Packages[0].Version = _packageNewVersionA.ToNormalizedString(); ToolUpdateLocalCommand toolUpdateLocalCommand = new( @@ -267,7 +267,7 @@ ParseResult parseResult _localToolsResolverCache, _reporter); - toolUpdateLocalCommand.Execute().Should().Be(0); + toolUpdateLocalCommand.Execute(CancellationToken.None).Should().Be(0); AssertUpdateSuccess(new FilePath(explicitManifestFilePath)); } @@ -276,7 +276,7 @@ public void WhenRunFromToolUpdateRedirectCommandWithPackageIdItShouldUpdateFromM { ParseResult parseResult = Parser.Parse($"dotnet tool update {_packageIdA.ToString()}"); - _toolRestoreCommand.Execute(); + _toolRestoreCommand.Execute(CancellationToken.None); _mockFeed.Packages[0].Version = _packageNewVersionA.ToNormalizedString(); ToolUpdateLocalCommand toolUpdateLocalCommand = new( @@ -290,17 +290,17 @@ public void WhenRunFromToolUpdateRedirectCommandWithPackageIdItShouldUpdateFromM parseResult, toolUpdateLocalCommand: toolUpdateLocalCommand); - toolUpdateCommand.Execute().Should().Be(0); + toolUpdateCommand.Execute(CancellationToken.None).Should().Be(0); } [TestMethod] public void WhenRunWithPackageIdItShouldShowSuccessMessage() { - _toolRestoreCommand.Execute(); + _toolRestoreCommand.Execute(CancellationToken.None); _mockFeed.Packages[0].Version = _packageNewVersionA.ToNormalizedString(); _reporter.Clear(); - _defaultToolUpdateLocalCommand.Execute(); + _defaultToolUpdateLocalCommand.Execute(CancellationToken.None); _reporter.Lines.Single() .Should().Contain( @@ -318,11 +318,11 @@ public void GivenParentDirHasManifestWithSamePackageIdWhenRunWithPackageIdItShou var parentManifestFilePath = Path.Combine(_temporaryDirectoryParent, "dotnet-tools.json"); _fileSystem.File.WriteAllText(parentManifestFilePath, _jsonContent); - _toolRestoreCommand.Execute(); + _toolRestoreCommand.Execute(CancellationToken.None); _mockFeed.Packages[0].Version = _packageNewVersionA.ToNormalizedString(); _reporter.Clear(); - _defaultToolUpdateLocalCommand.Execute(); + _defaultToolUpdateLocalCommand.Execute(CancellationToken.None); AssertUpdateSuccess(); @@ -335,11 +335,11 @@ public void GivenParentDirHasManifestWithSamePackageIdWhenRunWithPackageIdItShou var parentManifestFilePath = Path.Combine(_temporaryDirectoryParent, "dotnet-tools.json"); _fileSystem.File.WriteAllText(parentManifestFilePath, _jsonContent); - _toolRestoreCommand.Execute(); + _toolRestoreCommand.Execute(CancellationToken.None); _reporter.Clear(); _mockFeed.Packages[0].Version = _packageNewVersionA.ToNormalizedString(); - _defaultToolUpdateLocalCommand.Execute(); + _defaultToolUpdateLocalCommand.Execute(CancellationToken.None); _reporter.Lines[0].Should().Contain(parentManifestFilePath); _reporter.Lines[0].Should().NotContain(_manifestFilePath); @@ -348,10 +348,10 @@ public void GivenParentDirHasManifestWithSamePackageIdWhenRunWithPackageIdItShou [TestMethod] public void GivenFeedVersionIsTheSameWhenRunWithPackageIdItShouldShowDifferentSuccessMessage() { - _toolRestoreCommand.Execute(); + _toolRestoreCommand.Execute(CancellationToken.None); _reporter.Clear(); - _defaultToolUpdateLocalCommand.Execute(); + _defaultToolUpdateLocalCommand.Execute(CancellationToken.None); AssertUpdateSuccess(packageVersion: _packageOriginalVersionA); @@ -367,11 +367,11 @@ public void GivenFeedVersionIsTheSameWhenRunWithPackageIdItShouldShowDifferentSu [TestMethod] public void GivenFeedVersionIsLowerRunPackageIdItShouldThrow() { - _toolRestoreCommand.Execute(); + _toolRestoreCommand.Execute(CancellationToken.None); _mockFeed.Packages[0].Version = "0.9.0"; _reporter.Clear(); - Action a = () => _defaultToolUpdateLocalCommand.Execute(); + Action a = () => _defaultToolUpdateLocalCommand.Execute(CancellationToken.None); a.Should().Throw().And.Message.Should().Contain(string.Format( CliCommandStrings.UpdateLocalToolToLowerVersion, "0.9.0", @@ -388,7 +388,7 @@ ParseResult parseResult = Parser.Parse( $"dotnet tool update {_packageIdA.ToString()} --version 0.9.0 --allow-downgrade"); - _toolRestoreCommand.Execute(); + _toolRestoreCommand.Execute(CancellationToken.None); _mockFeed.Packages[0].Version = "0.9.0"; ToolUpdateLocalCommand toolUpdateLocalCommand = new ToolUpdateLocalCommand( @@ -399,7 +399,7 @@ ParseResult parseResult _localToolsResolverCache, _reporter); - toolUpdateLocalCommand.Execute().Should().Be(0); + toolUpdateLocalCommand.Execute(CancellationToken.None).Should().Be(0); } private void AssertUpdateSuccess( diff --git a/test/dotnet.Tests/CommandTests/Tool/Update/UpdateToolParserTests.cs b/test/dotnet.Tests/CommandTests/Tool/Update/UpdateToolParserTests.cs index a440ed8bf356..84d87986e183 100644 --- a/test/dotnet.Tests/CommandTests/Tool/Update/UpdateToolParserTests.cs +++ b/test/dotnet.Tests/CommandTests/Tool/Update/UpdateToolParserTests.cs @@ -197,7 +197,7 @@ public void UpdateToolWithBothAtVersionAndVersionOptionThrowsError() var toolUpdateCommand = new Cli.Commands.Tool.Update.ToolUpdateCommand(result); - Action a = () => toolUpdateCommand.Execute(); + Action a = () => toolUpdateCommand.Execute(CancellationToken.None); a.Should().Throw().And.Message .Should().Contain(Cli.CliStrings.PackageIdentityArgumentVersionOptionConflict); diff --git a/test/dotnet.Tests/CommandTests/Workload/Clean/GivenDotnetWorkloadClean.cs b/test/dotnet.Tests/CommandTests/Workload/Clean/GivenDotnetWorkloadClean.cs index 8b15bebbb2ac..05f9df05e05d 100644 --- a/test/dotnet.Tests/CommandTests/Workload/Clean/GivenDotnetWorkloadClean.cs +++ b/test/dotnet.Tests/CommandTests/Workload/Clean/GivenDotnetWorkloadClean.cs @@ -67,7 +67,7 @@ public void GivenWorkloadCleanFileBasedItRemovesPacksAndPackRecords(bool userLoc var cleanCommand = cleanAll ? GenerateWorkloadCleanAllCommand(workloadResolver, userProfileDir, dotnetRoot) : GenerateWorkloadCleanCommand(workloadResolver, userProfileDir, dotnetRoot); - cleanCommand.Execute(); + cleanCommand.Execute(CancellationToken.None); AssertExtraneousPacksAreRemoved(extraPackPath, extraPackRecordPath); AssertValidPackCountsMatchExpected(installRoot, expectedPackCount: cleanAll ? 0 : 7, expectedPackRecordCount: cleanAll ? 0 : 8); @@ -102,7 +102,7 @@ public void GivenWorkloadCleanAllFileBasedItCleansAllFeatureBands(bool userLocal MakePseudoWorkloadRecord(oldWorkloadInstallationRecordDirectory); var cleanCommand = GenerateWorkloadCleanAllCommand(workloadResolver, userProfileDir, dotnetRoot); - cleanCommand.Execute(); + cleanCommand.Execute(CancellationToken.None); AssertExtraneousPacksAreRemoved(extraPackPath, extraBelowBandPackRecordPath, true); AssertExtraneousPacksAreRemoved(extraPackPath, extraAboveBandPackRecordPath); @@ -120,7 +120,7 @@ private void InstallWorkload(string userProfileDir, string dotnetRoot, string te var installCommand = new WorkloadInstallCommand(installParseResult, reporter: _reporter, workloadResolverFactory: workloadResolverFactory, nugetPackageDownloader: nugetDownloader, workloadManifestUpdater: _manifestUpdater, tempDirPath: testDirectory); - installCommand.Execute(); + installCommand.Execute(CancellationToken.None); } private WorkloadCleanCommand GenerateWorkloadCleanCommand(WorkloadResolver workloadResolver, string userProfileDir, string dotnetRoot) diff --git a/test/dotnet.Tests/CommandTests/Workload/Install/FailingNuGetPackageInstaller.cs b/test/dotnet.Tests/CommandTests/Workload/Install/FailingNuGetPackageInstaller.cs index 35edcc829c1f..3b061dd1fef5 100644 --- a/test/dotnet.Tests/CommandTests/Workload/Install/FailingNuGetPackageInstaller.cs +++ b/test/dotnet.Tests/CommandTests/Workload/Install/FailingNuGetPackageInstaller.cs @@ -20,7 +20,7 @@ public FailingNuGetPackageDownloader(string testDir) Directory.CreateDirectory(MockPackageDir); } - public Task DownloadPackageAsync(PackageId packageId, NuGetVersion packageVersion, + public Task DownloadPackageAsync(PackageId packageId, CancellationToken cancellationToken, NuGetVersion packageVersion, PackageSourceLocation packageSourceLocation = null, bool includePreview = false, bool? includeUnlisted = null, @@ -32,22 +32,23 @@ public Task DownloadPackageAsync(PackageId packageId, NuGetVersion packa return Task.FromResult(mockPackagePath); } - public Task> ExtractPackageAsync(string packagePath, DirectoryPath targetFolder) + public Task> ExtractPackageAsync(string packagePath, DirectoryPath targetFolder, CancellationToken cancellationToken) { Directory.CreateDirectory(targetFolder.Value); File.WriteAllText(Path.Combine(targetFolder.Value, "testfile.txt"), string.Empty); throw new Exception("Test Failure"); } - public Task GetLatestPackageVersion(PackageId packageId, PackageSourceLocation packageSourceLocation = null, bool includePreview = false) => throw new NotImplementedException(); - public Task> GetLatestPackageVersions(PackageId packageId, int numberOfResults, PackageSourceLocation packageSourceLocation = null, bool includePreview = false) => throw new NotImplementedException(); - public Task GetBestPackageVersionAsync(PackageId packageId, VersionRange versionRange, PackageSourceLocation packageSourceLocation = null) => throw new NotImplementedException(); + public Task GetLatestPackageVersion(PackageId packageId, CancellationToken cancellationToken, PackageSourceLocation packageSourceLocation = null, bool includePreview = false) => throw new NotImplementedException(); + public Task> GetLatestPackageVersions(PackageId packageId, int numberOfResults, CancellationToken cancellationToken, PackageSourceLocation packageSourceLocation = null, bool includePreview = false) => throw new NotImplementedException(); + public Task GetBestPackageVersionAsync(PackageId packageId, VersionRange versionRange, CancellationToken cancellationToken, PackageSourceLocation packageSourceLocation = null) => throw new NotImplementedException(); public Task<(NuGetVersion version, PackageSource source)> GetBestPackageVersionAndSourceAsync(PackageId packageId, - VersionRange versionRange, PackageSourceLocation packageSourceLocation = null, - CancellationToken cancellationToken = default) => throw new NotImplementedException(); + VersionRange versionRange, CancellationToken cancellationToken, + PackageSourceLocation packageSourceLocation = null) => throw new NotImplementedException(); public Task GetPackageUrl(PackageId packageId, + CancellationToken cancellationToken, NuGetVersion packageVersion, PackageSourceLocation packageSourceLocation = null, bool includePreview = false) diff --git a/test/dotnet.Tests/CommandTests/Workload/Install/GivenAFileBasedManifestInstaller.cs b/test/dotnet.Tests/CommandTests/Workload/Install/GivenAFileBasedManifestInstaller.cs index 5fba49a315ae..7f508dda1366 100644 --- a/test/dotnet.Tests/CommandTests/Workload/Install/GivenAFileBasedManifestInstaller.cs +++ b/test/dotnet.Tests/CommandTests/Workload/Install/GivenAFileBasedManifestInstaller.cs @@ -73,7 +73,10 @@ public async Task ExtractManifestAsyncMovesTheExtractedDataDirectoryToTheTargetP var installer = new FileBasedManifestInstaller(nugetDownloader, new DirectoryPath(testDirectory)); var targetPath = Path.Combine(testDirectory, "target-manifest"); - await installer.ExtractManifestAsync(Path.Combine(testDirectory, "fake.nupkg"), targetPath); + await installer.ExtractManifestAsync( + Path.Combine(testDirectory, "fake.nupkg"), + targetPath, + TestContext.CancellationToken); File.Exists(Path.Combine(targetPath, "WorkloadManifest.json")).Should().BeTrue(); } diff --git a/test/dotnet.Tests/CommandTests/Workload/Install/GivenAWindowsMsiManifestInstaller.cs b/test/dotnet.Tests/CommandTests/Workload/Install/GivenAWindowsMsiManifestInstaller.cs index a043b650face..7e65222b2104 100644 --- a/test/dotnet.Tests/CommandTests/Workload/Install/GivenAWindowsMsiManifestInstaller.cs +++ b/test/dotnet.Tests/CommandTests/Workload/Install/GivenAWindowsMsiManifestInstaller.cs @@ -50,8 +50,11 @@ public async Task ExtractManifestAsyncVerifiesTheResolvedMsiPathBeforeAdminInsta using var temporaryDirectory = new TemporaryDirectory(); string? expectedMsiPath = null; var downloader = new Mock(); - downloader.Setup(d => d.ExtractPackageAsync(It.IsAny(), It.IsAny())) - .Returns((string _, DirectoryPath targetFolder) => + downloader.Setup(d => d.ExtractPackageAsync( + It.IsAny(), + It.IsAny(), + It.IsAny())) + .Returns((string _, DirectoryPath targetFolder, CancellationToken _) => { string dataPath = Path.Combine(targetFolder.Value, "data"); Directory.CreateDirectory(dataPath); @@ -72,7 +75,10 @@ public async Task ExtractManifestAsyncVerifiesTheResolvedMsiPathBeforeAdminInsta }); var exception = await Assert.ThrowsExactlyAsync( - () => installer.ExtractManifestAsync("manifest.nupkg", Path.Combine(temporaryDirectory.DirectoryPath, "target"))); + () => installer.ExtractManifestAsync( + "manifest.nupkg", + Path.Combine(temporaryDirectory.DirectoryPath, "target"), + TestContext.CancellationToken)); Assert.AreSame(expectedException, exception); Assert.AreEqual(expectedMsiPath, verifiedMsiPath); diff --git a/test/dotnet.Tests/CommandTests/Workload/Install/GivenDotnetWorkloadInstall.cs b/test/dotnet.Tests/CommandTests/Workload/Install/GivenDotnetWorkloadInstall.cs index aebaeca4484b..f6bc16920f20 100644 --- a/test/dotnet.Tests/CommandTests/Workload/Install/GivenDotnetWorkloadInstall.cs +++ b/test/dotnet.Tests/CommandTests/Workload/Install/GivenDotnetWorkloadInstall.cs @@ -63,7 +63,8 @@ public void GivenWorkloadInstallItGracefullyErrorsOnInvalidWorkloadName() workloadManifestUpdater: new MockWorkloadManifestUpdater(), tempDirPath: testDirectory); - var exceptionThrown = Assert.ThrowsExactly(() => command.Execute()); + var exceptionThrown = Assert.ThrowsExactly( + () => command.Execute(TestContext.CancellationToken)); exceptionThrown.Message.Should().Be(string.Format(CliCommandStrings.WorkloadNotRecognized, invalidWorkloadId)); } @@ -93,7 +94,7 @@ public void GivenWorkloadInstallItCanInstallPacks(bool userLocal, string sdkVers var parseResult = Parser.Parse(new string[] { "dotnet", "workload", "install", "xamarin-android", "--skip-manifest-update" }); (_, var installManager, var installer, _, _, _, _) = GetTestInstallers(parseResult, userLocal, sdkVersion, installedFeatureBand: sdkVersion); - installManager.Execute() + installManager.Execute(CancellationToken.None) .Should().Be(0); installer.GarbageCollectionCalled.Should().BeTrue(); @@ -114,7 +115,7 @@ public void GivenWorkloadInstallItCanRollBackPackInstallation(bool userLocal, st var parseResult = Parser.Parse(new string[] { "dotnet", "workload", "install", "xamarin-android", "xamarin-android-build", "--skip-manifest-update" }); (_, var installManager, var installer, var workloadResolver, _, _, _) = GetTestInstallers(parseResult, userLocal, sdkVersion, failingWorkload: "xamarin-android-build", installedFeatureBand: sdkVersion); - var exceptionThrown = Assert.ThrowsExactly(() => installManager.Execute()); + var exceptionThrown = Assert.ThrowsExactly(() => installManager.Execute(CancellationToken.None)); exceptionThrown.Message.Should().Contain("Failing workload: xamarin-android-build"); var expectedPacks = mockWorkloadIds @@ -139,7 +140,7 @@ public void GivenWorkloadInstallOnFailingRollbackItDisplaysTopLevelError() var installManager = new WorkloadInstallCommand(parseResult, reporter: _reporter, workloadResolverFactory, workloadInstaller: installer); - var exceptionThrown = Assert.ThrowsExactly(() => installManager.Execute()); + var exceptionThrown = Assert.ThrowsExactly(() => installManager.Execute(CancellationToken.None)); exceptionThrown.Message.Should().Contain("Failing workload: xamarin-android-build"); string.Join(" ", _reporter.Lines).Should().Contain("Rollback failure"); } @@ -154,8 +155,8 @@ public void GivenWorkloadInstallItCanUpdateAdvertisingManifests(bool userLocal, var parseResult = Parser.Parse(new string[] { "dotnet", "workload", "install", "xamarin-android" }); (_, var installManager, var installer, _, var manifestUpdater, _, var resolverFactory) = GetTestInstallers(parseResult, userLocal, sdkVersion, installedFeatureBand: sdkVersion); - new WorkloadConfigCommand(Parser.Parse(["dotnet", "workload", "config", "--update-mode", "manifests"]), workloadResolverFactory: resolverFactory).Execute().Should().Be(0); - installManager.Execute() + new WorkloadConfigCommand(Parser.Parse(["dotnet", "workload", "config", "--update-mode", "manifests"]), workloadResolverFactory: resolverFactory).Execute(CancellationToken.None).Should().Be(0); + installManager.Execute(CancellationToken.None) .Should().Be(0); installer.InstalledManifests.Should().BeEmpty(); // Didn't try to alter any installed manifests @@ -176,7 +177,7 @@ public void GivenWorkloadInstallItWarnsOnGarbageCollectionFailure() var workloadResolverFactory = new MockWorkloadResolverFactory(dotnetRoot, "6.0.100", workloadResolver); var installManager = new WorkloadInstallCommand(parseResult, reporter: _reporter, workloadResolverFactory, workloadInstaller: installer); - installManager.Execute() + installManager.Execute(CancellationToken.None) .Should() .Be(0); string.Join(" ", _reporter.Lines).Should().Contain("Failing garbage collection"); @@ -243,8 +244,8 @@ public void GivenWorkloadInstallItCanUpdateInstalledManifests(bool userLocal, st (_, var installManager, var installer, _, _, _, var resolverFactory) = GetTestInstallers(parseResult, userLocal, sdkVersion, manifestUpdates: manifestsToUpdate, installedFeatureBand: sdkVersion); - new WorkloadConfigCommand(Parser.Parse(["dotnet", "workload", "config", "--update-mode", "manifests"]), workloadResolverFactory: resolverFactory).Execute().Should().Be(0); - installManager.Execute() + new WorkloadConfigCommand(Parser.Parse(["dotnet", "workload", "config", "--update-mode", "manifests"]), workloadResolverFactory: resolverFactory).Execute(CancellationToken.None).Should().Be(0); + installManager.Execute(CancellationToken.None) .Should().Be(0); installer.InstalledManifests[0].manifestUpdate.ManifestId.Should().Be(manifestsToUpdate[0].ManifestUpdate.ManifestId); @@ -275,8 +276,8 @@ public void GivenWorkloadInstallFromCacheItInstallsCachedManifest(bool userLocal (_, var installManager, var installer, _, _, _, var resolverFactory) = GetTestInstallers(parseResult, userLocal, sdkVersion, tempDirManifestPath: _manifestPath, manifestUpdates: manifestsToUpdate, installedFeatureBand: sdkVersion); - new WorkloadConfigCommand(Parser.Parse(["dotnet", "workload", "config", "--update-mode", "manifests"]), workloadResolverFactory: resolverFactory).Execute().Should().Be(0); - installManager.Execute(); + new WorkloadConfigCommand(Parser.Parse(["dotnet", "workload", "config", "--update-mode", "manifests"]), workloadResolverFactory: resolverFactory).Execute(CancellationToken.None).Should().Be(0); + installManager.Execute(CancellationToken.None); installer.InstalledManifests[0].manifestUpdate.ManifestId.Should().Be(manifestsToUpdate[0].ManifestUpdate.ManifestId); installer.InstalledManifests[0].manifestUpdate.NewVersion.Should().Be(manifestsToUpdate[0].ManifestUpdate.NewVersion); @@ -295,7 +296,7 @@ public void GivenWorkloadInstallItCanDownloadToOfflineCache(bool userLocal, stri var parseResult = Parser.Parse(new string[] { "dotnet", "workload", "install", "xamarin-android", "--download-to-cache", cachePath }); (_, var installManager, _, _, var manifestUpdater, var packageDownloader, _) = GetTestInstallers(parseResult, userLocal, sdkVersion, tempDirManifestPath: _manifestPath, installedFeatureBand: sdkVersion); - installManager.Execute(); + installManager.Execute(CancellationToken.None); // Manifest packages should have been 'downloaded' and used for pack resolution manifestUpdater.GetManifestPackageDownloadsCallCount.Should().Be(1); @@ -319,7 +320,7 @@ public void GivenWorkloadInstallItCanInstallFromOfflineCache(bool userLocal, str var parseResult = Parser.Parse(new string[] { "dotnet", "workload", "install", "xamarin-android", "--from-cache", cachePath }); (_, var installManager, var installer, _, _, var nugetDownloader, _) = GetTestInstallers(parseResult, userLocal, sdkVersion, installedFeatureBand: sdkVersion); - installManager.Execute(); + installManager.Execute(CancellationToken.None); installer.GarbageCollectionCalled.Should().BeTrue(); installer.CachePath.Should().Contain(cachePath); @@ -339,7 +340,7 @@ public void GivenWorkloadInstallItPrintsDownloadUrls(bool userLocal, string sdkV var parseResult = Parser.Parse(new string[] { "dotnet", "workload", "install", "xamarin-android", "--print-download-link-only" }); (_, var installManager, _, _, _, _, _) = GetTestInstallers(parseResult, userLocal, sdkVersion, tempDirManifestPath: _manifestPath, installedFeatureBand: sdkVersion); - installManager.Execute(); + installManager.Execute(CancellationToken.None); string.Join(" ", _reporter.Lines).Should().Contain("http://mock-url/xamarin.android.sdk.8.4.7.nupkg"); string.Join(" ", _reporter.Lines).Should().Contain("http://mock-url/mock-manifest-package.1.0.5.nupkg"); @@ -362,7 +363,7 @@ public void GivenWorkloadInstallItErrorsOnUnsupportedPlatform() var command = new WorkloadInstallCommand(parseResult, reporter: _reporter, workloadResolverFactory, workloadInstaller: installer, nugetPackageDownloader: nugetDownloader, workloadManifestUpdater: manifestUpdater); - var exceptionThrown = Assert.ThrowsExactly(() => command.Execute()); + var exceptionThrown = Assert.ThrowsExactly(() => command.Execute(CancellationToken.None)); exceptionThrown.Message.Should().Be(String.Format(CliCommandStrings.WorkloadInstallationFailed, String.Format(CliCommandStrings.WorkloadNotSupportedOnPlatform, mockWorkloadId))); } @@ -394,13 +395,13 @@ public void GivenWorkloadInstallItDoesNotRemoveOldInstallsOnRollback(bool userLo var installParseResult = Parser.Parse(new string[] { "dotnet", "workload", "install", existingWorkload }); var installCommand = new WorkloadInstallCommand(installParseResult, reporter: _reporter, workloadResolverFactory, nugetPackageDownloader: new MockNuGetPackageDownloader(tmpDir), workloadManifestUpdater: manifestUpdater, tempDirPath: testDirectory); - installCommand.Execute(); + installCommand.Execute(CancellationToken.None); // Install a workload with a mocked nuget failure installParseResult = Parser.Parse(new string[] { "dotnet", "workload", "install", installingWorkload }); installCommand = new WorkloadInstallCommand(installParseResult, reporter: _reporter, workloadResolverFactory, nugetPackageDownloader: nugetDownloader, workloadManifestUpdater: manifestUpdater, tempDirPath: testDirectory); - var exceptionThrown = Assert.ThrowsExactly(() => installCommand.Execute()); + var exceptionThrown = Assert.ThrowsExactly(() => installCommand.Execute(CancellationToken.None)); exceptionThrown.Message.Should().Contain("Test Failure"); // Existing installation is still present @@ -450,12 +451,12 @@ static void CreateFile(string path) var installParseResult = Parser.Parse(new string[] { "dotnet", "workload", "install", existingWorkload }); var installCommand = new WorkloadInstallCommand(installParseResult, reporter: _reporter, prev7workloadResolverFactory, nugetPackageDownloader: new MockNuGetPackageDownloader(tmpDir), workloadManifestUpdater: manifestUpdater, tempDirPath: testDirectory); - installCommand.Execute(); + installCommand.Execute(CancellationToken.None); // Install workload for RC1 installCommand = new WorkloadInstallCommand(installParseResult, reporter: _reporter, rc1WorkloadResolverFactory, nugetPackageDownloader: new MockNuGetPackageDownloader(tmpDir), workloadManifestUpdater: manifestUpdater, tempDirPath: testDirectory); - installCommand.Execute(); + installCommand.Execute(CancellationToken.None); // Existing installation is present var prev7InstallRecordPath = Path.Combine(dotnetRoot, "metadata", "workloads", prev7FormattedFeatureVersion, "InstalledWorkloads"); @@ -541,7 +542,7 @@ public void GivenWorkloadInstallItErrorsOnInvalidWorkloadRollbackFile() var installCommand = new WorkloadInstallCommand(installParseResult, reporter: _reporter, workloadResolverFactory, nugetPackageDownloader: new MockNuGetPackageDownloader(tmpDir), tempDirPath: testDirectory); - var ex = Assert.ThrowsExactly(() => installCommand.Execute()); + var ex = Assert.ThrowsExactly(() => installCommand.Execute(CancellationToken.None)); ex.Message.Should().StartWith("Workload installation failed:"); string.Join(" ", _reporter.Lines).Should().Contain("Workload installation failed."); } @@ -567,7 +568,7 @@ public void GivenWorkloadInstallItWarnsWhenManifestFromRollbackFileIsntInstalled var installCommand = new WorkloadInstallCommand(installParseResult, reporter: _reporter, workloadResolverFactory, nugetPackageDownloader: new MockNuGetPackageDownloader(tmpDir), tempDirPath: testDirectory); - installCommand.Execute().Should().Be(0); + installCommand.Execute(CancellationToken.None).Should().Be(0); string.Join(" ", _reporter.Lines).Should().Contain("Invalid rollback definition. The manifest IDs in rollback definition"); } @@ -589,7 +590,7 @@ public void GivenWorkloadInstallItWarnsWhenTheWorkloadIsAlreadyInstalled() var installParseResult = Parser.Parse(new string[] { "dotnet", "workload", "install", workloadId }); var installCommand = new WorkloadInstallCommand(installParseResult, reporter: _reporter, workloadResolverFactory, nugetPackageDownloader: new MockNuGetPackageDownloader(tmpDir), workloadManifestUpdater: manifestUpdater, tempDirPath: testDirectory); - installCommand.Execute() + installCommand.Execute(CancellationToken.None) .Should().Be(0); _reporter.Clear(); @@ -597,7 +598,7 @@ public void GivenWorkloadInstallItWarnsWhenTheWorkloadIsAlreadyInstalled() installParseResult = Parser.Parse(new string[] { "dotnet", "workload", "install", workloadId, "mock-2" }); installCommand = new WorkloadInstallCommand(installParseResult, reporter: _reporter, workloadResolverFactory, nugetPackageDownloader: new MockNuGetPackageDownloader(tmpDir), workloadManifestUpdater: manifestUpdater, tempDirPath: testDirectory); - installCommand.Execute() + installCommand.Execute(CancellationToken.None) .Should().Be(0); // Install command warns @@ -659,7 +660,7 @@ public void ShowManifestUpdatesWhenVerbosityIsDetailedOrDiagnostic(string verbos (_, var installManager, _, _, _, _, _) = GetTestInstallers(parseResult, true, sdkFeatureBand, manifestUpdates: manifestsToUpdate); - installManager.Execute().Should().Be(0); + installManager.Execute(CancellationToken.None).Should().Be(0); string.Join(" ", _reporter.Lines).Should().Contain(CliCommandStrings.CheckForUpdatedWorkloadManifests); string.Join(" ", _reporter.Lines).Should().Contain(string.Format(CliCommandStrings.CheckForUpdatedWorkloadManifests, "mock-manifest")); diff --git a/test/dotnet.Tests/CommandTests/Workload/Install/GivenFileBasedWorkloadInstall.cs b/test/dotnet.Tests/CommandTests/Workload/Install/GivenFileBasedWorkloadInstall.cs index d371b2b2d6fd..59024e3f77ed 100644 --- a/test/dotnet.Tests/CommandTests/Workload/Install/GivenFileBasedWorkloadInstall.cs +++ b/test/dotnet.Tests/CommandTests/Workload/Install/GivenFileBasedWorkloadInstall.cs @@ -148,7 +148,11 @@ public void GivenManagedInstallItCanInstallDirectoryPacks() var packId = "Xamarin.Android.Sdk"; var packVersion = "8.4.7"; var version = "6.0.100"; - CliTransaction.RunNew(context => installer.InstallWorkloads(new[] { new WorkloadId("android-sdk-workload") }, new SdkFeatureBand(version), context)); + CliTransaction.RunNew(context => installer.InstallWorkloads( + [new WorkloadId("android-sdk-workload")], + new SdkFeatureBand(version), + context, + TestContext.CancellationToken)); var mockNugetInstaller = nugetInstaller as MockNuGetPackageDownloader; mockNugetInstaller.DownloadCallParams.Count.Should().Be(1); @@ -171,7 +175,11 @@ public void GivenManagedInstallItCanInstallSingleFilePacks() var packVersion = "1.0.3"; var version = "6.0.100"; - CliTransaction.RunNew(context => installer.InstallWorkloads(new[] { new WorkloadId("android-templates-workload") }, new SdkFeatureBand(version), context)); + CliTransaction.RunNew(context => installer.InstallWorkloads( + [new WorkloadId("android-templates-workload")], + new SdkFeatureBand(version), + context, + TestContext.CancellationToken)); (nugetInstaller as MockNuGetPackageDownloader).DownloadCallParams.Count.Should().Be(1); (nugetInstaller as MockNuGetPackageDownloader).DownloadCallParams[0].Should().BeEquivalentTo((new PackageId(packId), new NuGetVersion(packVersion), null as DirectoryPath?, null as PackageSourceLocation)); @@ -196,7 +204,11 @@ public void GivenManagedInstallItCanInstallPacksWithAliases() var packVersion = "8.4.7"; var version = "6.0.100"; - CliTransaction.RunNew(context => installer.InstallWorkloads(new[] { new WorkloadId("android-buildtools-workload") }, new SdkFeatureBand(version), context)); + CliTransaction.RunNew(context => installer.InstallWorkloads( + [new WorkloadId("android-buildtools-workload")], + new SdkFeatureBand(version), + context, + TestContext.CancellationToken)); mockNugetInstaller.DownloadCallParams.Count.Should().Be(1); mockNugetInstaller.DownloadCallParams[0].Should().BeEquivalentTo((new PackageId(packId), new NuGetVersion(packVersion), null as DirectoryPath?, null as PackageSourceLocation)); @@ -216,7 +228,11 @@ public void GivenManagedInstallItHonorsNuGetSources() var packVersion = "8.4.7"; var version = "6.0.100"; - CliTransaction.RunNew(context => installer.InstallWorkloads(new[] { new WorkloadId("android-sdk-workload") }, new SdkFeatureBand(version), context)); + CliTransaction.RunNew(context => installer.InstallWorkloads( + [new WorkloadId("android-sdk-workload")], + new SdkFeatureBand(version), + context, + TestContext.CancellationToken)); var mockNugetInstaller = nugetInstaller as MockNuGetPackageDownloader; mockNugetInstaller.DownloadCallParams.Count.Should().Be(1); @@ -234,7 +250,11 @@ public void GivenManagedInstallItDetectsInstalledPacks() // Mock installing the pack Directory.CreateDirectory(Path.Combine(dotnetRoot, "packs", packId, packVersion)); - CliTransaction.RunNew(context => installer.InstallWorkloads(new[] { new WorkloadId("android-sdk-workload") }, new SdkFeatureBand(version), context)); + CliTransaction.RunNew(context => installer.InstallWorkloads( + [new WorkloadId("android-sdk-workload")], + new SdkFeatureBand(version), + context, + TestContext.CancellationToken)); (nugetInstaller as MockNuGetPackageDownloader).DownloadCallParams.Count.Should().Be(0); } @@ -249,7 +269,11 @@ public void GivenManagedInstallItCanRollBackInstallFailures() var exceptionThrown = Assert.ThrowsExactly(() => { - CliTransaction.RunNew(context => installer.InstallWorkloads(new[] { new WorkloadId("android-sdk-workload") }, new SdkFeatureBand(version), context)); + CliTransaction.RunNew(context => installer.InstallWorkloads( + [new WorkloadId("android-sdk-workload")], + new SdkFeatureBand(version), + context, + TestContext.CancellationToken)); }); exceptionThrown.Message.Should().Be("Test Failure"); var failingNugetInstaller = nugetInstaller as FailingNuGetPackageDownloader; @@ -293,7 +317,7 @@ public void GivenManagedInstallItDoesNotRemovePacksWithInstallRecords() var installedWorkloadsPath = Path.Combine(dotnetRoot, "metadata", "workloads", sdkVersions[1], "InstalledWorkloads", "xamarin-android-build"); File.WriteAllText(installedWorkloadsPath, string.Empty); - installer.GarbageCollect(getResolver); + installer.GarbageCollect(getResolver, TestContext.CancellationToken); Directory.EnumerateFileSystemEntries(installedPacksPath) .Should() @@ -328,7 +352,10 @@ public void GivenManagedInstallItCanInstallManifestVersion() var manifestUpdate = new ManifestVersionUpdate(manifestId, manifestVersion, featureBand.ToString()); - CliTransaction.RunNew(context => installer.InstallWorkloadManifest(manifestUpdate, context)); + CliTransaction.RunNew(context => installer.InstallWorkloadManifest( + manifestUpdate, + context, + TestContext.CancellationToken)); var mockNugetInstaller = nugetDownloader as MockNuGetPackageDownloader; mockNugetInstaller.DownloadCallParams.Count.Should().Be(1); @@ -388,7 +415,12 @@ public void GivenManagedInstallItCanInstallPacksFromOfflineCache() var nupkgPath = Path.Combine(cachePath, $"{packId}.{packVersion}.nupkg"); File.Create(nupkgPath).Close(); - CliTransaction.RunNew(context => installer.InstallWorkloads(new[] { new WorkloadId("android-sdk-workload") }, new SdkFeatureBand(version), context, new DirectoryPath(cachePath))); + CliTransaction.RunNew(context => installer.InstallWorkloads( + [new WorkloadId("android-sdk-workload")], + new SdkFeatureBand(version), + context, + TestContext.CancellationToken, + new DirectoryPath(cachePath))); var mockNugetInstaller = nugetInstaller as MockNuGetPackageDownloader; // We shouldn't download anything, use the cache @@ -413,7 +445,12 @@ public void GivenManagedInstallItCanErrorsWhenMissingOfflineCache() var cachePath = Path.Combine(dotnetRoot, "MockCache"); var exceptionThrown = Assert.ThrowsExactly(() => - CliTransaction.RunNew(context => installer.InstallWorkloads(new[] { new WorkloadId("android-sdk-workload") }, new SdkFeatureBand(version), context, new DirectoryPath(cachePath)))); + CliTransaction.RunNew(context => installer.InstallWorkloads( + [new WorkloadId("android-sdk-workload")], + new SdkFeatureBand(version), + context, + TestContext.CancellationToken, + new DirectoryPath(cachePath)))); exceptionThrown.InnerException.Message.Should().Contain(packId); exceptionThrown.InnerException.Message.Should().Contain(packVersion); exceptionThrown.InnerException.Message.Should().Contain(cachePath); diff --git a/test/dotnet.Tests/CommandTests/Workload/Install/GivenMsiCancellation.cs b/test/dotnet.Tests/CommandTests/Workload/Install/GivenMsiCancellation.cs new file mode 100644 index 000000000000..0baabe955dcf --- /dev/null +++ b/test/dotnet.Tests/CommandTests/Workload/Install/GivenMsiCancellation.cs @@ -0,0 +1,192 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Runtime.Versioning; +using Microsoft.DotNet.Cli.Commands.Workload.Install; +using Microsoft.DotNet.Cli.Installer.Windows; +using Microsoft.DotNet.Cli.NuGetPackageDownloader; +using Microsoft.DotNet.Cli.Utils; +using Microsoft.Extensions.EnvironmentAbstractions; +using Microsoft.NET.Sdk.WorkloadManifestReader; +using Moq; +using static Microsoft.NET.Sdk.WorkloadManifestReader.WorkloadResolver; + +namespace Microsoft.DotNet.Cli.Workload.Install.Tests; + +[TestClass] +[OSCondition(OperatingSystems.Windows)] +[SupportedOSPlatform("windows")] +public class GivenMsiCancellation : SdkTest +{ + [TestMethod] + [DataRow(false, false)] + [DataRow(true, false)] + [DataRow(false, true)] + [DataRow(true, true)] + public void CancellationAfterInstallationStartsStillRollsBack(bool manifest, bool cancelDuringInstallation) + { + string directory = TestAssetsManager.CreateTestDirectory().Path; + using CancellationTokenSource cancellation = new(); + using TimestampedFileLogger logger = new(Path.Combine(directory, "install.log")); + var resolver = new Mock(); + WorkloadId workloadId = new("test-workload"); + WorkloadPackId packId = new("test-pack"); + resolver.Setup(r => r.GetInstalledManifests()).Returns([]); + resolver.Setup(r => r.GetPacksInWorkload(workloadId)).Returns([packId]); + resolver.Setup(r => r.TryGetPackInfo(packId)).Returns(new PackInfo( + packId, "1.0.0", WorkloadPackKind.Sdk, directory, "test-pack")); + var installer = new TestInstaller(directory, logger, resolver.Object); + var originalCancellation = new OperationCanceledException(cancellation.Token); + if (cancelDuringInstallation) + { + installer.OnInstall = () => + { + cancellation.Cancel(); + throw originalCancellation; + }; + } + + try + { + Action install = () => CliTransaction.RunNew(context => + { + if (manifest) + { + installer.InstallWorkloadManifest( + new ManifestVersionUpdate(new ManifestId("test-manifest"), new ManifestVersion("1.0.0"), "6.0.100"), + context, cancellation.Token); + } + else + { + installer.InstallWorkloads([workloadId], new SdkFeatureBand("6.0.100"), context, cancellation.Token); + } + + installer.Actions.Should().Equal(InstallAction.Install); + cancellation.Cancel(); + throw originalCancellation; + }); + + install.Should().Throw().Which.Should().BeSameAs(originalCancellation); + installer.Actions.Should().Equal(InstallAction.Install, InstallAction.Uninstall); + installer.Installed.Should().BeFalse(); + installer.PayloadTokens.Should().HaveCount(2); + installer.PayloadTokens[0].Should().Be(cancellation.Token); + installer.PayloadTokens[1].CanBeCanceled.Should().BeTrue(); + installer.PayloadTokens[1].Should().NotBe(cancellation.Token); + installer.PayloadTokens[1].IsCancellationRequested.Should().BeFalse(); + } + finally + { + installer.Shutdown(); + } + } + + [TestMethod] + [DataRow(true)] + [DataRow(false)] + public void CancellationWithoutAManifestInstallationPreservesTheExistingManifest(bool precancelled) + { + string directory = TestAssetsManager.CreateTestDirectory().Path; + using CancellationTokenSource cancellation = new(); + using TimestampedFileLogger logger = new(Path.Combine(directory, "install.log")); + var installer = new TestInstaller(directory, logger, new Mock().Object, installed: true); + var originalCancellation = new OperationCanceledException(cancellation.Token); + if (precancelled) + { + cancellation.Cancel(); + } + + try + { + Action install = () => CliTransaction.RunNew(context => + { + installer.InstallWorkloadManifest( + new ManifestVersionUpdate(new ManifestId("test-manifest"), new ManifestVersion("1.0.0"), "6.0.100"), + context, cancellation.Token); + installer.Actions.Should().Equal(InstallAction.None); + cancellation.Cancel(); + throw originalCancellation; + }); + + var exception = install.Should().Throw().Which; + exception.CancellationToken.Should().Be(cancellation.Token); + if (precancelled) + { + installer.Actions.Should().BeEmpty(); + installer.PayloadTokens.Should().BeEmpty(); + } + else + { + exception.Should().BeSameAs(originalCancellation); + installer.Actions.Should().Equal(InstallAction.None); + installer.PayloadTokens.Should().ContainSingle(); + } + + installer.Installed.Should().BeTrue(); + } + finally + { + installer.Shutdown(); + } + } + + private sealed class TestInstaller : NetSdkMsiInstallerClient + { + private readonly MsiPayload _payload; + public List Actions { get; } = []; + public List PayloadTokens { get; } = []; + public bool Installed { get; private set; } + public Action? OnInstall { get; set; } + + public TestInstaller(string directory, ISetupLogger logger, IWorkloadResolver resolver, bool installed = false) + : base(new TestElevationContext(), logger, verifyMsiSignature: false, resolver, new SdkFeatureBand("6.0.100"), + new MockNuGetPackageDownloader(), reporter: NullReporter.Instance) + { + Installed = installed; + string manifestPath = Path.Combine(directory, "msi.json"); + File.WriteAllText(manifestPath, $$""" + {"Payload":"test.msi","ProductCode":"{{Guid.NewGuid():B}}","ProductVersion":"1.0.0","ProviderKeyName":"{{Guid.NewGuid():B}}"} + """); + _payload = new MsiPayload(manifestPath, Path.Combine(directory, "test.msi")); + } + + protected override MsiPayload GetCachedMsiPayload( + string packageId, string packageVersion, CancellationToken cancellationToken, DirectoryPath? offlineCache) + { + cancellationToken.ThrowIfCancellationRequested(); + PayloadTokens.Add(cancellationToken); + return _payload; + } + + protected override void ValidateMsiDatabase(MsiPayload msiPayload) { } + + protected override DetectState DetectPackage(string productCode, out Version installedVersion) + { + installedVersion = new Version("1.0.0"); + return Installed ? DetectState.Present : DetectState.Absent; + } + + protected override void ExecutePackage(MsiPayload msi, InstallAction action, string? displayName = null) + { + Actions.Add(action); + if (action == InstallAction.Install) + { + Installed = true; + OnInstall?.Invoke(); + } + else if (action == InstallAction.Uninstall) + { + Installed = false; + } + } + + protected override void UpdateDependent(InstallRequestType requestType, string providerKeyName, string dependent) { } + } + + private sealed class TestElevationContext : InstallElevationContextBase + { + public override bool IsClient => true; + public override bool IsElevated => false; + public override void Elevate() => throw new InvalidOperationException("The test must not elevate."); + } +} diff --git a/test/dotnet.Tests/CommandTests/Workload/Install/GivenWorkloadManifestUpdater.cs b/test/dotnet.Tests/CommandTests/Workload/Install/GivenWorkloadManifestUpdater.cs index 8f8d4553080c..d3abfbc5f556 100644 --- a/test/dotnet.Tests/CommandTests/Workload/Install/GivenWorkloadManifestUpdater.cs +++ b/test/dotnet.Tests/CommandTests/Workload/Install/GivenWorkloadManifestUpdater.cs @@ -37,7 +37,9 @@ public async Task GivenWorkloadManifestUpdateItCanUpdateAdvertisingManifests() { (var manifestUpdater, var nugetDownloader, _, _) = GetTestUpdater(); - await manifestUpdater.UpdateAdvertisingManifestsAsync(true); + await manifestUpdater.UpdateAdvertisingManifestsAsync( + TestContext.CancellationToken, + includePreviews: true); nugetDownloader.DownloadCallParams.Should().BeEquivalentTo(GetExpectedDownloadedPackages()); } @@ -46,8 +48,8 @@ public async Task GivenAdvertisingManifestUpdateItUpdatesWhenNoSentinelExists() { (var manifestUpdater, var nugetDownloader, var sentinelPath, var configCommand) = GetTestUpdater(); - configCommand.Execute().Should().Be(0); - await manifestUpdater.BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(); + configCommand.Execute(TestContext.CancellationToken).Should().Be(0); + await manifestUpdater.BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(TestContext.CancellationToken); nugetDownloader.DownloadCallParams.Should().BeEquivalentTo(GetExpectedDownloadedPackages()); File.Exists(sentinelPath).Should().BeTrue(); } @@ -61,8 +63,8 @@ public async Task GivenAdvertisingManifestUpdateItUpdatesWhenDue() File.WriteAllText(sentinelPath, string.Empty); var createTime = DateTime.Now; - configCommand.Execute().Should().Be(0); - await manifestUpdater.BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(); + configCommand.Execute(TestContext.CancellationToken).Should().Be(0); + await manifestUpdater.BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(TestContext.CancellationToken); nugetDownloader.DownloadCallParams.Should().BeEquivalentTo(GetExpectedDownloadedPackages()); File.Exists(sentinelPath).Should().BeTrue(); @@ -77,7 +79,7 @@ public async Task GivenAdvertisingManifestUpdateItDoesNotUpdateWhenNotDue() File.Create(sentinelPath).Close(); var createTime = DateTime.Now; - await manifestUpdater.BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(); + await manifestUpdater.BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(TestContext.CancellationToken); nugetDownloader.DownloadCallParams.Should().BeEmpty(); File.GetLastAccessTime(sentinelPath).Should().BeBefore(createTime); } @@ -88,7 +90,7 @@ public async Task GivenAdvertisingManifestUpdateItHonorsDisablingEnvVar() Func getEnvironmentVariable = (envVar) => envVar.Equals(EnvironmentVariableNames.WORKLOAD_UPDATE_NOTIFY_DISABLE) ? "true" : string.Empty; (var manifestUpdater, var nugetDownloader, _, _) = GetTestUpdater(getEnvironmentVariable: getEnvironmentVariable); - await manifestUpdater.BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(); + await manifestUpdater.BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(TestContext.CancellationToken); nugetDownloader.DownloadCallParams.Should().BeEmpty(); } @@ -251,13 +253,18 @@ public async Task ItCanFallbackAndAdvertiseCorrectUpdate(bool useOfflineCache) Directory.CreateDirectory(offlineCacheDir); File.Create(Path.Combine(offlineCacheDir, $"{testManifestName}.Manifest-6.0.200.nupkg")).Close(); - await manifestUpdater.UpdateAdvertisingManifestsAsync(includePreviews: true, offlineCache: new DirectoryPath(offlineCacheDir)); + await manifestUpdater.UpdateAdvertisingManifestsAsync( + TestContext.CancellationToken, + includePreviews: true, + offlineCache: new DirectoryPath(offlineCacheDir)); } else { nugetDownloader.PackageIdsToNotFind.Add($"{testManifestName}.Manifest-6.0.300"); - await manifestUpdater.UpdateAdvertisingManifestsAsync(includePreviews: true); + await manifestUpdater.UpdateAdvertisingManifestsAsync( + TestContext.CancellationToken, + includePreviews: true); // Assert // 6.0.300 manifest was requested and then 6.0.200 manifest was requested @@ -327,14 +334,19 @@ public async Task ItCanFallbackWithNoUpdates(bool useOfflineCache) offlineCacheDir = Path.Combine(testDir, "offlineCache"); Directory.CreateDirectory(offlineCacheDir); // empty dir because it shouldn't find any manifests to update - await manifestUpdater.UpdateAdvertisingManifestsAsync(includePreviews: true, offlineCache: new DirectoryPath(offlineCacheDir)); + await manifestUpdater.UpdateAdvertisingManifestsAsync( + TestContext.CancellationToken, + includePreviews: true, + offlineCache: new DirectoryPath(offlineCacheDir)); } else { nugetDownloader.PackageIdsToNotFind.Add($"{testManifestName}.Manifest-6.0.300"); nugetDownloader.PackageIdsToNotFind.Add($"{testManifestName}.Manifest-6.0.200"); - await manifestUpdater.UpdateAdvertisingManifestsAsync(includePreviews: true); + await manifestUpdater.UpdateAdvertisingManifestsAsync( + TestContext.CancellationToken, + includePreviews: true); // 6.0.300 manifest was requested and then 6.0.200 manifest was requested // we can't assert this for the offline cache @@ -393,13 +405,18 @@ public async Task GivenNoUpdatesAreAvailableAndNoRollbackItGivesAppropriateMessa offlineCacheDir = Path.Combine(testDir, "offlineCache"); Directory.CreateDirectory(offlineCacheDir); // empty dir because it shouldn't find any manifests to update - await manifestUpdater.UpdateAdvertisingManifestsAsync(includePreviews: true, offlineCache: new DirectoryPath(offlineCacheDir)); + await manifestUpdater.UpdateAdvertisingManifestsAsync( + TestContext.CancellationToken, + includePreviews: true, + offlineCache: new DirectoryPath(offlineCacheDir)); } else { nugetDownloader.PackageIdsToNotFind.Add($"{testManifestName}.Manifest-6.0.300"); - await manifestUpdater.UpdateAdvertisingManifestsAsync(includePreviews: true); + await manifestUpdater.UpdateAdvertisingManifestsAsync( + TestContext.CancellationToken, + includePreviews: true); // only 6.0.300 manifest was requested @@ -566,7 +583,11 @@ public async Task GivenWorkloadManifestUpdateItChoosesHighestManifestVersionInCa var installationRepo = new MockInstallationRecordRepository(); var installer = new MockPackWorkloadInstaller(dotnetRoot); var manifestUpdater = new WorkloadManifestUpdater(_reporter, workloadResolver, nugetDownloader, testDir, installationRepo, installer); - await manifestUpdater.UpdateAdvertisingManifestsAsync(false, false, new DirectoryPath(offlineCache)); + await manifestUpdater.UpdateAdvertisingManifestsAsync( + TestContext.CancellationToken, + includePreviews: false, + useWorkloadSets: false, + offlineCache: new DirectoryPath(offlineCache)); // We should have chosen the higher version manifest package to install/ extract installer.ExtractCallParams.Count().Should().Be(1); @@ -653,27 +674,27 @@ public async Task TestSideBySideUpdateChecks() new WorkloadConfigCommand( Parser.Parse(["dotnet", "workload", "config", "--update-mode", "manifests"]), - workloadResolverFactory: new MockWorkloadResolverFactory(testDir, "6.0.100", resolver1)).Execute().Should().Be(0); - await updater1.BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(); + workloadResolverFactory: new MockWorkloadResolverFactory(testDir, "6.0.100", resolver1)).Execute(TestContext.CancellationToken).Should().Be(0); + await updater1.BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(TestContext.CancellationToken); File.Exists(sentinelPath2).Should().BeFalse(); downloader1.DownloadCallParams.Should().BeEquivalentTo(GetExpectedDownloadedPackages("6.0.100")); new WorkloadConfigCommand( Parser.Parse(["dotnet", "workload", "config", "--update-mode", "manifests"]), - workloadResolverFactory: new MockWorkloadResolverFactory(testDir, "6.0.200", resolver2)).Execute().Should().Be(0); - await updater2.BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(); + workloadResolverFactory: new MockWorkloadResolverFactory(testDir, "6.0.200", resolver2)).Execute(TestContext.CancellationToken).Should().Be(0); + await updater2.BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(TestContext.CancellationToken); File.Exists(sentinelPath2).Should().BeTrue(); downloader2.DownloadCallParams.Should().BeEquivalentTo(GetExpectedDownloadedPackages("6.0.200")); var updateTime2 = DateTime.Now; downloader1.DownloadCallParams.Clear(); - await updater1.BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(); + await updater1.BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(TestContext.CancellationToken); downloader1.DownloadCallParams.Should().BeEmpty(); File.GetLastAccessTime(sentinelPath1).Should().BeBefore(updateTime2); downloader2.DownloadCallParams.Clear(); - await updater2.BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(); + await updater2.BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(TestContext.CancellationToken); // var updateTime1 = DateTime.Now; downloader2.DownloadCallParams.Should().BeEmpty(); File.GetLastAccessTime(sentinelPath2).Should().BeCloseTo(updateTime2, 1.Seconds()); diff --git a/test/dotnet.Tests/CommandTests/Workload/Install/MockPackWorkloadInstaller.cs b/test/dotnet.Tests/CommandTests/Workload/Install/MockPackWorkloadInstaller.cs index 9c7bed6b7e9a..8177bbc3774a 100644 --- a/test/dotnet.Tests/CommandTests/Workload/Install/MockPackWorkloadInstaller.cs +++ b/test/dotnet.Tests/CommandTests/Workload/Install/MockPackWorkloadInstaller.cs @@ -23,6 +23,7 @@ internal class MockPackWorkloadInstaller : IInstaller new List<(ManifestVersionUpdate manifestUpdate, DirectoryPath?)>(); public string CachePath; public bool GarbageCollectionCalled = false; + public bool ShutdownCalled = false; public bool InstallWorkloadSetCalled = false; public MockInstallationRecordRepository InstallationRecordRepository; public bool FailingRollback; @@ -80,8 +81,9 @@ public void AdjustWorkloadSetInInstallState(SdkFeatureBand sdkFeatureBand, strin } } - public void InstallWorkloads(IEnumerable workloadIds, SdkFeatureBand sdkFeatureBand, ITransactionContext transactionContext, DirectoryPath? offlineCache = null) + public void InstallWorkloads(IEnumerable workloadIds, SdkFeatureBand sdkFeatureBand, ITransactionContext transactionContext, CancellationToken cancellationToken, DirectoryPath? offlineCache = null) { + cancellationToken.ThrowIfCancellationRequested(); List packs = new(); transactionContext.Run(action: () => @@ -119,10 +121,15 @@ public void InstallWorkloads(IEnumerable workloadIds, SdkFeatureBand }); } - public WorkloadSet GetWorkloadSetContents(string workloadSetVersion) => WorkloadSet.FromJson(workloadSetContents[workloadSetVersion], new SdkFeatureBand("6.0.100")); + public WorkloadSet GetWorkloadSetContents(string workloadSetVersion, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + return WorkloadSet.FromJson(workloadSetContents[workloadSetVersion], new SdkFeatureBand("6.0.100")); + } - public WorkloadSet InstallWorkloadSet(ITransactionContext context, string workloadSetVersion, DirectoryPath? offlineCache = null) + public WorkloadSet InstallWorkloadSet(ITransactionContext context, string workloadSetVersion, CancellationToken cancellationToken, DirectoryPath? offlineCache = null) { + cancellationToken.ThrowIfCancellationRequested(); InstallWorkloadSetCalled = true; InstalledWorkloadSet = WorkloadSet.FromJson(workloadSetContents[workloadSetVersion], new SdkFeatureBand("6.0.100")); InstalledWorkloadSet.Version = workloadSetVersion; @@ -139,14 +146,16 @@ public IEnumerable GetWorkloadHistoryRecords(string sdkFe return HistoryRecords; } - public void RepairWorkloads(IEnumerable workloadIds, SdkFeatureBand sdkFeatureBand, DirectoryPath? offlineCache = null) + public void RepairWorkloads(IEnumerable workloadIds, SdkFeatureBand sdkFeatureBand, CancellationToken cancellationToken, DirectoryPath? offlineCache = null) { + cancellationToken.ThrowIfCancellationRequested(); // Repair is essentially a reinstall of existing workloads - CliTransaction.RunNew(context => InstallWorkloads(workloadIds, sdkFeatureBand, context, offlineCache)); + CliTransaction.RunNew(context => InstallWorkloads(workloadIds, sdkFeatureBand, context, cancellationToken, offlineCache)); } - public void GarbageCollect(Func getResolverForWorkloadSet, DirectoryPath? offlineCache = null, bool cleanAllPacks = false) + public void GarbageCollect(Func getResolverForWorkloadSet, CancellationToken cancellationToken, DirectoryPath? offlineCache = null, bool cleanAllPacks = false) { + cancellationToken.ThrowIfCancellationRequested(); if (FailingGarbageCollection) { throw new Exception("Failing garbage collection"); @@ -161,8 +170,9 @@ public IWorkloadInstallationRecordRepository GetWorkloadInstallationRecordReposi return InstallationRecordRepository; } - public void InstallWorkloadManifest(ManifestVersionUpdate manifestUpdate, ITransactionContext transactionContext, DirectoryPath? offlineCache = null) + public void InstallWorkloadManifest(ManifestVersionUpdate manifestUpdate, ITransactionContext transactionContext, CancellationToken cancellationToken, DirectoryPath? offlineCache = null) { + cancellationToken.ThrowIfCancellationRequested(); InstalledManifests.Add((manifestUpdate, offlineCache)); // Also create the actual manifest file on disk so that SdkDirectoryWorkloadManifestProvider can find it @@ -202,7 +212,7 @@ public IEnumerable GetDownloads(IEnumerable worklo public void Shutdown() { - + ShutdownCalled = true; } public PackageId GetManifestPackageId(ManifestId manifestId, SdkFeatureBand featureBand) @@ -212,8 +222,9 @@ public PackageId GetManifestPackageId(ManifestId manifestId, SdkFeatureBand feat public List<(string nupkgPath, string targetPath)> ExtractCallParams = new(); - public Task ExtractManifestAsync(string nupkgPath, string targetPath) + public Task ExtractManifestAsync(string nupkgPath, string targetPath, CancellationToken cancellationToken) { + cancellationToken.ThrowIfCancellationRequested(); ExtractCallParams.Add((nupkgPath, targetPath)); if (Directory.Exists(targetPath)) diff --git a/test/dotnet.Tests/CommandTests/Workload/Install/MockWorkloadManifestUpdater.cs b/test/dotnet.Tests/CommandTests/Workload/Install/MockWorkloadManifestUpdater.cs index af555afdcfc8..7b785b759462 100644 --- a/test/dotnet.Tests/CommandTests/Workload/Install/MockWorkloadManifestUpdater.cs +++ b/test/dotnet.Tests/CommandTests/Workload/Install/MockWorkloadManifestUpdater.cs @@ -28,8 +28,9 @@ public MockWorkloadManifestUpdater(IEnumerable mani _resolver = resolver; } - public Task UpdateAdvertisingManifestsAsync(bool includePreview, bool useWorkloadSets = false, DirectoryPath? cachePath = null) + public Task UpdateAdvertisingManifestsAsync(CancellationToken cancellationToken, bool includePreview, bool useWorkloadSets = false, DirectoryPath? cachePath = null) { + cancellationToken.ThrowIfCancellationRequested(); UpdateAdvertisingManifestsCallCount++; return Task.CompletedTask; } @@ -56,8 +57,9 @@ public IEnumerable CalculateManifestUpdatesFromHistory(Wo } } - public Task> GetManifestPackageDownloadsAsync(bool includePreviews, SdkFeatureBand providedSdkFeatureBand, SdkFeatureBand installedSdkFeatureBand) + public Task> GetManifestPackageDownloadsAsync(CancellationToken cancellationToken, bool includePreviews, SdkFeatureBand providedSdkFeatureBand, SdkFeatureBand installedSdkFeatureBand) { + cancellationToken.ThrowIfCancellationRequested(); GetManifestPackageDownloadsCallCount++; return Task.FromResult>(new List() { @@ -75,7 +77,7 @@ public IEnumerable CalculateManifestRollbacks(string roll return _manifestUpdates.Select(t => t.ManifestUpdate); } - public Task BackgroundUpdateAdvertisingManifestsWhenRequiredAsync() => throw new NotImplementedException(); + public Task BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(CancellationToken cancellationToken) => throw new NotImplementedException(); public IEnumerable GetUpdatableWorkloadsToAdvertise(IEnumerable installedWorkloads) => throw new NotImplementedException(); public void DeleteUpdatableWorkloadsFile() { } public IEnumerable ParseRollbackDefinitionFiles(IEnumerable files, WorkloadHistoryRecorder recorder = null) => _manifestUpdates.Select(t => t.ManifestUpdate); diff --git a/test/dotnet.Tests/CommandTests/Workload/Install/WorkloadGarbageCollectionTests.cs b/test/dotnet.Tests/CommandTests/Workload/Install/WorkloadGarbageCollectionTests.cs index cc561d50fdec..5d61c490cf25 100644 --- a/test/dotnet.Tests/CommandTests/Workload/Install/WorkloadGarbageCollectionTests.cs +++ b/test/dotnet.Tests/CommandTests/Workload/Install/WorkloadGarbageCollectionTests.cs @@ -60,7 +60,7 @@ public void GivenManagedInstallItCanGarbageCollect() Directory.CreateDirectory(workloadsRecordPath); File.Create(Path.Combine(workloadsRecordPath, "xamarin-android-build")).Close(); - installer.GarbageCollect(getResolver); + installer.GarbageCollect(getResolver, TestContext.CancellationToken); foreach (var pack in packsToCollect) { @@ -99,7 +99,7 @@ public void GivenManagedInstallItCanGarbageCollectPacksMissingFromManifest() } } - installer.GarbageCollect(getResolver); + installer.GarbageCollect(getResolver, TestContext.CancellationToken); Directory.EnumerateFileSystemEntries(installedPacksPath) .Should() @@ -153,7 +153,7 @@ public void GarbageCollectManifests() } // ACT: garbage collect - installer.GarbageCollect(getResolver); + installer.GarbageCollect(getResolver, TestContext.CancellationToken); // ASSERT @@ -233,7 +233,7 @@ public void GarbageCollectManifestsWithInstallState() } // ACT: garbage collect - installer.GarbageCollect(getResolver); + installer.GarbageCollect(getResolver, TestContext.CancellationToken); // ASSERT diff --git a/test/dotnet.Tests/CommandTests/Workload/Install/WorkloadInstallAspireDeprecationTests.cs b/test/dotnet.Tests/CommandTests/Workload/Install/WorkloadInstallAspireDeprecationTests.cs index cedc7338edd7..d8b0be161b6e 100644 --- a/test/dotnet.Tests/CommandTests/Workload/Install/WorkloadInstallAspireDeprecationTests.cs +++ b/test/dotnet.Tests/CommandTests/Workload/Install/WorkloadInstallAspireDeprecationTests.cs @@ -44,7 +44,7 @@ public void GivenOnlyAspireWorkloadItShowsDeprecationMessage() workloadManifestUpdater: manifestUpdater, tempDirPath: testDirectory); - var exitCode = command.Execute(); + var exitCode = command.Execute(CancellationToken.None); // Should exit successfully but show deprecation message exitCode.Should().Be(0); @@ -79,7 +79,7 @@ public void GivenAspireWithOtherWorkloadsItShowsDeprecationAndInstallsOthers() workloadManifestUpdater: manifestUpdater, tempDirPath: testDirectory); - var exitCode = command.Execute(); + var exitCode = command.Execute(CancellationToken.None); // Should exit successfully, show deprecation message, but install android workload exitCode.Should().Be(0); @@ -115,7 +115,7 @@ public void GivenAspireWorkloadDeprecationMessageIsShownOnlyOnce() workloadManifestUpdater: manifestUpdater, tempDirPath: testDirectory); - var exitCode = command.Execute(); + var exitCode = command.Execute(CancellationToken.None); // Should exit successfully and show deprecation message only once exitCode.Should().Be(0); diff --git a/test/dotnet.Tests/CommandTests/Workload/List/GivenDotnetWorkloadList.cs b/test/dotnet.Tests/CommandTests/Workload/List/GivenDotnetWorkloadList.cs index 7d46c4e4b4e4..257485cc4379 100644 --- a/test/dotnet.Tests/CommandTests/Workload/List/GivenDotnetWorkloadList.cs +++ b/test/dotnet.Tests/CommandTests/Workload/List/GivenDotnetWorkloadList.cs @@ -34,7 +34,7 @@ public void GivenNoWorkloadsAreInstalledListIsEmpty() var expectedWorkloads = new List(); var workloadInstaller = new MockWorkloadRecordRepo(expectedWorkloads); var command = new WorkloadListCommand(_parseResult, _reporter, workloadInstaller, "6.0.100"); - command.Execute(); + command.Execute(TestContext.CancellationToken); // Expected number of lines for table headers // Expecting a workload set adds two lines @@ -61,7 +61,7 @@ public void GivenNoWorkloadsAreInstalledMachineReadableListIsEmpty() var expectedWorkloads = new List(); var workloadInstaller = new MockWorkloadRecordRepo(expectedWorkloads); var command = new WorkloadListCommand(_machineReadableParseResult, _reporter, workloadInstaller, "6.0.100"); - command.Execute(); + command.Execute(TestContext.CancellationToken); _reporter.Lines.Should().Contain(l => l.Contains(@"""installed"":[]")); } @@ -74,7 +74,7 @@ public void GivenWorkloadsAreInstalledListIsNotEmpty() var workloadInstaller = new MockWorkloadRecordRepo(expectedWorkloads); var workloadResolver = WorkloadResolver.CreateForTests(new MockManifestProvider(("SampleManifest", _manifestPath, "5.0.0", "6.0.100")), Directory.GetCurrentDirectory()); var command = new WorkloadListCommand(_parseResult, _reporter, workloadInstaller, "6.0.100", workloadResolver: workloadResolver); - command.Execute(); + command.Execute(TestContext.CancellationToken); foreach (var workload in expectedWorkloads) { @@ -89,7 +89,7 @@ public void GivenWorkloadsAreInstalledMachineReadableListIsNotEmpty() var expectedWorkloads = new List() { new WorkloadId("mock-workload-1"), new WorkloadId("mock-workload-2"), new WorkloadId("mock-workload-3") }; var workloadInstaller = new MockWorkloadRecordRepo(expectedWorkloads); var command = new WorkloadListCommand(_machineReadableParseResult, _reporter, workloadInstaller, "6.0.100"); - command.Execute(); + command.Execute(TestContext.CancellationToken); _reporter.Lines.Should().Contain(l => l.Contains("{\"installed\":[\"mock-workload-1\",\"mock-workload-2\",\"mock-workload-3\"]")); } @@ -110,7 +110,7 @@ public void GivenWorkloadsAreOutOfDateUpdatesAreAdvertised() File.Copy(Path.Combine(TestAssetsManager.GetAndValidateTestProjectDirectory("SampleManifest"), "MockListSampleUpdated.json"), manifestPath); var command = new WorkloadListCommand(_parseResult, _reporter, workloadInstaller, "6.0.100", workloadResolver: workloadResolver, userProfileDir: userProfileDir); - command.Execute(); + command.Execute(TestContext.CancellationToken); // Workloads 1 and 3 should have updates _reporter.Lines.Should().Contain(string.Format(CliCommandStrings.WorkloadListWorkloadUpdatesAvailable, "mock-workload-1 mock-workload-3")); diff --git a/test/dotnet.Tests/CommandTests/Workload/List/GivenWorkloadInstallerAndWorkloadsInstalled.cs b/test/dotnet.Tests/CommandTests/Workload/List/GivenWorkloadInstallerAndWorkloadsInstalled.cs index 6c533048d131..1ba1f574a320 100644 --- a/test/dotnet.Tests/CommandTests/Workload/List/GivenWorkloadInstallerAndWorkloadsInstalled.cs +++ b/test/dotnet.Tests/CommandTests/Workload/List/GivenWorkloadInstallerAndWorkloadsInstalled.cs @@ -128,7 +128,9 @@ public void ItShouldGetAvailableUpdate() { Setup(); WorkloadListCommand.UpdateAvailableEntry[] result = - _workloadListCommand.GetUpdateAvailable(new List { new("xamarin-android") }).ToArray(); + _workloadListCommand.GetUpdateAvailable( + new List { new("xamarin-android") }, + TestContext.CancellationToken).ToArray(); result.Should().NotBeEmpty(); result[0].WorkloadId.Should().Be(InstallingWorkload, "Only should installed workload"); @@ -141,7 +143,7 @@ public void ItShouldGetAvailableUpdate() public void ItShouldGetListOfWorkloadWithCurrentSdkVersionBand() { Setup(); - _workloadListCommand.Execute(); + _workloadListCommand.Execute(CancellationToken.None); _reporter.Lines.Should().Contain(c => c.Contains("\"installed\":[\"xamarin-android\"]")); } @@ -161,7 +163,7 @@ public void GivenLowerTargetVersionItShouldThrow() dotnetDir: _dotnetRoot, workloadRecordRepo: new MockMatchingFeatureBandInstallationRecordRepository()); - Action a = () => _workloadListCommand.Execute(); + Action a = () => _workloadListCommand.Execute(CancellationToken.None); a.Should().Throw(); } @@ -181,7 +183,7 @@ public void GivenSameLowerTargetVersionBandItShouldNotThrow() dotnetDir: _dotnetRoot, workloadRecordRepo: new MockMatchingFeatureBandInstallationRecordRepository()); - Action a = () => _workloadListCommand.Execute(); + Action a = () => _workloadListCommand.Execute(CancellationToken.None); a.Should().NotThrow(); } diff --git a/test/dotnet.Tests/CommandTests/Workload/Repair/GivenDotnetWorkloadRepair.cs b/test/dotnet.Tests/CommandTests/Workload/Repair/GivenDotnetWorkloadRepair.cs index acd2dab7a256..f87063dfe2c9 100644 --- a/test/dotnet.Tests/CommandTests/Workload/Repair/GivenDotnetWorkloadRepair.cs +++ b/test/dotnet.Tests/CommandTests/Workload/Repair/GivenDotnetWorkloadRepair.cs @@ -52,7 +52,7 @@ public void GivenNoWorkloadsAreInstalledRepairIsNoOp(bool userLocal) var repairCommand = new WorkloadRepairCommand(_parseResult, reporter: _reporter, workloadResolverFactory, nugetPackageDownloader: nugetDownloader); - repairCommand.Execute(); + repairCommand.Execute(CancellationToken.None); _reporter.Lines.Should().Contain(CliCommandStrings.NoWorkloadsToRepair); } @@ -83,7 +83,7 @@ public void GivenExtraPacksInstalledRepairGarbageCollects(bool userLocal) var installParseResult = Parser.Parse(new string[] { "dotnet", "workload", "install", installingWorkload }); var installCommand = new WorkloadInstallCommand(installParseResult, reporter: _reporter, workloadResolverFactory, nugetPackageDownloader: nugetDownloader, workloadManifestUpdater: manifestUpdater, tempDirPath: testDirectory); - installCommand.Execute(); + installCommand.Execute(CancellationToken.None); // Add extra pack dirs and records var extraPackRecordPath = Path.Combine(installRoot, "metadata", "workloads", "InstalledPacks", "v1", "Test.Pack.A", "1.0.0", sdkFeatureVersion); @@ -95,7 +95,7 @@ public void GivenExtraPacksInstalledRepairGarbageCollects(bool userLocal) var repairCommand = new WorkloadRepairCommand(_parseResult, reporter: _reporter, workloadResolverFactory, nugetPackageDownloader: nugetDownloader); - repairCommand.Execute(); + repairCommand.Execute(CancellationToken.None); // Check that pack dirs and records have been removed File.Exists(extraPackRecordPath).Should().BeFalse(); @@ -133,7 +133,7 @@ public void GivenMissingPacksRepairFixesInstall(bool userLocal) var installParseResult = Parser.Parse(new string[] { "dotnet", "workload", "install", installingWorkload }); var installCommand = new WorkloadInstallCommand(installParseResult, reporter: _reporter, workloadResolverFactory, nugetPackageDownloader: nugetDownloader, workloadManifestUpdater: manifestUpdater, tempDirPath: testDirectory); - installCommand.Execute(); + installCommand.Execute(CancellationToken.None); // Delete pack dirs/ records var deletedPackRecordPath = Path.Combine(installRoot, "metadata", "workloads", "InstalledPacks", "v1", "Xamarin.Android.Sdk", "8.4.7", sdkFeatureVersion); @@ -143,7 +143,7 @@ public void GivenMissingPacksRepairFixesInstall(bool userLocal) var repairCommand = new WorkloadRepairCommand(_parseResult, reporter: _reporter, workloadResolverFactory, nugetPackageDownloader: nugetDownloader); - repairCommand.Execute(); + repairCommand.Execute(CancellationToken.None); // Check that pack dirs and records have been replaced File.Exists(deletedPackRecordPath).Should().BeTrue(); diff --git a/test/dotnet.Tests/CommandTests/Workload/Restore/DiscoverAllProjectsTests.cs b/test/dotnet.Tests/CommandTests/Workload/Restore/DiscoverAllProjectsTests.cs index f5604a2591b9..50111c70af8b 100644 --- a/test/dotnet.Tests/CommandTests/Workload/Restore/DiscoverAllProjectsTests.cs +++ b/test/dotnet.Tests/CommandTests/Workload/Restore/DiscoverAllProjectsTests.cs @@ -20,7 +20,9 @@ public void WhenCallWithNoSlnOrProjectArgumentItCollectProjectsFromSolution() .WithSource() .Path; - var result = WorkloadRestoreCommand.DiscoverAllProjects(projectDirectory); + var result = WorkloadRestoreCommand.DiscoverAllProjects( + projectDirectory, + TestContext.CancellationToken); result.Should().Contain(f => Path.GetFileName(f) == "App.csproj"); } @@ -34,6 +36,7 @@ public void WhenCallWithSlnOrProjectArgumentItCollectProjectsFromSolution() var result = WorkloadRestoreCommand.DiscoverAllProjects("", + TestContext.CancellationToken, new[] { Path.Combine(projectDirectory, "App.sln"), @@ -54,7 +57,9 @@ public void WhenCallWithDirectoryWith2ProjectItShouldFindAll() .Path; var result = - WorkloadRestoreCommand.DiscoverAllProjects(Path.Combine(projectDirectory, "Multiple")); + WorkloadRestoreCommand.DiscoverAllProjects( + Path.Combine(projectDirectory, "Multiple"), + TestContext.CancellationToken); result.Should().Contain(f => Path.GetFileName(f) == "First.csproj"); result.Should().Contain(f => Path.GetFileName(f) == "Second.csproj"); @@ -70,6 +75,7 @@ public void WhenCallWithSlnContainingSolutionFolderItExcludesFolderProjectsFromS var result = WorkloadRestoreCommand.DiscoverAllProjects("", + TestContext.CancellationToken, new[] { Path.Combine(projectDirectory, "App.sln"), diff --git a/test/dotnet.Tests/CommandTests/Workload/Search/GivenDotnetWorkloadSearch.cs b/test/dotnet.Tests/CommandTests/Workload/Search/GivenDotnetWorkloadSearch.cs index 3fcfdf4372d0..c875f6f2dd7c 100644 --- a/test/dotnet.Tests/CommandTests/Workload/Search/GivenDotnetWorkloadSearch.cs +++ b/test/dotnet.Tests/CommandTests/Workload/Search/GivenDotnetWorkloadSearch.cs @@ -60,7 +60,7 @@ public void GivenNoWorkloadsAreInstalledSearchIsEmpty() var workloadResolver = new MockWorkloadResolver(Enumerable.Empty()); var workloadResolverFactory = new MockWorkloadResolverFactory(dotnetPath: null, "6.0.100", workloadResolver); var command = new WorkloadSearchCommand(parseResult, _reporter, workloadResolverFactory); - command.Execute(); + command.Execute(CancellationToken.None); _reporter.Lines.Count.Should().Be(4, because: "Output should have header and no values."); } @@ -108,7 +108,7 @@ [new WorkloadResolver.WorkloadInfo(new WorkloadId("Microsoft.NET.Sdk.Android"), WorkloadManifest.CreateForTests("Microsoft.NET.Sdk.Maui")); var command = new WorkloadSearchVersionsCommand(parseResult, _reporter, installer: installer, nugetPackageDownloader: nugetPackageDownloader, resolver: resolver, sdkVersion: new ReleaseVersion(9, 0, 100)); _reporter.Clear(); - command.Execute(); + command.Execute(CancellationToken.None); _reporter.Lines.Count.Should().Be(1); _reporter.Lines.Single().Should().Be("9.0.101"); } @@ -121,7 +121,7 @@ public void GivenNoStubIsProvidedSearchShowsAllWorkloads() var workloadResolver = new MockWorkloadResolver(_availableWorkloads); var workloadResolverFactory = new MockWorkloadResolverFactory(dotnetPath: null, "6.0.100", workloadResolver); var command = new WorkloadSearchCommand(parseResult, _reporter, workloadResolverFactory); - command.Execute(); + command.Execute(CancellationToken.None); var output = string.Join(" ", _reporter.Lines); foreach (var workload in _availableWorkloads) @@ -142,7 +142,7 @@ public void GivenDetailedVerbositySearchShowsAllColumns() var workloadResolver = new MockWorkloadResolver(_availableWorkloads); var workloadResolverFactory = new MockWorkloadResolverFactory(dotnetPath: null, "6.0.100", workloadResolver); var command = new WorkloadSearchCommand(parseResult, _reporter, workloadResolverFactory); - command.Execute(); + command.Execute(CancellationToken.None); var output = string.Join(" ", _reporter.Lines); foreach (var workload in _availableWorkloads) @@ -163,7 +163,7 @@ public void GivenStubIsProvidedSearchShowsAllMatchingWorkloads() var workloadResolver = new MockWorkloadResolver(_availableWorkloads); var workloadResolverFactory = new MockWorkloadResolverFactory(dotnetPath: null, "6.0.100", workloadResolver); var command = new WorkloadSearchCommand(parseResult, _reporter, workloadResolverFactory); - command.Execute(); + command.Execute(CancellationToken.None); var output = string.Join(" ", _reporter.Lines); var expectedWorkloads = _availableWorkloads.Take(3); @@ -185,7 +185,7 @@ public void GivenSearchResultsAreOrdered() var workloadResolver = new MockWorkloadResolver(_availableWorkloads); var workloadResolverFactory = new MockWorkloadResolverFactory(dotnetPath: null, "6.0.100", workloadResolver); var command = new WorkloadSearchCommand(parseResult, _reporter, workloadResolverFactory); - command.Execute(); + command.Execute(CancellationToken.None); _reporter.Lines[3].Should().Contain("fake-workload-1"); _reporter.Lines[4].Should().Contain("fake-workload-2"); @@ -202,7 +202,7 @@ public void GivenWorkloadSearchItSearchesDescription() var workloadResolver = new MockWorkloadResolver(_availableWorkloads); var workloadResolverFactory = new MockWorkloadResolverFactory(dotnetPath: null, "6.0.100", workloadResolver); var command = new WorkloadSearchCommand(parseResult, _reporter, workloadResolverFactory); - command.Execute(); + command.Execute(CancellationToken.None); _reporter.Lines.Count.Should().Be(5); _reporter.Lines[3].Should().Contain("fake-workload-2"); diff --git a/test/dotnet.Tests/CommandTests/Workload/Uninstall/GivenDotnetWorkloadUninstall.cs b/test/dotnet.Tests/CommandTests/Workload/Uninstall/GivenDotnetWorkloadUninstall.cs index 262d94c4da37..4d6b9a56b1f4 100644 --- a/test/dotnet.Tests/CommandTests/Workload/Uninstall/GivenDotnetWorkloadUninstall.cs +++ b/test/dotnet.Tests/CommandTests/Workload/Uninstall/GivenDotnetWorkloadUninstall.cs @@ -108,6 +108,34 @@ public void GivenWorkloadUninstallItWorksWithVerbosityFlag() exitCode.Should().Be(0, "The exit code of workload uninstall should be 0 to indicate success when the flag was added."); } + [TestMethod] + public void GivenCancellationDuringGarbageCollectionItPropagatesCancellationAfterShutdown() + { + const string workloadId = "mock-1"; + const string sdkFeatureVersion = "6.0.100"; + string testDirectory = TestAssetsManager.CreateTestDirectory().Path; + string dotnetRoot = Path.Combine(testDirectory, "dotnet"); + string userProfileDir = Path.Combine(testDirectory, "user-profile"); + var workloadResolver = WorkloadResolver.CreateForTests(new MockManifestProvider(new[] { _manifestPath }), dotnetRoot, userLocal: false, userProfileDir); + var workloadResolverFactory = new MockWorkloadResolverFactory(dotnetRoot, sdkFeatureVersion, workloadResolver, userProfileDir); + var workloadInstaller = new MockPackWorkloadInstaller(installedWorkloads: [new WorkloadId(workloadId)]); + var parseResult = Parser.Parse(["dotnet", "workload", "uninstall", workloadId]); + var command = new WorkloadUninstallCommand( + parseResult, + reporter: _reporter, + workloadResolverFactory, + new MockNuGetPackageDownloader(dotnetRoot), + workloadInstaller); + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + OperationCanceledException exception = Assert.ThrowsExactly( + () => command.Execute(cancellationTokenSource.Token)); + + Assert.AreEqual(cancellationTokenSource.Token, exception.CancellationToken); + Assert.IsTrue(workloadInstaller.ShutdownCalled); + } + [TestMethod] [DataRow(true)] [DataRow(false)] @@ -224,7 +252,7 @@ private void InstallWorkload(string installingWorkload, string testDirectory, st var workloadResolverFactory = new MockWorkloadResolverFactory(dotnetRoot, sdkFeatureVersion, workloadResolver, userProfileDir); var installCommand = new WorkloadInstallCommand(installParseResult, reporter: _reporter, workloadResolverFactory, nugetPackageDownloader: nugetDownloader, workloadManifestUpdater: manifestUpdater, tempDirPath: testDirectory); - installCommand.Execute(); + installCommand.Execute(CancellationToken.None); } private int UninstallWorkload(string uninstallingWorkload, string testDirectory, string sdkFeatureVersion, string[] args = null) @@ -244,7 +272,7 @@ private int UninstallWorkload(string uninstallingWorkload, string testDirectory, var uninstallParseResult = Parser.Parse([.. command]); var workloadResolverFactory = new MockWorkloadResolverFactory(dotnetRoot, sdkFeatureVersion, workloadResolver, userProfileDir); var uninstallCommand = new WorkloadUninstallCommand(uninstallParseResult, reporter: _reporter, workloadResolverFactory, nugetDownloader); - return uninstallCommand.Execute(); + return uninstallCommand.Execute(CancellationToken.None); } } } diff --git a/test/dotnet.Tests/CommandTests/Workload/Update/GivenDotnetWorkloadUpdate.cs b/test/dotnet.Tests/CommandTests/Workload/Update/GivenDotnetWorkloadUpdate.cs index 21d9df16952d..2ef3454fa5dc 100644 --- a/test/dotnet.Tests/CommandTests/Workload/Update/GivenDotnetWorkloadUpdate.cs +++ b/test/dotnet.Tests/CommandTests/Workload/Update/GivenDotnetWorkloadUpdate.cs @@ -104,7 +104,7 @@ public void GivenWorkloadUpdateFromHistory() mockInstaller.InstallationRecordRepository.InstalledWorkloads.Should().BeEquivalentTo(new List() { new WorkloadId("maui-android"), new WorkloadId("maui-ios") }); mockInstaller.GarbageCollectionCalled.Should().BeFalse(); - update.Execute(); + update.Execute(CancellationToken.None); mockInstaller.InstallationRecordRepository.InstalledWorkloads.Should().BeEquivalentTo(new List() { new WorkloadId("maui-android") }); mockInstaller.GarbageCollectionCalled.Should().BeTrue(); mockInstaller.InstalledManifests.Select(m => m.manifestUpdate.ManifestId.ToString()).Should().BeEquivalentTo(new List() { "microsoft.net.sdk.android" }); @@ -136,7 +136,7 @@ public void GivenWorkloadUpdateItRemovesOldPacksAfterInstall(bool userLocal) var installParseResult = Parser.Parse(new string[] { "dotnet", "workload", "install", installingWorkload }); var installCommand = new WorkloadInstallCommand(installParseResult, reporter: _reporter, workloadResolverFactory, nugetPackageDownloader: nugetDownloader, workloadManifestUpdater: manifestUpdater, tempDirPath: testDirectory); - installCommand.Execute(); + installCommand.Execute(CancellationToken.None); // 7 packs in packs dir, 1 template pack var installPacks = Directory.GetDirectories(Path.Combine(installRoot, "packs")); @@ -170,7 +170,7 @@ public void GivenWorkloadUpdateItRemovesOldPacksAfterInstall(bool userLocal) var updateParseResult = Parser.Parse(new string[] { "dotnet", "workload", "update" }); var updateCommand = new WorkloadUpdateCommand(updateParseResult, reporter: _reporter, workloadResolverFactory, nugetPackageDownloader: nugetDownloader, workloadManifestUpdater: manifestUpdater, tempDirPath: testDirectory); - updateCommand.Execute(); + updateCommand.Execute(CancellationToken.None); // 6 packs in packs dir, 1 template pack var updatePacks = Directory.GetDirectories(Path.Combine(installRoot, "packs")); @@ -243,7 +243,7 @@ public void GivenWorkloadUpdateAcrossFeatureBandsItUpdatesPacks(bool userLocal) File.Create(Path.Combine(installRoot, "metadata", "workloads", sdkFeatureVersion, "InstalledWorkloads", installingWorkload)).Close(); // Update workload (without installing any workloads to this feature band) - new WorkloadConfigCommand(Parser.Parse(["dotnet", "workload", "config", "--update-mode", "manifests"]), workloadResolverFactory: workloadResolverFactory).Execute().Should().Be(0); + new WorkloadConfigCommand(Parser.Parse(["dotnet", "workload", "config", "--update-mode", "manifests"]), workloadResolverFactory: workloadResolverFactory).Execute(CancellationToken.None).Should().Be(0); var updateParseResult = Parser.Parse(new string[] { "dotnet", "workload", "update", "--from-previous-sdk" }); var updateCommand = new WorkloadUpdateCommand(updateParseResult, reporter: _reporter, workloadResolverFactory, nugetPackageDownloader: nugetDownloader, workloadManifestUpdater: manifestUpdater, tempDirPath: testDirectory); @@ -255,8 +255,8 @@ public void GivenWorkloadUpdateAcrossFeatureBandsItUpdatesPacks(bool userLocal) }; Directory.CreateDirectory(Path.GetDirectoryName(installStatePath)); File.WriteAllText(installStatePath, oldInstallState.ToString()); - new WorkloadConfigCommand(Parser.Parse(["dotnet", "workload", "config", "--update-mode", "manifests"]), workloadResolverFactory: workloadResolverFactory).Execute().Should().Be(0); - updateCommand.Execute(); + new WorkloadConfigCommand(Parser.Parse(["dotnet", "workload", "config", "--update-mode", "manifests"]), workloadResolverFactory: workloadResolverFactory).Execute(CancellationToken.None).Should().Be(0); + updateCommand.Execute(CancellationToken.None); var newInstallState = InstallStateContents.FromPath(installStatePath); newInstallState.Manifests.Should().BeNull(); @@ -280,7 +280,7 @@ public void GivenWorkloadUpdateItUpdatesOutOfDatePacks() var mockWorkloadIds = new WorkloadId[] { new WorkloadId("xamarin-android") }; (_, var command, var installer, _, _, _, _) = GetTestInstallers(_parseResult, installedWorkloads: mockWorkloadIds, installedFeatureBand: "6.0.100"); - command.Execute(); + command.Execute(CancellationToken.None); installer.GarbageCollectionCalled.Should().BeTrue(); installer.CachePath.Should().BeNull(); @@ -331,7 +331,7 @@ public void UpdateViaWorkloadSet(bool upgrade, bool? installStateUseWorkloadSet, Directory.CreateDirectory(Path.GetDirectoryName(installStatePath)); File.WriteAllText(installStatePath, contents.ToString()); - updateCommand.Execute(); + updateCommand.Execute(CancellationToken.None); workloadInstaller.InstalledManifests.Count.Should().Be(1); workloadInstaller.InstalledManifests[0].manifestUpdate.NewVersion.ToString().Should().Be("2.3.4"); @@ -398,7 +398,7 @@ public void GivenWorkloadUpdateItFindsGreatestWorkloadSetWithSpecifiedComponents nugetPackageDownloader: nugetPackageDownloader, workloadManifestUpdater: new MockWorkloadManifestUpdater() ); - command.Execute(); + command.Execute(CancellationToken.None); installer.InstalledWorkloadSet.Version.Should().Be("9.0.101"); } @@ -410,7 +410,7 @@ public void GivenWorkloadUpdateItRollsBackOnFailedUpdate() (_, var command, var installer, var workloadResolver, _, _, _) = GetTestInstallers(_parseResult, installedWorkloads: mockWorkloadIds, failingPack: "Xamarin.Android.Framework", installedFeatureBand: "6.0.100"); - var exceptionThrown = Assert.ThrowsExactly(() => command.Execute()); + var exceptionThrown = Assert.ThrowsExactly(() => command.Execute(CancellationToken.None)); exceptionThrown.Message.Should().Contain("Failing pack: Xamarin.Android.Framework"); var expectedPacks = mockWorkloadIds .SelectMany(workloadId => workloadResolver.GetPacksInWorkload(workloadId)) @@ -429,7 +429,7 @@ public void GivenWorkloadUpdateItCanDownloadToOfflineCache() var parseResult = Parser.Parse(new string[] { "dotnet", "workload", "update", "--download-to-cache", cachePath }); (_, var command, _, _, var manifestUpdater, var packageDownloader, _) = GetTestInstallers(parseResult, installedWorkloads: mockWorkloadIds, includeInstalledPacks: true, installedFeatureBand: "6.0.100"); - command.Execute(); + command.Execute(CancellationToken.None); // Manifest packages should have been 'downloaded' and used for pack resolution manifestUpdater.GetManifestPackageDownloadsCallCount.Should().Be(1); @@ -450,7 +450,7 @@ public void GivenWorkloadUpdateItCanInstallFromOfflineCache() var parseResult = Parser.Parse(new string[] { "dotnet", "workload", "update", "--from-cache", cachePath }); (_, var command, var installer, _, _, var nugetDownloader, _) = GetTestInstallers(parseResult, installedWorkloads: mockWorkloadIds, installedFeatureBand: "6.0.100"); - command.Execute(); + command.Execute(CancellationToken.None); installer.GarbageCollectionCalled.Should().BeTrue(); installer.CachePath.Should().Contain(cachePath); @@ -466,7 +466,7 @@ public void GivenWorkloadUpdateItPrintsDownloadUrls() var parseResult = Parser.Parse(new string[] { "dotnet", "workload", "update", "--print-download-link-only" }); (_, var command, _, _, _, _, _) = GetTestInstallers(parseResult, installedWorkloads: mockWorkloadIds, includeInstalledPacks: true, installedFeatureBand: "6.0.100"); - command.Execute(); + command.Execute(CancellationToken.None); string.Join(" ", _reporter.Lines).Should().Contain("http://mock-url/xamarin.android.templates.1.0.3.nupkg", "New pack urls should be included in output"); string.Join(" ", _reporter.Lines).Should().Contain("http://mock-url/xamarin.android.framework.8.4.0.nupkg", "Urls for packs with updated versions should be included in output"); @@ -480,7 +480,7 @@ public void GivenWorkloadUpdateItPrintsDownloadUrlsForNewFeatureBand() var parseResult = Parser.Parse(new string[] { "dotnet", "workload", "update", "--print-download-link-only", "--sdk-version", "7.0.100" }); (_, var command, _, _, _, _, _) = GetTestInstallers(parseResult, installedWorkloads: mockWorkloadIds, includeInstalledPacks: true, sdkVersion: "6.0.400"); - command.Execute(); + command.Execute(CancellationToken.None); string.Join(" ", _reporter.Lines).Should().Contain("http://mock-url/xamarin.android.templates.1.0.3.nupkg", "New pack urls should be included in output"); string.Join(" ", _reporter.Lines).Should().Contain("http://mock-url/xamarin.android.framework.8.4.0.nupkg", "Urls for packs with updated versions should be included in output"); @@ -508,7 +508,7 @@ public void GivenOnlyUpdateAdManifestItSucceeds() var parseResult = Parser.Parse(new string[] { "dotnet", "workload", "update", "--advertising-manifests-only" }); (_, var command, _, _, var manifestUpdater, _, _) = GetTestInstallers(parseResult, installedFeatureBand: "6.0.100"); - command.Execute(); + command.Execute(CancellationToken.None); manifestUpdater.UpdateAdvertisingManifestsCallCount.Should().Be(1); } @@ -519,7 +519,7 @@ public void GivenPrintRollbackDefinitionItIncludesAllInstalledManifests() (_, var updateCommand, _, _, _, _, _) = GetTestInstallers(parseResult, installedFeatureBand: "6.0.100"); - updateCommand.Execute(); + updateCommand.Execute(CancellationToken.None); _reporter.Lines.Count().Should().Be(1); string.Join("", _reporter.Lines).Should().Contain("samplemanifest"); } @@ -545,8 +545,8 @@ public void ApplyRollbackAcrossFeatureBand(string existingSdkFeatureBand, string parseResult = Parser.Parse(["dotnet", "workload", "config", "--update-mode", "manifests"]); WorkloadConfigCommand configCommand = new(parseResult, workloadResolverFactory: resolverFactory); - configCommand.Execute().Should().Be(0); - updateCommand.Execute() + configCommand.Execute(CancellationToken.None).Should().Be(0); + updateCommand.Execute(CancellationToken.None) .Should().Be(0); packInstaller.InstalledManifests[0].manifestUpdate.ManifestId.Should().Be(manifestsToUpdate[0].ManifestUpdate.ManifestId); @@ -575,7 +575,7 @@ public void ApplyRollbackWithMultipleManifestsAcrossFeatureBand() }; (_, var updateCommand, var packInstaller, _, _, _, _) = GetTestInstallers(parseResult, manifestUpdates: manifestsToUpdate, sdkVersion: "6.0.300", installedFeatureBand: "6.0.300"); - updateCommand.Execute() + updateCommand.Execute(CancellationToken.None) .Should().Be(0); packInstaller.InstalledManifests[0].manifestUpdate.ManifestId.Should().Be(manifestsToUpdate[0].ManifestUpdate.ManifestId); @@ -611,7 +611,7 @@ public void GivenInvalidVersionInRollbackFileItErrors() var updateCommand = new WorkloadUpdateCommand(updateParseResult, reporter: _reporter, workloadResolverFactory: workloadResolverFactory, tempDirPath: testDirectory); - var exception = Assert.ThrowsExactly(() => updateCommand.Execute()); + var exception = Assert.ThrowsExactly(() => updateCommand.Execute(CancellationToken.None)); exception.InnerException.Should().BeOfType(); exception.InnerException.Message.Should().Contain(string.Format(CliCommandStrings.InvalidVersionForWorkload, "mock.workload", "6.0.0.15")); } @@ -701,7 +701,7 @@ public void GivenMissingManifestsInWorkloadSetModeUpdateReinstallsManifests(bool // Run update command var updateCommand = new WorkloadUpdateCommand(parseResult, reporter: _reporter, workloadResolverFactory, workloadInstaller: mockInstaller, workloadManifestUpdater: workloadManifestUpdater); - updateCommand.Execute(); + updateCommand.Execute(CancellationToken.None); // Verify that manifests were reinstalled mockInstaller.InstalledManifests.Should().HaveCount(2); diff --git a/test/dotnet.Tests/GivenExponentialRetry.cs b/test/dotnet.Tests/GivenExponentialRetry.cs index 2e0d3d0e54bc..6d594b200b8b 100644 --- a/test/dotnet.Tests/GivenExponentialRetry.cs +++ b/test/dotnet.Tests/GivenExponentialRetry.cs @@ -21,7 +21,9 @@ public async Task ItReturnsOnSuccess() retryCount++; return Task.FromResult("done"); }; - var res = await ExponentialRetry.ExecuteWithRetryOnFailure(action); + var res = await ExponentialRetry.ExecuteWithRetryOnFailure( + action, + TestContext.CancellationToken); retryCount.Should().Be(1); } @@ -35,10 +37,41 @@ public async Task ItRetriesOnError() retryCount++; return Task.FromResult(null); // Updated to match nullable reference type }; - var res = await ExponentialRetry.ExecuteWithRetryOnFailure(action, 2, timer: () => ExponentialRetry.Timer(ExponentialRetry.TestingIntervals)); + var res = await ExponentialRetry.ExecuteWithRetryOnFailure( + action, + TestContext.CancellationToken, + 2, + timer: () => ExponentialRetry.Timer(ExponentialRetry.TestingIntervals, TestContext.CancellationToken)); res.Should().BeNull(); retryCount.Should().Be(2); } + + [TestMethod] + public async Task ItCancelsWhileWaitingToRetry() + { + using var cancellationSource = CancellationTokenSource.CreateLinkedTokenSource(TestContext.CancellationToken); + TaskCompletionSource firstAttemptCompleted = new(TaskCreationOptions.RunContinuationsAsynchronously); + var retryCount = 0; + + Task retryTask = ExponentialRetry.ExecuteWithRetryOnFailure( + () => + { + retryCount++; + firstAttemptCompleted.TrySetResult(); + return Task.FromResult(null); + }, + cancellationSource.Token, + timer: () => ExponentialRetry.Timer( + [TimeSpan.Zero, TimeSpan.FromMinutes(1)], + cancellationSource.Token)); + + await firstAttemptCompleted.Task.WaitAsync(TestContext.CancellationToken); + await cancellationSource.CancelAsync(); + + await Assert.ThrowsExactlyAsync( + () => retryTask.WaitAsync(TestContext.CancellationToken)); + retryCount.Should().Be(1); + } } } diff --git a/test/dotnet.Tests/NuGetPackageDownloaderTests.cs b/test/dotnet.Tests/NuGetPackageDownloaderTests.cs index 7421ddf784f2..6aa2c9af9781 100644 --- a/test/dotnet.Tests/NuGetPackageDownloaderTests.cs +++ b/test/dotnet.Tests/NuGetPackageDownloaderTests.cs @@ -55,7 +55,9 @@ public async Task BackgroundWorkloadUpdaterUsesTheCapturedInvocationDirectory() .Invoke(downloader, [new ToolPackage.PackageId("Test.Package"), null, null])!; sources.Should().ContainSingle().Which.Source.Should().Be(feedDirectory); - var version = await downloader.GetLatestPackageVersion(new ToolPackage.PackageId("Test.Package")); + var version = await downloader.GetLatestPackageVersion( + new ToolPackage.PackageId("Test.Package"), + TestContext.CancellationToken); version.ToNormalizedString().Should().Be("1.0.0"); } @@ -76,6 +78,7 @@ public async Task GetLatestPackageVersionsReturnsAllPreviewVersionsWhenCountIsZe var versions = await downloader.GetLatestPackageVersions( new ToolPackage.PackageId("Test.Package"), numberOfResults: 0, + TestContext.CancellationToken, sourceLocation, includePreview: true); @@ -83,6 +86,29 @@ public async Task GetLatestPackageVersionsReturnsAllPreviewVersionsWhenCountIsZe .Should().Equal("1.0.0-preview.2", "1.0.0-preview.1"); } + [TestMethod] + public async Task GetLatestPackageVersionsHonorsCancellation() + { + TestDirectory testDirectory = TestAssetsManager.CreateTestDirectory(); + string feedDirectory = Path.Combine(testDirectory.Path, "feed"); + Directory.CreateDirectory(feedDirectory); + CreatePackage(feedDirectory, "Test.Package", "1.0.0"); + + NuGetPackageDownloader downloader = new( + new DirectoryPath(Path.Combine(testDirectory.Path, "packages")), + currentWorkingDirectory: testDirectory.Path); + PackageSourceLocation sourceLocation = new(sourceFeedOverrides: [feedDirectory]); + using var cancellationSource = CancellationTokenSource.CreateLinkedTokenSource(TestContext.CancellationToken); + await cancellationSource.CancelAsync(); + + await Assert.ThrowsExactlyAsync( + () => downloader.GetLatestPackageVersions( + new ToolPackage.PackageId("Test.Package"), + numberOfResults: 1, + cancellationSource.Token, + sourceLocation)); + } + private static void CreatePackage(string feedDirectory, string packageId, string version) { string packagePath = Path.Combine(feedDirectory, $"{packageId}.{version}.nupkg"); diff --git a/test/dotnet.Tests/ProgramTests.cs b/test/dotnet.Tests/ProgramTests.cs new file mode 100644 index 000000000000..2ffa08aa80d7 --- /dev/null +++ b/test/dotnet.Tests/ProgramTests.cs @@ -0,0 +1,57 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace Microsoft.DotNet.Cli.Tests; + +[TestClass] +[ResourceLock(WellKnownResources.EnvironmentVariables)] +public class ProgramTests +{ + [TestMethod] + public void PreCanceledExternalCommandIsNotLaunched() + { + string toolDirectory = Path.Combine(Path.GetTempPath(), $"dotnet-canceled-tool-{Guid.NewGuid():N}"); + Directory.CreateDirectory(toolDirectory); + string markerPath = Path.Combine(toolDirectory, "launched"); + string originalPath = Environment.GetEnvironmentVariable("PATH") ?? string.Empty; + + try + { + const string commandName = "canceledtool"; + if (OperatingSystem.IsWindows()) + { + File.WriteAllText( + Path.Combine(toolDirectory, $"dotnet-{commandName}.cmd"), + $"@echo off{Environment.NewLine}echo launched>\"{markerPath}\"{Environment.NewLine}"); + } + else + { + string toolPath = Path.Combine(toolDirectory, $"dotnet-{commandName}"); + File.WriteAllText( + toolPath, + $"#!/bin/sh{Environment.NewLine}touch '{markerPath}'{Environment.NewLine}"); + File.SetUnixFileMode( + toolPath, + UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute | + UnixFileMode.GroupRead | UnixFileMode.GroupExecute | + UnixFileMode.OtherRead | UnixFileMode.OtherExecute); + } + + Environment.SetEnvironmentVariable("PATH", toolDirectory + Path.PathSeparator + originalPath); + string[] args = [commandName]; + var parseResult = Parser.Parse(args); + using var cancellationSource = new CancellationTokenSource(); + cancellationSource.Cancel(); + + Assert.ThrowsExactly(() => + Program.ExecuteExternalCommand(args, parseResult, cancellationSource.Token)); + + Assert.IsFalse(File.Exists(markerPath)); + } + finally + { + Environment.SetEnvironmentVariable("PATH", originalPath); + Directory.Delete(toolDirectory, recursive: true); + } + } +} diff --git a/test/dotnet.Tests/ShellShimTests/AppHostShellShimMakerTests.cs b/test/dotnet.Tests/ShellShimTests/AppHostShellShimMakerTests.cs index 7aa793083256..14e408241ca5 100644 --- a/test/dotnet.Tests/ShellShimTests/AppHostShellShimMakerTests.cs +++ b/test/dotnet.Tests/ShellShimTests/AppHostShellShimMakerTests.cs @@ -33,7 +33,7 @@ public void GivenNonWindowsMachineWhenCallWithWpfDllItCanCreateShimWithoutThrow( a.Should().NotThrow("It should skip copying PE bits without throw"); } - private static string CreateApphostAndReturnShimPath() + private string CreateApphostAndReturnShimPath() { var tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(tempDirectory); @@ -42,7 +42,8 @@ private static string CreateApphostAndReturnShimPath() appHostShellShimMaker.CreateApphostShellShim( new FilePath(Path.GetFullPath(Path.Combine("WpfBinaryTestAssets", "testwpf.dll"))), - new FilePath(shimPath)); + new FilePath(shimPath), + TestContext.CancellationToken); return shimPath; } } diff --git a/test/dotnet.Tests/ShellShimTests/ShellShimRepositoryTests.cs b/test/dotnet.Tests/ShellShimTests/ShellShimRepositoryTests.cs index aea8020b8c07..75775baa7727 100644 --- a/test/dotnet.Tests/ShellShimTests/ShellShimRepositoryTests.cs +++ b/test/dotnet.Tests/ShellShimTests/ShellShimRepositoryTests.cs @@ -35,7 +35,7 @@ public void GivenAnExecutablePathItCanGenerateShimFile() var command = new ToolCommand(new ToolCommandName(shellCommandName), "dotnet", outputDll); - shellShimRepository.CreateShim(command); + shellShimRepository.CreateShim(command, TestContext.CancellationToken); var stdOut = ExecuteInShell(shellCommandName, pathToShim); @@ -57,7 +57,7 @@ public void GivenAnExecutableAndRelativePathToShimPathItCanGenerateShimFile() var shellCommandName = nameof(ShellShimRepositoryTests) + Path.GetRandomFileName(); var command = new ToolCommand(new ToolCommandName(shellCommandName), "dotnet", outputDll); - shellShimRepository.CreateShim(command); + shellShimRepository.CreateShim(command, TestContext.CancellationToken); var stdOut = ExecuteInShell(shellCommandName, relativePathToShim); @@ -85,7 +85,7 @@ public void GivenAnExecutablePathItCanGenerateShimFileInTransaction() TransactionScopeOption.Required, TimeSpan.Zero)) { - shellShimRepository.CreateShim(command); + shellShimRepository.CreateShim(command, TestContext.CancellationToken); transactionScope.Complete(); } @@ -104,7 +104,7 @@ public void GivenAnExecutablePathDirectoryThatDoesNotExistItCanGenerateShimFile( var shellCommandName = nameof(ShellShimRepositoryTests) + Path.GetRandomFileName(); var command = new ToolCommand(new ToolCommandName(shellCommandName), "dotnet", outputDll); - Action a = () => shellShimRepository.CreateShim(command); + Action a = () => shellShimRepository.CreateShim(command, TestContext.CancellationToken); a.Should().NotThrow(); } @@ -121,7 +121,7 @@ public void GivenAShimItPassesThroughArguments(string arguments, string[] expect var shellCommandName = nameof(ShellShimRepositoryTests) + Path.GetRandomFileName(); var command = new ToolCommand(new ToolCommandName(shellCommandName), "dotnet", outputDll); - shellShimRepository.CreateShim(command); + shellShimRepository.CreateShim(command, TestContext.CancellationToken); var stdOut = ExecuteInShell(shellCommandName, pathToShim, arguments); @@ -158,7 +158,7 @@ public void GivenAShimConflictItWillRollback(bool testMockBehaviorIsInSync) TransactionScopeOption.Required, TimeSpan.Zero)) { - shellShimRepository.CreateShim(command); + shellShimRepository.CreateShim(command, TestContext.CancellationToken); scope.Complete(); } @@ -208,7 +208,7 @@ public void GivenAnExceptionItWillRollback(bool testMockBehaviorIsInSync) { FilePath targetExecutablePath = MakeHelloWorldExecutableDll(identifier: testMockBehaviorIsInSync.ToString()); var command = new ToolCommand(new ToolCommandName(shellCommandName), "dotnet", targetExecutablePath); - shellShimRepository.CreateShim(command); + shellShimRepository.CreateShim(command, TestContext.CancellationToken); intendedError(); scope.Complete(); @@ -268,7 +268,7 @@ public void GivenAnInstalledShimRemoveDeletesTheShimFiles(bool testMockBehaviorI FilePath targetExecutablePath = MakeHelloWorldExecutableDll(identifier: testMockBehaviorIsInSync.ToString()); var command = new ToolCommand(new ToolCommandName(shellCommandName), "dotnet", targetExecutablePath); - shellShimRepository.CreateShim(command); + shellShimRepository.CreateShim(command, TestContext.CancellationToken); Directory.EnumerateFileSystemEntries(pathToShim).Should().NotBeEmpty(); @@ -299,7 +299,7 @@ public void GivenAnInstalledShimRemoveRollsbackIfTransactionIsAborted(bool testM FilePath targetExecutablePath = MakeHelloWorldExecutableDll(identifier: testMockBehaviorIsInSync.ToString()); var command = new ToolCommand(new ToolCommandName(shellCommandName), "dotnet", targetExecutablePath); - shellShimRepository.CreateShim(command); + shellShimRepository.CreateShim(command, TestContext.CancellationToken); Directory.EnumerateFileSystemEntries(pathToShim).Should().NotBeEmpty(); @@ -337,7 +337,7 @@ public void GivenAnInstalledShimRemoveCommitsIfTransactionIsCompleted(bool testM FilePath targetExecutablePath = MakeHelloWorldExecutableDll(identifier: testMockBehaviorIsInSync.ToString()); var command = new ToolCommand(new ToolCommandName(shellCommandName), "dotnet", targetExecutablePath); - shellShimRepository.CreateShim(command); + shellShimRepository.CreateShim(command, TestContext.CancellationToken); Directory.EnumerateFileSystemEntries(pathToShim).Should().NotBeEmpty(); @@ -378,6 +378,7 @@ public void WhenPackagedShimProvidedItCopies() shellShimRepository.CreateShim( command, + TestContext.CancellationToken, new[] { new FilePath(dummyShimPath) }); var createdShim = Directory.EnumerateFileSystemEntries(pathToShim).Single(); @@ -408,6 +409,7 @@ public void WhenMultipleSameNamePackagedShimProvidedItThrows() Action a = () => shellShimRepository.CreateShim( command, + TestContext.CancellationToken, new[] { new FilePath(dummyShimPath), new FilePath("path" + dummyShimPath) }); a.Should().Throw() @@ -426,7 +428,11 @@ public void WhenRidNotSupportedOnWindowsItIsImplicit(string tfm) { var tempDir = TestAssetsManager.CreateTestDirectory(identifier: tfm).Path; var templateFinder = new ShellShimTemplateFinder(new MockNuGetPackageDownloader(), new DirectoryPath(tempDir), null); - var path = templateFinder.ResolveAppHostSourceDirectoryAsync(null, NuGetFramework.Parse(tfm), Architecture.Arm64).Result; + var path = templateFinder.ResolveAppHostSourceDirectoryAsync( + null, + NuGetFramework.Parse(tfm), + Architecture.Arm64, + TestContext.CancellationToken).Result; path.Should().Contain(tfm.Equals("net5.0") ? "AppHostTemplate" : "win-x64"); } @@ -481,7 +487,7 @@ private string ExecuteInShell(string shellCommandName, string cleanFolderUnderTe SdkTestContext.Current.ToolsetUnderTest.DotNetRoot; } - processStartInfo.ExecuteAndCaptureOutput(out var stdOut, out var stdErr); + processStartInfo.ExecuteAndCaptureOutput(out var stdOut, out var stdErr, TestContext.CancellationToken); stdErr.Should().BeEmpty(); diff --git a/test/dotnet.Tests/dotnet.Tests.csproj b/test/dotnet.Tests/dotnet.Tests.csproj index 9ef8dd2a2664..c92a121f6d76 100644 --- a/test/dotnet.Tests/dotnet.Tests.csproj +++ b/test/dotnet.Tests/dotnet.Tests.csproj @@ -31,6 +31,7 @@ + @@ -79,6 +80,7 @@ +