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
77 changes: 77 additions & 0 deletions DevProxy.Tests/SystemProxyManagerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.

using System.Text.Json;
using DevProxy.Commands;
using DevProxy.Proxy;
using DevProxy.State;
using Microsoft.Extensions.Logging.Abstractions;
Expand Down Expand Up @@ -451,6 +452,82 @@ await StateManager.SaveStateAsync(new()
folder.Delete(recursive: true);
}
}

[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task FindLiveSystemProxyOwner_IgnoresGivenProcess(bool withSnapshot)
{
var folder = Directory.CreateTempSubdirectory("devproxy-owner-");
var statePath = StateManager.GetInstanceStateFilePath(Environment.ProcessId);
Assert.False(File.Exists(statePath));
try
{
// This process owns the system proxy, like an instance restarting for a hot reload.
var snapshotPath = Path.Combine(folder.FullName, "snapshot.json");
if (withSnapshot)
{
SystemProxySnapshotStore.Save(snapshotPath, new()
{
Pid = Environment.ProcessId,
ProcessStartTime = StateManager.GetCurrentProcessStartTime(),
});
}
else
{
await StateManager.SaveStateAsync(new()
{
Pid = Environment.ProcessId,
ProcessStartTime = StateManager.GetCurrentProcessStartTime(),
AsSystemProxy = true,
});
}

Assert.Null(await SystemProxyManager.FindLiveSystemProxyOwnerAsync(snapshotPath, Environment.ProcessId));
Assert.Equal(Environment.ProcessId, await SystemProxyManager.FindLiveSystemProxyOwnerAsync(snapshotPath, Environment.ProcessId + 1));
}
finally
{
File.Delete(statePath);
folder.Delete(recursive: true);
}
}

// The test process plays the live owner recorded in the snapshot. The snapshot is
// authoritative, so the shared instance records aren't read.
[Theory]
[InlineData("other live owner", true)]
[InlineData("hot reload of the owner", false)]
[InlineData("not as system proxy", false)]
[InlineData("platform without a system proxy", false)]
[InlineData("crashed owner", false)]
public async Task FindBlockingSystemProxyOwner_BlocksOnlyForAnotherLiveOwner(string scenario, bool blocks)
{
var folder = Directory.CreateTempSubdirectory("devproxy-owner-");
try
{
var snapshotPath = Path.Combine(folder.FullName, "snapshot.json");
var ownerPid = scenario == "crashed owner" ? int.MaxValue : Environment.ProcessId;
SystemProxySnapshotStore.Save(snapshotPath, new()
{
Pid = ownerPid,
ProcessStartTime = scenario == "crashed owner" ? DateTimeOffset.UnixEpoch : StateManager.GetCurrentProcessStartTime(),
});

var owner = await DevProxyCommand.FindBlockingSystemProxyOwnerAsync(
asSystemProxy: scenario != "not as system proxy",
platformRegistersSystemProxy: scenario != "platform without a system proxy",
snapshotPath,
currentPid: scenario == "hot reload of the owner" ? Environment.ProcessId : Environment.ProcessId + 1,
CancellationToken.None);

Assert.Equal(blocks ? ownerPid : (int?)null, owner);
}
finally
{
folder.Delete(recursive: true);
}
}
}

[Collection("management-environment")]
Expand Down
31 changes: 31 additions & 0 deletions DevProxy/Commands/DevProxyCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -601,6 +601,20 @@ private async Task<int> InvokeAsync(ParseResult parseResult, CancellationToken c

ConfigureFromOptions(parseResult);

// Only one instance can be the system proxy. This also runs on every hot reload,
// so a reload doesn't take the system proxy over from an instance that registered
// while this one was restarting.
if (await FindBlockingSystemProxyOwnerAsync(
_proxyConfiguration.AsSystemProxy,
OperatingSystem.IsWindows() || OperatingSystem.IsMacOS(),
SystemProxySnapshotStore.DefaultPath,
Environment.ProcessId,
cancellationToken) is int systemProxyOwnerPid)
{
_logger.LogError("{SystemProxyOwned}", SystemProxyManager.FormatAlreadyOwnedError(systemProxyOwnerPid));
return 1;
}

var portConflict =
await PortConflict.CheckAsync(PortKind.Proxy, _proxyConfiguration.IPAddress, _proxyConfiguration.Port, cancellationToken) ??
await PortConflict.CheckAsync(PortKind.Api, _proxyConfiguration.ApiIpAddress, _proxyConfiguration.ApiPort, cancellationToken);
Expand Down Expand Up @@ -1014,6 +1028,23 @@ private static List<Option> CreateRootOptions(IProxyConfiguration proxyConfigura
};
}

