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 @@ -28,14 +28,9 @@ internal sealed class HangDumpActivityIndicator : IDataConsumer, ITestSessionLif
private readonly IClock _clock;
private readonly ILogger<HangDumpActivityIndicator> _logger;
private readonly NamedPipeClient? _namedPipeClient;
private readonly ManualResetEventSlim _signalActivity = new(false);
private readonly ManualResetEventSlim _mutexCreated = new(false);
private readonly bool _traceLevelEnabled;
private readonly ConcurrentDictionary<TestNodeUid, (string Name, Type Type, DateTimeOffset StartTime)> _testsCurrentExecutionState = new();

private Task? _signalActivityIndicatorTask;
private Mutex? _activityIndicatorMutex;
private string? _mutexName;
private bool _exitSignalActivityIndicatorAsync;
private NamedPipeServer? _singleConnectionNamedPipeServer;
private PipeNameDescription? _pipeNameDescription;
Expand All @@ -57,17 +52,17 @@ public HangDumpActivityIndicator(
_clock = clock;
if (_commandLineOptions.IsOptionSet(HangDumpCommandLineProvider.HangDumpOptionName))
{
string namedPipeSuffix = _environment.GetEnvironmentVariable(HangDumpConfiguration.MutexNameSuffix)
?? throw new InvalidOperationException($"Expected {HangDumpConfiguration.MutexNameSuffix} environment variable set.");
string namedPipeSuffix = _environment.GetEnvironmentVariable(HangDumpConfiguration.NamedPipeNameSuffixEnvironmentVariable)
?? throw new InvalidOperationException($"Expected {HangDumpConfiguration.NamedPipeNameSuffixEnvironmentVariable} environment variable set.");
// @Marco: Why do we need to duplicate logic here instead of using HangDumpConfiguration.PipeNameKey?
string pipeNameEnvironmentVariable = $"{HangDumpConfiguration.PipeName}_{FNV_1aHashHelper.ComputeStringHash(testApplicationModuleInfo.GetCurrentTestApplicationFullPath())}_{namedPipeSuffix}";
string pipeNameEnvironmentVariable = $"{HangDumpConfiguration.PipeNameEnvironmentVariableNamePrefix}_{FNV_1aHashHelper.ComputeStringHash(testApplicationModuleInfo.GetCurrentTestApplicationFullPath())}_{namedPipeSuffix}";
string namedPipeName = _environment.GetEnvironmentVariable(pipeNameEnvironmentVariable)
?? throw new InvalidOperationException($"Expected {pipeNameEnvironmentVariable} environment variable set.");
_namedPipeClient = new NamedPipeClient(namedPipeName, _environment);
_namedPipeClient.RegisterSerializer(new ActivityIndicatorMutexNameRequestSerializer(), typeof(ActivityIndicatorMutexNameRequest));
_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 @@ -99,17 +94,6 @@ public async Task OnTestSessionStartingAsync(ITestSessionContext testSessionCont
await _logger.LogTraceAsync($"Connecting to the process lifetime handler {_namedPipeClient.PipeName}").ConfigureAwait(false);
await _namedPipeClient.ConnectAsync(cancellationToken).TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellationToken).ConfigureAwait(false);
await _logger.LogTraceAsync("Connected to the process lifetime handler").ConfigureAwait(false);
_activityIndicatorMutex = new Mutex(true);
_mutexName = $"{HangDumpConfiguration.MutexName}_{Guid.NewGuid():N}";

// Keep the custom thread to avoid to waste one from thread pool.
_signalActivityIndicatorTask = _task.RunLongRunning(SignalActivityIndicatorAsync, "[HangDump] SignalActivityIndicatorAsync", cancellationToken);
await _logger.LogTraceAsync($"Wait for mutex '{_mutexName}' creation").ConfigureAwait(false);
_mutexCreated.Wait(cancellationToken);
await _logger.LogTraceAsync($"Mutex '{_mutexName}' created").ConfigureAwait(false);
await _namedPipeClient.RequestReplyAsync<ActivityIndicatorMutexNameRequest, VoidResponse>(new ActivityIndicatorMutexNameRequest(_mutexName), cancellationToken)
.TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellationToken).ConfigureAwait(false);
await _logger.LogTraceAsync($"Mutex '{_mutexName}' sent to the process lifetime handler").ConfigureAwait(false);

// Setup the server channel with the testhost controller
_pipeNameDescription = NamedPipeServer.GetPipeName(Guid.NewGuid().ToString("N"), _environment);
Expand Down Expand Up @@ -143,7 +127,7 @@ private async Task<IResponse> CallbackAsync(IRequest request)
else if (request is ExitSignalActivityIndicatorTaskRequest)
{
await _logger.LogDebugAsync($"Received '{nameof(ExitSignalActivityIndicatorTaskRequest)}'").ConfigureAwait(false);
await ExitSignalActivityIndicatorTaskAsync().ConfigureAwait(false);
_exitSignalActivityIndicatorAsync = true;
return VoidResponse.CachedInstance;
}
else
Expand Down Expand Up @@ -185,55 +169,27 @@ or FailedTestNodeStateProperty or TimeoutTestNodeStateProperty or SkippedTestNod
{
if (_traceLevelEnabled)
{
await _logger.LogTraceAsync($"Signal for action node {nodeChangedMessage.TestNode.DisplayName} - '{state}'").ConfigureAwait(false);
await _logger.LogTraceAsync($"Signal for action node {nodeChangedMessage.TestNode.DisplayName} - '{state}'. _exitSignalActivityIndicatorAsync: {_exitSignalActivityIndicatorAsync}").ConfigureAwait(false);
}

// Signal the activity if it's not set
if (!_signalActivity.IsSet)
// Signal the activity.
if (!_exitSignalActivityIndicatorAsync)
{
_signalActivity.Set();
}
}
}

