/// <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
        private ClusterType DetermineClusterType(ServerDescription serverDescription)
        {
            switch (serverDescription.Type)
            {
                case ServerType.ReplicaSetArbiter:
                case ServerType.ReplicaSetGhost:
                case ServerType.ReplicaSetOther:
                case ServerType.ReplicaSetPassive:
                case ServerType.ReplicaSetPrimary:
                case ServerType.ReplicaSetSecondary:
                    return ClusterType.ReplicaSet;

                case ServerType.ShardRouter:
                    return ClusterType.Sharded;

                case ServerType.Standalone:
                    return ClusterType.Standalone;

                case ServerType.Unknown:
                    return ClusterType.Unknown;

                default:
                    throw new MongoException("Unexpected ServerTypes.");
            }
        }
Ejemplo n.º 3
0
        // methods
        private BsonDocument CreateWrappedCommand(ServerDescription serverDescription, ReadPreference readPreference)
        {
            BsonDocument readPreferenceDocument = null;

            if (serverDescription.Type == ServerType.ShardRouter)
            {
                readPreferenceDocument = QueryHelper.CreateReadPreferenceDocument(serverDescription.Type, readPreference);
            }

            var wrappedCommand = new BsonDocument
            {
                { "$query", _command },
                { "$readPreference", readPreferenceDocument, readPreferenceDocument != null },
                { "$comment", () => _comment, _comment != null }
            };

            if (_additionalOptions != null)
            {
                wrappedCommand.Merge(_additionalOptions, overwriteExistingElements: false);
            }

            if (wrappedCommand.ElementCount == 1)
            {
                return(_command);
            }
            else
            {
                return(wrappedCommand);
            }
        }
Ejemplo n.º 4
0
 // constructors
 public Request(ServerDescription serverDescription, MongoServerInstance serverInstance, IReadBindingHandle binding, ConnectionId connectionId)
 {
     _serverDescription = serverDescription;
     _serverInstance    = serverInstance;
     _binding           = binding;
     _connectionId      = connectionId;
     _nestingLevel      = 1;
 }
        private void PublishDisconnectedDescription(EndPoint endPoint)
        {
            var current = _serverFactory.GetServerDescription(endPoint);

            var description = new ServerDescription(current.ServerId, endPoint);

            _serverFactory.PublishDescription(description);
        }
Ejemplo n.º 6
0
 /// <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>
 /// <param name="operationId">The operation identifier.</param>
 public ClusterSelectedServerEvent(ClusterDescription clusterDescription, IServerSelector serverSelector, ServerDescription selectedServer, TimeSpan duration, long?operationId)
 {
     _clusterDescription = clusterDescription;
     _serverSelector     = serverSelector;
     _selectedServer     = selectedServer;
     _duration           = duration;
     _operationId        = operationId;
 }
Ejemplo n.º 7
0
        private CursorBatch <TDocument> ExecuteCommand(IReadBinding binding, ServerDescription serverDescription, CancellationToken cancellationToken)
        {
            var command   = CreateCommand(serverDescription);
            var operation = CreateCommandOperation(command);
            var result    = operation.Execute(binding, cancellationToken);

            return(CreateCursorBatch(result));
        }
 public ServerNode(ServersTree owner, ServerDescription description)
 {
     Owner      = owner;
     Id         = description.Id;
     Name       = description.ProgramId;
     ServerName = description.Name;
     IsExpanded = true;
     Icon       = "/Images/ServerOff.png";
 }
Ejemplo n.º 9
0
        private Mock <IChannelSourceHandle> CreateMockChannelSource(ServerDescription serverDescription, IChannelHandle channel)
        {
            var mockChannelSource = new Mock <IChannelSourceHandle>();

            mockChannelSource.SetupGet(s => s.ServerDescription).Returns(serverDescription);
            mockChannelSource.Setup(s => s.GetChannel(It.IsAny <CancellationToken>())).Returns(channel);
            mockChannelSource.Setup(s => s.GetChannelAsync(It.IsAny <CancellationToken>())).Returns(Task.FromResult(channel));
            return(mockChannelSource);
        }
        public void PublishDescription(ServerDescription description)
        {
            var server = GetServer(description.EndPoint);

            var oldDescription = server.Description;
            server.Description.Returns(description);

            server.DescriptionChanged += Raise.EventWith(new ServerDescriptionChangedEventArgs(oldDescription, description));
        }
Ejemplo n.º 11
0
        private IChannelSourceHandle CreateFakeChannelSource(ServerDescription serverDescription, IChannelHandle channel)
        {
            var channelSource = Substitute.For <IChannelSourceHandle>();

            channelSource.ServerDescription.Returns(serverDescription);
            channelSource.GetChannel(CancellationToken.None).ReturnsForAnyArgs(channel);
            channelSource.GetChannelAsync(CancellationToken.None).ReturnsForAnyArgs(Task.FromResult(channel));
            return(channelSource);
        }
        public void PublishDescription(ServerDescription description)
        {
            var server = GetServer(description.EndPoint);

            var oldDescription = server.Description;

            server.Description.Returns(description);

            server.DescriptionChanged += Raise.EventWith(new ServerDescriptionChangedEventArgs(oldDescription, description));
        }
