Example #1
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public static boolean inconsistentCommittedLogEntries(ClusterState state) throws java.io.IOException
        public static bool InconsistentCommittedLogEntries(ClusterState state)
        {
            int  index   = 0;
            bool moreLog = true;

            while (moreLog)
            {
                moreLog = false;
                RaftLogEntry clusterLogEntry = null;
                foreach (ComparableRaftState memberState in state.States.Values)
                {
                    if (index <= memberState.CommitIndex())
                    {
                        RaftLogEntry memberLogEntry = readLogEntry(memberState.EntryLog(), index);
                        if (clusterLogEntry == null)
                        {
                            clusterLogEntry = memberLogEntry;
                        }
                        else
                        {
                            if (!clusterLogEntry.Equals(memberLogEntry))
                            {
                                return(true);
                            }
                        }
                    }
                    if (index < memberState.CommitIndex())
                    {
                        moreLog = true;
                    }
                }
                index++;
            }
            return(false);
        }
Example #2
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldNeverUseMapAgainAfterHavingFallenBackToTheRaftLog() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldNeverUseMapAgainAfterHavingFallenBackToTheRaftLog()
        {
            // given
            InFlightLogEntryReader reader = new InFlightLogEntryReader(_raftLog, _inFlightCache, ClearCache);

            StartingFromIndexReturnEntries(_inFlightCache, _logIndex, _entry, null, mock(typeof(RaftLogEntry)));
            RaftLogEntry[] entries = new RaftLogEntry[] { _entry, mock(typeof(RaftLogEntry)), mock(typeof(RaftLogEntry)) };
            StartingFromIndexReturnEntries(_raftLog, _logIndex + 1, entries[1], entries[2]);

            for (int offset = 0; offset < 3; offset++)
            {
                // when
                RaftLogEntry raftLogEntry = reader.Get(offset + _logIndex);

                // then
                assertEquals(entries[offset], raftLogEntry);

                if (offset <= 1)
                {
                    verify(_inFlightCache).get(offset + _logIndex);
                }

                if (offset == 1)
                {
                    verify(_raftLog).getEntryCursor(offset + _logIndex);
                }

                AssertCacheIsUpdated(_inFlightCache, offset + _logIndex);
            }

            verifyNoMoreInteractions(_inFlightCache);
            verifyNoMoreInteractions(_raftLog);
        }
Example #3
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public synchronized void write(long logIndex, org.neo4j.causalclustering.core.consensus.log.RaftLogEntry entry) throws java.io.IOException
        public virtual void Write(long logIndex, RaftLogEntry entry)
        {
            lock (this)
            {
                EntryRecord.write(OrCreateWriter, _contentMarshal, logIndex, entry.Term(), entry.Content());
            }
        }
Example #4
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldStepDownIfAppendEntriesRequestFromLaterTerm() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldStepDownIfAppendEntriesRequestFromLaterTerm()
        {
            // given
            long leaderTerm        = 1;
            long leaderCommitIndex = 10;
            long rivalTerm         = leaderTerm + 1;
            long logIndex          = 20;

            RaftLogEntry[] entries = new RaftLogEntry[] { new RaftLogEntry(rivalTerm, ReplicatedInteger.valueOf(99)) };

            Leader    leader = new Leader();
            RaftState state  = raftState().term(leaderTerm).commitIndex(leaderCommitIndex).build();

            // when
            Outcome outcome = leader.Handle(new Org.Neo4j.causalclustering.core.consensus.RaftMessages_AppendEntries_Request(_member1, rivalTerm, logIndex, leaderTerm, entries, leaderCommitIndex), state, Log());

            // then
            assertThat(outcome.Role, equalTo(FOLLOWER));
            assertThat(outcome.Leader, equalTo(_member1));
            assertThat(outcome.Term, equalTo(rivalTerm));

            Org.Neo4j.causalclustering.core.consensus.RaftMessages_RaftMessage response = messageFor(outcome, _member1);
            assertThat(response, instanceOf(typeof(Org.Neo4j.causalclustering.core.consensus.RaftMessages_AppendEntries_Response)));
            Org.Neo4j.causalclustering.core.consensus.RaftMessages_AppendEntries_Response typedResponse = (Org.Neo4j.causalclustering.core.consensus.RaftMessages_AppendEntries_Response)response;
            assertThat(typedResponse.Term(), equalTo(rivalTerm));
            // Not checking success or failure of append
        }
