Search in sources :

Example 41 with LogEntry

use of com.alipay.sofa.jraft.entity.LogEntry in project sofa-jraft by sofastack.

the class RocksDBLogStorage method appendEntries.

@Override
public int appendEntries(final List<LogEntry> entries) {
    if (entries == null || entries.isEmpty()) {
        return 0;
    }
    final int entriesCount = entries.size();
    final boolean ret = executeBatch(batch -> {
        final WriteContext writeCtx = newWriteContext();
        for (int i = 0; i < entriesCount; i++) {
            final LogEntry entry = entries.get(i);
            if (entry.getType() == EntryType.ENTRY_TYPE_CONFIGURATION) {
                addConfBatch(entry, batch);
            } else {
                writeCtx.startJob();
                addDataBatch(entry, batch, writeCtx);
            }
        }
        writeCtx.joinAll();
        doSync();
    });
    if (ret) {
        return entriesCount;
    } else {
        return 0;
    }
}
Also used : LogEntry(com.alipay.sofa.jraft.entity.LogEntry)

Example 42 with LogEntry

use of com.alipay.sofa.jraft.entity.LogEntry in project sofa-jraft by sofastack.

the class V2Decoder method decode.

@Override
public LogEntry decode(final byte[] bs) {
    if (bs == null || bs.length < LogEntryV2CodecFactory.HEADER_SIZE) {
        return null;
    }
    int i = 0;
    for (; i < LogEntryV2CodecFactory.MAGIC_BYTES.length; i++) {
        if (bs[i] != LogEntryV2CodecFactory.MAGIC_BYTES[i]) {
            return null;
        }
    }
    if (bs[i++] != LogEntryV2CodecFactory.VERSION) {
        return null;
    }
    // Ignored reserved
    i += LogEntryV2CodecFactory.RESERVED.length;
    try {
        final PBLogEntry entry = PBLogEntry.parseFrom(ZeroByteStringHelper.wrap(bs, i, bs.length - i));
        final LogEntry log = new LogEntry();
        log.setType(entry.getType());
        log.getId().setIndex(entry.getIndex());
        log.getId().setTerm(entry.getTerm());
        if (entry.hasChecksum()) {
            log.setChecksum(entry.getChecksum());
        }
        if (entry.getPeersCount() > 0) {
            final List<PeerId> peers = new ArrayList<>(entry.getPeersCount());
            for (final ByteString bstring : entry.getPeersList()) {
                peers.add(JRaftUtils.getPeerId(AsciiStringUtil.unsafeDecode(bstring)));
            }
            log.setPeers(peers);
        }
        if (entry.getOldPeersCount() > 0) {
            final List<PeerId> peers = new ArrayList<>(entry.getOldPeersCount());
            for (final ByteString bstring : entry.getOldPeersList()) {
                peers.add(JRaftUtils.getPeerId(AsciiStringUtil.unsafeDecode(bstring)));
            }
            log.setOldPeers(peers);
        }
        if (entry.getLearnersCount() > 0) {
            final List<PeerId> peers = new ArrayList<>(entry.getLearnersCount());
            for (final ByteString bstring : entry.getLearnersList()) {
                peers.add(JRaftUtils.getPeerId(AsciiStringUtil.unsafeDecode(bstring)));
            }
            log.setLearners(peers);
        }
        if (entry.getOldLearnersCount() > 0) {
            final List<PeerId> peers = new ArrayList<>(entry.getOldLearnersCount());
            for (final ByteString bstring : entry.getOldLearnersList()) {
                peers.add(JRaftUtils.getPeerId(AsciiStringUtil.unsafeDecode(bstring)));
            }
            log.setOldLearners(peers);
        }
        final ByteString data = entry.getData();
        if (!data.isEmpty()) {
            log.setData(ByteBuffer.wrap(ZeroByteStringHelper.getByteArray(data)));
        }
        return log;
    } catch (final InvalidProtocolBufferException e) {
        LOG.error("Fail to decode pb log entry", e);
        return null;
    }
}
Also used : ByteString(com.google.protobuf.ByteString) PBLogEntry(com.alipay.sofa.jraft.entity.codec.v2.LogOutter.PBLogEntry) ArrayList(java.util.ArrayList) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) LogEntry(com.alipay.sofa.jraft.entity.LogEntry) PBLogEntry(com.alipay.sofa.jraft.entity.codec.v2.LogOutter.PBLogEntry) PeerId(com.alipay.sofa.jraft.entity.PeerId)