Ejemplo n.º 13
0
        public void WithServerDescription_should_add_server_if_server_does_not_exist()
        {
            var subject1             = CreateSubject();
            var newServerDescription = new ServerDescription(new ServerId(__clusterId, new DnsEndPoint("127.0.0.1", 27018)), new DnsEndPoint("127.0.0.1", 27018));
            var subject2             = subject1.WithServerDescription(newServerDescription);

            subject2.Should().NotBeSameAs(subject1);
            subject2.Should().NotBe(subject1);
            subject2.Servers.Count.Should().Be(3);
        }
Ejemplo n.º 14
0
        // private methods
        private ClusterDescription CreateClusterDescription(ClusterType type)
        {
            var clusterId = new ClusterId(1);
            var servers   = new ServerDescription[0];

#pragma warning disable CS0618 // Type or member is obsolete
            return(new ClusterDescription(clusterId, ClusterConnectionMode.Automatic, type, servers));

#pragma warning restore CS0618 // Type or member is obsolete
        }
Ejemplo n.º 15
0
        private void PublishDisconnectedDescription(ICluster cluster, EndPoint endPoint)
        {
            var current = _serverFactory.GetServerDescription(endPoint);

            var serverDescription         = new ServerDescription(current.ServerId, endPoint);
            var currentClusterDescription = cluster.Description;

            _serverFactory.PublishDescription(serverDescription);
            SpinWait.SpinUntil(() => !object.ReferenceEquals(cluster.Description, currentClusterDescription), 100); // sometimes returns false and that's OK
        }
 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);
 }
Ejemplo n.º 17
0
 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, wireVersionRange: new Range<int>(0, 0), type: ServerType.Standalone);
     var servers = new[] { server };
     _clusterDescription = new ClusterDescription(clusterId, connectionMode, clusterType, servers);
 }
Ejemplo n.º 18
0
        // static constructor
        static ClusterDescriptionTests()
        {
            __clusterId = new ClusterId();

            __endPoint1          = new DnsEndPoint("localhost", 27017);
            __endPoint2          = new DnsEndPoint("localhost", 27018);
            __serverId1          = new ServerId(__clusterId, __endPoint1);
            __serverId2          = new ServerId(__clusterId, __endPoint2);
            __serverDescription1 = new ServerDescription(__serverId1, __endPoint1);
            __serverDescription2 = new ServerDescription(__serverId2, __endPoint2);
        }
Ejemplo n.º 19
0
        private IEnumerable <ServerDescription> SelectFreshSecondariesWithPrimary(ServerDescription primary, IEnumerable <ServerDescription> secondaries)
        {
            var p = primary;

            return(secondaries
                   .Where(s =>
            {
                var estimatedStaleness = (s.LastUpdateTimestamp - s.LastWriteTimestamp.Value) - (p.LastUpdateTimestamp - p.LastWriteTimestamp.Value) + s.HeartbeatInterval;
                return estimatedStaleness <= _maxStaleness;
            }));
        }
Ejemplo n.º 20
0
        public IClusterableServer CreateServer(ClusterId clusterId, IClusterClock clusterClock, EndPoint endPoint)
        {
            ServerTuple result;

            if (!_servers.TryGetValue(endPoint, out result))
            {
                var description = new ServerDescription(new ServerId(clusterId, endPoint), endPoint);

                if (_eventSubscriber == null)
                {
                    var mockServer = new Mock <IClusterableServer>()
                    {
                        DefaultValue = DefaultValue.Mock
                    };
                    mockServer.SetupGet(s => s.Description).Returns(description);
                    mockServer.SetupGet(s => s.EndPoint).Returns(endPoint);
                    mockServer.SetupGet(s => s.ServerId).Returns(new ServerId(clusterId, endPoint));
                    result = new ServerTuple
                    {
                        Server = mockServer.Object
                    };
                }
                else
                {
                    var mockMonitorFactory = new Mock <IServerMonitorFactory>();
                    var mockMonitor        = new Mock <IServerMonitor>()
                    {
                        DefaultValue = DefaultValue.Mock
                    };
                    mockMonitorFactory.Setup(f => f.Create(It.IsAny <ServerId>(), It.IsAny <EndPoint>())).Returns(mockMonitor.Object);
                    mockMonitor.SetupGet(m => m.Description).Returns(description);

                    result = new ServerTuple
                    {
                        Server = new Server(
                            clusterId,
                            clusterClock,
                            ClusterConnectionMode.Automatic,
                            new ServerSettings(),
                            endPoint,
                            (new Mock <IConnectionPoolFactory> {
                            DefaultValue = DefaultValue.Mock
                        }).Object,
                            mockMonitorFactory.Object,
                            _eventSubscriber),
                        Monitor = mockMonitor.Object
                    };
                }

                _servers[endPoint] = result;
            }

            return(result.Server);
        }
 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);
 }
Ejemplo n.º 22
0
        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);
        }
