public void CompareTo_should_return_the_correct_value(string oidA, string oidB, int result) { var subject1 = new ElectionId(ObjectId.Parse(oidA)); ElectionId subject2 = oidB == null ? (ElectionId)null : new ElectionId(ObjectId.Parse(oidB)); subject1.CompareTo(subject2).Should().Be(result); }
public void Equals_should_return_false_if_any_field_is_not_equal() { var subject1 = new ElectionId(ObjectId.Empty); var subject2 = new ElectionId(ObjectId.GenerateNewId()); subject1.Equals(subject2).Should().BeFalse(); subject1.Equals((object)subject2).Should().BeFalse(); subject1.GetHashCode().Should().NotBe(subject2.GetHashCode()); }
public void Equals_should_return_true_if_all_fiels_are_equal() { var subject1 = new ElectionId(ObjectId.Empty); var subject2 = new ElectionId(ObjectId.Empty); subject1.Equals(subject2).Should().BeTrue(); subject1.Equals((object)subject2).Should().BeTrue(); subject1.GetHashCode().Should().Be(subject2.GetHashCode()); }
// 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); }
public void EndElection(ElectionId electionId) { ManagementCommand command = GetManagementCommand(ConfigurationCommandUtil.MethodName.EndElection, 1); command.Parameters.AddParameter(electionId); ExecuteCommandOnConfigurationServer(command, false); }
public void EndElection(ElectionId electionId) { try { this.service.EndElection(this.cluster, this.shard, electionId); NotifyConfigurationChange(this.cluster); } catch (System.Exception ex) { } }
public void UpdateElectionId(string cluster, string shard, ElectionId electionId) { lock (this) { if (_configurationStore.GetMembershipData(cluster, shard) != null) { _configurationStore.GetMembershipData(cluster, shard).ElectionId = electionId; _configurationStore.InsertOrUpdateMembershipData(_configurationStore.GetMembershipData(cluster, shard)); } } }
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 helloOk = true; var logicalSessionTimeout = TimeSpan.FromMinutes(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(3, 6, 0); var wireVersionRange = new Range <int>(6, 14); var subject = new ServerDescription( __serverId, __endPoint, state: state, type: type, averageRoundTripTime: averageRoundTripTime, canonicalEndPoint: canonicalEndPoint, electionId: electionId, helloOk: helloOk, logicalSessionTimeout: logicalSessionTimeout, 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.HelloOk.Should().Be(helloOk); subject.LogicalSessionTimeout.Should().Be(logicalSessionTimeout); 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); }
// 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="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="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="type">The server type.</param> /// <param name="version">The server version.</param> /// <param name="wireVersionRange">The wire version range.</param> /// <exception cref="System.ArgumentException">EndPoint and ServerId.EndPoint must match.</exception> public ServerDescription( ServerId serverId, EndPoint endPoint, 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 <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 <ServerType> type = default(Optional <ServerType>), Optional <SemanticVersion> version = default(Optional <SemanticVersion>), Optional <Range <int> > wireVersionRange = default(Optional <Range <int> >)) { Ensure.IsNotNull(endPoint, "endPoint"); Ensure.IsNotNull(serverId, "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); _maxBatchCount = maxBatchCount.WithDefault(1000); _maxDocumentSize = maxDocumentSize.WithDefault(4 * 1024 * 1024); _maxMessageSize = maxMessageSize.WithDefault(Math.Max(_maxDocumentSize + 1024, 16000000)); _maxWireDocumentSize = maxWireDocumentSize.WithDefault(_maxDocumentSize + 16 * 1024); _replicaSetConfig = replicaSetConfig.WithDefault(null); _serverId = serverId; _state = state.WithDefault(ServerState.Disconnected); _tags = tags.WithDefault(null); _type = type.WithDefault(ServerType.Unknown); _version = version.WithDefault(null); _wireVersionRange = wireVersionRange.WithDefault(null); }
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 ElectionInfo(int setVersion, ElectionId electionId) { _setVersion = setVersion; _electionId = electionId; }
public void With_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 heartbeatException = new Exception(); var heartbeatInterval = TimeSpan.FromSeconds(10); var lastUpdateTimestamp = DateTime.UtcNow; var lastWriteTimestamp = DateTime.UtcNow; var logicalSessionTimeout = TimeSpan.FromMinutes(1); var maxBatchCount = 1000; var maxDocumentSize = 16000000; var maxMessageSize = 48000000; var maxWireDocumentSize = 16000000; 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, averageRoundTripTime: averageRoundTripTime, canonicalEndPoint: canonicalEndPoint, electionId: electionId, heartbeatException: heartbeatException, heartbeatInterval: heartbeatInterval, lastUpdateTimestamp: lastUpdateTimestamp, lastWriteTimestamp: lastWriteTimestamp, logicalSessionTimeout: logicalSessionTimeout, maxBatchCount: maxBatchCount, maxDocumentSize: maxDocumentSize, maxMessageSize: maxMessageSize, maxWireDocumentSize: maxWireDocumentSize, replicaSetConfig: replicaSetConfig, state: state, tags: tags, type: type, 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 "HeartbeatException": heartbeatException = new Exception(); break; case "HeartbeatInterval": heartbeatInterval = TimeSpan.FromSeconds(11); break; case "LastUpdateTimestamp": lastUpdateTimestamp = lastUpdateTimestamp.Add(TimeSpan.FromSeconds(1)); break; case "LastWriteTimestamp": lastWriteTimestamp = lastWriteTimestamp.Add(TimeSpan.FromSeconds(1)); break; case "LogicalSessionTimeout": logicalSessionTimeout = TimeSpan.FromMinutes(2); break; case "MaxBatchCount": maxBatchCount += 1; break; case "MaxDocumentSize": maxDocumentSize += 1; break; case "MaxMessageSize": maxMessageSize += 1; break; case "MaxWireDocumentSize": maxWireDocumentSize += 1; break; case "ReplicaSetConfig": replicaSetConfig = new ReplicaSetConfig(replicaSetConfig.Members, "newname", replicaSetConfig.Primary, replicaSetConfig.Version); break; case "State": state = ServerState.Disconnected; 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 result = subject.With( averageRoundTripTime: averageRoundTripTime, canonicalEndPoint: canonicalEndPoint, electionId: electionId, heartbeatException: heartbeatException, heartbeatInterval: heartbeatInterval, lastUpdateTimestamp: lastUpdateTimestamp, lastWriteTimestamp: lastWriteTimestamp, logicalSessionTimeout: logicalSessionTimeout, maxBatchCount: maxBatchCount, maxDocumentSize: maxDocumentSize, maxMessageSize: maxMessageSize, maxWireDocumentSize: maxWireDocumentSize, replicaSetConfig: replicaSetConfig, state: state, tags: tags, type: type, version: version, wireVersionRange: wireVersionRange); result.Should().NotBeSameAs(subject); result.Equals(subject).Should().BeFalse(); result.Equals((object)subject).Should().BeFalse(); result.GetHashCode().Should().NotBe(subject.GetHashCode()); }
public void Equals_should_return_false_when_any_field_is_not_equal(string notEqualField) { var averageRoundTripTime = TimeSpan.FromSeconds(1); var canonicalEndPoint = new DnsEndPoint("localhost", 27017); var electionId = new ElectionId(ObjectId.GenerateNewId()); var endPoint = new DnsEndPoint("localhost", 27017); var logicalSessionTimeout = TimeSpan.FromMinutes(1); 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: state, type: type, averageRoundTripTime: averageRoundTripTime, canonicalEndPoint: canonicalEndPoint, logicalSessionTimeout: logicalSessionTimeout, 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 "EndPoint": endPoint = new DnsEndPoint(endPoint.Host, endPoint.Port + 1); serverId = new ServerId(__clusterId, endPoint); break; case "LogicalSessionTimeout": logicalSessionTimeout = TimeSpan.FromMinutes(2); 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: state, type: type, averageRoundTripTime: averageRoundTripTime, canonicalEndPoint: canonicalEndPoint, electionId: electionId, logicalSessionTimeout: logicalSessionTimeout, replicaSetConfig: replicaSetConfig, tags: tags, version: version, wireVersionRange: wireVersionRange); subject.Equals(serverDescription2).Should().BeFalse(); subject.Equals((object)serverDescription2).Should().BeFalse(); subject.GetHashCode().Should().NotBe(serverDescription2.GetHashCode()); }
private void VerifyServerDescription(ServerDescription actualDescription, BsonDocument expectedDescription) { VerifyFields(expectedDescription, "electionId", "setName", "setVersion", "type"); var expectedType = (string)expectedDescription["type"]; switch (expectedType) { case "RSPrimary": actualDescription.Type.Should().Be(ServerType.ReplicaSetPrimary); break; case "RSSecondary": actualDescription.Type.Should().Be(ServerType.ReplicaSetSecondary); break; case "RSArbiter": actualDescription.Type.Should().Be(ServerType.ReplicaSetArbiter); break; case "RSGhost": actualDescription.Type.Should().Be(ServerType.ReplicaSetGhost); break; case "RSOther": actualDescription.Type.Should().Be(ServerType.ReplicaSetOther); break; case "Mongos": actualDescription.Type.Should().Be(ServerType.ShardRouter); break; case "Standalone": actualDescription.Type.Should().Be(ServerType.Standalone); break; default: actualDescription.Type.Should().Be(ServerType.Unknown); break; } if (expectedDescription.Contains("setName")) { string expectedSetName; switch (expectedDescription["setName"].BsonType) { case BsonType.Null: expectedSetName = null; break; case BsonType.String: expectedSetName = expectedDescription["setName"].AsString;; break; default: throw new FormatException($"Invalid setName BSON type: {expectedDescription["setName"].BsonType}."); } actualDescription.ReplicaSetConfig?.Name.Should().Be(expectedSetName); } if (expectedDescription.Contains("setVersion")) { int?expectedSetVersion; switch (expectedDescription["setVersion"].BsonType) { case BsonType.Null: expectedSetVersion = null; break; case BsonType.Int32: case BsonType.Int64: expectedSetVersion = expectedDescription["setVersion"].ToInt32(); break; default: throw new FormatException($"Invalid setVersion BSON type: {expectedDescription["setVersion"].BsonType}."); } actualDescription.ReplicaSetConfig?.Version.Should().Be(expectedSetVersion); } if (expectedDescription.Contains("electionId")) { ElectionId expectedElectionId; switch (expectedDescription["electionId"].BsonType) { case BsonType.Null: expectedElectionId = null; break; case BsonType.ObjectId: expectedElectionId = new ElectionId(expectedDescription["electionId"].AsObjectId); break; default: throw new FormatException($"Invalid electionId BSON type: {expectedDescription["electionId"].BsonType}."); } actualDescription.ElectionId.Should().Be(expectedElectionId); } }
private void VerifyServerDescription(ServerDescription actualDescription, BsonDocument expectedDescription, string phaseDescription) { JsonDrivenHelper.EnsureAllFieldsAreValid(expectedDescription, "electionId", "pool", "setName", "setVersion", "topologyVersion", "type"); var expectedType = (string)expectedDescription["type"]; switch (expectedType) { case "RSPrimary": actualDescription.Type.Should().Be(ServerType.ReplicaSetPrimary); break; case "RSSecondary": actualDescription.Type.Should().Be(ServerType.ReplicaSetSecondary); break; case "RSArbiter": actualDescription.Type.Should().Be(ServerType.ReplicaSetArbiter); break; case "RSGhost": actualDescription.Type.Should().Be(ServerType.ReplicaSetGhost); break; case "RSOther": actualDescription.Type.Should().Be(ServerType.ReplicaSetOther); break; case "Mongos": actualDescription.Type.Should().Be(ServerType.ShardRouter); break; case "Standalone": actualDescription.Type.Should().Be(ServerType.Standalone); break; default: actualDescription.Type.Should().Be(ServerType.Unknown); break; } if (expectedDescription.Contains("setName")) { string expectedSetName; switch (expectedDescription["setName"].BsonType) { case BsonType.Null: expectedSetName = null; break; case BsonType.String: expectedSetName = expectedDescription["setName"].AsString;; break; default: throw new FormatException($"Invalid setName BSON type: {expectedDescription["setName"].BsonType}."); } actualDescription.ReplicaSetConfig?.Name.Should().Be(expectedSetName); } if (expectedDescription.Contains("setVersion")) { int?expectedSetVersion; switch (expectedDescription["setVersion"].BsonType) { case BsonType.Null: expectedSetVersion = null; break; case BsonType.Int32: case BsonType.Int64: expectedSetVersion = expectedDescription["setVersion"].ToInt32(); break; default: throw new FormatException($"Invalid setVersion BSON type: {expectedDescription["setVersion"].BsonType}."); } actualDescription.ReplicaSetConfig?.Version.Should().Be(expectedSetVersion); } if (expectedDescription.Contains("electionId")) { ElectionId expectedElectionId; switch (expectedDescription["electionId"].BsonType) { case BsonType.Null: expectedElectionId = null; break; case BsonType.ObjectId: expectedElectionId = new ElectionId(expectedDescription["electionId"].AsObjectId); break; default: throw new FormatException($"Invalid electionId BSON type: {expectedDescription["electionId"].BsonType}."); } actualDescription.ElectionId.Should().Be(expectedElectionId); } if (expectedDescription.TryGetValue("topologyVersion", out var topologyVersionValue)) { switch (topologyVersionValue) { case BsonDocument topologyVersion: TopologyVersion expectedTopologyType = TopologyVersion.FromBsonDocument(topologyVersion); expectedTopologyType.Should().NotBeNull(); actualDescription.TopologyVersion.Should().Be(expectedTopologyType, phaseDescription); break; case BsonNull _: actualDescription.TopologyVersion.Should().BeNull(); break; default: throw new FormatException($"Invalid topologyVersion BSON type: {topologyVersionValue.BsonType}."); } } }
public void ToString_should_return_string_representation() { var subject = new ElectionId(ObjectId.Empty); subject.ToString().Should().Be(ObjectId.Empty.ToString()); }
public void EndElection(ElectionId electionId) { _shardSession.EndElection(electionId); }
private void PublishDescription(ICluster cluster, EndPoint endPoint, ServerType serverType, IEnumerable<EndPoint> hosts = null, string setName = null, EndPoint primary = null, ElectionId electionId = null, EndPoint canonicalEndPoint = null, int? setVersion = null) { var current = _serverFactory.GetServerDescription(endPoint); var config = new ReplicaSetConfig( hosts ?? new[] { _firstEndPoint, _secondEndPoint, _thirdEndPoint }, setName ?? "test", primary, setVersion); var serverDescription = current.With( averageRoundTripTime: TimeSpan.FromMilliseconds(10), replicaSetConfig: serverType.IsReplicaSetMember() ? config : null, canonicalEndPoint: canonicalEndPoint, electionId: electionId, state: ServerState.Connected, tags: null, type: serverType, version: new SemanticVersion(2, 6, 3), wireVersionRange: new Range<int>(0, int.MaxValue)); var currentClusterDescription = cluster.Description; _serverFactory.PublishDescription(serverDescription); SpinWait.SpinUntil(() => !object.ReferenceEquals(cluster.Description, currentClusterDescription), 100); // sometimes returns false and that's OK }
private void PublishDescription(EndPoint endPoint, ServerType serverType, IEnumerable<EndPoint> hosts = null, string setName = null, EndPoint primary = null, ElectionId electionId = null, EndPoint canonicalEndPoint = null) { var current = _serverFactory.GetServerDescription(endPoint); var config = new ReplicaSetConfig( hosts ?? new[] { _firstEndPoint, _secondEndPoint, _thirdEndPoint }, setName ?? "test", primary, null); var description = current.With( averageRoundTripTime: TimeSpan.FromMilliseconds(10), replicaSetConfig: serverType.IsReplicaSetMember() ? config : null, canonicalEndPoint: canonicalEndPoint, electionId: electionId, state: ServerState.Connected, tags: null, type: serverType, version: new SemanticVersion(2, 6, 3), wireVersionRange: new Range<int>(0, int.MaxValue)); _serverFactory.PublishDescription(description); }
public bool IsStale(int setVersion, ElectionId electionId) { if (_setVersion < setVersion) { return true; } if (_setVersion > setVersion) { return false; } if (_electionId == null) { return true; } return _electionId.CompareTo(electionId) <= 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.CanonicalEndPoint != null && !EndPointHelper.Equals(args.NewServerDescription.CanonicalEndPoint, args.NewServerDescription.EndPoint)) { return RemoveServer(clusterDescription, args.NewServerDescription.EndPoint, "CanonicalEndPoint is different than seed list EndPoint."); } if (args.NewServerDescription.Type == ServerType.ReplicaSetPrimary) { if (args.NewServerDescription.ElectionId != null) { if (_maxElectionId != null && _maxElectionId.CompareTo(args.NewServerDescription.ElectionId) > 0) { // ignore this change because we've already seen this election id lock (_serversLock) { var server = _servers.SingleOrDefault(x => EndPointHelper.Equals(args.NewServerDescription.EndPoint, x.EndPoint)); server.Invalidate(); return clusterDescription.WithServerDescription( new ServerDescription(server.ServerId, server.EndPoint)); } } _maxElectionId = args.NewServerDescription.ElectionId; } 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; }
public void EndElection(string cluster, string shard, ElectionId electionId) { _session.EndElection(cluster, shard, electionId); }
internal Configuration.Services.ElectionResult ConductElection(ElectionId electionId, Address[] activeNodes, Activity activity) { Address[] votingNodes = null; if (activeNodes == null) { throw new ArgumentNullException("Active nodes are null"); } Election election = null; if (votingNodes == null) { votingNodes = new Address[activeNodes.Length]; } try { ElectionType electionType = ElectionType.None; if (activity == Activity.GeneralElectionsTriggered) { electionType = ElectionType.GeneralElections; } else if (activity == Activity.TakeoverElectionsTriggered) { electionType = ElectionType.TakeoverElections; } election = new Election(electionId, electionType); votingNodes = activeNodes; election.RequestingServerInfo = LocalServerInfo(); if (election.StartElection(votingNodes)) { ResponseCollection <object> response = (ResponseCollection <object>)MulticastRequest(election); if (response != null) { foreach (var server in _shard.ActiveChannelsList) { IClusterResponse <object> serverResponse = response.GetResponse(server); if (serverResponse.IsSuccessfull) { if (serverResponse.Value != null) { ElectionVote vote = serverResponse.Value as ElectionVote; if (vote != null) { election.AddVote(vote); } } } } } return(election.GetElectionResult()); } } catch (Exception e) { if (LoggerManager.Instance.ShardLogger != null && LoggerManager.Instance.ShardLogger.IsErrorEnabled) { LoggerManager.Instance.ShardLogger.Error("ElectionManager.ConductElection()", e.ToString()); } } return(null); }
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()); }