Search in sources :

Example 1 with LogEntryProto

use of org.apache.ratis.shaded.proto.RaftProtos.LogEntryProto in project incubator-ratis by apache.

the class StateMachineUpdater method run.

@Override
public void run() {
    final RaftStorage storage = server.getState().getStorage();
    while (isRunning()) {
        try {
            synchronized (this) {
                // Thus initially lastAppliedIndex can be greater than lastCommitted.
                while (lastAppliedIndex >= raftLog.getLastCommittedIndex()) {
                    wait();
                }
            }
            final long committedIndex = raftLog.getLastCommittedIndex();
            Preconditions.assertTrue(lastAppliedIndex < committedIndex);
            if (state == State.RELOAD) {
                Preconditions.assertTrue(stateMachine.getLifeCycleState() == LifeCycle.State.PAUSED);
                stateMachine.reinitialize(server.getId(), properties, storage);
                SnapshotInfo snapshot = stateMachine.getLatestSnapshot();
                Preconditions.assertTrue(snapshot != null && snapshot.getIndex() > lastAppliedIndex, "Snapshot: %s, lastAppliedIndex: %s", snapshot, lastAppliedIndex);
                lastAppliedIndex = snapshot.getIndex();
                lastSnapshotIndex = snapshot.getIndex();
                state = State.RUNNING;
            }
            final MemoizedSupplier<List<CompletableFuture<Message>>> futures = MemoizedSupplier.valueOf(() -> new ArrayList<>());
            while (lastAppliedIndex < committedIndex) {
                final long nextIndex = lastAppliedIndex + 1;
                final LogEntryProto next = raftLog.get(nextIndex);
                if (next != null) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("{}: applying nextIndex={}, nextLog={}", this, nextIndex, ServerProtoUtils.toString(next));
                    }
                    final CompletableFuture<Message> f = server.applyLogToStateMachine(next);
                    if (f != null) {
                        futures.get().add(f);
                    }
                    lastAppliedIndex = nextIndex;
                } else {
                    LOG.debug("{}: logEntry {} is null. There may be snapshot to load. state:{}", this, nextIndex, state);
                    break;
                }
            }
            // check if need to trigger a snapshot
            if (shouldTakeSnapshot(lastAppliedIndex)) {
                if (futures.isInitialized()) {
                    JavaUtils.allOf(futures.get()).get();
                }
                stateMachine.takeSnapshot();
                // TODO purge logs, including log cache. but should keep log for leader's RPCSenders
                lastSnapshotIndex = lastAppliedIndex;
            }
        } catch (InterruptedException e) {
            if (!isRunning()) {
                LOG.info("{}: the StateMachineUpdater is interrupted and will exit.", this);
            } else {
                final String s = this + ": the StateMachineUpdater is wrongly interrupted";
                ExitUtils.terminate(1, s, e, LOG);
            }
        } catch (Throwable t) {
            final String s = this + ": the StateMachineUpdater hits Throwable";
            ExitUtils.terminate(2, s, t, LOG);
        }
    }
}
Also used : SnapshotInfo(org.apache.ratis.statemachine.SnapshotInfo) LogEntryProto(org.apache.ratis.shaded.proto.RaftProtos.LogEntryProto) RaftStorage(org.apache.ratis.server.storage.RaftStorage) Message(org.apache.ratis.protocol.Message) ArrayList(java.util.ArrayList) List(java.util.List)

Example 2 with LogEntryProto

use of org.apache.ratis.shaded.proto.RaftProtos.LogEntryProto in project incubator-ratis by apache.

the class LogInputStream method scanEditLog.

/**
 * Find the last valid entry index in the stream.
 * If there are invalid or corrupt entries in the middle of the stream,
 * scanEditLog will skip over them.
 *
 * This reads through the stream but does not close it.
 *
 * @param maxIndexToScan Maximum entry index to try to scan. The scan returns
 *                       after reading this or a higher index. The file
 *                       portion beyond this index is potentially being
 *                       updated.
 */
