コード例 #1
0
        async Task <Stream> DownloadCertificate()
        {
            HttpResponseMessage response = await HttpRequest.GetHttpResponse(EndPointHelper.GetCertificateURL());

            Stream stream = await response.Content.ReadAsStreamAsync();

            return(stream);
        }
コード例 #2
0
        public void Me_should_parse_document_correctly(string json, string expectedEndPoint)
        {
            var endPoint = expectedEndPoint == null ? (EndPoint)null : EndPointHelper.Parse(expectedEndPoint);

            var subject = new IsMasterResult(BsonDocument.Parse(json));

            subject.Me.Should().Be(endPoint);
        }
コード例 #3
0
        private void VerifyEvent(BsonDocument content, ServerOpeningEvent @event)
        {
            @event.ClusterId.Should().Be(_cluster.ClusterId);
            var expectedEndPoint = EndPointHelper.Parse(content["address"].ToString());

            EndPointHelper.EndPointEqualityComparer.Equals(@event.ServerId.EndPoint, expectedEndPoint)
            .Should().BeTrue();
        }
コード例 #4
0
 // static methods
 private static string FormatMessage(ConnectionId connectionId, long cursorId)
 {
     return(string.Format(
                "Cursor {0} not found on server {1} using connection {2}.",
                cursorId,
                EndPointHelper.ToString(connectionId.ServerId.EndPoint),
                connectionId.ServerValue));
 }
コード例 #5
0
        // static methods
        internal static MongoWaitQueueFullException ForConnectionPool(EndPoint endPoint)
        {
            var message = string.Format(
                "The wait queue for acquiring a connection to server {0} is full.",
                EndPointHelper.ToString(endPoint));

            return(new MongoWaitQueueFullException(message));
        }
コード例 #6
0
 protected override bool TryGetServer(EndPoint endPoint, out IClusterableServer server)
 {
     lock (_serversLock)
     {
         server = _servers.FirstOrDefault(s => EndPointHelper.Equals(s.EndPoint, endPoint));
         return(server != null);
     }
 }
コード例 #7
0
        private void VerifyEvent(ServerClosedEvent actualEvent, BsonDocument expectedEvent)
        {
            JsonDrivenHelper.EnsureAllFieldsAreValid(expectedEvent, "address", "topologyId");
            var expectedEndPoint = EndPointHelper.Parse(expectedEvent["address"].AsString);

            actualEvent.ClusterId.Should().Be(_cluster.ClusterId);
            actualEvent.ServerId.EndPoint.WithComparer(EndPointHelper.EndPointEqualityComparer).Should().Be(expectedEndPoint);
        }