Example #5
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldBatchSingleEntryAppendEntries()
        public virtual void ShouldBatchSingleEntryAppendEntries()
        {
            BatchingMessageHandler batchHandler = new BatchingMessageHandler(_downstreamHandler, _inQueueConfig, _batchConfig, _jobSchedulerFactory, NullLogProvider.Instance);

            long leaderTerm   = 1;
            long prevLogIndex = -1;
            long prevLogTerm  = -1;
            long leaderCommit = 0;

            RaftLogEntry entryA = new RaftLogEntry(0, Content("A"));
            RaftLogEntry entryB = new RaftLogEntry(0, Content("B"));

            AppendEntries.Request appendA = new AppendEntries.Request(_leader, leaderTerm, prevLogIndex, prevLogTerm, new RaftLogEntry[] { entryA }, leaderCommit);

            AppendEntries.Request appendB = new AppendEntries.Request(_leader, leaderTerm, prevLogIndex + 1, 0, new RaftLogEntry[] { entryB }, leaderCommit);

            batchHandler.Handle(Wrap(appendA));
            batchHandler.Handle(Wrap(appendB));
            verifyZeroInteractions(_downstreamHandler);

            // when
            batchHandler.Run();

            // then
            AppendEntries.Request expected = new AppendEntries.Request(_leader, leaderTerm, prevLogIndex, prevLogTerm, new RaftLogEntry[] { entryA, entryB }, leaderCommit);

            verify(_downstreamHandler).handle(Wrap(expected));
        }
Example #6
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void applyUpTo(long applyUpToIndex) throws Exception
        private void ApplyUpTo(long applyUpToIndex)
        {
            using (InFlightLogEntryReader logEntrySupplier = new InFlightLogEntryReader(_raftLog, _inFlightCache, true))
            {
                for (long logIndex = _applierState.lastApplied + 1; _applierState.keepRunning && logIndex <= applyUpToIndex; logIndex++)
                {
                    RaftLogEntry entry = logEntrySupplier.Get(logIndex);
                    if (entry == null)
                    {
                        throw new System.InvalidOperationException(format("Committed log entry at index %d must exist.", logIndex));
                    }

                    if (entry.Content() is DistributedOperation)
                    {
                        DistributedOperation distributedOperation = ( DistributedOperation )entry.Content();
                        _progressTracker.trackReplication(distributedOperation);
                        _batcher.add(logIndex, distributedOperation);
                    }
                    else
                    {
                        _batcher.flush();
                        // since this last entry didn't get in the batcher we need to update the lastApplied:
                        _applierState.lastApplied = logIndex;
                    }
                }
                _batcher.flush();
            }
        }
Example #7
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldReturnLatestItems()
        public virtual void ShouldReturnLatestItems()
        {
            // given
            int capacity = 4;
            ConsecutiveInFlightCache cache = new ConsecutiveInFlightCache(capacity, 1000, InFlightCacheMonitor.VOID, true);

            // when
            for (int i = 0; i < 3 * capacity; i++)
            {
                cache.Put(i, Content(i));
            }

            // then
            for (int i = 0; i < 3 * capacity; i++)
            {
                RaftLogEntry entry = cache.Get(i);
                if (i < 2 * capacity)
                {
                    assertNull(entry);
                }
                else
                {
                    assertTrue(entry.Content().size().HasValue);
                    assertEquals(i, entry.Content().size().Value);
                }
            }
        }
Example #8
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldRemovePrunedItems()
        public virtual void ShouldRemovePrunedItems()
        {
            // given
            int capacity = 20;
            ConsecutiveInFlightCache cache = new ConsecutiveInFlightCache(capacity, 1000, InFlightCacheMonitor.VOID, true);

            for (int i = 0; i < capacity; i++)
            {
                cache.Put(i, Content(i));
            }

            // when
            int upToIndex = capacity / 2 - 1;

            cache.Prune(upToIndex);

            // then
            assertEquals(capacity / 2, cache.ElementCount());

            for (int i = 0; i < capacity; i++)
            {
                RaftLogEntry entry = cache.Get(i);
                if (i <= upToIndex)
                {
                    assertNull(entry);
                }
                else
                {
                    assertTrue(entry.Content().size().HasValue);
                    assertEquals(i, entry.Content().size().Value);
                }
            }
        }
