Beispiel #1
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldGracefullyHandleEmptyDiscoveryHeader()
        public virtual void ShouldGracefullyHandleEmptyDiscoveryHeader()
        {
            // Given
            InstanceId me      = new InstanceId(1);
            InstanceId joining = new InstanceId(2);

            CommonContextState commonContextState = mock(typeof(CommonContextState), RETURNS_MOCKS);
            Timeouts           timeouts           = mock(typeof(Timeouts));
            Executor           executor           = mock(typeof(Executor));

            HeartbeatContext heartbeatContext = mock(typeof(HeartbeatContext));

            ClusterContext context = new ClusterContextImpl(me, commonContextState, NullLogProvider.Instance, timeouts, executor, mock(typeof(ObjectOutputStreamFactory)), mock(typeof(ObjectInputStreamFactory)), mock(typeof(LearnerContext)), heartbeatContext, mock(typeof(Config)));

            ClusterMessage.ConfigurationRequestState request = mock(typeof(ClusterMessage.ConfigurationRequestState));
            when(request.JoiningId).thenReturn(joining);

            // When
            // Instance 2 contacts us with a request but it is empty
            context.AddContactingInstance(request, "");

            // Then
            // The discovery header we generate should still contain that instance
            assertEquals("2", context.GenerateDiscoveryHeader());
        }
Beispiel #2
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldUpdateDiscoveryHeaderWithContactingInstances()
        public virtual void ShouldUpdateDiscoveryHeaderWithContactingInstances()
        {
            // Given
            InstanceId me         = new InstanceId(1);
            InstanceId joiningOne = new InstanceId(2);
            InstanceId joiningTwo = new InstanceId(3);

            CommonContextState commonContextState = mock(typeof(CommonContextState), RETURNS_MOCKS);
            Timeouts           timeouts           = mock(typeof(Timeouts));
            Executor           executor           = mock(typeof(Executor));

            HeartbeatContext heartbeatContext = mock(typeof(HeartbeatContext));

            ClusterContext context = new ClusterContextImpl(me, commonContextState, NullLogProvider.Instance, timeouts, executor, mock(typeof(ObjectOutputStreamFactory)), mock(typeof(ObjectInputStreamFactory)), mock(typeof(LearnerContext)), heartbeatContext, mock(typeof(Config)));

            ClusterMessage.ConfigurationRequestState requestOne = mock(typeof(ClusterMessage.ConfigurationRequestState));
            when(requestOne.JoiningId).thenReturn(joiningOne);

            ClusterMessage.ConfigurationRequestState requestTwo = mock(typeof(ClusterMessage.ConfigurationRequestState));
            when(requestTwo.JoiningId).thenReturn(joiningTwo);

            // When
            // Instance 2 contacts us twice and Instance 3 contacts us once
            context.AddContactingInstance(requestOne, "4, 5");                 // discovery headers are random here
            context.AddContactingInstance(requestOne, "4, 5");
            context.AddContactingInstance(requestTwo, "2, 5");

            // Then
            // The discovery header we generate should still contain one copy of each instance
            assertEquals("2,3", context.GenerateDiscoveryHeader());
        }
Beispiel #3
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testSuspicions()
        public virtual void TestSuspicions()
        {
            InstanceId suspect = _instanceIds[1];

            _toTest.suspect(suspect);
            assertEquals(Collections.singleton(suspect), _toTest.getSuspicionsFor(_context.MyId));
            assertEquals(Collections.singletonList(_context.MyId), _toTest.getSuspicionsOf(suspect));
            // Being suspected by just one (us) is not enough
            assertFalse(_toTest.isFailedBasedOnSuspicions(suspect));
            assertTrue(_toTest.alive(suspect));                   // This resets the suspicion above

            // If we suspect an instance twice in a row, it shouldn't change its status in any way.
            _toTest.suspect(suspect);
            _toTest.suspect(suspect);
            assertEquals(Collections.singleton(suspect), _toTest.getSuspicionsFor(_context.MyId));
            assertEquals(Collections.singletonList(_context.MyId), _toTest.getSuspicionsOf(suspect));
            assertFalse(_toTest.isFailedBasedOnSuspicions(suspect));
            assertTrue(_toTest.alive(suspect));

            // The other one sends suspicions too
            InstanceId newSuspiciousBastard = _instanceIds[2];

            _toTest.suspicions(newSuspiciousBastard, Collections.singleton(suspect));
            _toTest.suspect(suspect);
            // Now two instances suspect it, it should be reported failed
            assertEquals(Collections.singleton(suspect), _toTest.getSuspicionsFor(_context.MyId));
            assertEquals(Collections.singleton(suspect), _toTest.getSuspicionsFor(newSuspiciousBastard));
            IList <InstanceId> suspiciousBastards = new List <InstanceId>(2);

            suspiciousBastards.Add(_context.MyId);
            suspiciousBastards.Add(newSuspiciousBastard);
            assertEquals(suspiciousBastards, _toTest.getSuspicionsOf(suspect));
            assertTrue(_toTest.isFailedBasedOnSuspicions(suspect));
            assertTrue(_toTest.alive(suspect));
        }