コード例 #8
0
        // constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="ServerDescription" /> class.
        /// </summary>
        /// <param name="serverId">The server identifier.</param>
        /// <param name="endPoint">The end point.</param>
        /// <param name="reasonChanged">The reason the server description was last changed.</param>
        /// <param name="averageRoundTripTime">The average round trip time.</param>
        /// <param name="canonicalEndPoint">The canonical end point.</param>
        /// <param name="electionId">The election identifier.</param>
        /// <param name="heartbeatException">The heartbeat exception.</param>
        /// <param name="heartbeatInterval">The heartbeat interval.</param>
        /// <param name="helloOk">Whether the server supports the hello command.</param>
        /// <param name="lastHeartbeatTimestamp">The last heartbeat timestamp.</param>
        /// <param name="lastUpdateTimestamp">The last update timestamp.</param>
        /// <param name="lastWriteTimestamp">The last write timestamp.</param>
        /// <param name="logicalSessionTimeout">The logical session timeout.</param>
        /// <param name="maxBatchCount">The maximum batch count.</param>
        /// <param name="maxDocumentSize">The maximum size of a document.</param>
        /// <param name="maxMessageSize">The maximum size of a message.</param>
        /// <param name="maxWireDocumentSize">The maximum size of a wire document.</param>
        /// <param name="replicaSetConfig">The replica set configuration.</param>
        /// <param name="state">The server state.</param>
        /// <param name="tags">The replica set tags.</param>
        /// <param name="topologyVersion">The topology version.</param>
        /// <param name="type">The server type.</param>
        /// <param name="version">The server version.</param>
        /// <param name="wireVersionRange">The wire version range.</param>
        /// <exception cref="ArgumentException">EndPoint and ServerId.EndPoint must match.</exception>
        public ServerDescription(
            ServerId serverId,
            EndPoint endPoint,
            Optional <string> reasonChanged          = default(Optional <string>),
            Optional <TimeSpan> averageRoundTripTime = default(Optional <TimeSpan>),
            Optional <EndPoint> canonicalEndPoint    = default(Optional <EndPoint>),
            Optional <ElectionId> electionId         = default(Optional <ElectionId>),
            Optional <Exception> heartbeatException  = default(Optional <Exception>),
            Optional <TimeSpan> heartbeatInterval    = default(Optional <TimeSpan>),
            Optional <bool> helloOk = default(Optional <bool>),
            Optional <DateTime?> lastHeartbeatTimestamp = default(Optional <DateTime?>),
            Optional <DateTime> lastUpdateTimestamp     = default(Optional <DateTime>),
            Optional <DateTime?> lastWriteTimestamp     = default(Optional <DateTime?>),
            Optional <TimeSpan?> logicalSessionTimeout  = default(Optional <TimeSpan?>),
            Optional <int> maxBatchCount                 = default(Optional <int>),
            Optional <int> maxDocumentSize               = default(Optional <int>),
            Optional <int> maxMessageSize                = default(Optional <int>),
            Optional <int> maxWireDocumentSize           = default(Optional <int>),
            Optional <ReplicaSetConfig> replicaSetConfig = default(Optional <ReplicaSetConfig>),
            Optional <ServerState> state                 = default(Optional <ServerState>),
            Optional <TagSet> tags = default(Optional <TagSet>),
            Optional <TopologyVersion> topologyVersion = default(Optional <TopologyVersion>),
            Optional <ServerType> type               = default(Optional <ServerType>),
            Optional <SemanticVersion> version       = default(Optional <SemanticVersion>),
            Optional <Range <int> > wireVersionRange = default(Optional <Range <int> >))
        {
            Ensure.IsNotNull(endPoint, nameof(endPoint));
            Ensure.IsNotNull(serverId, nameof(serverId));
            if (!EndPointHelper.Equals(endPoint, serverId.EndPoint))
            {
                throw new ArgumentException("EndPoint and ServerId.EndPoint must match.");
            }

            _averageRoundTripTime = averageRoundTripTime.WithDefault(TimeSpan.Zero);
            _canonicalEndPoint    = canonicalEndPoint.WithDefault(null);
            _electionId           = electionId.WithDefault(null);
            _endPoint             = endPoint;
            _heartbeatException   = heartbeatException.WithDefault(null);
            _heartbeatInterval    = heartbeatInterval.WithDefault(TimeSpan.Zero);
            _helloOk = helloOk.WithDefault(false);
            _lastHeartbeatTimestamp = lastHeartbeatTimestamp.WithDefault(null);
            _lastUpdateTimestamp    = lastUpdateTimestamp.WithDefault(DateTime.UtcNow);
            _lastWriteTimestamp     = lastWriteTimestamp.WithDefault(null);
            _logicalSessionTimeout  = logicalSessionTimeout.WithDefault(null);
            _maxBatchCount          = maxBatchCount.WithDefault(1000);
            _maxDocumentSize        = maxDocumentSize.WithDefault(4 * 1024 * 1024);
            _maxMessageSize         = maxMessageSize.WithDefault(Math.Max(_maxDocumentSize + 1024, 16000000));
            _maxWireDocumentSize    = maxWireDocumentSize.WithDefault(_maxDocumentSize + 16 * 1024);
            _reasonChanged          = reasonChanged.WithDefault("NotSpecified");
            _replicaSetConfig       = replicaSetConfig.WithDefault(null);
            _serverId         = serverId;
            _state            = state.WithDefault(ServerState.Disconnected);
            _tags             = tags.WithDefault(null);
            _topologyVersion  = topologyVersion.WithDefault(null);
            _type             = type.WithDefault(ServerType.Unknown);
            _version          = version.WithDefault(null);
            _wireVersionRange = wireVersionRange.WithDefault(null);
        }