Example #9
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldRespondNegativelyToAppendEntriesRequestFromEarlierTerm() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldRespondNegativelyToAppendEntriesRequestFromEarlierTerm()
        {
            // given
            long leaderTerm        = 5;
            long leaderCommitIndex = 10;
            long rivalTerm         = leaderTerm - 1;
            long logIndex          = 20;

            RaftLogEntry[] entries = new RaftLogEntry[] { new RaftLogEntry(rivalTerm, ReplicatedInteger.valueOf(99)) };

            Leader    leader = new Leader();
            RaftState state  = raftState().term(leaderTerm).commitIndex(leaderCommitIndex).build();

            // when
            Outcome outcome = leader.Handle(new Org.Neo4j.causalclustering.core.consensus.RaftMessages_AppendEntries_Request(_member1, rivalTerm, logIndex, leaderTerm, entries, leaderCommitIndex), state, Log());

            // then
            assertThat(outcome.Role, equalTo(LEADER));
            assertThat(outcome.Term, equalTo(leaderTerm));

            Org.Neo4j.causalclustering.core.consensus.RaftMessages_RaftMessage response = messageFor(outcome, _member1);
            assertThat(response, instanceOf(typeof(Org.Neo4j.causalclustering.core.consensus.RaftMessages_AppendEntries_Response)));
            Org.Neo4j.causalclustering.core.consensus.RaftMessages_AppendEntries_Response typedResponse = (Org.Neo4j.causalclustering.core.consensus.RaftMessages_AppendEntries_Response)response;
            assertThat(typedResponse.Term(), equalTo(leaderTerm));
            assertThat(typedResponse.Success(), equalTo(false));
        }
Example #10
0
 private RaftLogEntry[] Entries(long term, int min, int max)
 {
     RaftLogEntry[] entries = new RaftLogEntry[max - min + 1];
     for (int i = min; i <= max; i++)
     {
         entries[i - min] = new RaftLogEntry(term, new ReplicatedString(i.ToString()));
     }
     return(entries);
 }
Example #11
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: static void appendNewEntry(org.neo4j.causalclustering.core.consensus.state.ReadableRaftState ctx, org.neo4j.causalclustering.core.consensus.outcome.Outcome outcome, org.neo4j.causalclustering.core.replication.ReplicatedContent content) throws java.io.IOException
        internal static void AppendNewEntry(ReadableRaftState ctx, Outcome outcome, ReplicatedContent content)
        {
            long prevLogIndex = ctx.EntryLog().appendIndex();
            long prevLogTerm  = prevLogIndex == -1 ? -1 : prevLogIndex > ctx.LastLogIndexBeforeWeBecameLeader() ? ctx.Term() : ctx.EntryLog().readEntryTerm(prevLogIndex);

            RaftLogEntry newLogEntry = new RaftLogEntry(ctx.Term(), content);

            outcome.AddShipCommand(new ShipCommand.NewEntries(prevLogIndex, prevLogTerm, new RaftLogEntry[] { newLogEntry }));
            outcome.AddLogCommand(new AppendLogEntry(prevLogIndex + 1, newLogEntry));
        }
Example #12
0
        public override void Put(long logIndex, RaftLogEntry entry)
        {
            lock (this)
            {
                if (!_enabled)
                {
                    return;
                }

                _map[logIndex] = entry;
            }
        }
