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 @@ -3,6 +3,7 @@

using Microsoft.Testing.Extensions.Diagnostics.Resources;
using Microsoft.Testing.Platform.CommandLine;
using Microsoft.Testing.Platform.TestHostControllers;

namespace Microsoft.Testing.Extensions.Diagnostics;

Expand All @@ -12,8 +13,8 @@ internal sealed class HangDumpEnvironmentVariableProvider : global::Microsoft.Te

private readonly ICommandLineOptions _commandLineOptions;

public HangDumpEnvironmentVariableProvider(ICommandLineOptions commandLineOptions, string pipeName)
: base(pipeName, PipeNameEnvironmentVariableName)
public HangDumpEnvironmentVariableProvider(ICommandLineOptions commandLineOptions, NamedPipeServerEndpoint endpoint)
: base(endpoint, PipeNameEnvironmentVariableName)
{
_commandLineOptions = commandLineOptions;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Microsoft.Testing.Platform.Extensions;
using Microsoft.Testing.Platform.IPC;
using Microsoft.Testing.Platform.Services;
using Microsoft.Testing.Platform.TestHostControllers;

#if !NETCOREAPP
using Polyfills;
Expand Down Expand Up @@ -43,11 +44,11 @@ public static void AddHangDumpProvider(this ITestApplicationBuilder builder)
throw new PlatformNotSupportedException("Hang dump extension is not available on wasi");
}

PipeNameDescription pipeNameDescription = NamedPipeServer.GetPipeName(Guid.NewGuid().ToString("N"));
var endpoint = new NamedPipeServerEndpoint(NamedPipeServer.GetPipeName(Guid.NewGuid().ToString("N")).Name);

builder.TestHostControllers.AddProcessLifetimeHandler(serviceProvider
=> new HangDumpProcessLifetimeHandler(
pipeNameDescription,
endpoint,
serviceProvider.GetMessageBus(),
serviceProvider.GetOutputDevice(),
serviceProvider.GetCommandLineOptions(),
Expand All @@ -56,10 +57,11 @@ public static void AddHangDumpProvider(this ITestApplicationBuilder builder)
serviceProvider.GetLoggerFactory(),
serviceProvider.GetConfiguration(),
serviceProvider.GetProcessHandler(),
serviceProvider.GetClock()));
serviceProvider.GetClock(),
serviceProvider));

builder.TestHostControllers.AddEnvironmentVariableProvider(serviceProvider
=> new HangDumpEnvironmentVariableProvider(serviceProvider.GetCommandLineOptions(), pipeNameDescription.Name));
=> new HangDumpEnvironmentVariableProvider(serviceProvider.GetCommandLineOptions(), endpoint));

builder.CommandLine.AddProvider(()
=> new HangDumpCommandLineProvider());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
using Microsoft.Testing.Platform.Logging;
using Microsoft.Testing.Platform.Messages;
using Microsoft.Testing.Platform.OutputDevice;
using Microsoft.Testing.Platform.Services;
using Microsoft.Testing.Platform.TestHostControllers;

namespace Microsoft.Testing.Extensions.Diagnostics;

Expand All @@ -36,7 +38,8 @@ internal sealed partial class HangDumpProcessLifetimeHandler : ITestHostProcessL
private readonly IConfiguration _configuration;
private readonly IProcessHandler _processHandler;
private readonly IClock _clock;
private readonly PipeNameDescription _pipeNameDescription;
private readonly IServiceProvider _serviceProvider;
private readonly NamedPipeServerEndpoint _endpoint;
private readonly bool _traceEnabled;
private readonly ILogger<HangDumpProcessLifetimeHandler> _logger;
private readonly ManualResetEventSlim _waitConsumerPipeName = new(false);
Expand Down Expand Up @@ -84,7 +87,7 @@ internal sealed partial class HangDumpProcessLifetimeHandler : ITestHostProcessL
private CancellationTokenSource? _handshakeCancellationTokenSource;