Ejemplo n.º 23
0
 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);
 }
        // static constructor
        static ClusterDescriptionTests()
        {
            __clusterId = new ClusterId();

            __endPoint1 = new DnsEndPoint("localhost", 27017);
            __endPoint2 = new DnsEndPoint("localhost", 27018);
            __serverId1 = new ServerId(__clusterId, __endPoint1);
            __serverId2 = new ServerId(__clusterId, __endPoint2);
            __serverDescription1 = new ServerDescription(__serverId1, __endPoint1);
            __serverDescription2 = new ServerDescription(__serverId2, __endPoint2);
        }
Ejemplo n.º 25
0
        public void LogicalSessionTimeout_should_return_expected_result_with_0_servers()
        {
            var clusterId      = new ClusterId(1);
            var connectionMode = ClusterConnectionMode.Automatic;
            var type           = ClusterType.ReplicaSet;
            var servers        = new ServerDescription[0];
            var subject        = new ClusterDescription(clusterId, connectionMode, type, servers);

            var result = subject.LogicalSessionTimeout;

            result.Should().NotHaveValue();
        }
        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 });
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Generate a QR Barcode with the server information
        /// </summary>
        private BitmapSource GenerateBarcode(User auth)
        {
            try
            {
                ServerDescription desc = new ServerDescription();

                desc.QRVersion    = QR_VERSION;
                desc.GeneratorApp = GENERATOR_APP;

                desc.HardwareAddresses = String.Join(";", NetworkInformation.GetMACAddresses());
                desc.Addresses         = String.Join(";", NetworkInformation.GetIPAddresses());
                desc.Name        = Configuration.Services.GetServiceName();
                desc.NetbiosName = System.Environment.MachineName;
                desc.ExternalIp  = ExternalAddress.GetAddress();

                desc.Services = new List <ServiceDescription>();
                User wifiRemoteAuth = WifiRemote.IsInstalled ? WifiRemote.GetAuthentication() : null;
                foreach (var srv in Installation.GetInstalledServices())
                {
                    var srvdesc = new ServiceDescription()
                    {
                        Name = srv.Service,
                        Port = srv.Port
                    };

                    if (auth != null)
                    {
                        srvdesc.User     = (srv.Service == "WifiRemote" ? wifiRemoteAuth : auth).Username;
                        srvdesc.Password = (srv.Service == "WifiRemote" ? wifiRemoteAuth : auth).GetPassword();
                    }

                    desc.Services.Add(srvdesc);
                }

                var writer = new BarcodeWriter()
                {
                    Format  = BarcodeFormat.QR_CODE,
                    Options = new EncodingOptions()
                    {
                        Height = 400,
                        Width  = 400
                    }
                };

                var bitmap = writer.Write(desc.ToJSON());
                return(bitmap.ToWpfBitmap());
            }
            catch (Exception ex)
            {
                Log.Error("Error generating barcode", ex);
                return(null);
            }
        }
        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);
        }
 private static void PrintServerDescription(ServerDescription serverDescription)
 {
     Logger.Info("OptiTrack Server Info:");
     Logger.Info("\tHost: {0}", serverDescription.HostComputerName);
     Logger.Info("\tApplication Name: {0}", serverDescription.HostApp);
     Logger.Info("\tApplication Version: {0}.{1}.{2}.{3}", serverDescription.HostAppVersion[0],
                 serverDescription.HostAppVersion[1], serverDescription.HostAppVersion[2],
                 serverDescription.HostAppVersion[3]);
     Logger.Info("\tNatNet Version: {0}.{1}.{2}.{3}\n", serverDescription.NatNetVersion[0],
                 serverDescription.NatNetVersion[1], serverDescription.NatNetVersion[2],
                 serverDescription.NatNetVersion[3]);
 }
 public void Constructor_with_serverId_and_endPoint_only_should_return_disconnected_instance()
 {
     var subject = new ServerDescription(__serverId, __endPoint);
     subject.AverageRoundTripTime.Should().Be(TimeSpan.Zero);
     subject.EndPoint.Should().Be(__endPoint);
     subject.ReplicaSetConfig.Should().BeNull();
     subject.ServerId.Should().Be(__serverId);
     subject.State.Should().Be(ServerState.Disconnected);
     subject.Tags.Should().BeNull();
     subject.Type.Should().Be(ServerType.Unknown);
     subject.Version.Should().BeNull();
     subject.WireVersionRange.Should().BeNull();
 }
        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 });
        }
        public void CanUseSecondary_should_return_expected_result(int maxWireVersion, bool expectedResult)
        {
            var subject   = new AggregateToCollectionOperation.MayUseSecondary(ReadPreference.Secondary);
            var clusterId = new ClusterId(1);
            var endPoint  = new DnsEndPoint("localhost", 27017);
            var serverId  = new ServerId(clusterId, endPoint);

            var serverDescription = new ServerDescription(serverId, endPoint, wireVersionRange: new Range <int>(0, maxWireVersion));

            var result = subject.CanUseSecondary(serverDescription);

            result.Should().Be(expectedResult);
        }