private Task SignalActivityIndicatorAsync()
{
_activityIndicatorMutex = new Mutex(true, _mutexName);
_mutexCreated.Set();

while (!_exitSignalActivityIndicatorAsync)
{
// Wait for the signal
// We don't add the timeout here because depends on the user value specified with the --hangdump-timeout option
_signalActivity.Wait();
ApplicationStateGuard.Ensure(_namedPipeClient is not null);
await _namedPipeClient.RequestReplyAsync<ActivitySignalRequest, VoidResponse>(ActivitySignalRequest.Instance, cancellationToken).ConfigureAwait(false);

if (_traceLevelEnabled)
{
_logger.LogTrace($"Signal process lifetime handler, exitSignalActivityIndicatorAsync {_exitSignalActivityIndicatorAsync}");
}

_activityIndicatorMutex.ReleaseMutex();
_activityIndicatorMutex.WaitOne();

if (_traceLevelEnabled)
{
_logger.LogTrace($"Signaled by process lifetime handler, exitSignalActivityIndicatorAsync {_exitSignalActivityIndicatorAsync}");
if (_traceLevelEnabled)
{
_logger.LogTrace($"Activity signal sent.");
}
}

// Reset the signal
_signalActivity.Reset();
}

_logger.LogDebug("Exit 'SignalActivityIndicatorAsync'");

return Task.CompletedTask;
}

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

if (!await IsEnabledAsync().ConfigureAwait(false))
{
Expand All @@ -244,25 +200,12 @@ await _namedPipeClient.RequestReplyAsync<SessionEndSerializerRequest, VoidRespon
.TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellationToken).ConfigureAwait(false);

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

await _logger.LogTraceAsync("Signaled by process for it's exit").ConfigureAwait(false);
_sessionEndCalled = true;
}

private async Task ExitSignalActivityIndicatorTaskAsync()
{
if (_exitSignalActivityIndicatorAsync)
{
return;
}

ApplicationStateGuard.Ensure(_signalActivityIndicatorTask is not null);
_exitSignalActivityIndicatorAsync = true;
_signalActivity.Set();
await _signalActivityIndicatorTask.TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout).ConfigureAwait(false);
}

#if NETCOREAPP
public async ValueTask DisposeAsync()
{
Expand All @@ -275,10 +218,6 @@ public async ValueTask DisposeAsync()
{
await DisposeHelper.DisposeAsync(_singleConnectionNamedPipeServer).ConfigureAwait(false);
}

_mutexCreated.Dispose();
_signalActivity.Dispose();
_activityIndicatorMutex?.Dispose();
}
#endif

Expand All @@ -293,9 +232,5 @@ public void Dispose()
{
_singleConnectionNamedPipeServer?.Dispose();
}

_mutexCreated.Dispose();
_signalActivity.Dispose();
_activityIndicatorMutex?.Dispose();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,23 @@ namespace Microsoft.Testing.Extensions.Diagnostics;