Beispiel #4
0
        /*
         * This test ensures that an instance that is marked as failed has its elector version reset. This means that
         * the instance, once it comes back, will still be able to do elections even if it lost state
         */
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void nonElectorFailingMustNotCauseElectorVersionToBeReset()
        public virtual void NonElectorFailingMustNotCauseElectorVersionToBeReset()
        {
            // Given
            InstanceId me      = new InstanceId(1);
            InstanceId elector = new InstanceId(2);

            CommonContextState commonContextState = mock(typeof(CommonContextState), RETURNS_MOCKS);
            Timeouts           timeouts           = mock(typeof(Timeouts));
            Executor           executor           = mock(typeof(Executor));

            HeartbeatContext heartbeatContext = mock(typeof(HeartbeatContext));

            ArgumentCaptor <HeartbeatListener> listenerCaptor = ArgumentCaptor.forClass(typeof(HeartbeatListener));

            ClusterContext context = new ClusterContextImpl(me, commonContextState, NullLogProvider.Instance, timeouts, executor, mock(typeof(ObjectOutputStreamFactory)), mock(typeof(ObjectInputStreamFactory)), mock(typeof(LearnerContext)), heartbeatContext, mock(typeof(Config)));

            verify(heartbeatContext).addHeartbeatListener(listenerCaptor.capture());

            HeartbeatListener theListener = listenerCaptor.Value;

            // This means instance 2 was the elector at version 8
            context.LastElector        = elector;
            context.LastElectorVersion = 8;

            // When
            theListener.Failed(new InstanceId(3));

            // Then
            assertEquals(context.LastElector, elector);
            assertEquals(context.LastElectorVersion, 8);
        }
 /// <summary>
 ///     This constructor creates a new XiList element and sets its state to NewValue.
 /// </summary>
 /// <param name="clientAlias"> The client alias to be assigned to this list element. </param>
 /// <param name="instanceId"> The InstanceId for this list element. </param>
 protected XiDataAndDataJournalListItemBase(uint clientAlias, InstanceId instanceId)
 {
     ClientAlias = clientAlias;
     InstanceId  = new InstanceId(instanceId);
     ServerAlias = 0;
     ResultCode  = 0xFFFFFFFFu;
 }
Beispiel #6
0
        public static ClusterInstance NewClusterInstance(InstanceId id, URI uri, Monitors monitors, ClusterConfiguration configuration, int maxSurvivableFailedMembers, LogProvider logging)
        {
            MultiPaxosServerFactory factory = new MultiPaxosServerFactory(configuration, logging, monitors.NewMonitor(typeof(StateMachines.Monitor)));

            ClusterInstanceInput  input  = new ClusterInstanceInput();
            ClusterInstanceOutput output = new ClusterInstanceOutput(uri);

            ObjectStreamFactory objStreamFactory = new ObjectStreamFactory();

            ProverTimeouts timeouts = new ProverTimeouts(uri);

            InMemoryAcceptorInstanceStore acceptorInstances = new InMemoryAcceptorInstanceStore();

            Config config = mock(typeof(Config));

            when(config.Get(ClusterSettings.max_acceptors)).thenReturn(maxSurvivableFailedMembers);

            DelayedDirectExecutor executor = new DelayedDirectExecutor(logging);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.cluster.protocol.atomicbroadcast.multipaxos.context.MultiPaxosContext context = new org.neo4j.cluster.protocol.atomicbroadcast.multipaxos.context.MultiPaxosContext(id, org.neo4j.helpers.collection.Iterables.iterable(new org.neo4j.cluster.protocol.election.ElectionRole(org.neo4j.cluster.protocol.cluster.ClusterConfiguration.COORDINATOR)), new org.neo4j.cluster.protocol.cluster.ClusterConfiguration(configuration.getName(), logging, configuration.getMemberURIs()), executor, logging, objStreamFactory, objStreamFactory, acceptorInstances, timeouts, new org.neo4j.kernel.ha.cluster.DefaultElectionCredentialsProvider(id, new StateVerifierLastTxIdGetter(), new MemberInfoProvider()), config);
            MultiPaxosContext context = new MultiPaxosContext(id, Iterables.iterable(new ElectionRole(ClusterConfiguration.COORDINATOR)), new ClusterConfiguration(configuration.Name, logging, configuration.MemberURIs), executor, logging, objStreamFactory, objStreamFactory, acceptorInstances, timeouts, new DefaultElectionCredentialsProvider(id, new StateVerifierLastTxIdGetter(), new MemberInfoProvider()), config);

            context.ClusterContext.BoundAt = uri;

            SnapshotContext snapshotContext = new SnapshotContext(context.ClusterContext, context.LearnerContext);

            DelayedDirectExecutor taskExecutor = new DelayedDirectExecutor(logging);
            ProtocolServer        ps           = factory.NewProtocolServer(id, input, output, DirectExecutor, taskExecutor, timeouts, context, snapshotContext);

            return(new ClusterInstance(DirectExecutor, logging, factory, ps, context, acceptorInstances, timeouts, input, output, uri));
        }