Ejemplo n.º 33
0
 private void InitChannel()
 {
     Task.Run(async() => { server = await this.serverRouteManager.GetServerRouteAsync(this.serverName, this.group); }).Wait();
     currentClientChannelPool = new ClientChannelPool(
         () => new IChannelHandler[]
     {
         new SimpleEncoder <SimpleRequestMessage>(serializer),
         new SimpleDecoder <SimpleResponseMessage>(serializer),
         new SimpleClientHandler(this)
     },
         server.ClientOptions
         );
 }
 // static constructor
 static ServerDescriptionTests()
 {
     __clusterId = new ClusterId();
     __endPoint = new DnsEndPoint("localhost", 27017);
     __serverId = new ServerId(__clusterId, __endPoint);
     __subject = new ServerDescription(
         __serverId,
         __endPoint,
         state: ServerState.Connected,
         type: ServerType.Standalone,
         averageRoundTripTime: TimeSpan.FromSeconds(1),
         version: new SemanticVersion(2, 6, 3),
         wireVersionRange:  new Range<int>(0, 2));
 }
        public IClusterableServer CreateServer(ClusterId clusterId, EndPoint endPoint)
        {
            IClusterableServer result;
            if(!_servers.TryGetValue(endPoint, out result))
            {
                var description = new ServerDescription(new ServerId(clusterId, endPoint), endPoint);
                _servers[endPoint] = result = Substitute.For<IClusterableServer>();
                result.Description.Returns(description);
                result.EndPoint.Returns(endPoint);
                result.ServerId.Returns(new ServerId(clusterId, endPoint));
            }

            return result;
        }
Ejemplo n.º 36
0
        private Task <TCommandResult> ExecuteProtocolAsync(IChannelHandle channel, ServerDescription serverDescription, ReadPreference readPreference, CancellationToken cancellationToken)
        {
            var wrappedCommand = CreateWrappedCommand(serverDescription, readPreference);
            var slaveOk        = readPreference != null && readPreference.ReadPreferenceMode != ReadPreferenceMode.Primary;

            return(channel.CommandAsync <TCommandResult>(
                       _databaseNamespace,
                       wrappedCommand,
                       _commandValidator,
                       slaveOk,
                       _resultSerializer,
                       _messageEncoderSettings,
                       cancellationToken));
        }
        public IClusterableServer CreateServer(ClusterId clusterId, EndPoint endPoint)
        {
            IClusterableServer result;

            if (!_servers.TryGetValue(endPoint, out result))
            {
                var description = new ServerDescription(new ServerId(clusterId, endPoint), endPoint);
                _servers[endPoint] = result = Substitute.For <IClusterableServer>();
                result.Description.Returns(description);
                result.EndPoint.Returns(endPoint);
                result.ServerId.Returns(new ServerId(clusterId, endPoint));
            }

            return(result);
        }
        public ServerMonitor(ServerId serverId, EndPoint endPoint, IConnectionFactory connectionFactory, TimeSpan interval, TimeSpan timeout, IEventSubscriber eventSubscriber)
        {
            _serverId = Ensure.IsNotNull(serverId, nameof(serverId));
            _endPoint = Ensure.IsNotNull(endPoint, nameof(endPoint));
            _connectionFactory = Ensure.IsNotNull(connectionFactory, nameof(connectionFactory));
            Ensure.IsNotNull(eventSubscriber, nameof(eventSubscriber));

            _baseDescription = _currentDescription = new ServerDescription(_serverId, endPoint);
            _interval = interval;
            _timeout = timeout;
            _state = new InterlockedInt32(State.Initial);
            eventSubscriber.TryGetEventHandler(out _heartbeatStartedEventHandler);
            eventSubscriber.TryGetEventHandler(out _heartbeatSucceededEventHandler);
            eventSubscriber.TryGetEventHandler(out _heartbeatFailedEventHandler);
        }
        public MongoIncompatibleDriverExceptionTests()
        {
            var clusterId = new ClusterId(1);

#pragma warning disable CS0618 // Type or member is obsolete
            var connectionMode = ClusterConnectionMode.Standalone;
#pragma warning restore CS0618 // Type or member is obsolete
            var clusterType = ClusterType.Standalone;
            var endPoint    = new DnsEndPoint("localhost", 27017);
            var serverId    = new ServerId(clusterId, endPoint);
            var server      = new ServerDescription(serverId, endPoint, wireVersionRange: new Range <int>(0, 0), type: ServerType.Standalone);
            var servers     = new[] { server };
#pragma warning disable CS0618 // Type or member is obsolete
            _clusterDescription = new ClusterDescription(clusterId, connectionMode, clusterType, servers);
#pragma warning restore CS0618 // Type or member is obsolete
        }
        public ReadPreferenceServerSelectorTests()
        {
            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") }));

#pragma warning disable CS0618 // Type or member is obsolete
            _description = new ClusterDescription(
                clusterId,
                ClusterConnectionMode.ReplicaSet,
                ClusterType.ReplicaSet,
                new[] { _primary, _secondary1, _secondary2 });
#pragma warning restore CS0618 // Type or member is obsolete
        }