コード例 #9
0
        private async Task <List <Attachment> > GetAttachments(Document doc)
        {
            using (var progress = DialogHelper.ShowProgress(AppResources.LOADING_DOCUMENT_INFO))
            {
                var autores = await HttpRequest.GetJson <List <Attachment> >(EndPointHelper.GetDocumentAttachments(doc.Id));

                return(autores);
            }
        }
コード例 #10
0
        public void GetEndPointForService_ProgramNameContainsBundledAndCategoryIsSettlingIn_ShouldReturnDestinationChecklist()
        {
            _service.ServiceType.Category = ServiceCategory.SettlingIn;
            _service.Order.ProgramName    = "Test Bundled Program";

            var endpoint = EndPointHelper.GetEndPointForService(_service);

            endpoint.Should().Be(EndPointHelper.DestinationChecklistEndPoint);
        }
コード例 #11
0
 private ServerId(SerializationInfo info, StreamingContext context)
 {
     _clusterId = (ClusterId)info.GetValue("_clusterId", typeof(ClusterId));
     _endPoint  = EndPointHelper.FromObjectData((List <object>)info.GetValue("_endPoint", typeof(List <object>)));
     _hashCode  = new Hasher()
                  .Hash(_clusterId)
                  .Hash(_endPoint)
                  .GetHashCode();
 }
コード例 #12
0
        public void IsValidHost_should_return_expected_result(string lookupDomainName, string host, bool expectedResult)
        {
            var subject  = CreateSubject(lookupDomainName: lookupDomainName);
            var endPoint = (DnsEndPoint)EndPointHelper.Parse(host);

            var result = subject.IsValidHost(endPoint);

            result.Should().Be(expectedResult);
        }
コード例 #13
0
        private IEnumerable <EndPoint> GetMembers(string elementName)
        {
            if (!_wrapped.Contains(elementName))
            {
                return(new EndPoint[0]);
            }

            return(((BsonArray)_wrapped[elementName]).Select(v => EndPointHelper.Parse((string)v)));
        }
コード例 #14
0
        /// <summary>
        /// returns a newly instantiated host with the given throttling.  The host is in the Uninitialized state.
        /// </summary>
        /// <param name="wireBuilderId"></param>
        /// <param name="port"></param>
        /// <param name="logic"></param>
        /// <param name="maxConnections"></param>
        /// <returns></returns>
        public static IEndPointHost BuildThrottledHost(string wireBuilderId, int port, IEndPointLogic logic, int maxConnections)
        {
            var builder       = EndPointHostBuilder.Instance.GetBuilder(wireBuilderId);
            var ep            = EndPointHelper.GetLocalEndPoint(port);
            var throttleLogic = ThrottleLogic(logic, maxConnections);
            var host          = builder.BuildEndPointHost(ep, throttleLogic);

            return(host);
        }
コード例 #15
0
        private async Task <List <AuthorViewModel> > GetAuthors(Document doc)
        {
            using (var progress = DialogHelper.ShowProgress(AppResources.LOADING_DOCUMENT_INFO))
            {
                var autores = await HttpRequest.GetJson <List <Author> >(EndPointHelper.GetDocumentAuthors(doc.Id));

                return(autores.Select(a => new AuthorViewModel(a)).ToList());
            }
        }