Example #13
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldNotAppendAtTheEndOfLogFileWithIncompleteEntries() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldNotAppendAtTheEndOfLogFileWithIncompleteEntries()
        {
            // Given
            // we use a RaftLog to create a raft log file and then we will chop some bits off the end
            SegmentedRaftLog raftLog = CreateRaftLog(100_000);

            raftLog.Start();

            raftLog.Append(new RaftLogEntry(4, new NewLeaderBarrier()));

            raftLog.Stop();

            // We use a temporary RecoveryProtocol to get the file to chop
            RecoveryProtocol recovery      = CreateRecoveryProtocol();
            State            recoveryState = Recovery.run();
            string           logFilename   = recoveryState.Segments.last().Filename;

            recoveryState.Segments.close();
            File         logFile     = new File(_logDirectory, logFilename);
            StoreChannel lastFile    = FsRule.get().open(logFile, OpenMode.READ_WRITE);
            long         currentSize = lastFile.size();

            lastFile.close();

            // When
            // We induce an incomplete entry at the end of the last file
            lastFile = FsRule.get().open(logFile, OpenMode.READ_WRITE);
            lastFile.Truncate(currentSize - 1);
            lastFile.close();

            // We start the raft log again, on the previous log file with truncated last entry.
            raftLog = CreateRaftLog(100_000);

            //  Recovery will run here
            raftLog.Start();

            // Append an entry
            raftLog.Append(new RaftLogEntry(4, new NewLeaderBarrier()));

            // Then
            // The log should report as containing only the last entry we've appended
            using (RaftLogCursor entryCursor = raftLog.GetEntryCursor(0))
            {
                // There should be exactly one entry, of type NewLeaderBarrier
                assertTrue(entryCursor.Next());
                RaftLogEntry raftLogEntry = entryCursor.get();
                assertEquals(typeof(NewLeaderBarrier), raftLogEntry.Content().GetType());
                assertFalse(entryCursor.Next());
            }
            raftLog.Stop();
        }
Example #14
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public long readEntryTerm(long logIndex) throws java.io.IOException
        public override long ReadEntryTerm(long logIndex)
        {
            if (logIndex > _state.appendIndex)
            {
                return(-1);
            }
            long term = _state.terms.get(logIndex);

            if (term == -1 && logIndex >= _state.prevIndex)
            {
                RaftLogEntry entry = ReadLogEntry(logIndex);
                term = (entry != null) ? entry.Term() : -1;
            }
            return(term);
        }
Example #15
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldAcceptInitialEntryAfterBootstrap() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldAcceptInitialEntryAfterBootstrap()
        {
            RaftLog   raftLog = BootstrappedLog();
            RaftState state   = raftState().entryLog(raftLog).myself(_myself).build();

            long         leaderTerm = state.Term() + LeaderTermDifference;
            RaftLogEntry logEntry   = new RaftLogEntry(leaderTerm, content());

            // when
            Outcome outcome = Role.handler.handle(appendEntriesRequest().from(_leader).leaderTerm(leaderTerm).prevLogIndex(0).prevLogTerm(0).logEntry(logEntry).build(), state, Log());

            // then
            assertTrue((( RaftMessages_AppendEntries_Response )messageFor(outcome, _leader)).success());
            assertThat(outcome.LogCommands, hasItem(new BatchAppendLogEntries(1, 0, new RaftLogEntry[] { logEntry })));
        }
Example #16
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void print(java.io.PrintStream out) throws java.io.IOException
        public virtual void Print(PrintStream @out)
        {
            @out.println(string.Format("{0,8} {1,5}  {2,2} {3}", "Index", "Term", "C?", "Content"));
            long index = 0L;

            using (RaftLogCursor cursor = _raftLog.getEntryCursor(0))
            {
                while (cursor.Next())
                {
                    RaftLogEntry raftLogEntry = cursor.get();
                    @out.printf("%8d %5d %s", index, raftLogEntry.Term(), raftLogEntry.Content());
                    index++;
                }
            }
        }
Example #17
0
        public void SetLogEntry(long commitIndex, long term)
        {
            if (commitIndex < 1)
            {
                throw new IndexOutOfRangeException("Commit index for log must start from 1.");
            }

            if (commitIndex > _log.Length)
            {
                var newLog = new RaftLogEntry[_log.Length + LogIncrementSize];
                _log.CopyTo(newLog, 0);
                _log = newLog;
            }

            _log[commitIndex - 1] = new RaftLogEntry(term);
        }