Beispiel #7
0
        public override bool Process <T1>(Message <T1> message) where T1 : Org.Neo4j.cluster.com.message.MessageType
        {
            if (!message.Internal && !message.MessageType.Equals(HeartbeatMessage.IAmAlive) && !message.MessageType.Equals(HeartbeatMessage.Suspicions))
            {
                // We assume the HEADER_FROM header always exists.
                string from = message.GetHeader(Message.HEADER_FROM);
                if (!from.Equals(message.GetHeader(Message.HEADER_TO)))
                {
                    InstanceId theId;
                    if (message.HasHeader(Message.HEADER_INSTANCE_ID))
                    {
                        // HEADER_INSTANCE_ID is there since after 1.9.6
                        theId = new InstanceId(int.Parse(message.GetHeader(Message.HEADER_INSTANCE_ID)));
                    }
                    else
                    {
                        theId = _clusterContext.Configuration.getIdForUri(URI.create(from));
                    }

                    if (theId != null && _clusterContext.Configuration.Members.ContainsKey(theId) && !_clusterContext.isMe(theId))
                    {
                        Message <HeartbeatMessage> heartbeatMessage = message.CopyHeadersTo(Message.@internal(HeartbeatMessage.IAmAlive, new HeartbeatMessage.IAmAliveState(theId)), Message.HEADER_FROM, Message.HEADER_INSTANCE_ID);
                        _output.offer(heartbeatMessage);
                    }
                }
            }
            return(true);
        }
Beispiel #8
0
        public override void Elected(string roleName, InstanceId instanceId, InstanceId electorId, long version)
        {
            if (electorId != null)
            {
                if (electorId.Equals(MyId))
                {
                    GetLog(this.GetType()).debug("I elected instance " + instanceId + " for role " + roleName + " at version " + version);
                    if (version < _electorVersion)
                    {
                        return;
                    }
                }
                else if (electorId.Equals(_lastElector) && (version < _electorVersion && version > 1))
                {
                    GetLog(this.GetType()).warn("Election result for role " + roleName + " received from elector instance " + electorId + " with version " + version + ". I had version " + _electorVersion + " for elector " + _lastElector);
                    return;
                }
                else
                {
                    GetLog(this.GetType()).debug("Setting elector to " + electorId + " and its version to " + version);
                }

                this._electorVersion = version;
                this._lastElector    = electorId;
            }
            CommonState.configuration().elected(roleName, instanceId);
            _clusterListeners.notify(_executor, listener => listener.elected(roleName, instanceId, CommonState.configuration().getUriForId(instanceId)));
        }
Beispiel #9
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void delayedVoteFromPreviousElectionMustNotCauseCurrentElectionToComplete() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void DelayedVoteFromPreviousElectionMustNotCauseCurrentElectionToComplete()
        {
            // Given
            ElectionContext context = mock(typeof(ElectionContext));
            MessageHolder   holder  = mock(typeof(MessageHolder));

            when(context.GetLog(Mockito.any())).thenReturn(NullLog.Instance);

            const string role = "master";
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.cluster.InstanceId voter = new org.neo4j.cluster.InstanceId(2);
            InstanceId voter = new InstanceId(2);

            ElectionCredentials       voteCredentialComparable = mock(typeof(ElectionCredentials));
            Message <ElectionMessage> vote = Message.@internal(voted, new ElectionMessage.VersionedVotedData(role, voter, voteCredentialComparable, 4));

            when(context.Voted(role, voter, voteCredentialComparable, 4)).thenReturn(false);

            // When
            election.handle(context, vote, holder);

            verify(context).getLog(ArgumentMatchers.any());
            verify(context).voted(role, voter, voteCredentialComparable, 4);

            // Then
            verifyNoMoreInteractions(context, holder);
        }
Beispiel #10
0
            internal virtual void SwitchToSlave(InstanceId me)
            {
                InstanceId someOneElseThanMyself = new InstanceId(me.ToIntegerIndex() + 1);

                Listener.memberIsAvailable("master", someOneElseThanMyself, URI.create("cluster://127.0.0.1:2390?serverId=2"), null);
                Listener.memberIsAvailable("slave", me, null, null);
            }
Beispiel #11
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void whenInToSlaveStateLosingQuorumShouldPutInPending()
        public virtual void WhenInToSlaveStateLosingQuorumShouldPutInPending()
        {
            // Given
            InstanceId me    = new InstanceId(1);
            InstanceId other = new InstanceId(2);
            HighAvailabilityMemberContext context = new SimpleHighAvailabilityMemberContext(me, false);
            AvailabilityGuard             guard   = mock(typeof(DatabaseAvailabilityGuard));
            ObservedClusterMembers        members = MockClusterMembers(me, emptyList(), singletonList(other));

            ClusterMemberEvents            events = mock(typeof(ClusterMemberEvents));
            ClusterMemberListenerContainer memberListenerContainer = MockAddClusterMemberListener(events);

            HighAvailabilityMemberStateMachine stateMachine = BuildMockedStateMachine(context, events, members, guard);

            stateMachine.Init();
            ClusterMemberListener memberListener = memberListenerContainer.Get();
            HAStateChangeListener probe          = new HAStateChangeListener();

            stateMachine.AddHighAvailabilityMemberListener(probe);

            // Send it to MASTER
            memberListener.MemberIsAvailable(MASTER, other, URI.create("ha://whatever"), StoreId.DEFAULT);

            assertThat(stateMachine.CurrentState, equalTo(HighAvailabilityMemberState.ToSlave));

            // When
            memberListener.MemberIsFailed(new InstanceId(2));

            // Then
            assertThat(stateMachine.CurrentState, equalTo(HighAvailabilityMemberState.Pending));
            assertThat(probe.InstanceStopsConflict, @is(false));
            assertThat(probe.InstanceDetachedConflict, @is(true));
            verify(guard, times(1)).require(any(typeof(AvailabilityRequirement)));
        }
