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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ internal sealed class HangDumpActivityIndicator : IDataConsumer, ITestSessionLif
private bool _exitSignalActivityIndicatorAsync;
private NamedPipeServer? _singleConnectionNamedPipeServer;
private PipeNameDescription? _pipeNameDescription;
private bool _sessionEndCalled;

public HangDumpActivityIndicator(
ICommandLineOptions commandLineOptions,
Expand All @@ -61,7 +60,6 @@ public HangDumpActivityIndicator(
?? throw new InvalidOperationException($"Expected {pipeNameEnvironmentVariable} environment variable set.");
_namedPipeClient = new NamedPipeClient(namedPipeName, _environment);
_namedPipeClient.RegisterSerializer(new VoidResponseSerializer(), typeof(VoidResponse));
_namedPipeClient.RegisterSerializer(new SessionEndSerializerRequestSerializer(), typeof(SessionEndSerializerRequest));
_namedPipeClient.RegisterSerializer(new ConsumerPipeNameRequestSerializer(), typeof(ConsumerPipeNameRequest));
_namedPipeClient.RegisterSerializer(new ActivitySignalRequestSerializer(), typeof(ActivitySignalRequest));
}
Expand Down Expand Up @@ -183,51 +181,17 @@ or FailedTestNodeStateProperty or TimeoutTestNodeStateProperty or SkippedTestNod
}
}

public async Task OnTestSessionFinishingAsync(ITestSessionContext testSessionContext)
{
CancellationToken cancellationToken = testSessionContext.CancellationToken;
ApplicationStateGuard.Ensure(_namedPipeClient is not null);

if (!await IsEnabledAsync().ConfigureAwait(false))
{
return;
}

await _namedPipeClient.RequestReplyAsync<SessionEndSerializerRequest, VoidResponse>(new SessionEndSerializerRequest(), cancellationToken)
.TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellationToken).ConfigureAwait(false);

await _logger.LogDebugAsync("Signal for test session end'").ConfigureAwait(false);
_exitSignalActivityIndicatorAsync = true;

await _logger.LogTraceAsync("Signaled by process for it's exit").ConfigureAwait(false);
_sessionEndCalled = true;
}
public Task OnTestSessionFinishingAsync(ITestSessionContext testSessionContext)
=> Task.CompletedTask;

#if NETCOREAPP
public async ValueTask DisposeAsync()
public ValueTask DisposeAsync()
{
_namedPipeClient?.Dispose();

// If the OnTestSessionFinishingAsync is not called means that something unhandled happened
// and we didn't correctly coordinate the shutdown with the HangDumpProcessLifetimeHandler.
// If we go do wait for the server we will hang.
if (_sessionEndCalled)
{
await DisposeHelper.DisposeAsync(_singleConnectionNamedPipeServer).ConfigureAwait(false);
}
return ValueTask.CompletedTask;
}
Comment thread
Youssef1313 marked this conversation as resolved.
Resolved
#endif