コード例 #16
0
 public void ParseFail()
 {
     Assert.Throws <ArgumentNullException>(() => EndPointHelper.Parse(null));
     Assert.Throws <ArgumentNullException>(() => EndPointHelper.Parse(""));
     Assert.Throws <ArgumentException>(() => EndPointHelper.Parse("host:"));
     Assert.Throws <ArgumentException>(() => EndPointHelper.Parse(":1234"));
     Assert.Throws <ArgumentOutOfRangeException>(() => EndPointHelper.Parse("abcd:-100"));
     Assert.Throws <ArgumentOutOfRangeException>(() => EndPointHelper.Parse("abcd:0"));
 }
コード例 #17
0
ファイル: TestRunner.cs プロジェクト: ideagenplc/mongo-driver
        private void VerifyOutcome(BsonDocument outcome)
        {
            VerifyFields(outcome, "compatible", "logicalSessionTimeoutMinutes", "servers", "setName", "topologyType");

            var expectedTopologyType = (string)outcome["topologyType"];

            VerifyTopology(_cluster, expectedTopologyType);

            var actualDescription = _cluster.Description;

            var actualServers   = actualDescription.Servers.Select(x => x.EndPoint);
            var expectedServers = outcome["servers"].AsBsonDocument.Elements.Select(x => new
            {
                EndPoint    = EndPointHelper.Parse(x.Name),
                Description = (BsonDocument)x.Value
            });

            actualServers.WithComparer(EndPointHelper.EndPointEqualityComparer).Should().BeEquivalentTo(expectedServers.Select(x => x.EndPoint).WithComparer(EndPointHelper.EndPointEqualityComparer));

            foreach (var actualServer in actualDescription.Servers)
            {
                var expectedServer = expectedServers.Single(x => EndPointHelper.EndPointEqualityComparer.Equals(x.EndPoint, actualServer.EndPoint));
                VerifyServerDescription(actualServer, expectedServer.Description);
            }

            if (outcome.Contains("setName"))
            {
                // TODO: assert something against setName
            }

            if (outcome.Contains("logicalSessionTimeoutMinutes"))
            {
                TimeSpan?expectedLogicalSessionTimeout;
                switch (outcome["logicalSessionTimeoutMinutes"].BsonType)
                {
                case BsonType.Null:
                    expectedLogicalSessionTimeout = null;
                    break;

                case BsonType.Int32:
                case BsonType.Int64:
                    expectedLogicalSessionTimeout = TimeSpan.FromMinutes(outcome["logicalSessionTimeoutMinutes"].ToDouble());
                    break;

                default:
                    throw new FormatException($"Invalid logicalSessionTimeoutMinutes BSON type: {outcome["setName"].BsonType}.");
                }
                actualDescription.LogicalSessionTimeout.Should().Be(expectedLogicalSessionTimeout);
            }

            if (outcome.Contains("compatible"))
            {
                var expectedIsCompatibleWithDriver = outcome["compatible"].ToBoolean();
                actualDescription.IsCompatibleWithDriver.Should().Be(expectedIsCompatibleWithDriver);
            }
        }
コード例 #18
0
        private void VerifyEvent(ServerDescriptionChangedEvent actualEvent, BsonDocument expectedEvent)
        {
            VerifyFields(expectedEvent, "address", "newDescription", "previousDescription", "topologyId");
            var expectedEndPoint = EndPointHelper.Parse(expectedEvent["address"].AsString);

            actualEvent.ClusterId.Should().Be(_cluster.ClusterId);
            actualEvent.ServerId.EndPoint.WithComparer(EndPointHelper.EndPointEqualityComparer).Should().Be(expectedEndPoint);
            VerifyServerDescription(actualEvent.OldDescription, expectedEvent["previousDescription"].AsBsonDocument);
            VerifyServerDescription(actualEvent.NewDescription, expectedEvent["newDescription"].AsBsonDocument);
        }