public HangDumpProcessLifetimeHandler(
PipeNameDescription pipeNameDescription,
NamedPipeServerEndpoint endpoint,
IMessageBus messageBus,
IOutputDevice outputDevice,
ICommandLineOptions commandLineOptions,
Expand All @@ -93,11 +96,12 @@ public HangDumpProcessLifetimeHandler(
ILoggerFactory loggerFactory,
IConfiguration configuration,
IProcessHandler processHandler,
IClock clock)
IClock clock,
IServiceProvider serviceProvider)
{
_logger = loggerFactory.CreateLogger<HangDumpProcessLifetimeHandler>();
_traceEnabled = _logger.IsEnabled(LogLevel.Trace);
_pipeNameDescription = pipeNameDescription;
_endpoint = endpoint;
_messageBus = messageBus;
_outputDisplay = new OutputDeviceWriter(outputDevice, this);
_commandLineOptions = commandLineOptions;
Expand All @@ -106,6 +110,7 @@ public HangDumpProcessLifetimeHandler(
_configuration = configuration;
_processHandler = processHandler;
_clock = clock;
_serviceProvider = serviceProvider;
}

public string Uid => nameof(HangDumpProcessLifetimeHandler);
Expand Down Expand Up @@ -163,7 +168,16 @@ await _outputDisplay.DisplayAsync(
await _logger.LogInformationAsync($"Hang dump deadline setup {_deadlineDumpAt:o}.").ConfigureAwait(false);
}

_singleConnectionNamedPipeServer = new(_pipeNameDescription, CallbackAsync, _environment, _logger, _task, cancellationToken);
_singleConnectionNamedPipeServer = new(
new PipeNameDescription(_endpoint.PipeName),
CallbackAsync,
_environment,
_logger,
_task,
maxNumberOfServerInstances: 1,
_serviceProvider.GetTestHostControllerAuthorizedSecurityIdentities(),
cancellationToken);
_endpoint.PipeName = _singleConnectionNamedPipeServer.PipeName.Name;
_singleConnectionNamedPipeServer.RegisterSerializer(new VoidResponseSerializer(), typeof(VoidResponse));
_singleConnectionNamedPipeServer.RegisterSerializer(new ConsumerPipeNameRequestSerializer(), typeof(ConsumerPipeNameRequest));
_singleConnectionNamedPipeServer.RegisterSerializer(new ActivitySignalRequestSerializer(), typeof(ActivitySignalRequest));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
#nullable enable
Microsoft.Testing.Extensions.Diagnostics.HangDumpEnvironmentVariableProvider.HangDumpEnvironmentVariableProvider(Microsoft.Testing.Platform.CommandLine.ICommandLineOptions! commandLineOptions, Microsoft.Testing.Platform.TestHostControllers.NamedPipeServerEndpoint! endpoint) -> void
Microsoft.Testing.Extensions.Diagnostics.HangDumpProcessLifetimeHandler.HangDumpProcessLifetimeHandler(Microsoft.Testing.Platform.TestHostControllers.NamedPipeServerEndpoint! endpoint, Microsoft.Testing.Platform.Messages.IMessageBus! messageBus, Microsoft.Testing.Platform.OutputDevice.IOutputDevice! outputDevice, Microsoft.Testing.Platform.CommandLine.ICommandLineOptions! commandLineOptions, Microsoft.Testing.Platform.Helpers.ITask! task, Microsoft.Testing.Platform.Helpers.IEnvironment! environment, Microsoft.Testing.Platform.Logging.ILoggerFactory! loggerFactory, Microsoft.Testing.Platform.Configurations.IConfiguration! configuration, Microsoft.Testing.Platform.Helpers.IProcessHandler! processHandler, Microsoft.Testing.Platform.Helpers.IClock! clock, System.IServiceProvider! serviceProvider) -> void
Microsoft.Testing.Extensions.PipeNameEnvironmentVariableProviderBase.PipeNameEnvironmentVariableProviderBase(Microsoft.Testing.Platform.TestHostControllers.NamedPipeServerEndpoint! endpoint, string! environmentVariableName) -> void
*REMOVED*Microsoft.Testing.Extensions.Diagnostics.HangDumpEnvironmentVariableProvider.HangDumpEnvironmentVariableProvider(Microsoft.Testing.Platform.CommandLine.ICommandLineOptions! commandLineOptions, string! pipeName) -> void
*REMOVED*Microsoft.Testing.Extensions.Diagnostics.HangDumpProcessLifetimeHandler.HangDumpProcessLifetimeHandler(Microsoft.Testing.Platform.IPC.PipeNameDescription! pipeNameDescription, Microsoft.Testing.Platform.Messages.IMessageBus! messageBus, Microsoft.Testing.Platform.OutputDevice.IOutputDevice! outputDevice, Microsoft.Testing.Platform.CommandLine.ICommandLineOptions! commandLineOptions, Microsoft.Testing.Platform.Helpers.ITask! task, Microsoft.Testing.Platform.Helpers.IEnvironment! environment, Microsoft.Testing.Platform.Logging.ILoggerFactory! loggerFactory, Microsoft.Testing.Platform.Configurations.IConfiguration! configuration, Microsoft.Testing.Platform.Helpers.IProcessHandler! processHandler, Microsoft.Testing.Platform.Helpers.IClock! clock) -> void
*REMOVED*Microsoft.Testing.Extensions.PipeNameEnvironmentVariableProviderBase.PipeNameEnvironmentVariableProviderBase(string! pipeName, string! environmentVariableName) -> void
const Microsoft.Testing.Platform.Helpers.EnvironmentVariableConstants.TESTINGPLATFORM_DOTNETTEST_ATTEMPTNUMBER = "TESTINGPLATFORM_DOTNETTEST_ATTEMPTNUMBER" -> string!
const Microsoft.Testing.Platform.IPC.FileArtifactMessageFieldsId.InputArtifactPaths = 8 -> ushort
const Microsoft.Testing.Platform.IPC.FileArtifactMessageFieldsId.Kind = 7 -> ushort
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,11 @@ static Microsoft.Testing.Extensions.PackagedApp.PackagedAppActivationArguments.R
static Microsoft.Testing.Extensions.PackagedApp.PackagedAppActivationArguments.TryDeletePayload(string? payloadPath) -> void
static Microsoft.Testing.Extensions.PackagedApp.PackagedAppActivationArguments.TryDeleteStalePayloads(string! localStateDirectory, System.DateTime utcNow) -> void
static Microsoft.Testing.Extensions.PackagedApp.PackagedAppConnectBackHandshake.GetHandshakeDirectory(string! packageFamilyName) -> string!
static Microsoft.Testing.Extensions.PackagedApp.PackagedAppConnectBackHandshake.GetHandshakeFileName(string! testHostControllerPid) -> string!
static Microsoft.Testing.Extensions.PackagedApp.PackagedAppConnectBackHandshake.GetHandshakeFilePath(string! packageFamilyName, string! testHostControllerPid) -> string!
static Microsoft.Testing.Extensions.PackagedApp.PackagedAppConnectBackHandshake.GetHandshakeFileName(string! handshakeId) -> string!
static Microsoft.Testing.Extensions.PackagedApp.PackagedAppConnectBackHandshake.GetHandshakeFilePath(string! packageFamilyName, string! handshakeId) -> string!
static Microsoft.Testing.Extensions.PackagedApp.PackagedAppConnectBackHandshake.ReadAndDelete(string! filePath) -> System.Collections.Generic.IReadOnlyDictionary<string!, string?>?
static Microsoft.Testing.Extensions.PackagedApp.PackagedAppConnectBackHandshake.TryDelete(string! filePath) -> void
static Microsoft.Testing.Extensions.PackagedApp.PackagedAppConnectBackHandshake.TryGetHandshakeId(System.Collections.Generic.IReadOnlyList<string!>! arguments) -> string?
static Microsoft.Testing.Extensions.PackagedApp.PackagedAppConnectBackHandshake.TryGetTestHostControllerPid(System.Collections.Generic.IReadOnlyList<string!>! arguments) -> string?
static Microsoft.Testing.Extensions.PackagedApp.PackagedAppConnectBackHandshake.Write(string! filePath, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string!, string?>>! entries) -> void
static Microsoft.Testing.Extensions.PackagedApp.PackagedAppConnectBackReader.TryApplyConnectBackEnvironment(System.Collections.Generic.IReadOnlyList<string!>! commandLineArguments) -> void
Expand All @@ -47,6 +48,7 @@ static Microsoft.Testing.Extensions.PackagedApp.PackagedAppConnectBackReader.Try
Microsoft.Testing.Extensions.PackagedApp.PackagedAppTestHostLauncher.PackagedAppTestHostLauncher(string! testApplicationDirectory, System.Func<string!, string?>! getEnvironmentVariable) -> void
const Microsoft.Testing.Extensions.PackagedApp.PackagedAppTestHostLauncher.LauncherModeEnvironmentVariable = "TESTINGPLATFORM_PACKAGEDAPP_LAUNCHER" -> string!
static Microsoft.Testing.Extensions.PackagedApp.PackagedAppTestHostLauncher.CreateActivationArguments(Microsoft.Testing.Extensions.PackagedApp.AppxApplicationInfo! application, System.Collections.Generic.IReadOnlyList<string!>! arguments, string! localStateDirectory) -> Microsoft.Testing.Extensions.PackagedApp.PackagedAppActivationData!
static Microsoft.Testing.Extensions.PackagedApp.PackagedAppTestHostLauncher.GetConnectBackEnvironment(Microsoft.Testing.Platform.Extensions.TestHostControllers.TestHostLaunchContext! context) -> System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string!, string?>>!
Microsoft.Testing.Extensions.PackagedApp.AppContainerSecurityIdentifier
static Microsoft.Testing.Extensions.PackagedApp.AppContainerSecurityIdentifier.TryDerive(string? packageFamilyName) -> string?
Microsoft.Testing.Extensions.PackagedApp.PackagedAppTestHostLauncher.GetAuthorizedSecurityIdentitiesAsync(string! testHostFileName, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<System.Collections.Generic.IReadOnlyList<string!>!>!
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Security.Cryptography;

namespace Microsoft.Testing.Extensions.PackagedApp;

/// <summary>
/// The out-of-band hand-off that lets a packaged (MSIX) test host receive the controller-to-host
/// connect-back environment variables that a plain <c>Process.Start</c> would have inherited.
/// The out-of-band hand-off that lets a packaged (MSIX) test host receive the controller and retry
/// environment variables that a plain <c>Process.Start</c> would have inherited.
/// </summary>
/// <remarks>
/// <para>
Expand All @@ -21,9 +23,9 @@ namespace Microsoft.Testing.Extensions.PackagedApp;
/// <see cref="TestingPlatformBuilderHook"/>.
/// </para>
/// <para>
/// The file is named with the test host controller PID (the value the platform passes on the command
/// line as <c>--internal-testhostcontroller-pid</c>) so that concurrent runs of the same package do
/// not collide, and it is deleted by the host as soon as it has been consumed.
/// The file is named with a stable handshake ID so concurrent runs of the same package do not collide.
/// Controller-host runs use the controller PID; retry runs use a hash of their unique pipe name. The
/// host deletes the file as soon as it has been consumed.
/// </para>
/// </remarks>
internal static class PackagedAppConnectBackHandshake
Expand All @@ -33,6 +35,7 @@ internal static class PackagedAppConnectBackHandshake
// because PlatformCommandLineProvider.TestHostControllerPIDOptionKey is internal to the platform
// assembly; the two ship and version together in this repo.
private const string TestHostControllerPidOptionKey = "internal-testhostcontroller-pid";
private const string RetryPipeNameOptionKey = "internal-retry-pipename";

// Marker prefixes distinguishing a null value from a (possibly empty) string value on each line,
// so an empty string round-trips as an empty string rather than as null.
Expand All @@ -55,32 +58,54 @@ public static string GetHandshakeDirectory(string packageFamilyName)
"LocalState");

/// <summary>
/// Returns the file name (without directory) of the handshake file for a given test host controller
/// PID. The directory differs between the two sides (see <see cref="GetHandshakeFilePath"/> and the
/// activated host, which resolves its own package LocalState), but the file name is shared.
/// Returns the file name (without directory) for a handshake ID. The directory differs between the
/// two sides (see <see cref="GetHandshakeFilePath"/> and the activated host, which resolves its own
/// package LocalState), but the file name is shared.
/// </summary>
public static string GetHandshakeFileName(string testHostControllerPid)
=> $"mtp-testhostcontroller-{testHostControllerPid}.handshake";
public static string GetHandshakeFileName(string handshakeId)
=> $"mtp-testhostcontroller-{handshakeId}.handshake";

/// <summary>
/// Returns the full path of the handshake file for a given package family name and test host
/// controller PID.
/// Returns the full path of the handshake file for a package family name and handshake ID.
/// </summary>
public static string GetHandshakeFilePath(string packageFamilyName, string testHostControllerPid)
public static string GetHandshakeFilePath(string packageFamilyName, string handshakeId)
=> Path.Combine(
GetHandshakeDirectory(packageFamilyName),
GetHandshakeFileName(testHostControllerPid));
GetHandshakeFileName(handshakeId));