static LogValidation scanEditLog(LogInputStream in, long maxIndexToScan) {
    long lastPos = 0;
    long end = INVALID_LOG_INDEX;
    long numValid = 0;
    boolean hitError = false;
    while (end < maxIndexToScan) {
        long index;
        lastPos = in.getPosition();
        try {
            if (hitError) {
                LogEntryProto entry = in.nextEntry();
                index = entry != null ? entry.getIndex() : INVALID_LOG_INDEX;
                LOG.warn("After resync, position is " + in.getPosition());
            } else {
                index = in.scanNextEntry();
            }
            if (index == INVALID_LOG_INDEX) {
                break;
            } else {
                hitError = false;
            }
        } catch (Throwable t) {
            LOG.warn("Caught exception after scanning through {} ops from {}" + " while determining its valid length. Position was " + lastPos, numValid, in, t);
            hitError = true;
            continue;
        }
        if (end == INVALID_LOG_INDEX || index > end) {
            end = index;
        }
        numValid++;
    }
    return new LogValidation(lastPos, end, false);
}
Also used : LogEntryProto(org.apache.ratis.shaded.proto.RaftProtos.LogEntryProto)

Example 3 with LogEntryProto

use of org.apache.ratis.shaded.proto.RaftProtos.LogEntryProto in project incubator-ratis by apache.

the class LogInputStream method nextEntry.

public LogEntryProto nextEntry() throws IOException {
    LogEntryProto entry = null;
    switch(state) {
        case UNINIT:
            try {
                init();
            } catch (Throwable e) {
                LOG.error("caught exception initializing " + this, e);
                throw IOUtils.asIOException(e);
            }
            Preconditions.assertTrue(state != State.UNINIT);
            return nextEntry();
        case OPEN:
            entry = reader.readEntry();
            if (entry != null) {
                long index = entry.getIndex();
                if (!isOpen() && index >= endIndex) {
                    /**
                     * The end index may be derived from the segment recovery
                     * process. It is possible that we still have some uncleaned garbage
                     * in the end. We should skip them.
                     */
                    long skipAmt = logFile.length() - reader.getPos();
                    if (skipAmt > 0) {
                        LOG.debug("skipping {} bytes at the end of log '{}': reached" + " entry {} out of {}", skipAmt, getName(), index, endIndex);
                        reader.skipFully(skipAmt);
                    }
                }
            }
            break;
        case CLOSED:
            // return null
            break;
    }
    return entry;
}
Also used : LogEntryProto(org.apache.ratis.shaded.proto.RaftProtos.LogEntryProto)

Example 4 with LogEntryProto

use of org.apache.ratis.shaded.proto.RaftProtos.LogEntryProto in project incubator-ratis by apache.

the class LogSegment method readSegmentFile.

private static void readSegmentFile(File file, long start, long end, boolean isOpen, Consumer<LogEntryProto> entryConsumer) throws IOException {
    try (LogInputStream in = new LogInputStream(file, start, end, isOpen)) {
        LogEntryProto next;
        LogEntryProto prev = null;
        while ((next = in.nextEntry()) != null) {
            if (prev != null) {
                Preconditions.assertTrue(next.getIndex() == prev.getIndex() + 1, "gap between entry %s and entry %s", prev, next);
            }
            if (entryConsumer != null) {
                entryConsumer.accept(next);
            }
            prev = next;
        }
    }
}
Also used : LogEntryProto(org.apache.ratis.shaded.proto.RaftProtos.LogEntryProto)

Example 5 with LogEntryProto

use of org.apache.ratis.shaded.proto.RaftProtos.LogEntryProto in project incubator-ratis by apache.

the class RaftBasicTests method testOldLeaderNotCommit.