コード例 #19
0
 // methods
 /// <inheritdoc/>
 public bool Equals(ServerId other)
 {
     if (other == null)
     {
         return(false);
     }
     return
         (_clusterId.Equals(other._clusterId) &&
          EndPointHelper.Equals(_endPoint, other._endPoint));
 }
        private void ApplyResponse(BsonArray response)
        {
            if (response.Count != 2)
            {
                throw new FormatException($"Invalid response count: {response.Count}.");
            }

            var address       = response[0].AsString;
            var helloDocument = response[1].AsBsonDocument;
            var expectedNames = new[]
            {
                "arbiterOnly",
                "arbiters",
                "electionId",
                "hidden",
                "hosts",
                "helloOk",
                "isWritablePrimary",
                OppressiveLanguageConstants.LegacyHelloResponseIsWritablePrimaryFieldName,
                "isreplicaset",
                "logicalSessionTimeoutMinutes",
                "maxWireVersion",
                "me",
                "minWireVersion",
                "msg",
                "ok",
                "passive",
                "passives",
                "primary",
                "secondary",
                "setName",
                "setVersion",
                "topologyVersion"
            };

            JsonDrivenHelper.EnsureAllFieldsAreValid(helloDocument, expectedNames);

            var endPoint    = EndPointHelper.Parse(address);
            var helloResult = new HelloResult(helloDocument);
            var currentServerDescription = _serverFactory.GetServerDescription(endPoint);
            var newServerDescription     = currentServerDescription.With(
                canonicalEndPoint: helloResult.Me,
                electionId: helloResult.ElectionId,
                logicalSessionTimeout: helloResult.LogicalSessionTimeout,
                replicaSetConfig: helloResult.GetReplicaSetConfig(),
                state: helloResult.Wrapped.GetValue("ok", false).ToBoolean() ? ServerState.Connected : ServerState.Disconnected,
                topologyVersion: helloResult.TopologyVersion,
                type: helloResult.ServerType,
                wireVersionRange: new Range <int>(helloResult.MinWireVersion, helloResult.MaxWireVersion));

            var currentClusterDescription = _cluster.Description;

            _serverFactory.PublishDescription(newServerDescription);
            SpinWait.SpinUntil(() => !object.ReferenceEquals(_cluster.Description, currentClusterDescription), 100); // sometimes returns false and that's OK
        }
コード例 #21
0
        private void ProcessServerDescriptionChanged(ServerDescriptionChangedEventArgs args)
        {
            var newServers = new List <IClusterableServer>();

            lock (_updateClusterDescriptionLock)
            {
                var newServerDescription  = args.NewServerDescription;
                var newClusterDescription = Description;

                if (!_servers.Any(x => EndPointHelper.Equals(x.EndPoint, newServerDescription.EndPoint)))
                {
                    return;
                }

                if (newServerDescription.State == ServerState.Disconnected)
                {
                    newClusterDescription = newClusterDescription.WithServerDescription(newServerDescription);
                }
                else
                {
                    if (IsServerValidForCluster(newClusterDescription.Type, Settings.ConnectionMode, newServerDescription.Type))
                    {
                        if (newClusterDescription.Type == ClusterType.Unknown)
                        {
                            newClusterDescription = newClusterDescription.WithType(newServerDescription.Type.ToClusterType());
                        }

                        switch (newClusterDescription.Type)
                        {
                        case ClusterType.ReplicaSet:
                            newClusterDescription = ProcessReplicaSetChange(newClusterDescription, args, newServers);
                            break;

                        case ClusterType.Sharded:
                            newClusterDescription = ProcessShardedChange(newClusterDescription, args);
                            break;

                        default:
                            throw new MongoInternalException("Unexpected cluster type.");
                        }
                    }
                    else
                    {
                        newClusterDescription = newClusterDescription.WithoutServerDescription(newServerDescription.EndPoint);
                    }
                }

                UpdateClusterDescription(newClusterDescription);
            }

            foreach (var server in newServers)
            {
                server.Initialize();
            }
        }
コード例 #22
0
 private void AssertServers(List <ServerDescription> actual, List <ServerDescription> expected)
 {
     if (expected.Count == 0)
     {
         actual.Count.Should().Be(0);
     }
     else
     {
         actual.Should().OnlyContain(x => expected.Any(y => EndPointHelper.Equals(x.EndPoint, y.EndPoint)));
     }
 }