Example #18
0
        private void ProcessEvictions()
        {
            for (int i = 0; i < _evictions.Length; i++)
            {
                RaftLogEntry entry = _evictions[i];
                if (entry == null)
                {
                    break;
                }
                _evictions[i] = null;
                _totalBytes  -= SizeOf(entry);
            }

            _monitor.TotalBytes   = _totalBytes;
            _monitor.ElementCount = _cache.size();
        }
Example #19
0
            public override Optional <Org.Neo4j.causalclustering.core.consensus.RaftMessages_RaftMessage> MaybeComplete(LinkedList <long> terms, LinkedList <ReplicatedContent> contents)
            {
                if (terms.Count < EntryCount || contents.Count < EntryCount)
                {
                    return(null);
                }

                RaftLogEntry[] entries = new RaftLogEntry[EntryCount];
                for (int i = 0; i < EntryCount; i++)
                {
                    long term = terms.RemoveFirst();
                    ReplicatedContent content = contents.RemoveFirst();
                    entries[i] = new RaftLogEntry(term, content);
                }
                return(new Org.Neo4j.causalclustering.core.consensus.RaftMessages_AppendEntries_Request(From, Term, PrevLogIndex, PrevLogTerm, entries, LeaderCommit));
            }
Example #20
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldNotCommitAheadOfMatchingHistory() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldNotCommitAheadOfMatchingHistory()
        {
            // given
            InMemoryRaftLog raftLog = new InMemoryRaftLog();
            RaftState       state   = raftState().entryLog(raftLog).myself(_myself).build();

            long         leaderTerm = state.Term() + LeaderTermDifference;
            RaftLogEntry previouslyAppendedEntry = new RaftLogEntry(leaderTerm, content());

            raftLog.Append(previouslyAppendedEntry);

            // when
            Outcome outcome = Role.handler.handle(appendEntriesRequest().from(_leader).leaderTerm(leaderTerm).prevLogIndex(raftLog.AppendIndex() + 1).prevLogTerm(leaderTerm).leaderCommit(0).build(), state, Log());

            // then
            assertFalse((( RaftMessages_AppendEntries_Response )messageFor(outcome, _leader)).success());
            assertThat(outcome.LogCommands, empty());
        }
Example #21
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldUseTheCacheWhenTheIndexIsPresent() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldUseTheCacheWhenTheIndexIsPresent()
        {
            // given
            InFlightLogEntryReader reader = new InFlightLogEntryReader(_raftLog, _inFlightCache, ClearCache);

            StartingFromIndexReturnEntries(_inFlightCache, _logIndex, _entry);
            StartingFromIndexReturnEntries(_raftLog, -1, null);

            // when
            RaftLogEntry raftLogEntry = reader.Get(_logIndex);

            // then
            assertEquals(_entry, raftLogEntry);
            verify(_inFlightCache).get(_logIndex);
            AssertCacheIsUpdated(_inFlightCache, _logIndex);
            verifyNoMoreInteractions(_inFlightCache);
            verifyZeroInteractions(_raftLog);
        }
Example #22
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldAppendNewEntryAndCommitPreviouslyAppendedEntry() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldAppendNewEntryAndCommitPreviouslyAppendedEntry()
        {
            // given
            InMemoryRaftLog raftLog = new InMemoryRaftLog();
            RaftState       state   = raftState().entryLog(raftLog).myself(_myself).build();

            long         leaderTerm = state.Term() + LeaderTermDifference;
            RaftLogEntry previouslyAppendedEntry = new RaftLogEntry(leaderTerm, content());

            raftLog.Append(previouslyAppendedEntry);
            RaftLogEntry newLogEntry = new RaftLogEntry(leaderTerm, content());

            // when
            Outcome outcome = Role.handler.handle(appendEntriesRequest().from(_leader).leaderTerm(leaderTerm).prevLogIndex(raftLog.AppendIndex()).prevLogTerm(leaderTerm).logEntry(newLogEntry).leaderCommit(0).build(), state, Log());

            // then
            assertTrue((( RaftMessages_AppendEntries_Response )messageFor(outcome, _leader)).success());
            assertThat(outcome.CommitIndex, Matchers.equalTo(0L));
            assertThat(outcome.LogCommands, hasItem(new BatchAppendLogEntries(1, 0, new RaftLogEntry[] { newLogEntry })));
        }