Beispiel #12
0
        /*
         * This test ensures that an instance that cleanly leaves the cluster but is not the elector has no effect on
         * elector id and last version
         */
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void nonElectorLeavingTheClusterMustNotAffectElectorInformation()
        public virtual void NonElectorLeavingTheClusterMustNotAffectElectorInformation()
        {
            // Given
            InstanceId me      = new InstanceId(1);
            InstanceId elector = new InstanceId(2);
            InstanceId other   = new InstanceId(3);

            ClusterConfiguration clusterConfiguration = mock(typeof(ClusterConfiguration));

            when(clusterConfiguration.GetUriForId(other)).thenReturn(URI.create("cluster://instance2"));

            CommonContextState commonContextState = mock(typeof(CommonContextState));

            when(commonContextState.Configuration()).thenReturn(clusterConfiguration);

            ClusterContext context = new ClusterContextImpl(me, commonContextState, NullLogProvider.Instance, mock(typeof(Timeouts)), mock(typeof(Executor)), mock(typeof(ObjectOutputStreamFactory)), mock(typeof(ObjectInputStreamFactory)), mock(typeof(LearnerContext)), mock(typeof(HeartbeatContext)), mock(typeof(Config)));

            // This means instance 2 was the elector at version 8
            context.LastElector        = elector;
            context.LastElectorVersion = 8;

            // When
            context.Left(other);

            // Then
            assertEquals(context.LastElector, elector);
            assertEquals(context.LastElectorVersion, 8);
        }
Beispiel #13
0
        public void WriteXml(XmlWriter writer)
        {
            writer.WriteStartElement("SceneObject");
            writer.WriteAttributeString("id", Id);
            writer.WriteAttributeString("instanceId", InstanceId.ToString());

            writer.WriteStartElement("Transform");
            writer.WriteAttributeString("position", XmlUtils.Vector3ToString(Transform.LocalPosition));
            writer.WriteAttributeString("rotation", XmlUtils.Vector4ToString(Transform.LocalRotation.ToAxisAngle()));
            writer.WriteAttributeString("scale", XmlUtils.Vector3ToString(Transform.LocalScale));
            writer.WriteEndElement();


            foreach (Component c in Components)
            {
                c.WriteXml(writer);
            }

            for (int i = 0; i < ChildCount; ++i)
            {
                GetChild(i).WriteXml(writer);
            }


            writer.WriteEndElement();
        }
Beispiel #14
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void whenInMasterStateLosingQuorumFromTwoInstancesShouldRemainMaster()
        public virtual void WhenInMasterStateLosingQuorumFromTwoInstancesShouldRemainMaster()
        {
            // Given
            InstanceId me    = new InstanceId(1);
            InstanceId other = new InstanceId(2);
            HighAvailabilityMemberContext context = new SimpleHighAvailabilityMemberContext(me, false);

            AvailabilityGuard      guard   = mock(typeof(DatabaseAvailabilityGuard));
            ObservedClusterMembers members = MockClusterMembers(me, emptyList(), singletonList(other));

            ClusterMemberEvents            events = mock(typeof(ClusterMemberEvents));
            ClusterMemberListenerContainer memberListenerContainer = MockAddClusterMemberListener(events);

            HighAvailabilityMemberStateMachine stateMachine = BuildMockedStateMachine(context, events, members, guard);

            stateMachine.Init();
            ClusterMemberListener memberListener = memberListenerContainer.Get();
            HAStateChangeListener probe          = new HAStateChangeListener();

            stateMachine.AddHighAvailabilityMemberListener(probe);

            // Send it to MASTER
            memberListener.CoordinatorIsElected(me);
            memberListener.MemberIsAvailable(MASTER, me, URI.create("ha://whatever"), StoreId.DEFAULT);

            assertThat(stateMachine.CurrentState, equalTo(HighAvailabilityMemberState.Master));

            // When
            memberListener.MemberIsFailed(new InstanceId(2));

            // Then
            assertThat(stateMachine.CurrentState, equalTo(HighAvailabilityMemberState.Master));
            assertThat(probe.InstanceStopsConflict, @is(false));
            assertThat(probe.InstanceDetachedConflict, @is(false));
        }
