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 @@ -262,25 +262,7 @@ public override async Task WaitForConnectionAsync(CancellationToken token)

private string GetDefaultAddress()
{
try
{
Process process = Process.GetProcessById(_pid);
}
catch (ArgumentException)
{
throw new ServerNotAvailableException($"Process {_pid} is not running.");
}
catch (InvalidOperationException)
{
throw new ServerNotAvailableException($"Process {_pid} seems to be elevated.");
}

if (!TryGetDefaultAddress(_pid, out string transportName))
{
throw new ServerNotAvailableException($"Process {_pid} not running compatible .NET runtime.");
}

return transportName;
return GetDefaultAddress(_pid);
}

private static bool TryGetDefaultAddress(int pid, out string defaultAddress)
Expand All @@ -290,6 +272,16 @@ private static bool TryGetDefaultAddress(int pid, out string defaultAddress)
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
defaultAddress = $"dotnet-diagnostic-{pid}";

try
{
string dsrouterAddress = Directory.GetFiles(IpcRootPath, $"dotnet-diagnostic-dsrouter-{pid}").FirstOrDefault();
if (!string.IsNullOrEmpty(dsrouterAddress))
{
defaultAddress = dsrouterAddress;
}
}
catch { }
}
else
{
Expand All @@ -298,15 +290,62 @@ private static bool TryGetDefaultAddress(int pid, out string defaultAddress)
defaultAddress = Directory.GetFiles(IpcRootPath, $"dotnet-diagnostic-{pid}-*-socket") // Try best match.
.OrderByDescending(f => new FileInfo(f).LastWriteTime)
.FirstOrDefault();

string dsrouterAddress = Directory.GetFiles(IpcRootPath, $"dotnet-diagnostic-dsrouter-{pid}-*-socket") // Try best match.
.OrderByDescending(f => new FileInfo(f).LastWriteTime)
.FirstOrDefault();

if (!string.IsNullOrEmpty(dsrouterAddress) && !string.IsNullOrEmpty(defaultAddress))
{
FileInfo defaultFile = new(defaultAddress);
FileInfo dsrouterFile = new(dsrouterAddress);

if (dsrouterFile.LastWriteTime >= defaultFile.LastWriteTime)
{
defaultAddress = dsrouterAddress;
}
}
}
catch (InvalidOperationException)
{
}
catch { }
}

return !string.IsNullOrEmpty(defaultAddress);
}

public static string GetDefaultAddress(int pid)
{
try
{
Process process = Process.GetProcessById(pid);
}
catch (ArgumentException)
{
throw new ServerNotAvailableException($"Process {pid} is not running.");
}
catch (InvalidOperationException)
{
throw new ServerNotAvailableException($"Process {pid} seems to be elevated.");
}

if (!TryGetDefaultAddress(pid, out string defaultAddress))
{
throw new ServerNotAvailableException($"Process {pid} not running compatible .NET runtime.");
}

return defaultAddress;
}

public static bool IsDefaultAddressDSRouter(int pid, string address)
{
if (address.StartsWith(IpcRootPath, StringComparison.OrdinalIgnoreCase))
{
address = address.Substring(IpcRootPath.Length);
}

string dsrouterAddress = $"dotnet-diagnostic-dsrouter-{pid}";
return address.StartsWith(dsrouterAddress, StringComparison.OrdinalIgnoreCase);
}