Example #23
0
        public override void Put(long logIndex, RaftLogEntry entry)
        {
            lock (this)
            {
                if (!_enabled)
                {
                    return;
                }

                _totalBytes += SizeOf(entry);
                _cache.put(logIndex, entry, _evictions);
                ProcessEvictions();

                while (_totalBytes > _maxBytes)
                {
                    RaftLogEntry evicted = _cache.remove();
                    _totalBytes -= SizeOf(evicted);
                }
            }
        }
Example #24
0
        public override RaftLogEntry Get(long logIndex)
        {
            lock (this)
            {
                if (!_enabled)
                {
                    return(null);
                }

                RaftLogEntry entry = _cache.get(logIndex);

                if (entry == null)
                {
                    _monitor.miss();
                }
                else
                {
                    _monitor.hit();
                }

                return(entry);
            }
        }
Example #25
0
 private void StartingFromIndexReturnEntries(InFlightCache inFlightCache, long startIndex, RaftLogEntry entry, params RaftLogEntry[] otherEntries)
 {
     when(inFlightCache.Get(startIndex)).thenReturn(entry);
     for (int offset = 0; offset < otherEntries.Length; offset++)
     {
         when(inFlightCache.Get(startIndex + offset + 1L)).thenReturn(otherEntries[offset]);
     }
 }
Example #26
0
 public virtual AppendEntriesRequestBuilder LogEntry(RaftLogEntry logEntry)
 {
     _logEntries.Add(logEntry);
     return(this);
 }
Example #27
0
 public override void Put(long logIndex, RaftLogEntry entry)
 {
 }