@Test
public void testOldLeaderNotCommit() throws Exception {
    LOG.info("Running testOldLeaderNotCommit");
    final MiniRaftCluster cluster = getCluster();
    final RaftPeerId leaderId = waitForLeader(cluster).getId();
    List<RaftServerImpl> followers = cluster.getFollowers();
    final RaftServerImpl followerToCommit = followers.get(0);
    for (int i = 1; i < NUM_SERVERS - 1; i++) {
        RaftServerImpl follower = followers.get(i);
        cluster.killServer(follower.getId());
    }
    SimpleMessage[] messages = SimpleMessage.create(1);
    sendMessageInNewThread(cluster, messages);
    Thread.sleep(cluster.getMaxTimeout() + 100);
    logEntriesContains(followerToCommit.getState().getLog(), messages);
    cluster.killServer(leaderId);
    cluster.killServer(followerToCommit.getId());
    for (int i = 1; i < NUM_SERVERS - 1; i++) {
        RaftServerImpl follower = followers.get(i);
        cluster.restartServer(follower.getId(), false);
    }
    waitForLeader(cluster);
    Thread.sleep(cluster.getMaxTimeout() + 100);
    final Predicate<LogEntryProto> predicate = l -> l.getTerm() != 1;
    cluster.getServerAliveStream().map(s -> s.getState().getLog()).forEach(log -> RaftTestUtil.checkLogEntries(log, messages, predicate));
}
Also used : RaftServerImpl(org.apache.ratis.server.impl.RaftServerImpl) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) RetryCacheTestUtil(org.apache.ratis.server.impl.RetryCacheTestUtil) Timer(java.util.Timer) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Level(org.apache.log4j.Level) After(org.junit.After) JavaUtils(org.apache.ratis.util.JavaUtils) TimerTask(java.util.TimerTask) BlockRequestHandlingInjection(org.apache.ratis.server.impl.BlockRequestHandlingInjection) Before(org.junit.Before) LogUtils(org.apache.ratis.util.LogUtils) Logger(org.slf4j.Logger) RaftServerImpl(org.apache.ratis.server.impl.RaftServerImpl) LogEntryProto(org.apache.ratis.shaded.proto.RaftProtos.LogEntryProto) Predicate(java.util.function.Predicate) RaftPeerId(org.apache.ratis.protocol.RaftPeerId) RaftServerConfigKeys(org.apache.ratis.server.RaftServerConfigKeys) RaftClientTestUtil(org.apache.ratis.client.impl.RaftClientTestUtil) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) RaftLog(org.apache.ratis.server.storage.RaftLog) RaftTestUtil(org.apache.ratis.RaftTestUtil) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) Stream(java.util.stream.Stream) RaftClientReply(org.apache.ratis.protocol.RaftClientReply) RaftProperties(org.apache.ratis.conf.RaftProperties) RaftClient(org.apache.ratis.client.RaftClient) Assert(org.junit.Assert) TimeDuration(org.apache.ratis.util.TimeDuration) LogEntryProto(org.apache.ratis.shaded.proto.RaftProtos.LogEntryProto) RaftPeerId(org.apache.ratis.protocol.RaftPeerId) Test(org.junit.Test)

Aggregations

LogEntryProto (org.apache.ratis.shaded.proto.RaftProtos.LogEntryProto)36 SimpleOperation (org.apache.ratis.RaftTestUtil.SimpleOperation)16 Test (org.junit.Test)16 BaseTest (org.apache.ratis.BaseTest)14 File (java.io.File)12 ArrayList (java.util.ArrayList)8 SMLogEntryProto (org.apache.ratis.shaded.proto.RaftProtos.SMLogEntryProto)8 IOException (java.io.IOException)7 CompletableFuture (java.util.concurrent.CompletableFuture)6 RandomAccessFile (java.io.RandomAccessFile)5 RaftServerImpl (org.apache.ratis.server.impl.RaftServerImpl)5 List (java.util.List)4 RaftProperties (org.apache.ratis.conf.RaftProperties)4 RaftPeerId (org.apache.ratis.protocol.RaftPeerId)4 TermIndex (org.apache.ratis.server.protocol.TermIndex)4 AutoCloseableLock (org.apache.ratis.util.AutoCloseableLock)4 Level (org.apache.log4j.Level)3 RaftServerConfigKeys (org.apache.ratis.server.RaftServerConfigKeys)3 RetryCache (org.apache.ratis.server.impl.RetryCache)3 RetryCacheTestUtil (org.apache.ratis.server.impl.RetryCacheTestUtil)3