Ejemplo n.º 41
0
        private CursorBatch <TDocument> ExecuteProtocol(IChannelHandle channel, ServerDescription serverDescription, ReadPreference readPreference, bool slaveOk, CancellationToken cancellationToken)
        {
            var command = CreateCommand(serverDescription, readPreference);

            var result = channel.Command <BsonDocument>(
                _collectionNamespace.DatabaseNamespace,
                command,
                NoOpElementNameValidator.Instance,
                () => CommandResponseHandling.Return,
                slaveOk,
                __findCommandResultSerializer,
                _messageEncoderSettings,
                cancellationToken);

            return(CreateCursorBatch(result));
        }
 // static constructor
 static ServerDescriptionTests()
 {
     __clusterId = new ClusterId();
     __endPoint = new DnsEndPoint("localhost", 27017);
     __serverId = new ServerId(__clusterId, __endPoint);
     __subject = new ServerDescription(
         __serverId,
         __endPoint,
         ServerState.Connected,
         ServerType.Standalone,
         TimeSpan.FromSeconds(1),
         null,
         null,
         new SemanticVersion(2, 6, 3),
         new Range<int>(0, 2));
 }
Ejemplo n.º 43
0
        private void VerifyServer(ServerDescription actualServer, BsonDocument expectedServer)
        {
            var type = (string)expectedServer["type"];

            switch (type)
            {
            case "RSPrimary":
                actualServer.Type.Should().Be(ServerType.ReplicaSetPrimary);
                break;

            case "RSSecondary":
                actualServer.Type.Should().Be(ServerType.ReplicaSetSecondary);
                break;

            case "RSArbiter":
                actualServer.Type.Should().Be(ServerType.ReplicaSetArbiter);
                break;

            case "RSGhost":
                actualServer.Type.Should().Be(ServerType.ReplicaSetGhost);
                break;

            case "RSOther":
                actualServer.Type.Should().Be(ServerType.ReplicaSetOther);
                break;

            case "Mongos":
                actualServer.Type.Should().Be(ServerType.ShardRouter);
                break;

            case "Standalone":
                actualServer.Type.Should().Be(ServerType.Standalone);
                break;

            default:
                actualServer.Type.Should().Be(ServerType.Unknown);
                break;
            }

            BsonValue setName;

            if (expectedServer.TryGetValue("setName", out setName) && !setName.IsBsonNull)
            {
                actualServer.ReplicaSetConfig.Should().NotBeNull();
                actualServer.ReplicaSetConfig.Name.Should().Be(setName.ToString());
            }
        }