Example 43 with LogEntry

use of com.alipay.sofa.jraft.entity.LogEntry in project sofa-jraft by sofastack.

the class TestUtils method mockEntry.

public static LogEntry mockEntry(final int index, final int term, final int dataSize) {
    LogEntry entry = new LogEntry(EnumOutter.EntryType.ENTRY_TYPE_NO_OP);
    entry.setId(new LogId(index, term));
    if (dataSize > 0) {
        byte[] bs = new byte[dataSize];
        ThreadLocalRandom.current().nextBytes(bs);
        entry.setData(ByteBuffer.wrap(bs));
    }
    return entry;
}
Also used : LogId(com.alipay.sofa.jraft.entity.LogId) LogEntry(com.alipay.sofa.jraft.entity.LogEntry)

Example 44 with LogEntry

use of com.alipay.sofa.jraft.entity.LogEntry in project sofa-jraft by sofastack.

the class NodeImpl method bootstrap.

public boolean bootstrap(final BootstrapOptions opts) throws InterruptedException {
    if (opts.getLastLogIndex() > 0 && (opts.getGroupConf().isEmpty() || opts.getFsm() == null)) {
        LOG.error("Invalid arguments for bootstrap, groupConf={}, fsm={}, lastLogIndex={}.", opts.getGroupConf(), opts.getFsm(), opts.getLastLogIndex());
        return false;
    }
    if (opts.getGroupConf().isEmpty()) {
        LOG.error("Bootstrapping an empty node makes no sense.");
        return false;
    }
    Requires.requireNonNull(opts.getServiceFactory(), "Null jraft service factory");
    this.serviceFactory = opts.getServiceFactory();
    // Term is not an option since changing it is very dangerous
    final long bootstrapLogTerm = opts.getLastLogIndex() > 0 ? 1 : 0;
    final LogId bootstrapId = new LogId(opts.getLastLogIndex(), bootstrapLogTerm);
    this.options = new NodeOptions();
    this.raftOptions = this.options.getRaftOptions();
    this.metrics = new NodeMetrics(opts.isEnableMetrics());
    this.options.setFsm(opts.getFsm());
    this.options.setLogUri(opts.getLogUri());
    this.options.setRaftMetaUri(opts.getRaftMetaUri());
    this.options.setSnapshotUri(opts.getSnapshotUri());
    this.configManager = new ConfigurationManager();
    // Create fsmCaller at first as logManager needs it to report error
    this.fsmCaller = new FSMCallerImpl();
    if (!initLogStorage()) {
        LOG.error("Fail to init log storage.");
        return false;
    }
    if (!initMetaStorage()) {
        LOG.error("Fail to init meta storage.");
        return false;
    }
    if (this.currTerm == 0) {
        this.currTerm = 1;
        if (!this.metaStorage.setTermAndVotedFor(1, new PeerId())) {
            LOG.error("Fail to set term.");
            return false;
        }
    }
    if (opts.getFsm() != null && !initFSMCaller(bootstrapId)) {
        LOG.error("Fail to init fsm caller.");
        return false;
    }
    final LogEntry entry = new LogEntry(EnumOutter.EntryType.ENTRY_TYPE_CONFIGURATION);
    entry.getId().setTerm(this.currTerm);
    entry.setPeers(opts.getGroupConf().listPeers());
    entry.setLearners(opts.getGroupConf().listLearners());
    final List<LogEntry> entries = new ArrayList<>();
    entries.add(entry);
    final BootstrapStableClosure bootstrapDone = new BootstrapStableClosure();
    this.logManager.appendEntries(entries, bootstrapDone);
    if (!bootstrapDone.await().isOk()) {
        LOG.error("Fail to append configuration.");
        return false;
    }
    if (opts.getLastLogIndex() > 0) {
        if (!initSnapshotStorage()) {
            LOG.error("Fail to init snapshot storage.");
            return false;
        }
        final SynchronizedClosure snapshotDone = new SynchronizedClosure();
        this.snapshotExecutor.doSnapshot(snapshotDone);
        if (!snapshotDone.await().isOk()) {
            LOG.error("Fail to save snapshot, status={}.", snapshotDone.getStatus());
            return false;
        }
    }
    if (this.logManager.getFirstLogIndex() != opts.getLastLogIndex() + 1) {
        throw new IllegalStateException("First and last log index mismatch");
    }
    if (opts.getLastLogIndex() > 0) {
        if (this.logManager.getLastLogIndex() != opts.getLastLogIndex()) {
            throw new IllegalStateException("Last log index mismatch");
        }
    } else {
        if (this.logManager.getLastLogIndex() != opts.getLastLogIndex() + 1) {
            throw new IllegalStateException("Last log index mismatch");
        }
    }
    return true;
}
Also used : SynchronizedClosure(com.alipay.sofa.jraft.closure.SynchronizedClosure) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) NodeOptions(com.alipay.sofa.jraft.option.NodeOptions) LogId(com.alipay.sofa.jraft.entity.LogId) ConfigurationManager(com.alipay.sofa.jraft.conf.ConfigurationManager) LogEntry(com.alipay.sofa.jraft.entity.LogEntry) PeerId(com.alipay.sofa.jraft.entity.PeerId)