コード例 #23
0
        public void GetValidEndPoints_should_return_expected_results(string[] srvEndPoints, string[] validEndPoints)
        {
            var lookupDomainName = "a.b.com";
            var subject          = CreateSubject(lookupDomainName: lookupDomainName);
            var srvRecords       = CreateSrvRecords(srvEndPoints);

            var result = subject.GetValidEndPoints(srvRecords);

            var expectedResult = validEndPoints.Select(x => (DnsEndPoint)EndPointHelper.Parse(x)).ToList();

            result.Should().Equal(expectedResult);
        }
コード例 #24
0
        /// <summary>
        /// Gets the server description.
        /// </summary>
        /// <returns>The server description.</returns>
        public ServerDescription GetServerDescription()
        {
            var serverDescription = _cluster.Description.Servers.FirstOrDefault(s => EndPointHelper.Equals(s.EndPoint, _endPoint));

            if (serverDescription == null)
            {
                throw new InvalidOperationException(string.Format(
                                                        "Cluster does not contain a server with end point: '{0}'.",
                                                        _endPoint));
            }
            return(serverDescription);
        }
コード例 #25
0
        private ClusterSettings ConfigureCluster(ClusterSettings settings, ClusterKey clusterKey)
        {
            var endPoints = clusterKey.Servers.Select(s => EndPointHelper.Parse(s.ToString()));

            return(settings.With(
                       connectionMode: clusterKey.ConnectionMode.ToCore(),
                       endPoints: Optional.Enumerable(endPoints),
                       replicaSetName: clusterKey.ReplicaSetName,
                       maxServerSelectionWaitQueueSize: clusterKey.WaitQueueSize,
                       serverSelectionTimeout: clusterKey.ServerSelectionTimeout,
                       postServerSelector: new LatencyLimitingServerSelector(clusterKey.LocalThreshold)));
        }
コード例 #26
0
        private ClusterDescription ProcessReplicaSetChange(ClusterDescription clusterDescription, ServerDescriptionChangedEventArgs args)
        {
            if (!args.NewServerDescription.Type.IsReplicaSetMember())
            {
                return(RemoveServer(clusterDescription, args.NewServerDescription.EndPoint, string.Format("Server is a {0}, not a replica set member.", args.NewServerDescription.Type)));
            }

            if (args.NewServerDescription.Type == ServerType.ReplicaSetGhost)
            {
                return(clusterDescription.WithServerDescription(args.NewServerDescription));
            }

            if (_replicaSetName == null)
            {
                _replicaSetName = args.NewServerDescription.ReplicaSetConfig.Name;
            }

            if (_replicaSetName != args.NewServerDescription.ReplicaSetConfig.Name)
            {
                return(RemoveServer(clusterDescription, args.NewServerDescription.EndPoint, string.Format("Server was a member of the '{0}' replica set, but should be '{1}'.", args.NewServerDescription.ReplicaSetConfig.Name, _replicaSetName)));
            }

            clusterDescription = clusterDescription.WithServerDescription(args.NewServerDescription);
            clusterDescription = EnsureServers(clusterDescription, args.NewServerDescription);

            if (args.NewServerDescription.Type == ServerType.ReplicaSetPrimary &&
                args.OldServerDescription.Type != ServerType.ReplicaSetPrimary)
            {
                var currentPrimaryEndPoints = clusterDescription.Servers
                                              .Where(x => x.Type == ServerType.ReplicaSetPrimary)
                                              .Where(x => !EndPointHelper.Equals(x.EndPoint, args.NewServerDescription.EndPoint))
                                              .Select(x => x.EndPoint)
                                              .ToList();

                if (currentPrimaryEndPoints.Count > 0)
                {
                    lock (_serversLock)
                    {
                        var currentPrimaries = _servers.Where(x => EndPointHelper.Contains(currentPrimaryEndPoints, x.EndPoint));
                        foreach (var currentPrimary in currentPrimaries)
                        {
                            // kick off the server to invalidate itself
                            currentPrimary.Invalidate();
                            // set it to disconnected in the cluster
                            clusterDescription = clusterDescription.WithServerDescription(
                                new ServerDescription(currentPrimary.ServerId, currentPrimary.EndPoint));
                        }
                    }
                }
            }

            return(clusterDescription);
        }
