Skip to content
Merged
Show file tree
Hide file tree
Changes from 9 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 @@ -33,7 +33,13 @@ internal sealed class HangDumpActivityIndicator : IDataConsumer, ITestSessionLif
private readonly bool _traceLevelEnabled;
private readonly ConcurrentDictionary<TestNodeUid, (string Name, Type Type, DateTimeOffset StartTime)> _testsCurrentExecutionState = new();

private bool _exitSignalActivityIndicatorAsync;
private readonly TimeSpan _activitySignalInterval;
private readonly TimeSpan _activitySignalShutdownTimeout = TimeSpan.FromSeconds(30);

private volatile bool _exitSignalActivityIndicatorAsync;
private int _activitySignalPending;
private CancellationTokenSource? _activitySignalCancellation;
private Task? _activitySignalTask;
private NamedPipeServer? _singleConnectionNamedPipeServer;
private PipeNameDescription? _pipeNameDescription;

Expand All @@ -58,6 +64,7 @@ public HangDumpActivityIndicator(
_namedPipeClient.RegisterSerializer(new VoidResponseSerializer(), typeof(VoidResponse));
_namedPipeClient.RegisterSerializer(new ConsumerPipeNameRequestSerializer(), typeof(ConsumerPipeNameRequest));
_namedPipeClient.RegisterSerializer(new ActivitySignalRequestSerializer(), typeof(ActivitySignalRequest));
_activitySignalInterval = HangDumpOptions.GetActivitySignalInterval(HangDumpOptions.GetTimeout(_commandLineOptions));
}
}

Expand Down Expand Up @@ -100,13 +107,87 @@ await _namedPipeClient.RequestReplyAsync<ConsumerPipeNameRequest, VoidResponse>(
// Wait the connection from the testhost controller
await _singleConnectionNamedPipeServer.WaitConnectionAsync(cancellationToken).TimeoutAfterAsync(TimeoutHelper.DefaultHangTimeSpanTimeout, cancellationToken).ConfigureAwait(false);
await _logger.LogTraceAsync("Test host controller connected").ConfigureAwait(false);

_activitySignalCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
CancellationToken stopToken = _activitySignalCancellation.Token;
_activitySignalTask = _task.Run(() => SignalActivityLoopAsync(stopToken, cancellationToken), CancellationToken.None);
}
catch (OperationCanceledException ex) when (ex.CancellationToken == cancellationToken)
{
// Do nothing, we're stopping
}
}

private async Task SignalActivityLoopAsync(CancellationToken stopToken, CancellationToken sessionCancellationToken)
{
try
{
while (true)
{
await _task.Delay(_activitySignalInterval, stopToken).ConfigureAwait(false);
Comment thread
Evangelink marked this conversation as resolved.
Resolved

// The stop token only interrupts the wait. A request in flight completes, so the pipe is never
// left with a half-read reply when the session ends.
await SendPendingActivitySignalAsync(sessionCancellationToken).ConfigureAwait(false);
Comment thread
Evangelink marked this conversation as resolved.
Resolved
}
}
catch (OperationCanceledException) when (stopToken.IsCancellationRequested)
{
// Stopped by the end of the session or by cancellation.
}
catch (Exception ex)
{
// Log now: without activity signals the controller can take a hang dump before the session ends
// and rethrows this failure.
await _logger.LogErrorAsync("Failed to send a hang dump activity signal to the test host controller; activity signals stopped.", ex).ConfigureAwait(false);
throw;
}
}

private async Task StopActivitySignalLoopAsync()
{
// Idempotent: whoever takes the fields stops the loop, so session end and disposal never race on them.
CancellationTokenSource? cancellation = Interlocked.Exchange(ref _activitySignalCancellation, null);
Task? loop = Interlocked.Exchange(ref _activitySignalTask, null);
Comment thread
Evangelink marked this conversation as resolved.
Resolved
if (cancellation is null)
{
return;
}

try
{
#if NET
await cancellation.CancelAsync().ConfigureAwait(false);
#else
cancellation.Cancel();
#endif
if (loop is not null)
{
await loop.ConfigureAwait(false);
}
}
finally
{
cancellation.Dispose();
}
}