Example #28
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void decode(io.netty.channel.ChannelHandlerContext ctx, io.netty.buffer.ByteBuf buffer, java.util.List<Object> list) throws Exception
        public override void Decode(ChannelHandlerContext ctx, ByteBuf buffer, IList <object> list)
        {
            ReadableChannel channel   = new NetworkReadableClosableChannelNetty4(buffer);
            ClusterId       clusterId = ClusterId.Marshal.INSTANCE.unmarshal(channel);

            int messageTypeWire = channel.Int;

            Org.Neo4j.causalclustering.core.consensus.RaftMessages_Type[] values      = Enum.GetValues(typeof(Org.Neo4j.causalclustering.core.consensus.RaftMessages_Type));
            Org.Neo4j.causalclustering.core.consensus.RaftMessages_Type   messageType = values[messageTypeWire];

            MemberId from = RetrieveMember(channel);

            Org.Neo4j.causalclustering.core.consensus.RaftMessages_RaftMessage result;

            if (messageType.Equals(VOTE_REQUEST))
            {
                MemberId candidate = RetrieveMember(channel);

                long term         = channel.Long;
                long lastLogIndex = channel.Long;
                long lastLogTerm  = channel.Long;

                result = new Org.Neo4j.causalclustering.core.consensus.RaftMessages_Vote_Request(from, term, candidate, lastLogIndex, lastLogTerm);
            }
            else if (messageType.Equals(VOTE_RESPONSE))
            {
                long term        = channel.Long;
                bool voteGranted = channel.Get() == 1;

                result = new Org.Neo4j.causalclustering.core.consensus.RaftMessages_Vote_Response(from, term, voteGranted);
            }
            else if (messageType.Equals(PRE_VOTE_REQUEST))
            {
                MemberId candidate = RetrieveMember(channel);

                long term         = channel.Long;
                long lastLogIndex = channel.Long;
                long lastLogTerm  = channel.Long;

                result = new Org.Neo4j.causalclustering.core.consensus.RaftMessages_PreVote_Request(from, term, candidate, lastLogIndex, lastLogTerm);
            }
            else if (messageType.Equals(PRE_VOTE_RESPONSE))
            {
                long term        = channel.Long;
                bool voteGranted = channel.Get() == 1;

                result = new Org.Neo4j.causalclustering.core.consensus.RaftMessages_PreVote_Response(from, term, voteGranted);
            }
            else if (messageType.Equals(APPEND_ENTRIES_REQUEST))
            {
                // how many
                long term         = channel.Long;
                long prevLogIndex = channel.Long;
                long prevLogTerm  = channel.Long;

                long leaderCommit = channel.Long;
                long count        = channel.Long;

                RaftLogEntry[] entries = new RaftLogEntry[( int )count];
                for (int i = 0; i < count; i++)
                {
                    long entryTerm = channel.Long;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.causalclustering.core.replication.ReplicatedContent content = marshal.unmarshal(channel);
                    ReplicatedContent content = _marshal.unmarshal(channel);
                    entries[i] = new RaftLogEntry(entryTerm, content);
                }

                result = new Org.Neo4j.causalclustering.core.consensus.RaftMessages_AppendEntries_Request(from, term, prevLogIndex, prevLogTerm, entries, leaderCommit);
            }
            else if (messageType.Equals(APPEND_ENTRIES_RESPONSE))
            {
                long term        = channel.Long;
                bool success     = channel.Get() == 1;
                long matchIndex  = channel.Long;
                long appendIndex = channel.Long;

                result = new Org.Neo4j.causalclustering.core.consensus.RaftMessages_AppendEntries_Response(from, term, success, matchIndex, appendIndex);
            }
            else if (messageType.Equals(NEW_ENTRY_REQUEST))
            {
                ReplicatedContent content = _marshal.unmarshal(channel);

                result = new Org.Neo4j.causalclustering.core.consensus.RaftMessages_NewEntry_Request(from, content);
            }
            else if (messageType.Equals(HEARTBEAT))
            {
                long leaderTerm      = channel.Long;
                long commitIndexTerm = channel.Long;
                long commitIndex     = channel.Long;

                result = new Org.Neo4j.causalclustering.core.consensus.RaftMessages_Heartbeat(from, leaderTerm, commitIndex, commitIndexTerm);
            }
            else if (messageType.Equals(HEARTBEAT_RESPONSE))
            {
                result = new Org.Neo4j.causalclustering.core.consensus.RaftMessages_HeartbeatResponse(from);
            }
            else if (messageType.Equals(LOG_COMPACTION_INFO))
            {
                long leaderTerm = channel.Long;
                long prevIndex  = channel.Long;

                result = new Org.Neo4j.causalclustering.core.consensus.RaftMessages_LogCompactionInfo(from, leaderTerm, prevIndex);
            }
            else
            {
                throw new System.ArgumentException("Unknown message type");
            }

            list.Add(Org.Neo4j.causalclustering.core.consensus.RaftMessages_ReceivedInstantClusterIdAwareMessage.of(_clock.instant(), clusterId, result));
        }
Example #29
0
 private long SizeOf(RaftLogEntry entry)
 {
     return(entry.Content().size().GetValueOrDefault(0L));
 }
Example #30
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void startingFromIndexReturnEntries(org.neo4j.causalclustering.core.consensus.log.ReadableRaftLog raftLog, long startIndex, org.neo4j.causalclustering.core.consensus.log.RaftLogEntry entry, org.neo4j.causalclustering.core.consensus.log.RaftLogEntry... otherEntries) throws java.io.IOException
        private void StartingFromIndexReturnEntries(ReadableRaftLog raftLog, long startIndex, RaftLogEntry entry, params RaftLogEntry[] otherEntries)
        {
            RaftLogCursor cursor = mock(typeof(RaftLogCursor));

            when(raftLog.GetEntryCursor(startIndex)).thenReturn(cursor, ( RaftLogCursor )null);

            bool?[] bools = new bool?[otherEntries.Length + 1];
            Arrays.fill(bools, true);
            bools[otherEntries.Length] = false;

            when(cursor.Next()).thenReturn(true, bools);

            long?[] indexes = new long?[otherEntries.Length + 1];
            for (int offset = 0; offset < indexes.Length; offset++)
            {
                indexes[offset] = startIndex + 1 + offset;
            }
            indexes[otherEntries.Length] = -1L;

            when(cursor.Index()).thenReturn(startIndex, indexes);

            RaftLogEntry[] raftLogEntries = Arrays.copyOf(otherEntries, otherEntries.Length + 1);
            when(cursor.get()).thenReturn(entry, raftLogEntries);
        }