Beispiel #15
0
            public override void CoordinatorIsElected(InstanceId coordinatorId)
            {
                lock (this)
                {
                    try
                    {
                        HighAvailabilityMemberState oldState = outerInstance.state;
                        InstanceId previousElected           = outerInstance.context.ElectedMasterId;

                        outerInstance.context.AvailableHaMasterId = null;
                        if (!AcceptNewState(outerInstance.state.masterIsElected(outerInstance.context, coordinatorId)))
                        {
                            return;
                        }

                        outerInstance.context.ElectedMasterId = coordinatorId;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final HighAvailabilityMemberChangeEvent event = new HighAvailabilityMemberChangeEvent(oldState, state, coordinatorId, null);
                        HighAvailabilityMemberChangeEvent @event = new HighAvailabilityMemberChangeEvent(oldState, outerInstance.state, coordinatorId, null);
                        outerInstance.memberListeners.Notify(listener => listener.masterIsElected(@event));

                        if (oldState.AccessAllowed && oldState != outerInstance.state)
                        {
                            outerInstance.databaseAvailabilityGuard.Require(AvailabilityRequirement);
                        }

                        outerInstance.log.Debug("Got masterIsElected(" + coordinatorId + "), moved to " + outerInstance.state + " from " + oldState + ". Previous elected master is " + previousElected);
                    }
                    catch (Exception t)
                    {
                        throw new Exception(t);
                    }
                }
            }
Beispiel #16
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (InstanceId != 0)
            {
                hash ^= InstanceId.GetHashCode();
            }
            if (deck_ != null)
            {
                hash ^= Deck.GetHashCode();
            }
            if (Gold != 0)
            {
                hash ^= Gold.GetHashCode();
            }
            if (Food != 0)
            {
                hash ^= Food.GetHashCode();
            }
            hash ^= items_.GetHashCode();
            hash ^= equips_.GetHashCode();
            hash ^= buffs_.GetHashCode();
            return(hash);
        }
Beispiel #17
0
 private HeartbeatContextImpl(InstanceId me, CommonContextState commonState, LogProvider logging, Timeouts timeouts, ISet <InstanceId> failed, IDictionary <InstanceId, ISet <InstanceId> > nodeSuspicions, Listeners <HeartbeatListener> heartBeatListeners, Executor executor) : base(me, commonState, logging, timeouts)
 {
     this._failed             = failed;
     this._nodeSuspicions     = nodeSuspicions;
     this._heartBeatListeners = heartBeatListeners;
     this._executor           = executor;
 }
Beispiel #18
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldFailAndAliveBothNotifyHeartbeatListenerInDelayedDirectExecutor()
        public virtual void ShouldFailAndAliveBothNotifyHeartbeatListenerInDelayedDirectExecutor()
        {
            // Given
            InstanceId me            = new InstanceId(1);
            InstanceId failedMachine = new InstanceId(2);
            InstanceId goodMachine   = new InstanceId(3);

            Timeouts timeouts = mock(typeof(Timeouts));

            CommonContextState   commonState   = mock(typeof(CommonContextState));
            ClusterConfiguration configuration = mock(typeof(ClusterConfiguration));

            when(commonState.Configuration()).thenReturn(configuration);
            when(configuration.Members).thenReturn(members(3));
            when(configuration.MemberIds).thenReturn(ids(3));

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.List<Runnable> runnables = new java.util.ArrayList<>();
            IList <ThreadStart> runnables = new List <ThreadStart>();
            HeartbeatContext    context   = new HeartbeatContextImpl(me, commonState, NullLogProvider.Instance, timeouts, new DelayedDirectExecutorAnonymousInnerClass(this, NullLogProvider.Instance, runnables));

            context.AddHeartbeatListener(mock(typeof(HeartbeatListener)));

            context.Suspicions(goodMachine, new HashSet <InstanceId>(singletonList(failedMachine)));
            context.Suspect(failedMachine);               // fail
            context.Alive(failedMachine);                 // alive

            // Then
            assertEquals(2, runnables.Count);                 // fail + alive
        }
