forked from mongodb/mongo-csharp-driver
/
Cluster.cs
600 lines (520 loc) · 22.5 KB
/
Cluster.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
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
/* Copyright 2013-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using MongoDB.Driver.Core.Bindings;
using MongoDB.Driver.Core.Clusters.ServerSelectors;
using MongoDB.Driver.Core.Configuration;
using MongoDB.Driver.Core.Events;
using MongoDB.Driver.Core.Misc;
using MongoDB.Driver.Core.Servers;
using MongoDB.Libmongocrypt;
namespace MongoDB.Driver.Core.Clusters
{
/// <summary>
/// Represents a cluster.
/// </summary>
internal abstract class Cluster : ICluster
{
#region static
// static fields
private static readonly TimeSpan __minHeartbeatInterval = TimeSpan.FromMilliseconds(500);
private static readonly SemanticVersion __minSupportedServerVersion = new SemanticVersion(2, 6, 0);
private static readonly IServerSelector __randomServerSelector = new RandomServerSelector();
private static readonly Range<int> __supportedWireVersionRange = new Range<int>(2, 8);
// static properties
/// <summary>
/// Gets the minimum supported server version.
/// </summary>
/// <value>
/// The minimum supported server version
/// </value>
public static SemanticVersion MinSupportedServerVersion => __minSupportedServerVersion;
/// <summary>
/// Gets the supported wire version range.
/// </summary>
/// <value>
/// The supported wire version range.
/// </value>
public static Range<int> SupportedWireVersionRange => __supportedWireVersionRange;
#endregion
// fields
private readonly IClusterClock _clusterClock = new ClusterClock();
private readonly ClusterId _clusterId;
private CryptClient _cryptClient = null;
private ClusterDescription _description;
private TaskCompletionSource<bool> _descriptionChangedTaskCompletionSource;
private readonly object _descriptionLock = new object();
private Timer _rapidHeartbeatTimer;
private readonly object _serverSelectionWaitQueueLock = new object();
private int _serverSelectionWaitQueueSize;
private readonly IClusterableServerFactory _serverFactory;
private readonly ICoreServerSessionPool _serverSessionPool;
private readonly ClusterSettings _settings;
private readonly InterlockedInt32 _state;
private readonly Action<ClusterDescriptionChangedEvent> _descriptionChangedEventHandler;
private readonly Action<ClusterSelectingServerEvent> _selectingServerEventHandler;
private readonly Action<ClusterSelectedServerEvent> _selectedServerEventHandler;
private readonly Action<ClusterSelectingServerFailedEvent> _selectingServerFailedEventHandler;
// constructors
protected Cluster(ClusterSettings settings, IClusterableServerFactory serverFactory, IEventSubscriber eventSubscriber)
{
_settings = Ensure.IsNotNull(settings, nameof(settings));
_serverFactory = Ensure.IsNotNull(serverFactory, nameof(serverFactory));
Ensure.IsNotNull(eventSubscriber, nameof(eventSubscriber));
_state = new InterlockedInt32(State.Initial);
_clusterId = new ClusterId();
_description = ClusterDescription.CreateInitial(_clusterId, _settings.ConnectionMode);
_descriptionChangedTaskCompletionSource = new TaskCompletionSource<bool>();
_rapidHeartbeatTimer = new Timer(RapidHeartbeatTimerCallback, null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
eventSubscriber.TryGetEventHandler(out _descriptionChangedEventHandler);
eventSubscriber.TryGetEventHandler(out _selectingServerEventHandler);
eventSubscriber.TryGetEventHandler(out _selectedServerEventHandler);
eventSubscriber.TryGetEventHandler(out _selectingServerFailedEventHandler);
_serverSessionPool = new CoreServerSessionPool(this);
}
// events
public event EventHandler<ClusterDescriptionChangedEventArgs> DescriptionChanged;
// properties
public ClusterId ClusterId
{
get { return _clusterId; }
}
public CryptClient CryptClient
{
get { return _cryptClient; }
}
public ClusterDescription Description
{
get
{
lock (_descriptionLock)
{
return _description;
}
}
}
public ClusterSettings Settings
{
get { return _settings; }
}
// methods
public ICoreServerSession AcquireServerSession()
{
return _serverSessionPool.AcquireSession();
}
protected IClusterableServer CreateServer(EndPoint endPoint)
{
return _serverFactory.CreateServer(_clusterId, _clusterClock, endPoint);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_state.TryChange(State.Disposed))
{
var newClusterDescription = new ClusterDescription(
_clusterId,
_description.ConnectionMode,
ClusterType.Unknown,
Enumerable.Empty<ServerDescription>());
UpdateClusterDescription(newClusterDescription);
_rapidHeartbeatTimer.Dispose();
}
}
private void EnterServerSelectionWaitQueue()
{
lock (_serverSelectionWaitQueueLock)
{
if (_serverSelectionWaitQueueSize >= _settings.MaxServerSelectionWaitQueueSize)
{
throw MongoWaitQueueFullException.ForServerSelection();
}
if (++_serverSelectionWaitQueueSize == 1)
{
_rapidHeartbeatTimer.Change(TimeSpan.Zero, __minHeartbeatInterval);
}
}
}
private void ExitServerSelectionWaitQueue()
{
lock (_serverSelectionWaitQueueLock)
{
if (--_serverSelectionWaitQueueSize == 0)
{
_rapidHeartbeatTimer.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
}
}
}
public virtual void Initialize()
{
ThrowIfDisposed();
if (_state.TryChange(State.Initial, State.Open))
{
if (_settings.KmsProviders != null || _settings.SchemaMap != null)
{
_cryptClient = CryptClientCreator.CreateCryptClient(_settings.KmsProviders, _settings.SchemaMap);
}
}
}
private void RapidHeartbeatTimerCallback(object args)
{
try
{
RequestHeartbeat();
}
catch
{
// TODO: Trace this
// If we don't protect this call, we could
// take down the app domain.
}
}
protected abstract void RequestHeartbeat();
protected void OnDescriptionChanged(ClusterDescription oldDescription, ClusterDescription newDescription)
{
if (_descriptionChangedEventHandler != null)
{
_descriptionChangedEventHandler(new ClusterDescriptionChangedEvent(oldDescription, newDescription));
}
var handler = DescriptionChanged;
if (handler != null)
{
var args = new ClusterDescriptionChangedEventArgs(oldDescription, newDescription);
handler(this, args);
}
}
public IServer SelectServer(IServerSelector selector, CancellationToken cancellationToken)
{
ThrowIfDisposedOrNotOpen();
Ensure.IsNotNull(selector, nameof(selector));
using (var helper = new SelectServerHelper(this, selector))
{
try
{
while (true)
{
var server = helper.SelectServer();
if (server != null)
{
return server;
}
helper.WaitingForDescriptionToChange();
WaitForDescriptionChanged(helper.Selector, helper.Description, helper.DescriptionChangedTask, helper.TimeoutRemaining, cancellationToken);
}
}
catch (Exception ex)
{
helper.HandleException(ex);
throw;
}
}
}
public async Task<IServer> SelectServerAsync(IServerSelector selector, CancellationToken cancellationToken)
{
ThrowIfDisposedOrNotOpen();
Ensure.IsNotNull(selector, nameof(selector));
using (var helper = new SelectServerHelper(this, selector))
{
try
{
while (true)
{
var server = helper.SelectServer();
if (server != null)
{
return server;
}
helper.WaitingForDescriptionToChange();
await WaitForDescriptionChangedAsync(helper.Selector, helper.Description, helper.DescriptionChangedTask, helper.TimeoutRemaining, cancellationToken).ConfigureAwait(false);
}
}
catch (Exception ex)
{
helper.HandleException(ex);
throw;
}
}
}
public ICoreSessionHandle StartSession(CoreSessionOptions options)
{
options = options ?? new CoreSessionOptions();
var serverSession = AcquireServerSession();
var session = new CoreSession(this, serverSession, options);
return new CoreSessionHandle(session);
}
protected abstract bool TryGetServer(EndPoint endPoint, out IClusterableServer server);
protected void UpdateClusterDescription(ClusterDescription newClusterDescription)
{
ClusterDescription oldClusterDescription = null;
TaskCompletionSource<bool> oldDescriptionChangedTaskCompletionSource = null;
lock (_descriptionLock)
{
oldClusterDescription = _description;
_description = newClusterDescription;
oldDescriptionChangedTaskCompletionSource = _descriptionChangedTaskCompletionSource;
_descriptionChangedTaskCompletionSource = new TaskCompletionSource<bool>();
}
OnDescriptionChanged(oldClusterDescription, newClusterDescription);
// TODO: use RunContinuationsAsynchronously instead once we require a new enough .NET Framework
Task.Run(() => oldDescriptionChangedTaskCompletionSource.TrySetResult(true));
}
private string BuildTimeoutExceptionMessage(TimeSpan timeout, IServerSelector selector, ClusterDescription clusterDescription)
{
var ms = (int)Math.Round(timeout.TotalMilliseconds);
return string.Format(
"A timeout occured after {0}ms selecting a server using {1}. Client view of cluster state is {2}.",
ms.ToString(),
selector.ToString(),
clusterDescription.ToString());
}
private void ThrowIfDisposed()
{
if (_state.Value == State.Disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
}
private void ThrowIfDisposedOrNotOpen()
{
if (_state.Value != State.Open)
{
ThrowIfDisposed();
throw new InvalidOperationException("Server must be initialized.");
}
}
private void WaitForDescriptionChanged(IServerSelector selector, ClusterDescription description, Task descriptionChangedTask, TimeSpan timeout, CancellationToken cancellationToken)
{
using (var helper = new WaitForDescriptionChangedHelper(this, selector, description, descriptionChangedTask, timeout, cancellationToken))
{
var index = Task.WaitAny(helper.Tasks);
helper.HandleCompletedTask(helper.Tasks[index]);
}
}
private async Task WaitForDescriptionChangedAsync(IServerSelector selector, ClusterDescription description, Task descriptionChangedTask, TimeSpan timeout, CancellationToken cancellationToken)
{
using (var helper = new WaitForDescriptionChangedHelper(this, selector, description, descriptionChangedTask, timeout, cancellationToken))
{
var completedTask = await Task.WhenAny(helper.Tasks).ConfigureAwait(false);
helper.HandleCompletedTask(completedTask);
}
}
private void ThrowTimeoutException(IServerSelector selector, ClusterDescription description)
{
var message = BuildTimeoutExceptionMessage(_settings.ServerSelectionTimeout, selector, description);
throw new TimeoutException(message);
}
// nested classes
private class SelectServerHelper : IDisposable
{
private readonly Cluster _cluster;
private ClusterDescription _description;
private Task _descriptionChangedTask;
private bool _serverSelectionWaitQueueEntered;
private readonly IServerSelector _selector;
private readonly Stopwatch _stopwatch;
private readonly DateTime _timeoutAt;
public SelectServerHelper(Cluster cluster, IServerSelector selector)
{
_cluster = cluster;
_selector = DecorateSelector(selector);
_stopwatch = Stopwatch.StartNew();
_timeoutAt = DateTime.UtcNow + _cluster.Settings.ServerSelectionTimeout;
}
public ClusterDescription Description
{
get { return _description; }
}
public Task DescriptionChangedTask
{
get { return _descriptionChangedTask; }
}
public IServerSelector Selector
{
get { return _selector; }
}
public TimeSpan TimeoutRemaining
{
get { return _timeoutAt - DateTime.UtcNow; }
}
public void Dispose()
{
if (_serverSelectionWaitQueueEntered)
{
_cluster.ExitServerSelectionWaitQueue();
}
}
public void HandleException(Exception exception)
{
var selectingServerFailedEventHandler = _cluster._selectingServerFailedEventHandler;
if (selectingServerFailedEventHandler != null)
{
selectingServerFailedEventHandler(new ClusterSelectingServerFailedEvent(
_description,
_selector,
exception,
EventContext.OperationId));
}
}
public IServer SelectServer()
{
lock (_cluster._descriptionLock)
{
_descriptionChangedTask = _cluster._descriptionChangedTaskCompletionSource.Task;
_description = _cluster._description;
}
if (!_serverSelectionWaitQueueEntered)
{
var selectingServerEventHandler = _cluster._selectingServerEventHandler;
if (selectingServerEventHandler != null)
{
// this is our first time through...
selectingServerEventHandler(new ClusterSelectingServerEvent(
_description,
_selector,
EventContext.OperationId));
}
}
MongoIncompatibleDriverException.ThrowIfNotSupported(_description);
var connectedServers = _description.Servers.Where(s => s.State == ServerState.Connected);
var selectedServers = _selector.SelectServers(_description, connectedServers).ToList();
while (selectedServers.Count > 0)
{
var server = selectedServers.Count == 1 ?
selectedServers[0] :
__randomServerSelector.SelectServers(_description, selectedServers).Single();
IClusterableServer selectedServer;
if (_cluster.TryGetServer(server.EndPoint, out selectedServer))
{
_stopwatch.Stop();
var selectedServerEventHandler = _cluster._selectedServerEventHandler;
if (selectedServerEventHandler != null)
{
selectedServerEventHandler(new ClusterSelectedServerEvent(
_description,
_selector,
server,
_stopwatch.Elapsed,
EventContext.OperationId));
}
return selectedServer;
}
selectedServers.Remove(server);
}
return null;
}
public void WaitingForDescriptionToChange()
{
if (!_serverSelectionWaitQueueEntered)
{
_cluster.EnterServerSelectionWaitQueue();
_serverSelectionWaitQueueEntered = true;
}
var timeoutRemaining = _timeoutAt - DateTime.UtcNow;
if (timeoutRemaining <= TimeSpan.Zero)
{
_cluster.ThrowTimeoutException(_selector, _description);
}
}
private IServerSelector DecorateSelector(IServerSelector selector)
{
var settings = _cluster.Settings;
if (settings.PreServerSelector != null || settings.PostServerSelector != null)
{
var allSelectors = new List<IServerSelector>();
if (settings.PreServerSelector != null)
{
allSelectors.Add(settings.PreServerSelector);
}
allSelectors.Add(selector);
if (settings.PostServerSelector != null)
{
allSelectors.Add(settings.PostServerSelector);
}
return new CompositeServerSelector(allSelectors);
}
return selector;
}
}
private sealed class WaitForDescriptionChangedHelper : IDisposable
{
private readonly CancellationToken _cancellationToken;
private readonly TaskCompletionSource<bool> _cancellationTaskCompletionSource;
private readonly CancellationTokenRegistration _cancellationTokenRegistration;
private readonly Cluster _cluster;
private readonly ClusterDescription _description;
private readonly Task _descriptionChangedTask;
private readonly IServerSelector _selector;
private readonly CancellationTokenSource _timeoutCancellationTokenSource;
private readonly Task _timeoutTask;
public WaitForDescriptionChangedHelper(Cluster cluster, IServerSelector selector, ClusterDescription description, Task descriptionChangedTask, TimeSpan timeout, CancellationToken cancellationToken)
{
_cluster = cluster;
_description = description;
_selector = selector;
_descriptionChangedTask = descriptionChangedTask;
_cancellationToken = cancellationToken;
_cancellationTaskCompletionSource = new TaskCompletionSource<bool>();
_cancellationTokenRegistration = cancellationToken.Register(() => _cancellationTaskCompletionSource.TrySetCanceled());
_timeoutCancellationTokenSource = new CancellationTokenSource();
_timeoutTask = Task.Delay(timeout, _timeoutCancellationTokenSource.Token);
}
public Task[] Tasks
{
get
{
return new Task[]
{
_descriptionChangedTask,
_timeoutTask,
_cancellationTaskCompletionSource.Task
};
}
}
public void Dispose()
{
_cancellationTokenRegistration.Dispose();
_timeoutCancellationTokenSource.Dispose();
}
public void HandleCompletedTask(Task completedTask)
{
if (completedTask == _timeoutTask)
{
_cluster.ThrowTimeoutException(_selector, _description);
}
_timeoutCancellationTokenSource.Cancel();
if (completedTask == _cancellationTaskCompletionSource.Task)
{
_cancellationToken.ThrowIfCancellationRequested();
}
_descriptionChangedTask.GetAwaiter().GetResult(); // propagate exceptions
}
}
private static class State
{
public const int Initial = 0;
public const int Open = 1;
public const int Disposed = 2;
}
}
}