diff --git a/src/MTP/Microsoft.Testing.Platform.MSBuild/PACKAGE.md b/src/MTP/Microsoft.Testing.Platform.MSBuild/PACKAGE.md index 5457a6801f..9a6d611c54 100644 --- a/src/MTP/Microsoft.Testing.Platform.MSBuild/PACKAGE.md +++ b/src/MTP/Microsoft.Testing.Platform.MSBuild/PACKAGE.md @@ -40,7 +40,7 @@ On MSBuild versions supporting `-mt`, configuration-file generation and self-reg ### MSBuild test output logs -The MSBuild test task writes its output log in the test application's results directory, including a custom `--results-directory`. The first run uses `__.log`. If that file already exists, a new log with a unique suffix is created in the same directory; existing files and file links are not overwritten. +The MSBuild test task writes its output log in the test application's results directory, including a custom `--results-directory`. The first run uses `__.log`. If that file already exists, a new log with a unique suffix is created in the same directory; existing files and file links are not overwritten. If a log cannot be created safely, the task reports an MSBuild error. The task's IPC listener allows only the current user. This protection also applies to the packaged `netstandard2.0` task when loaded by a modern .NET host; .NET Framework on Windows uses an owner-only pipe ACL. diff --git a/src/MTP/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.Execution.cs b/src/MTP/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.Execution.cs index cc9bd63da0..7d85951320 100644 --- a/src/MTP/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.Execution.cs +++ b/src/MTP/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.Execution.cs @@ -67,14 +67,34 @@ protected override void ProcessStarted() { while (!_waitForConnections.IsCancellationRequested) { - NamedPipeServer pipeServer = new(_pipeNameDescription, HandleRequestAsync, new SystemEnvironment(), new MSBuildLogger(), new SystemTask(), maxNumberOfServerInstances: 100, CancellationToken.None); - pipeServer.RegisterSerializer(new ModuleInfoRequestSerializer(), typeof(ModuleInfoRequest)); - pipeServer.RegisterSerializer(new VoidResponseSerializer(), typeof(VoidResponse)); - pipeServer.RegisterSerializer(new FailedTestInfoRequestSerializer(), typeof(FailedTestInfoRequest)); - pipeServer.RegisterSerializer(new RunSummaryInfoRequestSerializer(), typeof(RunSummaryInfoRequest)); - await pipeServer.WaitConnectionAsync(_waitForConnections.Token).ConfigureAwait(false); - _connections.Add(pipeServer); - Log.LogMessage(MessageImportance.Low, $"Client connected to '{_pipeNameDescription.Name}'"); + // Pass the connection loop's token (rather than CancellationToken.None) so connected servers stop + // their read loops when the task completes, and Dispose() on .NET Framework can close the pipe + // right away instead of waiting for the in-flight read. + NamedPipeServer pipeServer = new(_pipeNameDescription, HandleRequestAsync, new SystemEnvironment(), new MSBuildLogger(), new SystemTask(), maxNumberOfServerInstances: 100, _waitForConnections.Token); + try + { + pipeServer.RegisterSerializer(new ModuleInfoRequestSerializer(), typeof(ModuleInfoRequest)); + pipeServer.RegisterSerializer(new VoidResponseSerializer(), typeof(VoidResponse)); + pipeServer.RegisterSerializer(new FailedTestInfoRequestSerializer(), typeof(FailedTestInfoRequest)); + pipeServer.RegisterSerializer(new RunSummaryInfoRequestSerializer(), typeof(RunSummaryInfoRequest)); + await pipeServer.WaitConnectionAsync(_waitForConnections.Token).ConfigureAwait(false); + _connections.Add(pipeServer); + Log.LogMessage(MessageImportance.Low, $"Client connected to '{_pipeNameDescription.Name}'"); + } + finally + { + // Connected servers are tracked in _connections and disposed by Dispose(). A server that + // never got a client (cancelled at the end of the run or failed while waiting) is not, so + // dispose it here instead of leaking its pipe instance until finalization. + if (!pipeServer.WasConnected) + { +#if NET + await pipeServer.DisposeAsync().ConfigureAwait(false); +#else + pipeServer.Dispose(); +#endif + } + } } } catch (OperationCanceledException) when (_waitForConnections.IsCancellationRequested) @@ -83,6 +103,9 @@ protected override void ProcessStarted() } catch (Exception ex) { + // Losing the connection loop means module info, failure details and the run summary may never + // arrive; Execute() turns this into a failed task instead of trusting the child's exit code. + _hasInfrastructureError = true; Log.LogError(ex.ToString()); } }, @@ -98,19 +121,30 @@ public override bool Execute() _showTestsFailure = bool.Parse(TestingPlatformShowTestsFailure.ItemSpec); AddAppHostDotnetRootEnvironmentVariable(); - bool returnValue = base.Execute(); - if (_toolCommand is not null) + bool returnValue; + try { - _output.AppendLine(); - _output.AppendLine("=== COMMAND LINE ==="); - _output.AppendLine(_toolCommand); - } + returnValue = base.Execute(); + if (_toolCommand is not null) + { + _output.AppendLine(); + _output.AppendLine("=== COMMAND LINE ==="); + _output.AppendLine(_toolCommand); + } - // Persist the output to the file. - _outputFileStream?.WriteLine(_output); + // Persist the output to the file. + _outputFileStream?.WriteLine(_output); + } + finally + { + // Stop the connection loop and release the pipes and the log file even when base.Execute() throws; + // otherwise the listener keeps accepting connections after the task has finished. + Dispose(); + } - _waitForConnections.Cancel(); - Dispose(); + // The child process may have exited successfully while the task itself failed to receive its IPC messages + // or to create its log. Those failures were already reported as errors, so do not report success. + returnValue &= !_hasInfrastructureError; if (returnValue) { @@ -154,6 +188,19 @@ protected override void LogToolCommand(string message) /// protected override bool HandleTaskExecutionErrors() { + // ToolTask turns a zero exit code into -1 when errors were logged while the tool ran. When those errors are + // this task's own infrastructure failures, they were already reported; "Tests failed" would be misleading. + if (_hasInfrastructureError && ExitCode == -1) + { + if (_outputFileStream is null) + { + // Without a log file, keep the captured output available in detailed build logs. + Log.LogMessage(MessageImportance.Low, "{0}", _output); + } + + return false; + } + // This is an unexpected situation we simply print to the console the output and return false. if (RoslynString.IsNullOrEmpty(_outputFileName) && ExitCode != (int)Helpers.ExitCode.InvalidCommandLine) { @@ -164,7 +211,13 @@ protected override bool HandleTaskExecutionErrors() // If the output file name is null and the exit code is invalid command line we create a default one. if (_outputFileName is null && ExitCode == (int)Helpers.ExitCode.InvalidCommandLine) { - InitializeOutputFile(Path.Combine(Path.GetDirectoryName(TargetPath.ItemSpec.Trim())!, "TestResults")); + if (!TryInitializeOutputFile(Path.Combine(Path.GetDirectoryName(TargetPath.ItemSpec.Trim())!, "TestResults"))) + { + // The log-creation error was already reported and there is no log to point at, so show the + // captured output directly; it explains why the command line was rejected. + Log.LogError(null, "run failed", null, TargetPath.ItemSpec.Trim(), 0, 0, 0, 0, Resources.MSBuildResources.TestFailedNoDetail, _output); + return false; + } } Log.LogError(null, "run failed", null, TargetPath.ItemSpec.Trim(), 0, 0, 0, 0, Resources.MSBuildResources.TestFailed, _outputFileName, TargetFramework.ItemSpec, TestArchitecture.ItemSpec); @@ -187,8 +240,12 @@ private Task HandleRequestAsync(IRequest request) { if (_moduleInfo is null) { - _moduleInfo = moduleInfo; - InitializeOutputFile(_moduleInfo.TestResultFolder); + // Record the module only once its log exists. If creating the log failed (already reported), + // a later ModuleInfoRequest, e.g. from a retry test host, gets another chance to create it. + if (TryInitializeOutputFile(moduleInfo.TestResultFolder)) + { + _moduleInfo = moduleInfo; + } } } } @@ -277,31 +334,57 @@ private Task HandleRequestAsync(IRequest request) /// already exists. The directory can be chosen by the test application (e.g. --results-directory), /// so the task must not overwrite, or write through, a file or link that it did not create. /// - private void InitializeOutputFile(string resultsDirectory) + /// + /// when the log cannot be created. The error has then already been reported and the + /// task is marked as failed, because a run whose output cannot be persisted must not report success. + /// + private bool TryInitializeOutputFile(string resultsDirectory) { - _fileSystem.CreateDirectory(resultsDirectory); - string baseName = $"{Path.GetFileNameWithoutExtension(TargetPath.ItemSpec.Trim())}_{TargetFramework.ItemSpec}_{TestArchitecture.ItemSpec}"; - string outputFileName = Path.Combine(resultsDirectory, $"{baseName}.log"); - Stream output; try { - output = _fileSystem.CreateNew(outputFileName); + _fileSystem.CreateDirectory(resultsDirectory); + string baseName = $"{Path.GetFileNameWithoutExtension(TargetPath.ItemSpec.Trim())}_{TargetFramework.ItemSpec}_{TestArchitecture.ItemSpec}"; + string outputFileName = Path.Combine(resultsDirectory, $"{baseName}.log"); + Stream output; + try + { + output = _fileSystem.CreateNew(outputFileName); + } + catch (IOException) when (_fileSystem.Exist(outputFileName)) + { + // The usual reason the stable name exists is a previous run of the same project. Now that we no longer + // overwrite it, use a unique name so repeated runs keep working; this also preserves earlier logs. + // This second attempt is again create-new, so it cannot truncate or follow anything either. + outputFileName = Path.Combine(resultsDirectory, GetUniqueLogFileName(baseName)); + output = _fileSystem.CreateNew(outputFileName); + } + + try + { + _outputFileStream = new StreamWriter(output, Encoding.Unicode) + { + AutoFlush = true, + }; + } + catch + { + // The writer never took ownership of the stream, so nothing else would close the file handle. + output.Dispose(); + throw; + } + + _outputFileName = outputFileName; + Log.LogMessage(MessageImportance.Low, $"Initializing output file '{_outputFileName}'"); + return true; } - catch (IOException) when (_fileSystem.Exist(outputFileName)) + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { - // The usual reason the stable name exists is a previous run of the same project. Now that we no longer - // overwrite it, use a unique name so repeated runs keep working; this also preserves earlier logs. - // This second attempt is again create-new, so it cannot truncate or follow anything either. - outputFileName = Path.Combine(resultsDirectory, GetUniqueLogFileName(baseName)); - output = _fileSystem.CreateNew(outputFileName); + // Expected file-system failures (read-only or inaccessible results directory, the unique fallback name + // also existing, ...) become an MSBuild error instead of an unhandled exception on a pipe connection. + _hasInfrastructureError = true; + Log.LogErrorFromException(ex, showStackTrace: false); + return false; } - - _outputFileStream = new StreamWriter(output, Encoding.Unicode) - { - AutoFlush = true, - }; - _outputFileName = outputFileName; - Log.LogMessage(MessageImportance.Low, $"Initializing output file '{_outputFileName}'"); } /// diff --git a/src/MTP/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.cs b/src/MTP/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.cs index a6001f0643..fdbe5c7959 100644 --- a/src/MTP/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.cs +++ b/src/MTP/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.cs @@ -43,6 +43,8 @@ public partial class InvokeTestingPlatformTask : Build.Utilities.ToolTask, IDisp private string? _toolCommand; private bool _captureOutput; private bool _showTestsFailure; + // Written from pipe-connection threads and read on the task thread. + private volatile bool _hasInfrastructureError; /// /// Initializes a new instance of the class. @@ -164,7 +166,6 @@ internal InvokeTestingPlatformTask(IFileSystem fileSystem) /// public void Dispose() { - _outputFileStream?.Dispose(); _waitForConnections.Cancel(); _connectionLoopTask?.Wait(); @@ -173,6 +174,9 @@ public void Dispose() serverInstance.Dispose(); } + // Dispose the log only after the connection loop and every server have stopped: a ModuleInfoRequest + // handled on a connection can still create the log until then, and that writer would otherwise leak. + _outputFileStream?.Dispose(); GC.SuppressFinalize(this); } } diff --git a/test/UnitTests/Microsoft.Testing.Platform.MSBuild.UnitTests/InvokeTestingPlatformTaskTests.cs b/test/UnitTests/Microsoft.Testing.Platform.MSBuild.UnitTests/InvokeTestingPlatformTaskTests.cs index b2e690a19a..a62f5b5e7a 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.MSBuild.UnitTests/InvokeTestingPlatformTaskTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.MSBuild.UnitTests/InvokeTestingPlatformTaskTests.cs @@ -381,6 +381,133 @@ public void Execute_ExistingLogSymbolicLinkDoesNotCorruptTarget(bool targetExist } } + [TestMethod] + [DataRow(false, false)] + [DataRow(false, true)] + [DataRow(true, false)] + [DataRow(true, true)] + public void Execute_OutputFileCreationFailureFailsTask(bool hasModule, bool accessDenied) + { + using AppHostTaskFixture fixture = new(); + const string message = "Cannot create the task-owned output log."; + StubFileSystem fileSystem = new() + { + CreateFailure = accessDenied ? new UnauthorizedAccessException(message) : new IOException(message), + }; + using TestableInvokeTestingPlatformTask task = CreateSimulatedTask(fixture, fileSystem); + task.TestingPlatformUseDirectExecutable = true; + task.SimulatedExitCode = hasModule ? 0 : 5; + task.MirrorLoggedErrorExitCode = true; + List errors = []; + var engine = new Mock(); + engine.Setup(value => value.LogErrorEvent(It.IsAny())).Callback(errors.Add); + task.BuildEngine = engine.Object; + if (hasModule) + { + task.OnSimulatedLaunch = current => current.DeliverRequest(new ModuleInfoRequest("framework", "x64", "results")); + } + + Assert.IsFalse(task.Execute()); + + Assert.Contains(error => error.Message!.Contains(message, StringComparison.Ordinal), errors); + // ToolTask reports exceptions that escape the task as MSB6003; the failure must be handled by the task itself. + Assert.DoesNotContain(error => error.Code == "MSB6003", errors); + if (hasModule) + { + // The tests passed, so the log-creation error is the only one; no misleading "run failed" is added. + Assert.HasCount(1, errors); + } + else + { + // Without a log to point at, the captured output is reported directly. + Assert.HasCount(2, errors); + Assert.ContainsSingle(error => error.Code == "run failed", errors); + } + } + + [TestMethod] + public void Execute_UniqueLogCreationFailureFailsTask() + { + using AppHostTaskFixture fixture = new(); + const string message = "Cannot create the unique output log."; + string stableLog = Path.Combine("results", "apphost_net9.0_x64.log"); + StubFileSystem fileSystem = new() + { + CreateFailureForPath = path => path == stableLog ? null : new IOException(message), + }; + fileSystem.ExistingPaths.Add(stableLog); + using TestableInvokeTestingPlatformTask task = CreateSimulatedLogTask(fixture, fileSystem, out List errors); + task.OnSimulatedLaunch = current => + { + current.DeliverRequest(new ModuleInfoRequest("framework", "x64", "results")); + current.DeliverRequest(new RunSummaryInfoRequest(1, 0, 1, 0, "1s", AllowSkipped: true)); + }; + + Assert.IsFalse(task.Execute()); + + // The fallback name already failed; the task reports that failure instead of letting it escape. + Assert.Contains(message, Assert.ContainsSingle(errors).Message!); + Assert.IsEmpty(fileSystem.CreatedFiles); + } + + [TestMethod] + public void Execute_ModuleInfoRetryCreatesLogAfterFailedFirstAttempt() + { + using AppHostTaskFixture fixture = new(); + const string message = "Cannot create the first output log."; + StubFileSystem fileSystem = new() { CreateFailure = new IOException(message) }; + using TestableInvokeTestingPlatformTask task = CreateSimulatedLogTask(fixture, fileSystem, out List errors); + task.OnSimulatedLaunch = current => + { + current.DeliverRequest(new ModuleInfoRequest("framework", "x64", "first")); + fileSystem.CreateFailure = null; + current.DeliverRequest(new ModuleInfoRequest("framework", "x64", "retry")); + current.DeliverRequest(new RunSummaryInfoRequest(1, 0, 1, 0, "1s", AllowSkipped: true)); + }; + + Assert.IsFalse(task.Execute()); + + // A failed first attempt must not claim the module, so a later request (e.g. from Retry) creates the log. + Assert.Contains(message, Assert.ContainsSingle(errors).Message!); + Assert.AreEqual(Path.Combine("retry", "apphost_net9.0_x64.log"), Assert.ContainsSingle(fileSystem.CreatedFiles.Keys)); + } + + private static TestableInvokeTestingPlatformTask CreateSimulatedLogTask(AppHostTaskFixture fixture, StubFileSystem fileSystem, out List errors) + { + TestableInvokeTestingPlatformTask task = CreateSimulatedTask(fixture, fileSystem); + task.TargetFramework = new TaskItem("net9.0"); + task.TestArchitecture = new TaskItem("x64"); + task.TestingPlatformUseDirectExecutable = true; + task.SimulatedExitCode = 0; + task.MirrorLoggedErrorExitCode = true; + List loggedErrors = []; + var engine = new Mock(); + engine.Setup(value => value.LogErrorEvent(It.IsAny())).Callback(loggedErrors.Add); + task.BuildEngine = engine.Object; + errors = loggedErrors; + return task; + } + + [TestMethod] + public void Execute_OutputWriterInitializationFailureDisposesStreamAndFailsTask() + { + using AppHostTaskFixture fixture = new(); + using FailingFlushStream stream = new(); + StubFileSystem fileSystem = new() { OutputStream = stream }; + using TestableInvokeTestingPlatformTask task = CreateSimulatedTask(fixture, fileSystem); + task.TestingPlatformUseDirectExecutable = true; + task.OnSimulatedLaunch = current => current.DeliverRequest(new ModuleInfoRequest("framework", "x64", "results")); + List errors = []; + var engine = new Mock(); + engine.Setup(value => value.LogErrorEvent(It.IsAny())).Callback(errors.Add); + task.BuildEngine = engine.Object; + + Assert.IsFalse(task.Execute()); + + Assert.IsFalse(stream.CanWrite); + Assert.Contains(error => error.Message!.Contains("Cannot flush the output log.", StringComparison.Ordinal), errors); + } + [TestMethod] public void Execute_ModuleWithoutRunSummaryRejectsSuccessfulToolExit() { @@ -942,6 +1069,8 @@ public void InvokeLogEventsFromTextOutput(string singleLine) public int? SimulatedExitCode { get; set; } + public bool MirrorLoggedErrorExitCode { get; set; } + public int SimulatedLaunches { get; private set; } public Action? OnSimulatedLaunch { get; set; } @@ -963,7 +1092,9 @@ protected override int ExecuteTool(string pathToTool, string responseFileCommand LogToolCommand("simulated command"); LogEventsFromTextOutput("simulated output", MessageImportance.High); OnSimulatedLaunch?.Invoke(this); - return exitCode; + + // ToolTask.ExecuteTool reports a clean exit with logged errors as -1. + return MirrorLoggedErrorExitCode && exitCode == 0 && HasLoggedErrors ? -1 : exitCode; } public void DeliverRequest(object request) @@ -1031,18 +1162,34 @@ private sealed class StubFileSystem : IFileSystem public List CreatedDirectories { get; } = []; + public Exception? CreateFailure { get; set; } + + public Func? CreateFailureForPath { get; set; } + + public MemoryStream? OutputStream { get; set; } + public bool Exist(string path) => ExistingPaths.Contains(path) || CreatedFiles.ContainsKey(path); public void CreateDirectory(string directory) => CreatedDirectories.Add(directory); public Stream CreateNew(string path) { + if (CreateFailure is not null) + { + throw CreateFailure; + } + + if (CreateFailureForPath?.Invoke(path) is Exception pathFailure) + { + throw pathFailure; + } + if (Exist(path)) { throw new IOException($"The file '{path}' already exists."); } - MemoryStream stream = new(); + MemoryStream stream = OutputStream ?? new(); CreatedFiles.Add(path, stream); return stream; } @@ -1379,4 +1526,9 @@ public MonoRunnerInvokeTestingPlatformTask(ITaskItem targetPath) public string? GetFullToolPath() => GenerateFullPathToTool(); } + + private sealed class FailingFlushStream : MemoryStream + { + public override void Flush() => throw new IOException("Cannot flush the output log."); + } }