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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/MTP/Microsoft.Testing.Platform.MSBuild/PACKAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<assembly>_<framework>_<architecture>.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 `<assembly>_<framework>_<architecture>.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.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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());
}
},
Expand All @@ -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)
{
Expand Down Expand Up @@ -154,6 +188,19 @@ protected override void LogToolCommand(string message)
/// <inheritdoc />
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)
{
Expand All @@ -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);
Expand All @@ -187,8 +240,12 @@ private Task<IResponse> 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;
}
}
}
}
Expand Down Expand Up @@ -277,31 +334,57 @@ private Task<IResponse> HandleRequestAsync(IRequest request)
/// already exists. The directory can be chosen by the test application (e.g. <c>--results-directory</c>),
/// so the task must not overwrite, or write through, a file or link that it did not create.
/// </summary>
private void InitializeOutputFile(string resultsDirectory)
/// <returns>
/// <see langword="false"/> 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.
/// </returns>
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}'");
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/// <summary>
/// Initializes a new instance of the <see cref="InvokeTestingPlatformTask"/> class.
Expand Down Expand Up @@ -164,7 +166,6 @@ internal InvokeTestingPlatformTask(IFileSystem fileSystem)
/// <inheritdoc />
public void Dispose()
{
_outputFileStream?.Dispose();
_waitForConnections.Cancel();
_connectionLoopTask?.Wait();

Expand All @@ -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);
}
}
Loading
Loading