/// <summary>
/// Finds the PID of another live process that owns the system proxy and so prevents
/// this one from registering as the system proxy. Ignores <paramref name="currentPid"/>
/// so a hot reload can register again. Returns null when nothing blocks startup:
/// this instance doesn't register as the system proxy, the platform has no system
/// proxy to register (Linux), or the owner is dead and left to orphan recovery.
/// </summary>
internal static Task<int?> FindBlockingSystemProxyOwnerAsync(
bool asSystemProxy,
bool platformRegistersSystemProxy,
string snapshotPath,
int currentPid,
CancellationToken cancellationToken) =>
asSystemProxy && platformRegistersSystemProxy
? SystemProxyManager.FindLiveSystemProxyOwnerAsync(snapshotPath, currentPid, cancellationToken)
: Task.FromResult<int?>(null);

// Shared by every startup recovery message so a detached parent can find them in the daemon's log.
internal const string CrashedInstanceRecoveryMarker = "left by a crashed Dev Proxy instance";

Expand Down
8 changes: 4 additions & 4 deletions DevProxy/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,17 +61,17 @@ static async Task<int> StartDetachedProcessAsync(string[] args)
// (plugin) management command. Don't prune state here, because the daemon needs it.

// Check if an instance is already running as system proxy
var systemProxyInstance = await StateManager.FindSystemProxyInstanceAsync();
if (systemProxyInstance is not null)
var systemProxyOwnerPid = await SystemProxyManager.FindLiveSystemProxyOwnerAsync();
if (systemProxyOwnerPid is int ownerPid)
{
if (isJsonOutput)
{
await Console.Error.WriteLineAsync(
FormatJsonLogEntry("error", $"Dev Proxy is already running as system proxy (PID: {systemProxyInstance.Pid}). Use 'devproxy stop' to stop it first."));
FormatJsonLogEntry("error", SystemProxyManager.FormatAlreadyOwnedError(ownerPid)));
}
else
{
await Console.Error.WriteLineAsync($"Dev Proxy is already running as system proxy (PID: {systemProxyInstance.Pid}).");
await Console.Error.WriteLineAsync($"Dev Proxy is already running as system proxy (PID: {ownerPid}).");
await Console.Error.WriteLineAsync("Use 'devproxy stop' to stop it first.");
}
return 1;
Expand Down
16 changes: 10 additions & 6 deletions DevProxy/Proxy/SystemProxyManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -581,25 +581,29 @@ internal readonly record struct OrphanReconciliation(
/// <summary>
/// Finds the PID of a live process that owns the system proxy. The (foreground or
/// detached) instance recorded in the snapshot file is authoritative, because the
/// latest instance to take over the system proxy rewrites it. Without a snapshot,
/// falls back to a running detached instance registered as the system proxy.
/// instance that registers as the system proxy rewrites it. Without a snapshot,
/// falls back to a running instance registered as the system proxy.
/// Returns null when no live process owns it.
/// </summary>
internal static Task<int?> FindLiveSystemProxyOwnerAsync(CancellationToken cancellationToken = default) =>
FindLiveSystemProxyOwnerAsync(SystemProxySnapshotStore.DefaultPath, cancellationToken);
FindLiveSystemProxyOwnerAsync(SystemProxySnapshotStore.DefaultPath, cancellationToken: cancellationToken);

internal static async Task<int?> FindLiveSystemProxyOwnerAsync(string snapshotPath, CancellationToken cancellationToken = default)
internal static async Task<int?> FindLiveSystemProxyOwnerAsync(string snapshotPath, int? ignoredPid = null, CancellationToken cancellationToken = default)
{
var snapshot = SystemProxySnapshotStore.Load(snapshotPath);
if (snapshot is not null)
{
return snapshot.IsOwnerAlive() ? snapshot.Pid : null;
return snapshot.IsOwnerAlive() && snapshot.Pid != ignoredPid ? snapshot.Pid : null;
}

var liveInstance = await StateManager.FindSystemProxyInstanceAsync(cancellationToken);
var liveInstance = (await StateManager.LoadRunningStatesAsync(cancellationToken))
.Find(s => s.AsSystemProxy && s.Pid != ignoredPid && StateManager.IsInstanceAlive(s));
return liveInstance?.Pid;
}

internal static string FormatAlreadyOwnedError(int ownerPid) =>
$"Dev Proxy is already running as system proxy (PID: {ownerPid}). Use 'devproxy stop' to stop it first.";

/// <summary>
/// Reconciles system-proxy registrations left behind by crashed or killed instances.
/// Restores the OS proxy (unless a live instance still owns it) and removes
Expand Down
Loading