public override bool Equals(object obj)
{
return Equals(obj as PidIpcEndpoint);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,8 @@ private static async Task<int> runRouter(CancellationToken token, DiagnosticsSer
routerFactory.Logger?.LogInformation("Starting automatic shutdown.");
throw;
}

routerFactory.Logger?.LogTrace($"runRouter continues after exception: {ex.Message}");
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks Condition="'$(DotNetBuildFromSource)' != 'true'">netstandard2.0;net6.0</TargetFrameworks>
Expand Down Expand Up @@ -31,6 +31,7 @@
</ItemGroup>

<ItemGroup>
<InternalsVisibleTo Include="dotnet-gcdump" />
<InternalsVisibleTo Include="dotnet-counters" />
<InternalsVisibleTo Include="dotnet-dsrouter" />
<InternalsVisibleTo Include="dotnet-monitor" />
Expand Down
19 changes: 9 additions & 10 deletions src/Tools/Common/Commands/Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;
using System.Diagnostics;

using System.Collections.Generic;
using Microsoft.Diagnostics.NETCore.Client;

namespace Microsoft.Internal.Common.Utils
Expand Down Expand Up @@ -72,7 +71,7 @@ public static bool ValidateArgumentsForChildProcess(int processId, string name,
public static bool ValidateArgumentsForAttach(int processId, string name, string port, out int resolvedProcessId)
{
resolvedProcessId = -1;
if (processId == 0 && name == null && string.IsNullOrEmpty(port))
if (processId == 0 && string.IsNullOrEmpty(name) && string.IsNullOrEmpty(port))
{
Console.WriteLine("Must specify either --process-id, --name, or --diagnostic-port.");
return false;
Expand All @@ -82,24 +81,24 @@ public static bool ValidateArgumentsForAttach(int processId, string name, string
Console.WriteLine($"{processId} is not a valid process ID");
return false;
}
else if (processId != 0 && name != null && !string.IsNullOrEmpty(port))
else if (processId != 0 && !string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(port))
{
Console.WriteLine("Only one of the --name, --process-id, or --diagnostic-port options may be specified.");
return false;
}
else if (processId != 0 && name != null)
else if (processId != 0 && !string.IsNullOrEmpty(name))
{
Console.WriteLine("Can only one of specify --name or --process-id.");
Console.WriteLine("Only one of the --name or --process-id options may be specified.");
return false;
}
else if (processId != 0 && !string.IsNullOrEmpty(port))
{
Console.WriteLine("Can only one of specify --process-id or --diagnostic-port.");
Console.WriteLine("Only one of the --process-id or --diagnostic-port options may be specified.");
return false;
}
else if (name != null && !string.IsNullOrEmpty(port))
else if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(port))
{
Console.WriteLine("Can only one of specify --name or --diagnostic-port.");
Console.WriteLine("Only one of the --name or --diagnostic-port options may be specified.");
return false;
}
// If we got this far it means only one of --name/--diagnostic-port/--process-id was specified
Expand All @@ -108,7 +107,7 @@ public static bool ValidateArgumentsForAttach(int processId, string name, string
return true;
}
// Resolve name option
else if (name != null)
else if (!string.IsNullOrEmpty(name))
{
processId = CommandUtils.FindProcessIdWithName(name);
if (processId < 0)
Expand Down
1 change: 0 additions & 1 deletion src/Tools/dotnet-counters/CounterMonitor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -593,7 +593,6 @@ public async Task<int> Collect(
{
return (int)ReturnCode.ArgumentError;
}

ct.Register(() => _shouldExit.TrySetResult((int)ReturnCode.Ok));

DiagnosticsClientBuilder builder = new("dotnet-counters", 10);
Expand Down
2 changes: 1 addition & 1 deletion src/Tools/dotnet-counters/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ private static Option RuntimeVersionOption() =>

private static Option DiagnosticPortOption() =>
new(
alias: "--diagnostic-port",
aliases: new[] { "--dport", "--diagnostic-port" },
description: "The path to diagnostic port to be used.")
{
Argument = new Argument<string>(name: "diagnosticPort", getDefaultValue: () => "")
Expand Down
45 changes: 23 additions & 22 deletions src/Tools/dotnet-dsrouter/DiagnosticsServerRouterCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,8 @@ public async Task<int> CommonRunLoop(Func<ILogger, DiagnosticsServerRouterRunner

ILogger logger = loggerFactory.CreateLogger("dotnet-dsrouter");

logger.LogInformation($"Starting dotnet-dsrouter using pid={Process.GetCurrentProcess().Id}");

Task<int> routerTask = createRouterTask(logger, Launcher, linkedCancelToken);

while (!linkedCancelToken.IsCancellationRequested)
Expand All @@ -127,7 +129,19 @@ await Task.WhenAny(routerTask, Task.Delay(
}
}
}
return routerTask.Result;

if (!routerTask.IsCompleted)
{
cancelRouterTask.Cancel();
}

await Task.WhenAny(routerTask, Task.Delay(1000, CancellationToken.None)).ConfigureAwait(false);
if (routerTask.IsCompleted)
{
return routerTask.Result;
}

return 0;
}
}

Expand Down Expand Up @@ -335,19 +349,12 @@ public async Task<int> RunIpcClientWebSocketServerRouter(CancellationToken token

private static string GetDefaultIpcServerPath(ILogger logger)
{
string path = string.Empty;
int processId = Process.GetCurrentProcess().Id;

if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
string path = Path.Combine(PidIpcEndpoint.IpcRootPath, $"dotnet-diagnostic-{processId}");
if (File.Exists(path))
{
logger?.LogWarning($"Default IPC server path, {path}, already in use. To disable default diagnostics for dotnet-dsrouter, set DOTNET_EnableDiagnostics=0 and re-run.");

path = Path.Combine(PidIpcEndpoint.IpcRootPath, $"dotnet-dsrouter-{processId}");
logger?.LogWarning($"Fallback using none default IPC server path, {path}.");
}

return path.Substring(PidIpcEndpoint.IpcRootPath.Length);
path = $"dotnet-diagnostic-dsrouter-{processId}";
}
else
{
Expand All @@ -358,19 +365,13 @@ private static string GetDefaultIpcServerPath(ILogger logger)
unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
#endif
TimeSpan diff = Process.GetCurrentProcess().StartTime.ToUniversalTime() - unixEpoch;

string path = Path.Combine(PidIpcEndpoint.IpcRootPath, $"dotnet-diagnostic-{processId}-{(long)diff.TotalSeconds}-socket");
if (Directory.GetFiles(PidIpcEndpoint.IpcRootPath, $"dotnet-diagnostic-{processId}-*-socket").Length != 0)
{
logger?.LogWarning($"Default IPC server path, {Path.Combine(PidIpcEndpoint.IpcRootPath, $"dotnet-diagnostic-{processId}-*-socket")}, already in use. To disable default diagnostics for dotnet-dsrouter, set DOTNET_EnableDiagnostics=0 and re-run.");

path = Path.Combine(PidIpcEndpoint.IpcRootPath, $"dotnet-dsrouter-{processId}-{(long)diff.TotalSeconds}-socket");
logger?.LogWarning($"Fallback using none default IPC server path, {path}.");
}

return path;
path = Path.Combine(PidIpcEndpoint.IpcRootPath, $"dotnet-diagnostic-dsrouter-{processId}-{(long)diff.TotalSeconds}-socket");
}

logger?.LogDebug($"Using default IPC server path, {path}.");
logger?.LogDebug($"Attach to default dotnet-dsrouter IPC server using --process-id {processId} diagnostic tooling argument.");

return path;
}

private static TcpClientRouterFactory.CreateInstanceDelegate ChooseTcpClientRouterFactory(string forwardPort, ILogger logger)
Expand Down
2 changes: 2 additions & 0 deletions src/Tools/dotnet-dsrouter/USBMuxTcpClientRouterFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,7 @@ private int ConnectTcpClientOverUSBMux()
{
if (_deviceConnectionID == 0)
{
_logger.LogError($"Failed to connect device over USB, no device currently connected.");
throw new Exception($"Failed to connect device over USB, no device currently connected.");
}

Expand All @@ -370,6 +371,7 @@ private int ConnectTcpClientOverUSBMux()

if (result != 0)
{
_logger?.LogError($"Failed USBMuxConnectByPort: device = {_deviceConnectionID}, port = {_port}, result = {result}.");
throw new Exception($"Failed to connect device over USB using connection {_deviceConnectionID} and port {_port}.");
}

Expand Down
Loading