Beispiel #19
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void majorityOfNonSuspectedInstancesShouldBeEnoughToMarkAnInstanceAsFailed()
        public virtual void MajorityOfNonSuspectedInstancesShouldBeEnoughToMarkAnInstanceAsFailed()
        {
            // Given
            InstanceId me      = new InstanceId(1);
            InstanceId member2 = new InstanceId(2);
            InstanceId member3 = new InstanceId(3);
            InstanceId member4 = new InstanceId(4);
            InstanceId member5 = new InstanceId(5);

            Timeouts timeouts = mock(typeof(Timeouts));

            CommonContextState   commonState   = mock(typeof(CommonContextState));
            ClusterConfiguration configuration = mock(typeof(ClusterConfiguration));

            when(commonState.Configuration()).thenReturn(configuration);
            when(configuration.Members).thenReturn(members(5));
            when(configuration.MemberIds).thenReturn(ids(5));

            DelayedDirectExecutor executor = new DelayedDirectExecutor(NullLogProvider.Instance);
            HeartbeatContext      context  = new HeartbeatContextImpl(me, commonState, NullLogProvider.Instance, timeouts, executor);

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.List<org.neo4j.cluster.InstanceId> failed = new java.util.ArrayList<>(4);
            IList <InstanceId> failed   = new List <InstanceId>(4);
            HeartbeatListener  listener = new HeartbeatListenerAnonymousInnerClass2(this, failed);

            context.AddHeartbeatListener(listener);

            // when
            // just two suspicions come, no extra failing action should be taken since this is not majority
            context.Suspect(member2);
            context.Suspect(member3);
            executor.Drain();

            // then
            assertEquals(0, failed.Count);

            // when
            // the another instance suspects them, therefore have a majority of non suspected, then 2 and 3 must fail
            ISet <InstanceId> suspicionsFrom5 = new HashSet <InstanceId>();

            suspicionsFrom5.Add(member2);
            suspicionsFrom5.Add(member3);
            context.Suspicions(member5, suspicionsFrom5);
            executor.Drain();

            // then
            assertEquals(2, failed.Count);
            assertTrue(failed.Contains(member2));
            assertTrue(failed.Contains(member3));

            // when
            // an instance sends a heartbeat, it should be set as alive
            context.Alive(member2);
            executor.Drain();

            // then
            assertEquals(1, failed.Count);
            assertTrue(failed.Contains(member3));
        }
Beispiel #20
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void whenInSlaveStateLosingOtherSlaveShouldNotPutInPending()
        public virtual void WhenInSlaveStateLosingOtherSlaveShouldNotPutInPending()
        {
            // Given
            InstanceId me         = new InstanceId(1);
            InstanceId master     = new InstanceId(2);
            InstanceId otherSlave = new InstanceId(3);
            HighAvailabilityMemberContext context = new SimpleHighAvailabilityMemberContext(me, false);
            AvailabilityGuard             guard   = mock(typeof(DatabaseAvailabilityGuard));
            ObservedClusterMembers        members = MockClusterMembers(me, singletonList(master), singletonList(otherSlave));

            ClusterMemberEvents            events = mock(typeof(ClusterMemberEvents));
            ClusterMemberListenerContainer memberListenerContainer = MockAddClusterMemberListener(events);

            HighAvailabilityMemberStateMachine stateMachine = BuildMockedStateMachine(context, events, members, guard);

            stateMachine.Init();
            ClusterMemberListener memberListener = memberListenerContainer.Get();
            HAStateChangeListener probe          = new HAStateChangeListener();

            stateMachine.AddHighAvailabilityMemberListener(probe);

            // Send it to MASTER
            memberListener.MemberIsAvailable(MASTER, master, URI.create("ha://whatever"), StoreId.DEFAULT);
            memberListener.MemberIsAvailable(SLAVE, me, URI.create("ha://whatever3"), StoreId.DEFAULT);
            memberListener.MemberIsAvailable(SLAVE, otherSlave, URI.create("ha://whatever2"), StoreId.DEFAULT);

            assertThat(stateMachine.CurrentState, equalTo(HighAvailabilityMemberState.Slave));

            // When
            memberListener.MemberIsFailed(otherSlave);

            // Then
            assertThat(stateMachine.CurrentState, equalTo(HighAvailabilityMemberState.Slave));
            assertThat(probe.InstanceStopsConflict, @is(false));
        }
Beispiel #21
0
 public ClusterMember(InstanceId instanceId, IDictionary <string, URI> roles, StoreId storeId, bool alive)
 {
     this._instanceId = instanceId;
     this._roles      = roles;
     this._storeId    = storeId;
     this._alive      = alive;
 }
Beispiel #22
0
            public override void MemberIsFailed(InstanceId instanceId)
            {
                // If we don't have quorum anymore with the currently alive members, then go to pending

                /*
                 * Unless this is a two instance cluster and we are the MASTER. This is an edge case in which a cluster
                 * of two instances gets a partition and we want to maintain write capability on one side.
                 * This, in combination with use of slave_only, is a cheap way to provide quasi-read-replica
                 * functionality for HA under the 2-instance scenario.
                 */
                if (!isQuorum(AliveCount, TotalCount) && !(TotalCount == 2 && outerInstance.state == HighAvailabilityMemberState.Master))
                {
                    HighAvailabilityMemberState oldState = outerInstance.state;
                    ChangeStateToDetached();
                    outerInstance.log.Debug("Got memberIsFailed(" + instanceId + ") and cluster lost quorum to continue, moved to " + outerInstance.state + " from " + oldState + ", while maintaining read only capability.");
                }
                else if (instanceId.Equals(outerInstance.context.ElectedMasterId) && outerInstance.state == HighAvailabilityMemberState.Slave)
                {
                    HighAvailabilityMemberState oldState = outerInstance.state;
                    ChangeStateToDetached();
                    outerInstance.log.Debug("Got memberIsFailed(" + instanceId + ") which was the master and i am a slave, moved to " + outerInstance.state + " from " + oldState + ", while maintaining read only capability.");
                }
                else
                {
                    outerInstance.log.Debug("Got memberIsFailed(" + instanceId + ")");
                }
            }