private async Task SendPendingActivitySignalAsync(CancellationToken cancellationToken)
{
if (Interlocked.Exchange(ref _activitySignalPending, 0) == 0 || _exitSignalActivityIndicatorAsync)
{
return;
}

ApplicationStateGuard.Ensure(_namedPipeClient is not null);
await _namedPipeClient.RequestReplyAsync<ActivitySignalRequest, VoidResponse>(ActivitySignalRequest.Instance, cancellationToken).ConfigureAwait(false);

if (_traceLevelEnabled)
{
await _logger.LogTraceAsync("Activity signal sent.").ConfigureAwait(false);
}
}

private async Task<IResponse> CallbackAsync(IRequest request)
{
if (request is GetInProgressTestsRequest)
Expand Down Expand Up @@ -167,31 +248,97 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella
await _logger.LogTraceAsync($"Signal for action node {nodeChangedMessage.TestNode.DisplayName} - '{state}'. _exitSignalActivityIndicatorAsync: {_exitSignalActivityIndicatorAsync}").ConfigureAwait(false);
}

// Signal the activity.
if (!_exitSignalActivityIndicatorAsync)
{
ApplicationStateGuard.Ensure(_namedPipeClient is not null);
await _namedPipeClient.RequestReplyAsync<ActivitySignalRequest, VoidResponse>(ActivitySignalRequest.Instance, cancellationToken).ConfigureAwait(false);

if (_traceLevelEnabled)
{
await _logger.LogTraceAsync($"Activity signal sent.").ConfigureAwait(false);
}
}
// Record the activity; the signal loop forwards it to the controller.
Volatile.Write(ref _activitySignalPending, 1);
Comment thread
Evangelink marked this conversation as resolved.
Resolved
}
}

