-
Notifications
You must be signed in to change notification settings - Fork 2k
/
TestClusterPortAllocator.cs
251 lines (218 loc) · 8.15 KB
/
TestClusterPortAllocator.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Threading;
using Orleans.TestingHost.Utils;
namespace Orleans.TestingHost
{
public class TestClusterPortAllocator : ITestClusterPortAllocator
{
private bool disposed;
private readonly object lockObj = new object();
private readonly Dictionary<int, string> allocatedPorts = new Dictionary<int, string>();
public (int, int) AllocateConsecutivePortPairs(int numPorts = 5)
{
// Evaluate current system tcp connections
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpListeners();
// each returned port in the pair will have to have at least this amount of available ports following it
return (GetAvailableConsecutiveServerPorts(tcpConnInfoArray, 22300, 30000, numPorts),
GetAvailableConsecutiveServerPorts(tcpConnInfoArray, 40000, 50000, numPorts));
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
{
return;
}
lock (lockObj)
{
if (disposed)
{
return;
}
foreach (var pair in allocatedPorts)
{
MutexManager.Instance.SignalRelease(pair.Value);
}
allocatedPorts.Clear();
disposed = true;
}
}
~TestClusterPortAllocator()
{
Dispose(false);
}
private int GetAvailableConsecutiveServerPorts(IPEndPoint[] tcpConnInfoArray, int portStartRange, int portEndRange, int consecutivePortsToCheck)
{
const int MaxAttempts = 100;
var allocations = new List<(int Port, string Mutex)>();
for (int attempts = 0; attempts < MaxAttempts; attempts++)
{
int basePort = ThreadSafeRandom.Next(portStartRange, portEndRange);
// get ports in buckets, so we don't interfere with parallel runs of this same function
basePort = basePort - (basePort % consecutivePortsToCheck);
int endPort = basePort + consecutivePortsToCheck;
// make sure none of the ports in the sub range are in use
if (tcpConnInfoArray.All(endpoint => endpoint.Port < basePort || endpoint.Port >= endPort))
{
for (var i = 0; i < consecutivePortsToCheck; i++)
{
var port = basePort + i;
var name = $"Global.TestCluster.{port.ToString(CultureInfo.InvariantCulture)}";
if (MutexManager.Instance.Acquire(name))
{
allocations.Add((port, name));
}
else
{
foreach (var allocation in allocations)
{
MutexManager.Instance.SignalRelease(allocation.Mutex);
}
allocations.Clear();
break;
}
}
if (allocations.Count == 0)
{
// Try a different range.
continue;
}
lock (lockObj)
{
foreach (var allocation in allocations)
{
allocatedPorts[allocation.Port] = allocation.Mutex;
}
}
return basePort;
}
}
throw new InvalidOperationException("Cannot find enough free ports to spin up a cluster");
}
private class MutexManager
{
private readonly Dictionary<string, Mutex> _mutexes = new Dictionary<string, Mutex>();
private readonly BlockingCollection<Action> _workItems = new BlockingCollection<Action>();
private readonly Thread _thread;
public static MutexManager Instance { get; } = new MutexManager();
private MutexManager()
{
_thread = new Thread(Run)
{
Name = "MutexManager.Worker",
IsBackground = true,
};
_thread.Start();
AppDomain.CurrentDomain.DomainUnload += this.OnAppDomainUnload;
}
private void OnAppDomainUnload(object sender, EventArgs e)
{
Shutdown();
}
private void Shutdown()
{
_workItems.CompleteAdding();
_thread.Join();
}
public bool Acquire(string name)
{
var result = new [] { 0 };
var signal = new ManualResetEventSlim(initialState: false);
_workItems.Add(() =>
{
try
{
if (!_mutexes.TryGetValue(name, out var mutex))
{
mutex = new Mutex(false, name);
if (mutex.WaitOne(500))
{
// Acquired
_mutexes[name] = mutex;
Interlocked.Increment(ref result[0]);
return;
}
// Failed to acquire: the mutex is already held by another process.
try
{
mutex.ReleaseMutex();
}
finally
{
mutex.Close();
}
}
// Failed to acquire: the mutex is already held by this process.
}
finally
{
signal.Set();
}
});
if (!signal.Wait(TimeSpan.FromSeconds(10)))
{
throw new TimeoutException("Timed out while waiting for MutexManager to acquire mutex.");
}
return result[0] == 1;
}
public void SignalRelease(string name)
{
_workItems.Add(() =>
{
if (_mutexes.TryGetValue(name, out var value))
{
_mutexes.Remove(name);
value.ReleaseMutex();
value.Close();
}
});
}
private void Run()
{
try
{
foreach (var action in _workItems.GetConsumingEnumerable())
{
try
{
action();
}
catch
{
}
}
}
catch
{
}
finally
{
foreach (var mutex in _mutexes.Values)
{
try
{
mutex.ReleaseMutex();
}
catch { }
finally
{
mutex.Close();
}
}
_mutexes.Clear();
}
}
}
}
}