public void Dispose()
{
_namedPipeClient?.Dispose();

// If the OnTestSessionFinishingAsync is not called means that something unhandled happened
// and we didn't correctly coordinate the shutdown with the HangDumpProcessLifetimeHandler.
// If we go do wait for the server we will hang.
if (_sessionEndCalled)
{
_singleConnectionNamedPipeServer?.Dispose();
}
}
=> _namedPipeClient?.Dispose();
Comment thread
Evangelink marked this conversation as resolved.
Resolved
}
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,6 @@ public async Task BeforeTestHostProcessStartAsync(CancellationToken cancellation

_singleConnectionNamedPipeServer = new(_pipeNameDescription, CallbackAsync, _environment, _logger, _task, cancellationToken);
_singleConnectionNamedPipeServer.RegisterSerializer(new VoidResponseSerializer(), typeof(VoidResponse));
_singleConnectionNamedPipeServer.RegisterSerializer(new SessionEndSerializerRequestSerializer(), typeof(SessionEndSerializerRequest));
_singleConnectionNamedPipeServer.RegisterSerializer(new ConsumerPipeNameRequestSerializer(), typeof(ConsumerPipeNameRequest));
_singleConnectionNamedPipeServer.RegisterSerializer(new ActivitySignalRequestSerializer(), typeof(ActivitySignalRequest));

Expand All @@ -127,24 +126,7 @@ public async Task BeforeTestHostProcessStartAsync(CancellationToken cancellation

private async Task<IResponse> CallbackAsync(IRequest request)
{
if (request is SessionEndSerializerRequest)
{
await _logger.LogDebugAsync("Session end received by the test host").ConfigureAwait(false);

#pragma warning disable IDE0031 // Null check can be simplified - analyzer doesn't consider multigating. But we can fix when https://github.com/dotnet/csharplang/issues/8631 is implemented.
if (_activityTimer is not null)
{
#if NETCOREAPP
await _activityTimer.DisposeAsync().ConfigureAwait(false);
#else
_activityTimer.Dispose();
#endif
}

_namedPipeClient?.Dispose();
return VoidResponse.CachedInstance;
}
else if (request is ConsumerPipeNameRequest consumerPipeNameRequest)
if (request is ConsumerPipeNameRequest consumerPipeNameRequest)
{
await _logger.LogDebugAsync($"Consumer pipe name received '{consumerPipeNameRequest.PipeName}'").ConfigureAwait(false);
_namedPipeClient = new NamedPipeClient(consumerPipeNameRequest.PipeName, _environment);
Comment thread
Youssef1313 marked this conversation as resolved.
Resolved
Expand Down Expand Up @@ -217,6 +199,15 @@ public async Task OnTestHostProcessExitedAsync(ITestHostProcessInformation testH
{
cancellationToken.ThrowIfCancellationRequested();

if (_activityTimer is not null)
{
#if NETCOREAPP
await _activityTimer.DisposeAsync().ConfigureAwait(false);
#else
_activityTimer.Dispose();
#endif
}

if (!testHostProcessInformation.HasExitedGracefully)
{
_logger.LogDebug($"Testhost didn't exit gracefully '{testHostProcessInformation.ExitCode}')");
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,25 @@ public async Task HangDump_InvalidFormat_ShouldFail()
""");
}

[TestMethod]
public async Task HangDump_WithForegroundThreadAfterSessionFinish_CreateDump()
{
string resultDirectory = Path.Combine(AssetFixture.TargetAssetPath, Guid.NewGuid().ToString("N"), TargetFrameworks.NetCurrent);
var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, "HangDump", TargetFrameworks.NetCurrent);
TestHostResult testHostResult = await testHost.ExecuteAsync(
$"--hangdump --hangdump-timeout 8s --results-directory {resultDirectory}",
new Dictionary<string, string?>
{
{ "SLEEPTIMEMS1", "4000" },
{ "SLEEPTIMEMS2", "4000" },
{ "SPAWN_FOREGROUND_THREAD", "true" },
},
cancellationToken: TestContext.CancellationToken);
testHostResult.AssertExitCodeIs(ExitCodes.TestHostProcessExitedNonGracefully);
string[] dumpFiles = Directory.GetFiles(resultDirectory, "HangDump*.dmp", SearchOption.AllDirectories);
Assert.ContainsSingle(dumpFiles, $"Expected single dump file. Found: {Environment.NewLine}{string.Join(Environment.NewLine, dumpFiles)}{Environment.NewLine}{testHostResult}");
}

public sealed class TestAssetFixture() : TestAssetFixtureBase(AcceptanceFixture.NuGetGlobalPackagesFolder)
{
private const string AssetName = "AssetFixture";
Expand Down Expand Up @@ -254,6 +273,18 @@ public async Task ExecuteRequestAsync(ExecuteRequestContext context)
Properties = new PropertyBag(new PassedTestNodeStateProperty()),
}));

// Spawn a foreground thread that continues running after the test session finishes
// to verify that hang dump triggers even after session end
if (Environment.GetEnvironmentVariable("SPAWN_FOREGROUND_THREAD") == "true")
{
Thread foregroundThread = new Thread(() =>
{
Thread.Sleep(600000); // Sleep for 10 minutes to trigger hang dump
});
foregroundThread.IsBackground = false; // Foreground thread to prevent process exit
foregroundThread.Start();
}

context.Complete();
}
}
Expand Down