internal sealed class HangDumpConfiguration
{
public const string PipeName = "TESTINGPLATFORM_HANGDUMP_PIPENAME";
public const string MutexName = "TESTINGPLATFORM_HANGDUMP_MUTEXNAME";
public const string MutexNameSuffix = "TESTINGPLATFORM_HANGDUMP_MUTEXNAME_SUFFIX";
// HangDump extension sets to environment variables.
// 1. TESTINGPLATFORM_HANGDUMP_NAMEDPIPE_NAME_SUFFIX
// 2. TESTINGPLATFORM_HANGDUMP_PIPENAME_<hash>_<namedPipeSuffix> (hash is dependent on application path, namedPipeSuffix is a random guid and is the same as the value of TESTINGPLATFORM_HANGDUMP_NAMEDPIPE_NAME_SUFFIX)
// The value of TESTINGPLATFORM_HANGDUMP_PIPENAME_<hash>_<namedPipeSuffix> represents the name of the named pipe.
public const string PipeNameEnvironmentVariableNamePrefix = "TESTINGPLATFORM_HANGDUMP_PIPENAME";
public const string NamedPipeNameSuffixEnvironmentVariable = "TESTINGPLATFORM_HANGDUMP_NAMEDPIPE_NAME_SUFFIX";

public HangDumpConfiguration(ITestApplicationModuleInfo testApplicationModuleInfo, PipeNameDescription pipeNameDescription, string mutexSuffix)
public HangDumpConfiguration(ITestApplicationModuleInfo testApplicationModuleInfo, PipeNameDescription pipeNameDescription, string namedPipeSuffix)
{
PipeNameValue = pipeNameDescription.Name;
PipeNameKey = $"{PipeName}_{FNV_1aHashHelper.ComputeStringHash(testApplicationModuleInfo.GetCurrentTestApplicationFullPath())}_{mutexSuffix}";
MutexSuffix = mutexSuffix;
PipeNameKey = $"{PipeNameEnvironmentVariableNamePrefix}_{FNV_1aHashHelper.ComputeStringHash(testApplicationModuleInfo.GetCurrentTestApplicationFullPath())}_{namedPipeSuffix}";
NamedPipeSuffix = namedPipeSuffix;
}

public string PipeNameKey { get; }

public string PipeNameValue { get; }

public string MutexSuffix { get; }
public string NamedPipeSuffix { get; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public Task UpdateAsync(IEnvironmentVariables environmentVariables)
environmentVariables.SetVariable(
new(_hangDumpConfiguration.PipeNameKey, _hangDumpConfiguration.PipeNameValue, false, true));
environmentVariables.SetVariable(
new(HangDumpConfiguration.MutexNameSuffix, _hangDumpConfiguration.MutexSuffix, false, true));
new(HangDumpConfiguration.NamedPipeNameSuffixEnvironmentVariable, _hangDumpConfiguration.NamedPipeSuffix, false, true));
return Task.CompletedTask;
}

Expand All @@ -55,18 +55,18 @@ public Task<ValidationResult> ValidateTestHostEnvironmentVariablesAsync(IReadOnl
string.Format(CultureInfo.InvariantCulture, ExtensionResources.HangDumpEnvironmentVariableInvalidValueErrorMessage, _hangDumpConfiguration.PipeNameKey, envVar.Value, _hangDumpConfiguration.PipeNameKey)));
}

if (!environmentVariables.TryGetVariable(HangDumpConfiguration.MutexNameSuffix, out envVar))
if (!environmentVariables.TryGetVariable(HangDumpConfiguration.NamedPipeNameSuffixEnvironmentVariable, out envVar))
{
return Task.FromResult(
ValidationResult.Invalid(
string.Format(CultureInfo.InvariantCulture, ExtensionResources.HangDumpEnvironmentVariableIsMissingErrorMessage, HangDumpConfiguration.MutexNameSuffix)));
string.Format(CultureInfo.InvariantCulture, ExtensionResources.HangDumpEnvironmentVariableIsMissingErrorMessage, HangDumpConfiguration.NamedPipeNameSuffixEnvironmentVariable)));
}

if (envVar.Value != _hangDumpConfiguration.MutexSuffix)
if (envVar.Value != _hangDumpConfiguration.NamedPipeSuffix)
{
return Task.FromResult(
ValidationResult.Invalid(
string.Format(CultureInfo.InvariantCulture, ExtensionResources.HangDumpEnvironmentVariableInvalidValueErrorMessage, HangDumpConfiguration.MutexNameSuffix, envVar.Value, _hangDumpConfiguration.MutexSuffix)));
string.Format(CultureInfo.InvariantCulture, ExtensionResources.HangDumpEnvironmentVariableInvalidValueErrorMessage, HangDumpConfiguration.NamedPipeNameSuffixEnvironmentVariable, envVar.Value, _hangDumpConfiguration.NamedPipeSuffix)));
}

// No problem found
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ public static void AddHangDumpProvider(this ITestApplicationBuilder builder)
{
var environment = new SystemEnvironment();
CurrentTestApplicationModuleInfo testApplicationModuleInfo = new(environment, new SystemProcessHandler());
string mutexSuffix = Guid.NewGuid().ToString("N");
string namedPipeSuffix = Guid.NewGuid().ToString("N");
PipeNameDescription pipeNameDescription = NamedPipeServer.GetPipeName(Guid.NewGuid().ToString("N"), environment);
HangDumpConfiguration hangDumpConfiguration = new(testApplicationModuleInfo, pipeNameDescription, mutexSuffix);
HangDumpConfiguration hangDumpConfiguration = new(testApplicationModuleInfo, pipeNameDescription, namedPipeSuffix);

builder.TestHostControllers.AddProcessLifetimeHandler(serviceProvider
=> new HangDumpProcessLifetimeHandler(
Expand Down
Loading