/// <summary>
/// Extracts the value of the <c>--internal-testhostcontroller-pid</c> option from a command line,
/// or <see langword="null"/> when it is absent (which means the current process is not an activated
/// test host waiting on a controller connect-back).
/// </summary>
public static string? TryGetTestHostControllerPid(IReadOnlyList<string> arguments)
=> TryGetOptionValue(arguments, TestHostControllerPidOptionKey);

/// <summary>
/// Returns the stable identifier used to exchange environment variables for an activated host.
/// Controller-host runs use the controller PID; retry-orchestrated runs use a hash of their unique pipe name.
Comment thread
Evangelink marked this conversation as resolved.
Resolved
/// </summary>
public static string? TryGetHandshakeId(IReadOnlyList<string> arguments)
{
if (TryGetTestHostControllerPid(arguments) is { } testHostControllerPid)
{
return testHostControllerPid;
}

if (TryGetOptionValue(arguments, RetryPipeNameOptionKey) is not { } retryPipeName)
{
return null;
}

byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes(retryPipeName));
return $"retry-{Convert.ToHexString(hash)}";
}

private static string? TryGetOptionValue(IReadOnlyList<string> arguments, string optionKey)
{
for (int i = 0; i < arguments.Count - 1; i++)
{
if (string.Equals(arguments[i], $"--{TestHostControllerPidOptionKey}", StringComparison.Ordinal))
if (string.Equals(arguments[i], $"--{optionKey}", StringComparison.Ordinal))
{
return arguments[i + 1];
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,10 @@ public static void TryApplyConnectBackEnvironment(
Func<string?> getPackageLocalStateDirectory,
Action<string, string?> setEnvironmentVariable)
{
// Only the spawned test host leg carries the test host controller PID option; the controller
// process does not, so it never consumes a handshake.
string? testHostControllerPid = PackagedAppConnectBackHandshake.TryGetTestHostControllerPid(commandLineArguments);
if (testHostControllerPid is null)
// Controller-host and retry-orchestrated children both carry a unique handshake identifier in
// their command line. The parent process carries neither and never consumes a handshake.
string? handshakeId = PackagedAppConnectBackHandshake.TryGetHandshakeId(commandLineArguments);
Comment thread
Evangelink marked this conversation as resolved.
Resolved
if (handshakeId is null)
{
return;
}
Expand Down Expand Up @@ -95,11 +95,11 @@ public static void TryApplyConnectBackEnvironment(
// package-aware ApplicationData.Current.LocalFolder is the correct, unredirected
// %LOCALAPPDATA%\Packages\{PFN}\LocalState the (unpackaged) launcher wrote to;
// Environment.SpecialFolder.LocalApplicationData is redirected here and would not find the file.
string fileName = PackagedAppConnectBackHandshake.GetHandshakeFileName(testHostControllerPid);
string fileName = PackagedAppConnectBackHandshake.GetHandshakeFileName(handshakeId);
string? localStateDirectory = getPackageLocalStateDirectory();
string handshakePath = localStateDirectory is not null
? Path.Combine(localStateDirectory, fileName)
: PackagedAppConnectBackHandshake.GetHandshakeFilePath(packageFamilyName, testHostControllerPid);
: PackagedAppConnectBackHandshake.GetHandshakeFilePath(packageFamilyName, handshakeId);

IReadOnlyDictionary<string, string?>? environment = PackagedAppConnectBackHandshake.ReadAndDelete(handshakePath);
if (environment is null)
Expand Down
Loading