Beispiel #23
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldIgnoreSuspicionsForOurselves() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldIgnoreSuspicionsForOurselves()
        {
            // Given
            InstanceId           instanceId    = new InstanceId(1);
            HeartbeatState       heartbeat     = HeartbeatState.Heartbeat;
            ClusterConfiguration configuration = new ClusterConfiguration("whatever", NullLogProvider.Instance, "cluster://1", "cluster://2");

            configuration.Joined(instanceId, URI.create("cluster://1"));
            configuration.Joined(new InstanceId(2), URI.create("cluster://2"));

            Config config = mock(typeof(Config));

            when(config.Get(ClusterSettings.max_acceptors)).thenReturn(10);

            MultiPaxosContext context = new MultiPaxosContext(instanceId, iterable(new ElectionRole("coordinator")), configuration, Mockito.mock(typeof(Executor)), NullLogProvider.Instance, Mockito.mock(typeof(ObjectInputStreamFactory)), Mockito.mock(typeof(ObjectOutputStreamFactory)), Mockito.mock(typeof(AcceptorInstanceStore)), Mockito.mock(typeof(Timeouts)), mock(typeof(ElectionCredentialsProvider)), config);

            HeartbeatContext heartbeatContext = context.HeartbeatContext;
            Message          received         = Message.@internal(HeartbeatMessage.Suspicions, new HeartbeatMessage.SuspicionsState(asSet(iterable(instanceId))));

            received.setHeader(Message.HEADER_FROM, "cluster://2").SetHeader(Message.HEADER_INSTANCE_ID, "2");

            // When
            heartbeat.handle(heartbeatContext, received, mock(typeof(MessageHolder)));

            // Then
            assertThat(heartbeatContext.GetSuspicionsOf(instanceId).Count, equalTo(0));
        }
