// methods /// <inheritdoc/> public IEnumerable<ServerDescription> SelectServers(ClusterDescription cluster, IEnumerable<Servers.ServerDescription> servers) { return servers.Where(x => x.Type == ServerType.ReplicaSetPrimary || x.Type == ServerType.ShardRouter || x.Type == ServerType.Standalone); }
// methods /// <inheritdoc/> public IEnumerable<ServerDescription> SelectServers(ClusterDescription cluster, IEnumerable<ServerDescription> servers) { if (_maxStaleness.HasValue) { if (cluster.Servers.Any(s => s.Type != ServerType.Unknown && !Feature.MaxStaleness.IsSupported(s.Version))) { throw new NotSupportedException("All servers must be version 3.4 or newer to use max staleness."); } } if (cluster.ConnectionMode == ClusterConnectionMode.Direct) { return servers; } switch (cluster.Type) { case ClusterType.ReplicaSet: return SelectForReplicaSet(cluster, servers); case ClusterType.Sharded: return SelectForShardedCluster(servers); case ClusterType.Standalone: return SelectForStandaloneCluster(servers); case ClusterType.Unknown: return __noServers; default: var message = string.Format("ReadPreferenceServerSelector is not implemented for cluster of type: {0}.", cluster.Type); throw new NotImplementedException(message); } }
/// <summary> /// Initializes a new instance of the <see cref="ClusterSelectingServerFailedEvent" /> struct. /// </summary> /// <param name="clusterDescription">The cluster description.</param> /// <param name="serverSelector">The server selector.</param> /// <param name="exception">The exception.</param> /// <param name="operationId">The operation identifier.</param> public ClusterSelectingServerFailedEvent(ClusterDescription clusterDescription, IServerSelector serverSelector, Exception exception, long? operationId) { _clusterDescription = clusterDescription; _serverSelector = serverSelector; _exception = exception; _operationId = operationId; }
/// <summary> /// Initializes a new instance of the <see cref="ClusterSelectedServerEvent" /> struct. /// </summary> /// <param name="clusterDescription">The cluster description.</param> /// <param name="serverSelector">The server selector.</param> /// <param name="selectedServer">The selected server.</param> /// <param name="duration">The duration of time it took to select the server.</param> public ClusterSelectedServerEvent(ClusterDescription clusterDescription, IServerSelector serverSelector, ServerDescription selectedServer, TimeSpan duration) { _clusterDescription = clusterDescription; _serverSelector = serverSelector; _selectedServer = selectedServer; _duration = duration; }
// methods public IEnumerable<ServerDescription> SelectServers(ClusterDescription cluster, IEnumerable<ServerDescription> servers) { var selectedServers = servers; foreach (var selector in _selectors) { selectedServers = selector.SelectServers(cluster, selectedServers); } return selectedServers; }
public void TestFixtureSetup() { var clusterId = new ClusterId(1); var clusterType = ClusterType.Standalone; var endPoint = new DnsEndPoint("localhost", 27017); var serverId = new ServerId(clusterId, endPoint); var server = new ServerDescription(serverId, endPoint); var servers = new[] { server }; _clusterDescription = new ClusterDescription(clusterId, clusterType, servers); }
public void Constructor_should_initialize_instance() { var subject = new ClusterDescription( __clusterId, ClusterType.ReplicaSet, new[] { __serverDescription1, __serverDescription2 }); subject.ClusterId.Should().Be(__clusterId); subject.Servers.Should().ContainInOrder(new[] { __serverDescription1, __serverDescription2 }); subject.State.Should().Be(ClusterState.Disconnected); subject.Type.Should().Be(ClusterType.ReplicaSet); }
public MongoIncompatibleDriverExceptionTests() { var clusterId = new ClusterId(1); var connectionMode = ClusterConnectionMode.Standalone; var clusterType = ClusterType.Standalone; var endPoint = new DnsEndPoint("localhost", 27017); var serverId = new ServerId(clusterId, endPoint); var server = new ServerDescription(serverId, endPoint); var servers = new[] { server }; _clusterDescription = new ClusterDescription(clusterId, connectionMode, clusterType, servers); }
public void OneTimeSetUp() { var clusterId = new ClusterId(1); var connectionMode = ClusterConnectionMode.Standalone; var clusterType = ClusterType.Standalone; var endPoint = new DnsEndPoint("localhost", 27017); var serverId = new ServerId(clusterId, endPoint); var server = new ServerDescription(serverId, endPoint); var servers = new[] { server }; _clusterDescription = new ClusterDescription(clusterId, connectionMode, clusterType, servers); }
// constructors protected Cluster(ClusterSettings settings, IClusterableServerFactory serverFactory, IClusterListener listener) { _settings = Ensure.IsNotNull(settings, "settings"); _serverFactory = Ensure.IsNotNull(serverFactory, "serverFactory"); _listener = listener; _state = new InterlockedInt32(State.Initial); _clusterId = new ClusterId(); _description = ClusterDescription.CreateInitial(_clusterId, _settings.ConnectionMode.ToClusterType()); _descriptionChangedTaskCompletionSource = new TaskCompletionSource<bool>(); }
public void Setup() { var clusterId = new ClusterId(); _primary = ServerDescriptionHelper.Connected(clusterId, new DnsEndPoint("localhost", 27017), ServerType.ReplicaSetPrimary, new TagSet(new [] { new Tag("a", "1") })); _secondary1 = ServerDescriptionHelper.Connected(clusterId, new DnsEndPoint("localhost", 27018), ServerType.ReplicaSetSecondary, new TagSet(new [] { new Tag("a", "1") })); _secondary2 = ServerDescriptionHelper.Connected(clusterId, new DnsEndPoint("localhost", 27019), ServerType.ReplicaSetSecondary, new TagSet(new[] { new Tag("a", "2") })); _description = new ClusterDescription( clusterId, ClusterType.ReplicaSet, new[] { _primary, _secondary1, _secondary2 }); }
// methods public IEnumerable<ServerDescription> SelectServers(ClusterDescription cluster, IEnumerable<ServerDescription> servers) { var list = servers.ToList(); switch (list.Count) { case 0: case 1: return list; default: var index = ThreadStaticRandom.Next(list.Count); return new[] { list[index] }; } }
// methods /// <inheritdoc/> public IEnumerable<ServerDescription> SelectServers(ClusterDescription cluster, IEnumerable<ServerDescription> servers) { switch (cluster.Type) { case ClusterType.ReplicaSet: return SelectForReplicaSet(servers); case ClusterType.Sharded: return SelectForShardedCluster(servers); case ClusterType.Standalone: return SelectForStandaloneCluster(servers); case ClusterType.Unknown: return __noServers; default: var message = string.Format("ReadPreferenceServerSelector is not implemented for cluster of type: {0}.", cluster.Type); throw new NotImplementedException(message); } }
public void Setup() { var clusterId = new ClusterId(); _description = new ClusterDescription( clusterId, ClusterType.Unknown, new[] { ServerDescriptionHelper.Connected(clusterId, new DnsEndPoint("localhost", 27017)), ServerDescriptionHelper.Connected(clusterId, new DnsEndPoint("localhost", 27018)), ServerDescriptionHelper.Connected(clusterId, new DnsEndPoint("localhost", 27019)), }); }
public void Setup() { var clusterId = new ClusterId(); _description = new ClusterDescription( clusterId, ClusterType.Unknown, new[] { ServerDescriptionHelper.Connected(clusterId, new DnsEndPoint("localhost", 27017), averageRoundTripTime: TimeSpan.FromMilliseconds(10)), ServerDescriptionHelper.Connected(clusterId, new DnsEndPoint("localhost", 27018), averageRoundTripTime: TimeSpan.FromMilliseconds(30)), ServerDescriptionHelper.Connected(clusterId, new DnsEndPoint("localhost", 27019), averageRoundTripTime: TimeSpan.FromMilliseconds(20)) }); }
public async Task ExecuteAsync(ClusterDescription clusterDescription, IMongoDatabase database, IMongoCollection<BsonDocument> collection, BsonDocument arguments) { ClusterDescription = clusterDescription; foreach (var argument in arguments.Elements) { if (!TrySetArgument(argument.Name, argument.Value)) { throw new NotImplementedException("The argument " + argument.Name + " has not been implemented in " + GetType()); } } await ExecuteAsync(collection); }
public EndPointServerSelectorTests() { var clusterId = new ClusterId(); _description = new ClusterDescription( clusterId, ClusterConnectionMode.Automatic, ClusterType.Unknown, new[] { ServerDescriptionHelper.Connected(clusterId, new DnsEndPoint("localhost", 27017)), ServerDescriptionHelper.Connected(clusterId, new DnsEndPoint("localhost", 27018)), ServerDescriptionHelper.Connected(clusterId, new DnsEndPoint("localhost", 27019)), }); }
public LatencyLimitingServerSelectorTests() { var clusterId = new ClusterId(); _description = new ClusterDescription( clusterId, ClusterConnectionMode.Automatic, ClusterType.Unknown, new[] { ServerDescriptionHelper.Connected(clusterId, new DnsEndPoint("localhost", 27017), averageRoundTripTime: TimeSpan.FromMilliseconds(10)), ServerDescriptionHelper.Connected(clusterId, new DnsEndPoint("localhost", 27018), averageRoundTripTime: TimeSpan.FromMilliseconds(30)), ServerDescriptionHelper.Connected(clusterId, new DnsEndPoint("localhost", 27019), averageRoundTripTime: TimeSpan.FromMilliseconds(20)) }); }
// constructors protected Cluster(ClusterSettings settings, IClusterableServerFactory serverFactory, IEventSubscriber eventSubscriber) { _settings = Ensure.IsNotNull(settings, "settings"); _serverFactory = Ensure.IsNotNull(serverFactory, "serverFactory"); Ensure.IsNotNull(eventSubscriber, "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); }
// methods /// <inheritdoc/> public IEnumerable<ServerDescription> SelectServers(ClusterDescription cluster, IEnumerable<ServerDescription> servers) { if (_allowedLatencyRange == Timeout.InfiniteTimeSpan) { return servers; } var list = servers.ToList(); switch (list.Count) { case 0: case 1: return list; default: var minAverageRoundTripTime = list.Min(s => s.AverageRoundTripTime); var maxAverageRoundTripTime = minAverageRoundTripTime.Add(_allowedLatencyRange); return list.Where(s => s.AverageRoundTripTime <= maxAverageRoundTripTime); } }
public void GetReadChannelSource_should_use_a_writable_server_selector_to_select_the_server_from_the_cluster( [Values(false, true)] bool async) { var subject = new WritableServerBinding(_mockCluster.Object, NoCoreSession.NewHandle()); var selectedServer = new Mock <IServer>().Object; var clusterId = new ClusterId(); var endPoint = new DnsEndPoint("localhost", 27017); var initialClusterDescription = new ClusterDescription( clusterId, ClusterConnectionMode.Automatic, ClusterType.Unknown, new[] { new ServerDescription(new ServerId(clusterId, endPoint), endPoint) }); var finalClusterDescription = initialClusterDescription.WithType(ClusterType.Standalone); _mockCluster.SetupSequence(c => c.Description).Returns(initialClusterDescription).Returns(finalClusterDescription); if (async) { _mockCluster.Setup(c => c.SelectServerAsync(It.IsAny <WritableServerSelector>(), CancellationToken.None)).Returns(Task.FromResult(selectedServer)); subject.GetReadChannelSourceAsync(CancellationToken.None).GetAwaiter().GetResult(); _mockCluster.Verify(c => c.SelectServerAsync(It.IsAny <WritableServerSelector>(), CancellationToken.None), Times.Once); } else { _mockCluster.Setup(c => c.SelectServer(It.IsAny <WritableServerSelector>(), CancellationToken.None)).Returns(selectedServer); subject.GetReadChannelSource(CancellationToken.None); _mockCluster.Verify(c => c.SelectServer(It.IsAny <WritableServerSelector>(), CancellationToken.None), Times.Once); } }
private CoreServerSessionPool CreateSubject() { var clusterId = new ClusterId(); var endPoint = new DnsEndPoint("localhost", 27017); var serverId = new ServerId(clusterId, endPoint); var serverDescription = new ServerDescription( serverId, endPoint, logicalSessionTimeout: TimeSpan.FromMinutes(30), type: ServerType.ShardRouter, version: new SemanticVersion(3, 6, 0), wireVersionRange: new Range <int>(2, 6)); var connectionMode = ClusterConnectionMode.Automatic; var type = ClusterType.Sharded; var servers = new[] { serverDescription }; var clusterDescription = new ClusterDescription(clusterId, connectionMode, type, servers); var mockCluster = new Mock <ICluster>(); mockCluster.SetupGet(m => m.Description).Returns(clusterDescription); return(new CoreServerSessionPool(mockCluster.Object)); }
// methods /// <inheritdoc/> public IEnumerable <ServerDescription> SelectServers(ClusterDescription cluster, IEnumerable <ServerDescription> servers) { if (cluster.IsDirectConnection) { return(servers); } switch (cluster.Type) { case ClusterType.ReplicaSet: return(SelectForReplicaSet(cluster, servers)); case ClusterType.Sharded: return(SelectForShardedCluster(servers)); case ClusterType.Standalone: return(SelectForStandaloneCluster(servers)); case ClusterType.Unknown: return(__noServers); case ClusterType.LoadBalanced: return(SelectForLoadBalancedCluster(servers)); default: var message = string.Format("ReadPreferenceServerSelector is not implemented for cluster of type: {0}.", cluster.Type); throw new NotImplementedException(message); } }
public async Task ExecuteAsync(ClusterDescription clusterDescription, IMongoDatabase database, IMongoCollection <BsonDocument> collection, BsonDocument arguments, BsonDocument outcome) { ClusterDescription = clusterDescription; foreach (var argument in arguments.Elements) { if (!TrySetArgument(argument.Name, argument.Value)) { throw new NotImplementedException("The argument " + argument.Name + " has not been implemented in " + GetType()); } } await ExecuteAsync(collection, outcome); if (outcome.Contains("collection")) { var collectionToVerify = collection; if (outcome["collection"].AsBsonDocument.Contains("name")) { collectionToVerify = database.GetCollection <BsonDocument>(outcome["collection"]["name"].ToString()); } await VerifyCollectionAsync(collectionToVerify, (BsonArray)outcome["collection"]["data"]); } }
/// <summary> /// Initializes a new instance of the <see cref="ClusterSelectingServerEvent" /> struct. /// </summary> /// <param name="clusterDescription">The cluster description.</param> /// <param name="serverSelector">The server selector.</param> public ClusterSelectingServerEvent(ClusterDescription clusterDescription, IServerSelector serverSelector) { _clusterDescription = clusterDescription; _serverSelector = serverSelector; }
// static methods private static string FormatMessage(ClusterDescription clusterDescription) { return string.Format( "This version of the driver is not compatible with one or more of the servers to which it is connected: {0}.", clusterDescription); }
/// <summary> /// Initializes a new instance of the <see cref="ClusterSelectingServerFailedEvent" /> struct. /// </summary> /// <param name="clusterDescription">The cluster description.</param> /// <param name="serverSelector">The server selector.</param> /// <param name="exception">The exception.</param> public ClusterSelectingServerFailedEvent(ClusterDescription clusterDescription, IServerSelector serverSelector, Exception exception) { _clusterDescription = clusterDescription; _serverSelector = serverSelector; _exception = exception; }
public virtual bool CanExecute(ClusterDescription clusterDescription, BsonDocument arguments, out string reason) { reason = null; return(true); }
// constructors /// <summary> /// Initializes a new instance of the <see cref="MongoIncompatibleDriverException"/> class. /// </summary> /// <param name="clusterDescription">The cluster description.</param> public MongoIncompatibleDriverException(ClusterDescription clusterDescription) : base(FormatMessage(clusterDescription), null) { }
public void State_should_be_connected_if_any_server_is_connected() { var connected = ServerDescriptionHelper.Connected(new ClusterId(1)); var subject = new ClusterDescription(new ClusterId(1), ClusterConnectionMode.Standalone, ClusterType.Standalone, new[] { __serverDescription1, connected }); subject.State.Should().Be(ClusterState.Connected); }
public IEnumerable<ServerDescription> SelectServers(ClusterDescription cluster, IEnumerable<ServerDescription> servers) { return _selector(cluster, servers); }
/// <summary> /// Initializes a new instance of the <see cref="ClusterSelectingServerEvent" /> struct. /// </summary> /// <param name="clusterDescription">The cluster description.</param> /// <param name="serverSelector">The server selector.</param> public ClusterSelectingServerEvent(ClusterDescription clusterDescription, IServerSelector serverSelector) { _clusterDescription = clusterDescription; _serverSelector = serverSelector; }
public void ClusterDescriptionChanged(ClusterDescription oldClusterDescription, ClusterDescription newClusterDescription) { _first.ClusterDescriptionChanged(oldClusterDescription, newClusterDescription); _second.ClusterDescriptionChanged(oldClusterDescription, newClusterDescription); }
/// <summary> /// Initializes a new instance of the <see cref="ClusterSelectingServerFailedEvent" /> struct. /// </summary> /// <param name="clusterDescription">The cluster description.</param> /// <param name="serverSelector">The server selector.</param> /// <param name="exception">The exception.</param> public ClusterSelectingServerFailedEvent(ClusterDescription clusterDescription, IServerSelector serverSelector, Exception exception) { _clusterDescription = clusterDescription; _serverSelector = serverSelector; _exception = exception; }
private static bool IsInLoadBalancedMode(ClusterDescription clusterDescription) => clusterDescription?.Type == ClusterType.LoadBalanced;
public override void ClusterDescriptionChanged(ClusterDescription oldClusterDescription, ClusterDescription newClusterDescription) { Log(LogLevel.Info, "{0}: {1}", Label(oldClusterDescription.ClusterId), newClusterDescription); }
public static bool?AreSessionsSupported(this MongoClient obj, ClusterDescription clusterDescription) => (bool?)Reflector.Invoke(obj, nameof(AreSessionsSupported), clusterDescription);
// methods /// <inheritdoc/> public IEnumerable <ServerDescription> SelectServers(ClusterDescription cluster, IEnumerable <ServerDescription> servers) { return(servers.Where(server => EndPointHelper.Equals(server.EndPoint, _endPoint))); }
public IEnumerable <ServerDescription> SelectServers(ClusterDescription cluster, IEnumerable <ServerDescription> servers) { CustomSelectorWasCalled = true; return(servers); }
// methods /// <inheritdoc/> public IEnumerable <ServerDescription> SelectServers(ClusterDescription cluster, IEnumerable <ServerDescription> servers) { return(_selector(cluster, servers)); }
private void RunErrorTest(ClusterDescription clusterDescription, IServerSelector selector) { var exception = Record.Exception(() => selector.SelectServers(clusterDescription, clusterDescription.Servers).ToList()); exception.Should().NotBeNull(); }
public IEnumerable <ServerDescription> SelectServers(ClusterDescription cluster, IEnumerable <ServerDescription> servers) { ClusterDescription = cluster; return(servers.Where(s => s.IsDataBearing)); }
public TestCluster(ClusterType clusterType) { #pragma warning disable CS0618 // Type or member is obsolete Description = new ClusterDescription(new ClusterId(), ClusterConnectionMode.Automatic, clusterType, Enumerable.Empty <ServerDescription>()); #pragma warning restore CS0618 // Type or member is obsolete }
public void ToString_should_return_string_representation() { var subject = new ClusterDescription(new ClusterId(1), ClusterConnectionMode.Standalone, ClusterType.Standalone, new[] { __serverDescription1 }); var expected = string.Format("{{ ClusterId : \"1\", ConnectionMode : \"Standalone\", Type : \"Standalone\", State : \"Disconnected\", Servers : [{0}] }}", __serverDescription1.ToString()); subject.ToString().Should().Be(expected); }
private static bool AreSessionsSupported(ClusterDescription clusterDescription) { return (clusterDescription.Servers.Any(s => s.State == ServerState.Connected) && clusterDescription.LogicalSessionTimeout.HasValue); }
// private static methods private static IEnumerable <ServerDescription> SelectServersThatDetermineWhetherSessionsAreSupported(ClusterDescription cluster, IEnumerable <ServerDescription> servers) { var connectedServers = servers.Where(s => s.State == ServerState.Connected); if (cluster.IsDirectConnection) { return(connectedServers); } else { return(connectedServers.Where(s => s.IsDataBearing)); } }
private async Task WaitForDescriptionChangedAsync(IServerSelector selector, ClusterDescription description, Task descriptionChangedTask, TimeSpan timeout, CancellationToken cancellationToken) { var cancellationTaskCompletionSource = new TaskCompletionSource<bool>(); using (cancellationToken.Register(() => cancellationTaskCompletionSource.TrySetCanceled())) using (var timeoutCancellationTokenSource = new CancellationTokenSource()) { var timeoutTask = Task.Delay(timeout, timeoutCancellationTokenSource.Token); var completedTask = await Task.WhenAny(descriptionChangedTask, timeoutTask, cancellationTaskCompletionSource.Task).ConfigureAwait(false); if (completedTask == timeoutTask) { ThrowTimeoutException(selector, description); } timeoutCancellationTokenSource.Cancel(); if (completedTask == cancellationTaskCompletionSource.Task) { cancellationToken.ThrowIfCancellationRequested(); } await descriptionChangedTask.ConfigureAwait(false); // propagate exceptions } }
public IEnumerable <ServerDescription> SelectServers(ClusterDescription cluster, IEnumerable <ServerDescription> servers) { ClusterDescription = cluster; return(SelectServersThatDetermineWhetherSessionsAreSupported(cluster.ConnectionMode, servers)); }
private void ThrowTimeoutException(IServerSelector selector, ClusterDescription description) { var message = BuildTimeoutExceptionMessage(_settings.ServerSelectionTimeout, selector, description); throw new TimeoutException(message); }
/// <summary> /// Initializes a new instance of the <see cref="ClusterDescriptionChangedEvent"/> struct. /// </summary> /// <param name="oldDescription">The old description.</param> /// <param name="newDescription">The new description.</param> public ClusterDescriptionChangedEvent(ClusterDescription oldDescription, ClusterDescription newDescription) { _oldDescription = oldDescription; _newDescription = newDescription; }
// static methods private static string FormatMessage(ClusterDescription clusterDescription) { return(string.Format( "This version of the driver is not compatible with one or more of the servers to which it is connected: {0}.", clusterDescription)); }
// constructors /// <summary> /// Initializes a new instance of the <see cref="MongoIncompatibleDriverException"/> class. /// </summary> /// <param name="clusterDescription">The cluster description.</param> public MongoIncompatibleDriverException(ClusterDescription clusterDescription) : base(FormatMessage(clusterDescription), null) { }
// constructors /// <summary> /// Initializes a new instance of the <see cref="ClusterDescriptionChangedEventArgs"/> class. /// </summary> /// <param name="oldClusterDescription">The old cluster description.</param> /// <param name="newClusterDescription">The new cluster description.</param> public ClusterDescriptionChangedEventArgs(ClusterDescription oldClusterDescription, ClusterDescription newClusterDescription) { _oldClusterDescription = Ensure.IsNotNull(oldClusterDescription, "oldClusterDescription"); _newClusterDescription = Ensure.IsNotNull(newClusterDescription, "newClusterDescription"); }
/// <summary> /// Initializes a new instance of the <see cref="ClusterSelectingServerEvent" /> struct. /// </summary> /// <param name="clusterDescription">The cluster description.</param> /// <param name="serverSelector">The server selector.</param> /// <param name="operationId">The operation identifier.</param> public ClusterSelectingServerEvent(ClusterDescription clusterDescription, IServerSelector serverSelector, long?operationId) { _clusterDescription = clusterDescription; _serverSelector = serverSelector; _operationId = operationId; }
/// <summary> /// Initializes a new instance of the <see cref="ClusterDescriptionChangedEvent"/> struct. /// </summary> /// <param name="oldDescription">The old description.</param> /// <param name="newDescription">The new description.</param> public ClusterDescriptionChangedEvent(ClusterDescription oldDescription, ClusterDescription newDescription) { _oldDescription = oldDescription; _newDescription = newDescription; _timestamp = DateTime.UtcNow; }