コード例 #27
0
        private EndPoint GetPrimary()
        {
            BsonValue primary;

            if (_wrapped.TryGetValue("primary", out primary))
            {
                // TODO: what does primary look like when there is no current primary (null, empty string)?
                return(EndPointHelper.Parse((string)primary));
            }

            return(null);
        }
コード例 #28
0
        private ServerDescription BuildServerDescription(BsonDocument serverDescription, TimeSpan heartbeatInterval)
        {
            JsonDrivenHelper.EnsureAllFieldsAreValid(serverDescription, "address", "avg_rtt_ms", "tags", "type", "lastUpdateTime", "lastWrite", "maxWireVersion");

            var    endPoint             = EndPointHelper.Parse(serverDescription["address"].ToString());
            var    averageRoundTripTime = TimeSpan.FromMilliseconds(serverDescription.GetValue("avg_rtt_ms", 0.0).ToDouble());
            var    type   = GetServerType(serverDescription["type"].ToString());
            TagSet tagSet = null;

            if (serverDescription.Contains("tags"))
            {
                tagSet = BuildTagSet((BsonDocument)serverDescription["tags"]);
            }
            DateTime lastWriteTimestamp;

            if (serverDescription.Contains("lastWrite"))
            {
                lastWriteTimestamp = BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(serverDescription["lastWrite"]["lastWriteDate"].ToInt64());
            }
            else
            {
                lastWriteTimestamp = _utcNow;
            }
            var      maxWireVersion   = serverDescription.GetValue("maxWireVersion", 5).ToInt32();
            var      wireVersionRange = new Range <int>(0, maxWireVersion);
            var      serverVersion    = maxWireVersion == 5 ? new SemanticVersion(3, 4, 0) : new SemanticVersion(3, 2, 0);
            DateTime lastUpdateTimestamp;

            if (serverDescription.Contains("lastUpdateTime"))
            {
                lastUpdateTimestamp = BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(serverDescription.GetValue("lastUpdateTime", 0).ToInt64());
            }
            else
            {
                lastUpdateTimestamp = _utcNow;
            }

            var serverId = new ServerId(_clusterId, endPoint);

            return(new ServerDescription(
                       serverId,
                       endPoint,
                       averageRoundTripTime: averageRoundTripTime,
                       type: type,
                       lastUpdateTimestamp: lastUpdateTimestamp,
                       lastWriteTimestamp: lastWriteTimestamp,
                       heartbeatInterval: heartbeatInterval,
                       wireVersionRange: wireVersionRange,
                       version: serverVersion,
                       tags: tagSet,
                       state: ServerState.Connected));
        }
コード例 #29
0
 protected override bool TryGetServer(EndPoint endPoint, out IClusterableServer server)
 {
     if (EndPointHelper.Equals(_server.EndPoint, endPoint))
     {
         server = _server;
         return(true);
     }
     else
     {
         server = null;
         return(false);
     }
 }
コード例 #30
0
        private void ApplyResponse(BsonValue response)
        {
            var server             = (string)response[0];
            var endPoint           = EndPointHelper.Parse(server);
            var isMasterResult     = new IsMasterResult((BsonDocument)response[1]);
            var currentDescription = _serverFactory.GetServerDescription(endPoint);
            var description        = currentDescription.With(
                state: isMasterResult.Wrapped.GetValue("ok", false).ToBoolean() ? ServerState.Connected : ServerState.Disconnected,
                type: isMasterResult.ServerType,
                replicaSetConfig: isMasterResult.GetReplicaSetConfig());

            _serverFactory.PublishDescription(description);
        }