Beispiel #24
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (accessPointsConfig_ != null)
            {
                hash ^= AccessPointsConfig.GetHashCode();
            }
            if (SessKey.Length != 0)
            {
                hash ^= SessKey.GetHashCode();
            }
            if (InstanceId != 0L)
            {
                hash ^= InstanceId.GetHashCode();
            }
            if (sdkOption_ != null)
            {
                hash ^= SdkOption.GetHashCode();
            }
            if (accessPointsCOnfigIpv6_ != null)
            {
                hash ^= AccessPointsCOnfigIpv6.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
Beispiel #25
0
        public void OnNewEntity(Safir.Dob.EntityProxy entityProxy)
        {
            Consoden.TankGame.GameState gameState = entityProxy.Entity as Consoden.TankGame.GameState;
            if (gameState == null)
            {
                return;
            }

            for (int i = 0; i < gameState.Tanks.Count; i++)
            {
                if (!gameState.Tanks [i].IsNull())
                {
                    Consoden.TankGame.Tank tank = gameState.Tanks [i].Obj;
                    if (tank.PlayerId.Val == myPlayerId)
                    {
                        currentGameId = entityProxy.InstanceId;
                        myTankId      = tank.TankId.Val;
                        myJoystickId  = InstanceId.GenerateRandom();

                        Consoden.TankGame.Joystick joystick = new Consoden.TankGame.Joystick();
                        joystickCounter       = 0;
                        joystick.PlayerId.Val = myPlayerId;
                        joystick.GameId.Val   = currentGameId;
                        joystick.TankId.Val   = myTankId;
                        joystick.Counter.Val  = joystickCounter++;
                        connection.SetAll(joystick, myJoystickId, myHandlerId);
                        logic = new TankLogic(myTankId, UpdateJoystick);
                        break;
                    }
                }
            }
        }
Beispiel #26
0
 public override void Failed(InstanceId server)
 {
     foreach (KeyValuePair <string, Election> ongoingElection in _elections.SetOfKeyValuePairs())
     {
         ongoingElection.Value.Votes.remove(server);
     }
 }
Beispiel #27
0
        public void Run()
        {
            var ctx    = System.Threading.SynchronizationContext.Current;
            var client = new WebClient();
            var data   = new JObject();

            data["instanceId"] = InstanceId.ToString("N");
            data["ports"]      = new JArray(Ports);
            var succeeded = false;
            var stopwatch = new System.Diagnostics.Stopwatch();

            int[] response_ports = null;
            try {
                stopwatch.Start();
                var body          = System.Text.Encoding.UTF8.GetBytes(data.ToString());
                var response_body = System.Text.Encoding.UTF8.GetString(client.UploadData(Target, body));
                var response      = JToken.Parse(response_body);
                response_ports = response["ports"].Select(token => (int)token).ToArray();
                stopwatch.Stop();
                succeeded = true;
            }
            catch (WebException) {
                succeeded = false;
            }
            if (PortCheckCompleted != null)
            {
                PortCheckCompleted(
                    this,
                    new PortCheckCompletedEventArgs(
                        succeeded,
                        response_ports,
                        stopwatch.Elapsed));
            }
        }
Beispiel #28
0
 public StateMachineProxyFactory(StateMachines stateMachines, StateMachineConversations conversations, InstanceId me, LogProvider logProvider)
 {
     this._stateMachines = stateMachines;
     this._conversations = conversations;
     this._me            = me;
     this._log           = logProvider.getLog(this.GetType());
 }
Beispiel #29
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void substituteFailedNodeAndFailedComesOnlineAgain() throws java.net.URISyntaxException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void SubstituteFailedNodeAndFailedComesOnlineAgain()
        {
            IList <URI> correctMembers = new List <URI>();

            correctMembers.Add(URI.create("server1"));
            correctMembers.Add(URI.create("server2"));
            correctMembers.Add(URI.create("server4"));

            IList <URI> badMembers = new List <URI>();

            badMembers.Add(URI.create("server1"));
            badMembers.Add(URI.create("server2"));
            badMembers.Add(URI.create("server3"));

            IDictionary <string, InstanceId> roles = new Dictionary <string, InstanceId>();

            roles["coordinator"] = new InstanceId(1);

            ISet <InstanceId> clusterMemberFailed  = new HashSet <InstanceId>();            // no failures
            ISet <InstanceId> isolatedMemberFailed = new HashSet <InstanceId>();

            isolatedMemberFailed.Add(new InstanceId(1));                   // will never receive heartbeats again from 1,2 so they are failed
            isolatedMemberFailed.Add(new InstanceId(2));

            TestCluster(new int[] { 1, 2, 3, 3 }, new VerifyInstanceConfiguration[] { new VerifyInstanceConfiguration(correctMembers, roles, clusterMemberFailed), new VerifyInstanceConfiguration(correctMembers, roles, clusterMemberFailed), new VerifyInstanceConfiguration(badMembers, roles, isolatedMemberFailed), new VerifyInstanceConfiguration(correctMembers, roles, clusterMemberFailed) }, DefaultNetwork(), (new ClusterTestScriptDSL(this)).Rounds(800).join(100, 1, 1).join(100, 2, 1).join(100, 3, 1).down(3000, 3).join(1000, 4, 1, 2, 3).up(1000, 3));
        }
Beispiel #30
0
 public override void Alive(InstanceId server)
 {
     if (outerInstance.members.ContainsKey(server))
     {
         outerInstance.members[server] = outerInstance.getMember(server).Alive();
     }
 }
Beispiel #31
0
        public Player(string playerName)
        {
            //This players unique identifiers
            myHandlerId = new HandlerId (playerName + "Handler");
            myPlayerId = new InstanceId (playerName + "Instance");

            // Open DOB connection. Register player and joystick, subscribe for gameStates
            connection.Open (playerName, "", 0, this, this);
            connection.RegisterEntityHandler (Consoden.TankGame.Player.ClassTypeId, myHandlerId, Safir.Dob.InstanceIdPolicy.Enumeration.HandlerDecidesInstanceId, this);
            connection.RegisterEntityHandler (Consoden.TankGame.Joystick.ClassTypeId, myHandlerId, Safir.Dob.InstanceIdPolicy.Enumeration.HandlerDecidesInstanceId, this);
            connection.SubscribeEntity (Consoden.TankGame.GameState.ClassTypeId, this);

            //Create our player entity
            Consoden.TankGame.Player player = new Consoden.TankGame.Player ();
            player.Name.Val = playerName;
            connection.SetAll (player, myPlayerId, myHandlerId);

            //Run the game player
            Run ();
        }
Beispiel #32
0
        public void OnDeletedEntity(Safir.Dob.EntityProxy entityProxy, bool deprecated)
        {
            if (entityProxy.TypeId == Consoden.TankGame.GameState.ClassTypeId &&
                entityProxy.InstanceId == currentGameId) {
                if (myJoystickId != null) {
                    connection.Delete (new EntityId (Consoden.TankGame.Joystick.ClassTypeId, myJoystickId), myHandlerId);
                }

                logic = null;
                myJoystickId = null;
                currentGameId = null;
                myTankId = -1;
            }
        }
Beispiel #33
0
        public void OnNewEntity(Safir.Dob.EntityProxy entityProxy)
        {
            Consoden.TankGame.GameState gameState = entityProxy.Entity as Consoden.TankGame.GameState;
            if (gameState == null) {
                return;
            }

            for (int i=0; i<gameState.Tanks.Count; i++) {
                if (!gameState.Tanks [i].IsNull ()) {
                    Consoden.TankGame.Tank tank = gameState.Tanks [i].Obj;
                    if (tank.PlayerId.Val == myPlayerId) {
                        currentGameId = entityProxy.InstanceId;
                        myTankId = tank.TankId.Val;
                        myJoystickId = InstanceId.GenerateRandom ();

                        Consoden.TankGame.Joystick joystick = new Consoden.TankGame.Joystick ();
                        joystickCounter = 0;
                        joystick.PlayerId.Val = myPlayerId;
                        joystick.GameId.Val = currentGameId;
                        joystick.TankId.Val = myTankId;
                        joystick.Counter.Val = joystickCounter++;
                        connection.SetAll (joystick, myJoystickId, myHandlerId);
                        logic = new TankLogic (myTankId, UpdateJoystick);
                        break;
                    }
                }
            }
        }