forked from kenjiuno/Npgsql
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathMultiHostConnectorPool.cs
More file actions
353 lines (310 loc) · 15.6 KB
/
MultiHostConnectorPool.cs
File metadata and controls
353 lines (310 loc) · 15.6 KB
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
using Npgsql.Util;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
namespace Npgsql
{
sealed class MultiHostConnectorPool : ConnectorSource
{
readonly ConnectorPool[] _pools;
volatile int _roundRobinIndex = -1;
public MultiHostConnectorPool(NpgsqlConnectionStringBuilder settings, string connString) : base(settings, connString)
{
var hosts = settings.Host!.Split(',');
_pools = new ConnectorPool[hosts.Length];
for (var i = 0; i < hosts.Length; i++)
{
var host = hosts[i].Trim();
var port = settings.Port;
var portSeparator = host.IndexOf(':');
if (portSeparator != -1)
{
port = int.Parse(host.Substring(portSeparator + 1));
host = host.Substring(0, portSeparator);
}
var poolSettings = settings.Clone();
poolSettings.Host = host;
poolSettings.Port = port;
_pools[i] = new ConnectorPool(poolSettings, poolSettings.ConnectionString, this);
}
}
static bool IsPreferred(ClusterState state, TargetSessionAttributes preferredType)
=> state switch
{
ClusterState.Offline => false,
ClusterState.Unknown => true, // We will check compatibility again after refreshing the cluster state
ClusterState.PrimaryReadWrite when preferredType == TargetSessionAttributes.Primary || preferredType == TargetSessionAttributes.PreferPrimary
|| preferredType == TargetSessionAttributes.ReadWrite => true,
ClusterState.PrimaryReadOnly when preferredType == TargetSessionAttributes.Primary || preferredType == TargetSessionAttributes.PreferPrimary
|| preferredType == TargetSessionAttributes.ReadOnly => true,
ClusterState.Standby when preferredType == TargetSessionAttributes.Standby || preferredType == TargetSessionAttributes.PreferStandby
|| preferredType == TargetSessionAttributes.ReadOnly => true,
_ => preferredType == TargetSessionAttributes.Any
};
static bool IsFallbackOrPreferred(ClusterState state, TargetSessionAttributes preferredType)
=> state switch
{
ClusterState.Unknown => true, // We will check compatibility again after refreshing the cluster state
ClusterState.PrimaryReadWrite when preferredType == TargetSessionAttributes.PreferPrimary || preferredType == TargetSessionAttributes.PreferStandby => true,
ClusterState.PrimaryReadOnly when preferredType == TargetSessionAttributes.PreferPrimary || preferredType == TargetSessionAttributes.PreferStandby => true,
ClusterState.Standby when preferredType == TargetSessionAttributes.PreferPrimary || preferredType == TargetSessionAttributes.PreferStandby => true,
_ => false
};
static ClusterState GetClusterState(ConnectorPool pool, bool ignoreExpiration = false)
=> GetClusterState(pool.Settings.Host!, pool.Settings.Port, ignoreExpiration);
static ClusterState GetClusterState(string host, int port, bool ignoreExpiration)
=> ClusterStateCache.GetClusterState(host, port, ignoreExpiration);
async ValueTask<NpgsqlConnector?> TryGetIdle(NpgsqlConnection conn, TimeSpan timeoutPerHost, bool async, TargetSessionAttributes preferredType,
Func<ClusterState, TargetSessionAttributes, bool> clusterValidator, int poolIndex,
IList<Exception> exceptions, CancellationToken cancellationToken)
{
var pools = _pools;
for (var i = 0; i < pools.Length; i++)
{
var pool = pools[poolIndex];
poolIndex++;
if (poolIndex == pools.Length)
poolIndex = 0;
var clusterState = GetClusterState(pool);
if (!clusterValidator(clusterState, preferredType))
continue;
if (pool.TryGetIdleConnector(out var connector))
{
conn.Connector = connector;
connector.Connection = conn;
try
{
if (clusterState == ClusterState.Unknown)
{
clusterState = await connector.QueryClusterState(new NpgsqlTimeout(timeoutPerHost), async, cancellationToken);
Debug.Assert(clusterState != ClusterState.Unknown);
if (!clusterValidator(clusterState, preferredType))
{
conn.Connector = null;
connector.Connection = null;
pool.Return(connector);
continue;
}
}
return connector;
}
catch (Exception ex)
{
conn.FullState = ConnectionState.Connecting;
conn.Connector = null;
connector.Connection = null;
pool.Return(connector);
exceptions.Add(new NpgsqlException($"Unable to get an idle connection to {pool.Settings.Host}:{pool.Settings.Port}", ex));
}
}
}
return null;
}
async ValueTask<NpgsqlConnector?> TryOpenNew(NpgsqlConnection conn, TimeSpan timeoutPerHost, bool async, TargetSessionAttributes preferredType,
Func<ClusterState, TargetSessionAttributes, bool> clusterValidator, int poolIndex,
IList<Exception> exceptions, CancellationToken cancellationToken)
{
var pools = _pools;
for (var i = 0; i < pools.Length; i++)
{
var pool = pools[poolIndex];
poolIndex++;
if (poolIndex == pools.Length)
poolIndex = 0;
var clusterState = GetClusterState(pool);
if (!clusterValidator(clusterState, preferredType))
continue;
try
{
var connector = await pool.OpenNewConnector(conn, new NpgsqlTimeout(timeoutPerHost), async, cancellationToken);
if (connector is not null)
{
if (clusterState == ClusterState.Unknown)
{
// Opening a new physical connection refreshed the cluster state, check again
// Note that we purposefully ignore the expiration, as in case of the HostRecheckSeconds = 0
// it will always be expired
clusterState = GetClusterState(pool, ignoreExpiration: true);
Debug.Assert(clusterState != ClusterState.Unknown);
if (!clusterValidator(clusterState, preferredType))
{
conn.Connector = null;
connector.Connection = null;
pool.Return(connector);
continue;
}
}
conn.Connector = connector;
connector.Connection = conn;
return connector;
}
}
catch (Exception ex)
{
conn.FullState = ConnectionState.Connecting;
exceptions.Add(ex);
}
}
return null;
}
async ValueTask<NpgsqlConnector?> TryGet(NpgsqlConnection conn, TimeSpan timeoutPerHost, bool async, TargetSessionAttributes preferredType,
Func<ClusterState, TargetSessionAttributes, bool> clusterValidator, int poolIndex,
IList<Exception> exceptions, CancellationToken cancellationToken)
{
var pools = _pools;
for (var i = 0; i < pools.Length; i++)
{
var pool = pools[poolIndex];
poolIndex++;
if (poolIndex == pools.Length)
poolIndex = 0;
var clusterState = GetClusterState(pool);
if (!clusterValidator(clusterState, preferredType))
continue;
NpgsqlConnector? connector = null;
try
{
connector = await pool.Get(conn, new NpgsqlTimeout(timeoutPerHost), async, cancellationToken);
if (clusterState == ClusterState.Unknown)
{
// Get might have opened a new physical connection and refreshed the cluster state, check again
clusterState = GetClusterState(pool);
if (clusterState == ClusterState.Unknown)
clusterState = await connector.QueryClusterState(new NpgsqlTimeout(timeoutPerHost), async, cancellationToken);
Debug.Assert(clusterState != ClusterState.Unknown);
if (!clusterValidator(clusterState, preferredType))
{
conn.Connector = null;
connector.Connection = null;
pool.Return(connector);
continue;
}
}
conn.Connector = connector;
connector.Connection = conn;
return connector;
}
catch (Exception ex)
{
if (connector is not null)
{
conn.Connector = null;
connector.Connection = null;
pool.Return(connector);
}
conn.FullState = ConnectionState.Connecting;
exceptions.Add(new NpgsqlException($"Unable to connect to {pool.Settings.Host}:{pool.Settings.Port}", ex));
}
}
return null;
}
internal override async ValueTask<NpgsqlConnector> Get(NpgsqlConnection conn, NpgsqlTimeout timeout, bool async, CancellationToken cancellationToken)
{
var exceptions = new List<Exception>();
var poolIndex = conn.Settings.LoadBalanceHosts ? GetRoundRobinIndex() : 0;
var timeoutPerHost = timeout.IsSet ? timeout.CheckAndGetTimeLeft() : TimeSpan.Zero;
var preferredType = conn.Settings.TargetSessionAttributesParsed;
var checkUnpreferred =
preferredType == TargetSessionAttributes.PreferPrimary ||
preferredType == TargetSessionAttributes.PreferStandby;
var connector = await TryGetIdle(conn, timeoutPerHost, async, preferredType, IsPreferred, poolIndex, exceptions, cancellationToken) ??
await TryOpenNew(conn, timeoutPerHost, async, preferredType, IsPreferred, poolIndex, exceptions, cancellationToken) ??
(checkUnpreferred ?
await TryGetIdle(conn, timeoutPerHost, async, preferredType, IsFallbackOrPreferred, poolIndex, exceptions, cancellationToken) ??
await TryOpenNew(conn, timeoutPerHost, async, preferredType, IsFallbackOrPreferred, poolIndex, exceptions, cancellationToken)
: null) ??
await TryGet(conn, timeoutPerHost, async, preferredType, IsPreferred, poolIndex, exceptions, cancellationToken) ??
(checkUnpreferred ?
await TryGet(conn, timeoutPerHost, async, preferredType, IsFallbackOrPreferred, poolIndex, exceptions, cancellationToken)
: null);
if (connector is not null)
return connector;
conn.FullState = ConnectionState.Broken;
throw NoSuitableHostsException(exceptions);
}
static NpgsqlException NoSuitableHostsException(IList<Exception> exceptions)
=> exceptions.Count == 0
? new NpgsqlException("No suitable host was found.")
: new("Unable to connect to a suitable host. Check inner exception for more details.",
new AggregateException(exceptions));
int GetRoundRobinIndex()
{
int index;
while (true)
{
index = Interlocked.Increment(ref _roundRobinIndex);
if (index >= 0)
return index % _pools.Length;
// Worst case scenario - we've wrapped around integer counter
if (index == int.MinValue)
{
// This is the thread which wrapped around the counter - reset it to 0
_roundRobinIndex = 0;
return 0;
}
else
{
// This is not the thread which wrapped around the counter - just wait until it's 0 or more
var sw = new SpinWait();
while (_roundRobinIndex < 0)
sw.SpinOnce();
continue;
}
}
}
internal override void Return(NpgsqlConnector connector)
=> throw new NpgsqlException("Npgsql bug: a connector was returned to " + nameof(MultiHostConnectorPool));
internal override void Clear()
{
foreach (var pool in _pools)
pool.Clear();
}
internal override (int Total, int Idle, int Busy) Statistics
{
get
{
var numConnectors = 0;
var idleCount = 0;
foreach (var pool in _pools)
{
numConnectors += pool.NumConnectors;
idleCount += pool.IdleCount;
}
return (numConnectors, idleCount, numConnectors - idleCount);
}
}
internal override bool TryRentEnlistedPending(Transaction transaction, NpgsqlConnection connection,
[NotNullWhen(true)] out NpgsqlConnector? connector)
{
lock (_pendingEnlistedConnectors)
{
if (!_pendingEnlistedConnectors.TryGetValue(transaction, out var list))
{
connector = null;
return false;
}
for (var i = list.Count - 1; i >= 0; i--)
{
connector = list[i];
var lastKnownState = GetClusterState(connector.Host, connector.Port, ignoreExpiration: true);
Debug.Assert(lastKnownState != ClusterState.Unknown);
var preferredType = connection.Settings.TargetSessionAttributesParsed;
if (IsFallbackOrPreferred(lastKnownState, preferredType))
{
list.RemoveAt(i);
if (list.Count == 0)
_pendingEnlistedConnectors.Remove(transaction);
return true;
}
}
connector = null;
return false;
}
}
}
}