Example 45 with LogEntry

use of com.alipay.sofa.jraft.entity.LogEntry in project sofa-jraft by sofastack.

the class NodeImpl method apply.

@Override
public void apply(final Task task) {
    if (this.shutdownLatch != null) {
        Utils.runClosureInThread(task.getDone(), new Status(RaftError.ENODESHUTDOWN, "Node is shutting down."));
        throw new IllegalStateException("Node is shutting down");
    }
    Requires.requireNonNull(task, "Null task");
    final LogEntry entry = new LogEntry();
    entry.setData(task.getData());
    final EventTranslator<LogEntryAndClosure> translator = (event, sequence) -> {
        event.reset();
        event.done = task.getDone();
        event.entry = entry;
        event.expectedTerm = task.getExpectedTerm();
    };
    switch(this.options.getApplyTaskMode()) {
        case Blocking:
            this.applyQueue.publishEvent(translator);
            break;
        case NonBlocking:
        default:
            if (!this.applyQueue.tryPublishEvent(translator)) {
                String errorMsg = "Node is busy, has too many tasks, queue is full and bufferSize=" + this.applyQueue.getBufferSize();
                Utils.runClosureInThread(task.getDone(), new Status(RaftError.EBUSY, errorMsg));
                LOG.warn("Node {} applyQueue is overload.", getNodeId());
                this.metrics.recordTimes("apply-task-overload-times", 1);
                if (task.getDone() == null) {
                    throw new OverloadException(errorMsg);
                }
            }
            break;
    }
}
Also used : Status(com.alipay.sofa.jraft.Status) SnapshotExecutorImpl(com.alipay.sofa.jraft.storage.snapshot.SnapshotExecutorImpl) Platform(com.alipay.sofa.jraft.util.Platform) StringUtils(org.apache.commons.lang.StringUtils) Ballot(com.alipay.sofa.jraft.entity.Ballot) RaftOptions(com.alipay.sofa.jraft.option.RaftOptions) LeaderChangeContext(com.alipay.sofa.jraft.entity.LeaderChangeContext) SystemPropertyUtil(com.alipay.sofa.jraft.util.SystemPropertyUtil) InstallSnapshotResponse(com.alipay.sofa.jraft.rpc.RpcRequests.InstallSnapshotResponse) ReplicatorGroup(com.alipay.sofa.jraft.ReplicatorGroup) RaftMetaStorageOptions(com.alipay.sofa.jraft.option.RaftMetaStorageOptions) RaftMetaStorage(com.alipay.sofa.jraft.storage.RaftMetaStorage) AppendEntriesResponse(com.alipay.sofa.jraft.rpc.RpcRequests.AppendEntriesResponse) RpcFactoryHelper(com.alipay.sofa.jraft.util.RpcFactoryHelper) ConfigurationEntry(com.alipay.sofa.jraft.conf.ConfigurationEntry) RpcResponseClosure(com.alipay.sofa.jraft.rpc.RpcResponseClosure) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) ConfigurationManager(com.alipay.sofa.jraft.conf.ConfigurationManager) PeerId(com.alipay.sofa.jraft.entity.PeerId) Set(java.util.Set) RaftServerService(com.alipay.sofa.jraft.rpc.RaftServerService) JRaftServiceFactory(com.alipay.sofa.jraft.JRaftServiceFactory) JRaftUtils(com.alipay.sofa.jraft.JRaftUtils) CountDownLatch(java.util.concurrent.CountDownLatch) ReadOnlyServiceOptions(com.alipay.sofa.jraft.option.ReadOnlyServiceOptions) RequestVoteResponse(com.alipay.sofa.jraft.rpc.RpcRequests.RequestVoteResponse) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) LogId(com.alipay.sofa.jraft.entity.LogId) FSMCallerOptions(com.alipay.sofa.jraft.option.FSMCallerOptions) ReadIndexResponse(com.alipay.sofa.jraft.rpc.RpcRequests.ReadIndexResponse) ReadOnlyOption(com.alipay.sofa.jraft.option.ReadOnlyOption) JRaftSignalHandler(com.alipay.sofa.jraft.util.JRaftSignalHandler) ArrayList(java.util.ArrayList) LogManagerOptions(com.alipay.sofa.jraft.option.LogManagerOptions) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) LogManagerImpl(com.alipay.sofa.jraft.storage.impl.LogManagerImpl) RaftError(com.alipay.sofa.jraft.error.RaftError) EventHandler(com.lmax.disruptor.EventHandler) LinkedHashSet(java.util.LinkedHashSet) SignalHelper(com.alipay.sofa.jraft.util.SignalHelper) SnapshotExecutorOptions(com.alipay.sofa.jraft.option.SnapshotExecutorOptions) RaftOutter(com.alipay.sofa.jraft.entity.RaftOutter) NamedThreadFactory(com.alipay.sofa.jraft.util.NamedThreadFactory) DisruptorBuilder(com.alipay.sofa.jraft.util.DisruptorBuilder) ClosureQueue(com.alipay.sofa.jraft.closure.ClosureQueue) TimeoutNowRequest(com.alipay.sofa.jraft.rpc.RpcRequests.TimeoutNowRequest) RaftClientService(com.alipay.sofa.jraft.rpc.RaftClientService) Lock(java.util.concurrent.locks.Lock) FSMCaller(com.alipay.sofa.jraft.FSMCaller) RequestVoteRequest(com.alipay.sofa.jraft.rpc.RpcRequests.RequestVoteRequest) InstallSnapshotRequest(com.alipay.sofa.jraft.rpc.RpcRequests.InstallSnapshotRequest) CatchUpClosure(com.alipay.sofa.jraft.closure.CatchUpClosure) Disruptor(com.lmax.disruptor.dsl.Disruptor) OverloadException(com.alipay.sofa.jraft.error.OverloadException) ScheduledFuture(java.util.concurrent.ScheduledFuture) LoggerFactory(org.slf4j.LoggerFactory) ByteBuffer(java.nio.ByteBuffer) JRaftServiceLoader(com.alipay.sofa.jraft.util.JRaftServiceLoader) Describer(com.alipay.sofa.jraft.util.Describer) BlockingWaitStrategy(com.lmax.disruptor.BlockingWaitStrategy) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) LogManager(com.alipay.sofa.jraft.storage.LogManager) RaftTimerFactory(com.alipay.sofa.jraft.util.timer.RaftTimerFactory) LogExceptionHandler(com.alipay.sofa.jraft.util.LogExceptionHandler) OnlyForTest(com.alipay.sofa.jraft.util.OnlyForTest) TimeoutNowResponse(com.alipay.sofa.jraft.rpc.RpcRequests.TimeoutNowResponse) Configuration(com.alipay.sofa.jraft.conf.Configuration) Collection(java.util.Collection) SynchronizedClosure(com.alipay.sofa.jraft.closure.SynchronizedClosure) BootstrapOptions(com.alipay.sofa.jraft.option.BootstrapOptions) RpcRequestClosure(com.alipay.sofa.jraft.rpc.RpcRequestClosure) ReadIndexClosure(com.alipay.sofa.jraft.closure.ReadIndexClosure) LogStorage(com.alipay.sofa.jraft.storage.LogStorage) Collectors(java.util.stream.Collectors) List(java.util.List) RaftException(com.alipay.sofa.jraft.error.RaftException) Requires(com.alipay.sofa.jraft.util.Requires) LogIndexOutOfBoundsException(com.alipay.sofa.jraft.error.LogIndexOutOfBoundsException) AppendEntriesRequest(com.alipay.sofa.jraft.rpc.RpcRequests.AppendEntriesRequest) UserLog(com.alipay.sofa.jraft.entity.UserLog) LogNotFoundException(com.alipay.sofa.jraft.error.LogNotFoundException) ReadIndexRequest(com.alipay.sofa.jraft.rpc.RpcRequests.ReadIndexRequest) LongHeldDetectingReadWriteLock(com.alipay.sofa.jraft.util.concurrent.LongHeldDetectingReadWriteLock) Utils(com.alipay.sofa.jraft.util.Utils) EnumOutter(com.alipay.sofa.jraft.entity.EnumOutter) SnapshotExecutor(com.alipay.sofa.jraft.storage.SnapshotExecutor) DefaultRaftClientService(com.alipay.sofa.jraft.rpc.impl.core.DefaultRaftClientService) HashSet(java.util.HashSet) NodeManager(com.alipay.sofa.jraft.NodeManager) Closure(com.alipay.sofa.jraft.Closure) ThreadId(com.alipay.sofa.jraft.util.ThreadId) ClosureQueueImpl(com.alipay.sofa.jraft.closure.ClosureQueueImpl) Logger(org.slf4j.Logger) DisruptorMetricSet(com.alipay.sofa.jraft.util.DisruptorMetricSet) NodeId(com.alipay.sofa.jraft.entity.NodeId) RingBuffer(com.lmax.disruptor.RingBuffer) ProducerType(com.lmax.disruptor.dsl.ProducerType) Status(com.alipay.sofa.jraft.Status) NodeOptions(com.alipay.sofa.jraft.option.NodeOptions) TimeUnit(java.util.concurrent.TimeUnit) Task(com.alipay.sofa.jraft.entity.Task) EventTranslator(com.lmax.disruptor.EventTranslator) Node(com.alipay.sofa.jraft.Node) LogEntry(com.alipay.sofa.jraft.entity.LogEntry) ReplicatorGroupOptions(com.alipay.sofa.jraft.option.ReplicatorGroupOptions) Message(com.google.protobuf.Message) ReadOnlyService(com.alipay.sofa.jraft.ReadOnlyService) BallotBoxOptions(com.alipay.sofa.jraft.option.BallotBoxOptions) EventFactory(com.lmax.disruptor.EventFactory) RepeatedTimer(com.alipay.sofa.jraft.util.RepeatedTimer) RpcResponseClosureAdapter(com.alipay.sofa.jraft.rpc.RpcResponseClosureAdapter) OverloadException(com.alipay.sofa.jraft.error.OverloadException) LogEntry(com.alipay.sofa.jraft.entity.LogEntry)