public Task OnTestSessionFinishingAsync(ITestSessionContext testSessionContext)
=> Task.CompletedTask;
public async Task OnTestSessionFinishingAsync(ITestSessionContext testSessionContext)
{
if (Volatile.Read(ref _activitySignalTask) is null)
{
return;
}

// Stop the loop before sending the last pending signal, so two requests never share the pipe.
await StopActivitySignalLoopAsync().ConfigureAwait(false);

CancellationToken cancellationToken = testSessionContext.CancellationToken;
try
{
await SendPendingActivitySignalAsync(cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
// The final flush is best effort. A canceled session must not skip the session-finishing handlers
// that run after this one.
}
}

#if NETCOREAPP
public ValueTask DisposeAsync()
public async ValueTask DisposeAsync()
{
// Wait (bounded) for the loop before disposing the pipe client it may be using. This also covers runs
// where session finishing was skipped because execution or a lifecycle handler threw. If the wait times
// out, the pipe client is disposed only when the loop stops.
Task stop = StopActivitySignalLoopAsync();
try
{
Task completed = await Task.WhenAny(stop, Task.Delay(_activitySignalShutdownTimeout)).ConfigureAwait(false);
if (completed != stop)
{
DisposePipeClientAfterLateStop(stop);
return;
}

await stop.ConfigureAwait(false);
}
catch (Exception ex)
{
await _logger.LogDebugAsync($"Hang dump activity signal loop failed during disposal: {ex.Message}").ConfigureAwait(false);
}

_namedPipeClient?.Dispose();
return ValueTask.CompletedTask;
}
#endif

public void Dispose()
=> _namedPipeClient?.Dispose();
{
// Wait (bounded) for the loop before disposing the pipe client it may be using. If the wait times out, the
// pipe client is disposed only when the loop stops.
Task stop = StopActivitySignalLoopAsync();
try
{
if (!stop.Wait(_activitySignalShutdownTimeout))
{
DisposePipeClientAfterLateStop(stop);
return;
}
}
catch (Exception ex)
{
_logger.LogDebug($"Hang dump activity signal loop failed during disposal: {ex.Message}");
}

_namedPipeClient?.Dispose();
}

private void DisposePipeClientAfterLateStop(Task stop)
{
// A request that is still in flight uses the pipe client's stream and buffers. On Windows a write waits for
// the controller to drain the pipe, and the stop request cannot interrupt that wait. Disposing the client
// under it would make the request fail, and the client then exits the process. Dispose the client only
// after the loop has finished, and observe the loop's failure so it is never unobserved.
_logger.LogDebug("Hang dump activity signal loop did not stop within the shutdown timeout during disposal; the pipe client is disposed when it stops.");
_ = stop.ContinueWith(
static (task, state) =>
{
_ = task.Exception;
((NamedPipeClient?)state)?.Dispose();
},
_namedPipeClient,
CancellationToken.None,
TaskContinuationOptions.None,
TaskScheduler.Default);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,62 @@
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.Testing.Platform.CommandLine;
using Microsoft.Testing.Platform.Helpers;

namespace Microsoft.Testing.Extensions.Diagnostics;

internal static class HangDumpOptions
{
private static readonly TimeSpan DefaultTimeout = TimeSpan.FromMinutes(30);

/// <summary>
/// The longest period <see cref="Timer"/> accepts (<see cref="uint.MaxValue"/> - 1 milliseconds).
/// </summary>
public static readonly TimeSpan MaxTimerPeriod = TimeSpan.FromMilliseconds(uint.MaxValue - 1);

public static bool IsEnabled(ICommandLineOptions commandLineOptions)
=> commandLineOptions.IsOptionSet(HangDumpCommandLineProvider.HangDumpOptionName);

public static TimeSpan GetTimeout(ICommandLineOptions commandLineOptions)
=> commandLineOptions.TryGetOptionArgumentList(HangDumpCommandLineProvider.HangDumpTimeoutOptionName, out string[]? timeout)
? TimeSpanParser.Parse(timeout[0])
: DefaultTimeout;

/// <summary>
/// The test host coalesces activity and sends it to the controller at most once per interval instead of once per
/// test result, so fast tests do not pay a cross-process round trip each.
/// </summary>
public static TimeSpan GetActivitySignalInterval(TimeSpan hangTimeout)
{
var maxInterval = TimeSpan.FromSeconds(1);
var minInterval = TimeSpan.FromMilliseconds(10);
var interval = TimeSpan.FromTicks(hangTimeout.Ticks / 10);
return interval > maxInterval ? maxInterval : interval < minInterval ? minInterval : interval;
}

/// <summary>
/// Gets how long the controller waits after the last delivered activity signal before taking a hang dump.
/// Activity that happens right after a delivery can wait up to one signal interval before it is delivered, so
/// the controller adds that interval to the timeout. A dump then never fires before the configured timeout has
/// elapsed since the last activity; it can fire at most two intervals later.
/// </summary>
public static TimeSpan GetInactivityTimerDueTime(TimeSpan hangTimeout)
=> hangTimeout + GetActivitySignalInterval(hangTimeout);
Comment thread
Evangelink marked this conversation as resolved.
Resolved

/// <summary>
/// Splits <paramref name="dueTime"/> into the next period a <see cref="Timer"/> accepts and the time still to
/// wait after it, so a due time beyond <see cref="MaxTimerPeriod"/> is waited for in several periods instead of
/// being rejected or shortened.
/// </summary>
public static TimeSpan GetTimerPeriod(TimeSpan dueTime, out TimeSpan remainingDueTime)
{
if (dueTime > MaxTimerPeriod)
{
remainingDueTime = dueTime - MaxTimerPeriod;
return MaxTimerPeriod;
}

remainingDueTime = TimeSpan.Zero;
return dueTime;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,21 @@ internal sealed partial class HangDumpProcessLifetimeHandler : ITestHostProcessL
private readonly object _dumpLock = new();
#endif

// Serializes re-arming the inactivity timer (on each activity signal) with continuing a wait that is longer
// than one Timer period (in the timer callback).
#if NET9_0_OR_GREATER
private readonly Lock _activityTimerLock = new();
#else
private readonly object _activityTimerLock = new();
#endif

private TimeSpan? _activityTimerValue;
private TimeSpan? _activityTimerDueTime;
private Timer? _activityTimer;

// The part of the inactivity due time that is still to wait after the timer's current period. It is non-zero
// only when the due time exceeds the maximum period a Timer accepts. Read and written under _activityTimerLock.
private TimeSpan _activityTimerRemainingDueTime;
private DateTimeOffset? _deadlineDumpAt;
private Timer? _deadlineTimer;
private bool _hostExited;
Expand Down Expand Up @@ -127,9 +140,8 @@ public HangDumpProcessLifetimeHandler(

public async Task BeforeTestHostProcessStartAsync(CancellationToken cancellationToken)
{
_activityTimerValue = _commandLineOptions.TryGetOptionArgumentList(HangDumpCommandLineProvider.HangDumpTimeoutOptionName, out string[]? timeout)
? TimeSpanParser.Parse(timeout[0])
: TimeSpan.FromMinutes(30);
_activityTimerValue = HangDumpOptions.GetTimeout(_commandLineOptions);
_activityTimerDueTime = HangDumpOptions.GetInactivityTimerDueTime(_activityTimerValue.Value);

if (_commandLineOptions.TryGetOptionArgumentList(HangDumpCommandLineProvider.HangDumpTypeOptionName, out string[]? dumpType))
{
Expand Down Expand Up @@ -212,7 +224,7 @@ private async Task<IResponse> CallbackAsync(IRequest request)
}
else if (request is ActivitySignalRequest)
{
_activityTimer?.Change(_activityTimerValue!.Value, TimeSpan.FromMilliseconds(-1));
ArmActivityTimer();

if (_traceEnabled)
{
Expand Down Expand Up @@ -291,10 +303,11 @@ public async Task OnTestHostProcessStartedAsync(ITestHostProcessInformation test
// The inactivity timer only makes sense once the host has connected and can send activity
// signals; before that there is nothing to reset it. The deadline timer above is independent.
_activityTimer = new Timer(
_ => TriggerDumpOnce(cancellationToken, triggeredByDeadline: false),
_ => OnActivityTimerElapsed(cancellationToken),
null,
_activityTimerValue!.Value,
Timeout.InfiniteTimeSpan,
TimeSpan.FromMilliseconds(-1));
ArmActivityTimer();
}
catch (Exception ex) when (Volatile.Read(ref _dumpTaken) != 0)
{
Expand Down Expand Up @@ -379,6 +392,52 @@ await RunBestEffortDiagnosticAsync(
}
}

private void ArmActivityTimer()
{
lock (_activityTimerLock)
{
Timer? timer = _activityTimer;
if (timer is null)
{
return;
}

TimeSpan period = HangDumpOptions.GetTimerPeriod(_activityTimerDueTime!.Value, out _activityTimerRemainingDueTime);
try
{
timer.Change(period, Timeout.InfiniteTimeSpan);
}
catch (ObjectDisposedException)
{
// Teardown won the race with this activity signal.
}
}
}

private void OnActivityTimerElapsed(CancellationToken cancellationToken)
{
lock (_activityTimerLock)
{
if (_activityTimerRemainingDueTime > TimeSpan.Zero)
{
// The inactivity timeout is longer than one Timer period: keep waiting instead of dumping early.
TimeSpan period = HangDumpOptions.GetTimerPeriod(_activityTimerRemainingDueTime, out _activityTimerRemainingDueTime);
try
{
_activityTimer!.Change(period, Timeout.InfiniteTimeSpan);
}
catch (ObjectDisposedException)
{
// Teardown won the race with this timer callback.
}

return;
}
}

TriggerDumpOnce(cancellationToken, triggeredByDeadline: false);
}

private void OnDeadlineTimerElapsed(CancellationToken cancellationToken)
{
TimeSpan dueTime = DeadlineHelper.GetTimerDueTime(_deadlineDumpAt!.Value, _clock.UtcNow);
Expand Down
Loading
Loading