Ejemplo n.º 44
0
        public IClusterableServer CreateServer(ClusterId clusterId, EndPoint endPoint)
        {
            ServerTuple result;
            if (!_servers.TryGetValue(endPoint, out result))
            {
                var description = new ServerDescription(new ServerId(clusterId, endPoint), endPoint);

                if (_eventSubscriber == null)
                {
                    var server = Substitute.For<IClusterableServer>();
                    server.Description.Returns(description);
                    server.EndPoint.Returns(endPoint);
                    server.ServerId.Returns(new ServerId(clusterId, endPoint));
                    result = new ServerTuple
                    {
                        Server = server
                    };
                }
                else
                {
                    var monitorFactory = Substitute.For<IServerMonitorFactory>();
                    var monitor = Substitute.For<IServerMonitor>();
                    monitorFactory.Create(null, null).ReturnsForAnyArgs(monitor);
                    monitor.Description.Returns(description);

                    result = new ServerTuple
                    {
                        Server = new Server(
                            clusterId,
                            ClusterConnectionMode.Automatic,
                            new ServerSettings(),
                            endPoint,
                            Substitute.For<IConnectionPoolFactory>(),
                            monitorFactory,
                            _eventSubscriber),
                        Monitor = monitor
                    };
                }

                _servers[endPoint] = result;
            }

            return result.Server;
        }
        public IClusterableServer CreateServer(ClusterId clusterId, EndPoint endPoint)
        {
            ServerTuple result;
            if (!_servers.TryGetValue(endPoint, out result))
            {
                var description = new ServerDescription(new ServerId(clusterId, endPoint), endPoint);

                if (_eventSubscriber == null)
                {
                    var mockServer = new Mock<IClusterableServer>() { DefaultValue = DefaultValue.Mock };
                    mockServer.SetupGet(s => s.Description).Returns(description);
                    mockServer.SetupGet(s => s.EndPoint).Returns(endPoint);
                    mockServer.SetupGet(s => s.ServerId).Returns(new ServerId(clusterId, endPoint));
                    result = new ServerTuple
                    {
                        Server = mockServer.Object
                    };
                }
                else
                {
                    var mockMonitorFactory = new Mock<IServerMonitorFactory>();
                    var mockMonitor = new Mock<IServerMonitor>() { DefaultValue = DefaultValue.Mock };
                    mockMonitorFactory.Setup(f => f.Create(It.IsAny<ServerId>(), It.IsAny<EndPoint>())).Returns(mockMonitor.Object);
                    mockMonitor.SetupGet(m => m.Description).Returns(description);

                    result = new ServerTuple
                    {
                        Server = new Server(
                            clusterId,
                            ClusterConnectionMode.Automatic,
                            new ServerSettings(),
                            endPoint,
                            (new Mock<IConnectionPoolFactory> { DefaultValue = DefaultValue.Mock }).Object,
                            mockMonitorFactory.Object,
                            _eventSubscriber),
                        Monitor = mockMonitor.Object
                    };
                }

                _servers[endPoint] = result;
            }

            return result.Server;
        }
 // constructors
 /// <summary>
 /// Initializes a new instance of the <see cref="ServerDescriptionChangedEventArgs"/> class.
 /// </summary>
 /// <param name="oldServerDescription">The old server description.</param>
 /// <param name="newServerDescription">The new server description.</param>
 public ServerDescriptionChangedEventArgs(ServerDescription oldServerDescription, ServerDescription newServerDescription)
 {
     _oldServerDescription = Ensure.IsNotNull(oldServerDescription, nameof(oldServerDescription));
     _newServerDescription = Ensure.IsNotNull(newServerDescription, nameof(newServerDescription));
 }
        public void WithHeartbeat_should_return_same_instance_when_all_fields_are_equal()
        {
            var averageRoundTripTime = TimeSpan.FromSeconds(1);
            var replicaSetConfig = new ReplicaSetConfig(
                new[] { new DnsEndPoint("localhost", 27017), new DnsEndPoint("localhost", 27018) },
                "name",
                new DnsEndPoint("localhost", 27017),
                1);
            var state = ServerState.Connected;
            var tags = new TagSet(new[] { new Tag("x", "a") });
            var type = ServerType.ReplicaSetPrimary;
            var version = new SemanticVersion(2, 6, 3);
            var wireVersionRange = new Range<int>(0, 2);

            var subject = new ServerDescription(
                __serverId,
                __endPoint,
                state: state,
                type: type,
                averageRoundTripTime: averageRoundTripTime,
                replicaSetConfig: replicaSetConfig,
                tags: tags,
                version: version,
                wireVersionRange: wireVersionRange);

            var serverDescription2 = subject.With(
                averageRoundTripTime: averageRoundTripTime,
                replicaSetConfig: replicaSetConfig,
                state: ServerState.Connected,
                tags: tags,
                type: type,
                version: version,
                wireVersionRange: wireVersionRange);

            serverDescription2.Should().BeSameAs(subject);
        }
        private void OnDescriptionChanged(ServerDescription newDescription)
        {
            var oldDescription = Interlocked.CompareExchange(ref _currentDescription, null, null);
            if (oldDescription.Equals(newDescription))
            {
                return;
            }
            Interlocked.Exchange(ref _currentDescription, newDescription);

            var handler = DescriptionChanged;
            if (handler != null)
            {
                var args = new ServerDescriptionChangedEventArgs(oldDescription, newDescription);
                try { handler(this, args); }
                catch { } // ignore exceptions
            }
        }
        public void Equals_should_return_false_when_any_field_is_not_equal(string notEqualField)
        {
            var averageRoundTripTime = TimeSpan.FromSeconds(1);
            var endPoint = new DnsEndPoint("localhost", 27017);
            var replicaSetConfig = new ReplicaSetConfig(
                new[] { new DnsEndPoint("localhost", 27017), new DnsEndPoint("localhost", 27018) },
                "name",
                new DnsEndPoint("localhost", 27017),
                1);
            var serverId = new ServerId(__clusterId, endPoint);
            var state = ServerState.Connected;
            var tags = new TagSet(new[] { new Tag("x", "a") });
            var type = ServerType.ReplicaSetPrimary;
            var version = new SemanticVersion(2, 6, 3);
            var wireVersionRange = new Range<int>(2, 3);

            var subject = new ServerDescription(
                serverId,
                endPoint,
                state,
                type,
                averageRoundTripTime,
                replicaSetConfig,
                tags,
                version,
                wireVersionRange);

            switch (notEqualField)
            {
                case "AverageRoundTripTime": averageRoundTripTime = averageRoundTripTime.Add(TimeSpan.FromSeconds(1)); break;
                case "EndPoint": endPoint = new DnsEndPoint(endPoint.Host, endPoint.Port + 1); serverId = new ServerId(__clusterId, endPoint); break;
                case "ReplicaSetConfig": replicaSetConfig = new ReplicaSetConfig(replicaSetConfig.Members, "newname", replicaSetConfig.Primary, replicaSetConfig.Version); break;
                case "State": state = ServerState.Disconnected; break;
                case "ServerId": serverId = new ServerId(new ClusterId(), endPoint); break;
                case "Tags": tags = new TagSet(new[] { new Tag("x", "b") }); break;
                case "Type": type = ServerType.ReplicaSetSecondary; break;
                case "Version": version = new SemanticVersion(version.Major, version.Minor, version.Patch + 1); break;
                case "WireVersionRange": wireVersionRange = new Range<int>(0, 0); break;
            }

            var serverDescription2 = new ServerDescription(
                serverId,
                endPoint,
                state,
                type,
                averageRoundTripTime,
                replicaSetConfig,
                tags,
                version,
                wireVersionRange);

            subject.Equals(serverDescription2).Should().BeFalse();
            subject.Equals((object)serverDescription2).Should().BeFalse();
            subject.GetHashCode().Should().NotBe(serverDescription2.GetHashCode());
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ServerDescriptionChangedEvent"/> struct.
 /// </summary>
 /// <param name="oldDescription">The old description.</param>
 /// <param name="newDescription">The new description.</param>
 public ServerDescriptionChangedEvent(ServerDescription oldDescription, ServerDescription newDescription)
 {
     _oldDescription = oldDescription;
     _newDescription = newDescription;
 }
        private void PublishDisconnectedDescription(EndPoint endPoint)
        {
            var current = _serverFactory.GetServerDescription(endPoint);

            var description = new ServerDescription(current.ServerId, endPoint);
            _serverFactory.PublishDescription(description);
        }
Ejemplo n.º 52
0
        private void VerifyServer(ServerDescription actualServer, BsonDocument expectedServer)
        {
            var type = (string)expectedServer["type"];
            switch (type)
            {
                case "RSPrimary":
                    actualServer.Type.Should().Be(ServerType.ReplicaSetPrimary);
                    break;
                case "RSSecondary":
                    actualServer.Type.Should().Be(ServerType.ReplicaSetSecondary);
                    break;
                case "RSArbiter":
                    actualServer.Type.Should().Be(ServerType.ReplicaSetArbiter);
                    break;
                case "RSGhost":
                    actualServer.Type.Should().Be(ServerType.ReplicaSetGhost);
                    break;
                case "RSOther":
                    actualServer.Type.Should().Be(ServerType.ReplicaSetOther);
                    break;
                case "Mongos":
                    actualServer.Type.Should().Be(ServerType.ShardRouter);
                    break;
                case "Standalone":
                    actualServer.Type.Should().Be(ServerType.Standalone);
                    break;
                default:
                    actualServer.Type.Should().Be(ServerType.Unknown);
                    break;
            }

            BsonValue setName;
            if (expectedServer.TryGetValue("setName", out setName) && !setName.IsBsonNull)
            {
                actualServer.ReplicaSetConfig.Should().NotBeNull();
                actualServer.ReplicaSetConfig.Name.Should().Be(setName.ToString());
            }
        }
Ejemplo n.º 53
0
        private void PublishDisconnectedDescription(ICluster cluster, EndPoint endPoint)
        {
            var current = _serverFactory.GetServerDescription(endPoint);

            var serverDescription = new ServerDescription(current.ServerId, endPoint);
            var currentClusterDescription = cluster.Description;
            _serverFactory.PublishDescription(serverDescription);
            SpinWait.SpinUntil(() => !object.ReferenceEquals(cluster.Description, currentClusterDescription), 100); // sometimes returns false and that's OK
        }
        private ClusterDescription EnsureServers(ClusterDescription clusterDescription, ServerDescription serverDescription)
        {
            if (serverDescription.Type == ServerType.ReplicaSetPrimary ||
                !clusterDescription.Servers.Any(x => x.Type == ServerType.ReplicaSetPrimary))
            {
                foreach (var endPoint in serverDescription.ReplicaSetConfig.Members)
                {
                    clusterDescription = EnsureServer(clusterDescription, endPoint);
                }
            }

            if (serverDescription.Type == ServerType.ReplicaSetPrimary)
            {
                var requiredEndPoints = serverDescription.ReplicaSetConfig.Members;
                var extraEndPoints = clusterDescription.Servers.Where(x => !EndPointHelper.Contains(requiredEndPoints, x.EndPoint)).Select(x => x.EndPoint);
                foreach (var endPoint in extraEndPoints)
                {
                    clusterDescription = RemoveServer(clusterDescription, endPoint, "Server is not in the host list of the primary.");
                }
            }

            return clusterDescription;
        }
Ejemplo n.º 55
0
        public void A_description_changed_event_with_a_heartbeat_exception_should_clear_the_connection_pool()
        {
            _subject.Initialize();
            var description = new ServerDescription(_subject.ServerId, _subject.EndPoint)
                .With(heartbeatException: new Exception("ughhh"));
            _mockServerMonitor.Raise(m => m.DescriptionChanged += null, new ServerDescriptionChangedEventArgs(description, description));

            _mockConnectionPool.Verify(p => p.Clear(), Times.Once);
        }
 public void Equals_should_return_true_when_all_fields_are_equal()
 {
     ServerDescription subject = new ServerDescription(__serverId, __endPoint);
     ServerDescription serverDescription2 = new ServerDescription(__serverId, __endPoint);
     subject.Equals(serverDescription2).Should().BeTrue();
     subject.Equals((object)serverDescription2).Should().BeTrue();
     subject.GetHashCode().Should().Be(serverDescription2.GetHashCode());
 }
        public void WithHeartbeat_should_return_new_instance_when_a_field_is_not_equal(string notEqualField)
        {
            var averageRoundTripTime = TimeSpan.FromSeconds(1);
            var canonicalEndPoint = new DnsEndPoint("localhost", 27017);
            var electionId = new ElectionId(ObjectId.GenerateNewId());
            var replicaSetConfig = new ReplicaSetConfig(
                new[] { new DnsEndPoint("localhost", 27017), new DnsEndPoint("localhost", 27018) },
                "name",
                new DnsEndPoint("localhost", 27017),
                1);
            var state = ServerState.Connected;
            var tags = new TagSet(new[] { new Tag("x", "a") });
            var type = ServerType.ReplicaSetPrimary;
            var version = new SemanticVersion(2, 6, 3);
            var wireVersionRange = new Range<int>(2, 3);

            var subject = new ServerDescription(
                __serverId,
                __endPoint,
                state: state,
                type: type,
                averageRoundTripTime: averageRoundTripTime,
                electionId: electionId,
                replicaSetConfig: replicaSetConfig,
                tags: tags,
                version: version,
                wireVersionRange: wireVersionRange);

            switch (notEqualField)
            {
                case "AverageRoundTripTime": averageRoundTripTime = averageRoundTripTime.Add(TimeSpan.FromSeconds(1)); break;
                case "CanonicalEndPoint": canonicalEndPoint = new DnsEndPoint("localhost", 27018); break;
                case "ElectionId": electionId = new ElectionId(ObjectId.Empty); break;
                case "ReplicaSetConfig": replicaSetConfig = new ReplicaSetConfig(replicaSetConfig.Members, "newname", replicaSetConfig.Primary, replicaSetConfig.Version); break;
                case "Tags": tags = new TagSet(new[] { new Tag("x", "b") }); break;
                case "Type": type = ServerType.ReplicaSetSecondary; break;
                case "Version": version = new SemanticVersion(version.Major, version.Minor, version.Patch + 1); break;
                case "WireVersionRange": wireVersionRange = new Range<int>(0, 0); break;
            }

            var serverDescription2 = subject.With(
                averageRoundTripTime: averageRoundTripTime,
                canonicalEndPoint: canonicalEndPoint,
                replicaSetConfig: replicaSetConfig,
                state: ServerState.Connected,
                electionId: electionId,
                tags: tags,
                type: type,
                version: version,
                wireVersionRange: wireVersionRange);

            subject.Equals(serverDescription2).Should().BeFalse();
            subject.Equals((object)serverDescription2).Should().BeFalse();
            subject.GetHashCode().Should().NotBe(serverDescription2.GetHashCode());
        }
 public void WithServerDescription_should_add_server_if_server_does_not_exist()
 {
     var subject1 = CreateSubject();
     var newServerDescription = new ServerDescription(new ServerId(__clusterId, new DnsEndPoint("127.0.0.1", 27018)), new DnsEndPoint("127.0.0.1", 27018));
     var subject2 = subject1.WithServerDescription(newServerDescription);
     subject2.Should().NotBeSameAs(subject1);
     subject2.Should().NotBe(subject1);
     subject2.Servers.Count.Should().Be(3);
 }
        public void Constructor_with_multiple_parameters_should_return_properly_initialized_instance()
        {
            var averageRoundTripTime = TimeSpan.FromSeconds(1);
            var canonicalEndPoint = new DnsEndPoint("localhost", 27017);
            var electionId = new ElectionId(ObjectId.GenerateNewId());
            var replicaSetConfig = new ReplicaSetConfig(
                new[] { new DnsEndPoint("localhost", 27017), new DnsEndPoint("localhost", 27018) },
                "name",
                new DnsEndPoint("localhost", 27017),
                1);
            var state = ServerState.Connected;
            var tags = new TagSet(new[] { new Tag("x", "a") });
            var type = ServerType.ReplicaSetPrimary;
            var version = new SemanticVersion(2, 6, 3);
            var wireVersionRange = new Range<int>(2, 3);

            var subject = new ServerDescription(
                __serverId,
                __endPoint,
                state: state,
                type: type,
                averageRoundTripTime: averageRoundTripTime,
                canonicalEndPoint: canonicalEndPoint,
                electionId: electionId,
                replicaSetConfig: replicaSetConfig,
                tags: tags,
                version: version,
                wireVersionRange: wireVersionRange);

            subject.AverageRoundTripTime.Should().Be(TimeSpan.FromSeconds(1));
            subject.CanonicalEndPoint.Should().Be(canonicalEndPoint);
            subject.ElectionId.Should().Be(electionId);
            subject.EndPoint.Should().Be(__endPoint);
            subject.ReplicaSetConfig.Should().Be(replicaSetConfig);
            subject.ServerId.Should().Be(__serverId);
            subject.State.Should().Be(state);
            subject.Tags.Should().Be(tags);
            subject.Type.Should().Be(type);
        }
 // public methods
 public BsonDocument CreateCommand(ServerDescription serverDescription, ReadPreference readPreference)
 {
     var methodInfo = _instance.GetType().GetMethod("CreateCommand", BindingFlags.NonPublic | BindingFlags.Instance);
     return (BsonDocument)methodInfo.Invoke(_instance, new object[] { serverDescription, readPreference });
 }