Aggregations

LogEntry (com.alipay.sofa.jraft.entity.LogEntry)50 LogId (com.alipay.sofa.jraft.entity.LogId)27 Test (org.junit.Test)19 PeerId (com.alipay.sofa.jraft.entity.PeerId)13 Status (com.alipay.sofa.jraft.Status)11 BaseStorageTest (com.alipay.sofa.jraft.storage.BaseStorageTest)11 ArrayList (java.util.ArrayList)10 LogManager (com.alipay.sofa.jraft.storage.LogManager)7 CountDownLatch (java.util.concurrent.CountDownLatch)7 ConfigurationEntry (com.alipay.sofa.jraft.conf.ConfigurationEntry)6 ByteBuffer (java.nio.ByteBuffer)6 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)6 Configuration (com.alipay.sofa.jraft.conf.Configuration)5 Closure (com.alipay.sofa.jraft.Closure)3 SynchronizedClosure (com.alipay.sofa.jraft.closure.SynchronizedClosure)3 ConfigurationManager (com.alipay.sofa.jraft.conf.ConfigurationManager)3 RaftOutter (com.alipay.sofa.jraft.entity.RaftOutter)3 UserLog (com.alipay.sofa.jraft.entity.UserLog)3 FSMCaller (com.alipay.sofa.jraft.FSMCaller)2 JRaftServiceFactory (com.alipay.sofa.jraft.JRaftServiceFactory)2