Search in sources :

Example 1 with RepeatedTimer

use of com.alipay.sofa.jraft.util.RepeatedTimer in project sofa-jraft by sofastack.

the class NodeImpl method init.

@Override
public boolean init(final NodeOptions opts) {
    Requires.requireNonNull(opts, "Null node options");
    Requires.requireNonNull(opts.getRaftOptions(), "Null raft options");
    Requires.requireNonNull(opts.getServiceFactory(), "Null jraft service factory");
    this.serviceFactory = opts.getServiceFactory();
    this.options = opts;
    this.raftOptions = opts.getRaftOptions();
    this.metrics = new NodeMetrics(opts.isEnableMetrics());
    this.serverId.setPriority(opts.getElectionPriority());
    this.electionTimeoutCounter = 0;
    if (this.serverId.getIp().equals(Utils.IP_ANY)) {
        LOG.error("Node can't started from IP_ANY.");
        return false;
    }
    if (!NodeManager.getInstance().serverExists(this.serverId.getEndpoint())) {
        LOG.error("No RPC server attached to, did you forget to call addService?");
        return false;
    }
    this.timerManager = TIMER_FACTORY.getRaftScheduler(this.options.isSharedTimerPool(), this.options.getTimerPoolSize(), "JRaft-Node-ScheduleThreadPool");
    // Init timers
    final String suffix = getNodeId().toString();
    String name = "JRaft-VoteTimer-" + suffix;
    this.voteTimer = new RepeatedTimer(name, this.options.getElectionTimeoutMs(), TIMER_FACTORY.getVoteTimer(this.options.isSharedVoteTimer(), name)) {

        @Override
        protected void onTrigger() {
            handleVoteTimeout();
        }

        @Override
        protected int adjustTimeout(final int timeoutMs) {
            return randomTimeout(timeoutMs);
        }
    };
    name = "JRaft-ElectionTimer-" + suffix;
    this.electionTimer = new RepeatedTimer(name, this.options.getElectionTimeoutMs(), TIMER_FACTORY.getElectionTimer(this.options.isSharedElectionTimer(), name)) {

        @Override
        protected void onTrigger() {
            handleElectionTimeout();
        }

        @Override
        protected int adjustTimeout(final int timeoutMs) {
            return randomTimeout(timeoutMs);
        }
    };
    name = "JRaft-StepDownTimer-" + suffix;
    this.stepDownTimer = new RepeatedTimer(name, this.options.getElectionTimeoutMs() >> 1, TIMER_FACTORY.getStepDownTimer(this.options.isSharedStepDownTimer(), name)) {

        @Override
        protected void onTrigger() {
            handleStepDownTimeout();
        }
    };
    name = "JRaft-SnapshotTimer-" + suffix;
    this.snapshotTimer = new RepeatedTimer(name, this.options.getSnapshotIntervalSecs() * 1000, TIMER_FACTORY.getSnapshotTimer(this.options.isSharedSnapshotTimer(), name)) {

        private volatile boolean firstSchedule = true;

        @Override
        protected void onTrigger() {
            handleSnapshotTimeout();
        }

        @Override
        protected int adjustTimeout(final int timeoutMs) {
            if (!this.firstSchedule) {
                return timeoutMs;
            }
            // Randomize the first snapshot trigger timeout
            this.firstSchedule = false;
            if (timeoutMs > 0) {
                int half = timeoutMs / 2;
                return half + ThreadLocalRandom.current().nextInt(half);
            } else {
                return timeoutMs;
            }
        }
    };
    this.configManager = new ConfigurationManager();
    this.applyDisruptor = // 
    DisruptorBuilder.<LogEntryAndClosure>newInstance().setRingBufferSize(// 
    this.raftOptions.getDisruptorBufferSize()).setEventFactory(// 
    new LogEntryAndClosureFactory()).setThreadFactory(// 
    new NamedThreadFactory("JRaft-NodeImpl-Disruptor-", true)).setProducerType(// 
    ProducerType.MULTI).setWaitStrategy(// 
    new BlockingWaitStrategy()).build();
    this.applyDisruptor.handleEventsWith(new LogEntryAndClosureHandler());
    this.applyDisruptor.setDefaultExceptionHandler(new LogExceptionHandler<Object>(getClass().getSimpleName()));
    this.applyQueue = this.applyDisruptor.start();
    if (this.metrics.getMetricRegistry() != null) {
        this.metrics.getMetricRegistry().register("jraft-node-impl-disruptor", new DisruptorMetricSet(this.applyQueue));
    }
    this.fsmCaller = new FSMCallerImpl();
    if (!initLogStorage()) {
        LOG.error("Node {} initLogStorage failed.", getNodeId());
        return false;
    }
    if (!initMetaStorage()) {
        LOG.error("Node {} initMetaStorage failed.", getNodeId());
        return false;
    }
    if (!initFSMCaller(new LogId(0, 0))) {
        LOG.error("Node {} initFSMCaller failed.", getNodeId());
        return false;
    }
    this.ballotBox = new BallotBox();
    final BallotBoxOptions ballotBoxOpts = new BallotBoxOptions();
    ballotBoxOpts.setWaiter(this.fsmCaller);
    ballotBoxOpts.setClosureQueue(this.closureQueue);
    if (!this.ballotBox.init(ballotBoxOpts)) {
        LOG.error("Node {} init ballotBox failed.", getNodeId());
        return false;
    }
    if (!initSnapshotStorage()) {
        LOG.error("Node {} initSnapshotStorage failed.", getNodeId());
        return false;
    }
    final Status st = this.logManager.checkConsistency();
    if (!st.isOk()) {
        LOG.error("Node {} is initialized with inconsistent log, status={}.", getNodeId(), st);
        return false;
    }
    this.conf = new ConfigurationEntry();
    this.conf.setId(new LogId());
    // if have log using conf in log, else using conf in options
    if (this.logManager.getLastLogIndex() > 0) {
        checkAndSetConfiguration(false);
    } else {
        this.conf.setConf(this.options.getInitialConf());
        // initially set to max(priority of all nodes)
        this.targetPriority = getMaxPriorityOfNodes(this.conf.getConf().getPeers());
    }
    if (!this.conf.isEmpty()) {
        Requires.requireTrue(this.conf.isValid(), "Invalid conf: %s", this.conf);
    } else {
        LOG.info("Init node {} with empty conf.", this.serverId);
    }
    // TODO RPC service and ReplicatorGroup is in cycle dependent, refactor it
    this.replicatorGroup = new ReplicatorGroupImpl();
    this.rpcService = new DefaultRaftClientService(this.replicatorGroup);
    final ReplicatorGroupOptions rgOpts = new ReplicatorGroupOptions();
    rgOpts.setHeartbeatTimeoutMs(heartbeatTimeout(this.options.getElectionTimeoutMs()));
    rgOpts.setElectionTimeoutMs(this.options.getElectionTimeoutMs());
    rgOpts.setLogManager(this.logManager);
    rgOpts.setBallotBox(this.ballotBox);
    rgOpts.setNode(this);
    rgOpts.setRaftRpcClientService(this.rpcService);
    rgOpts.setSnapshotStorage(this.snapshotExecutor != null ? this.snapshotExecutor.getSnapshotStorage() : null);
    rgOpts.setRaftOptions(this.raftOptions);
    rgOpts.setTimerManager(this.timerManager);
    // Adds metric registry to RPC service.
    this.options.setMetricRegistry(this.metrics.getMetricRegistry());
    if (!this.rpcService.init(this.options)) {
        LOG.error("Fail to init rpc service.");
        return false;
    }
    this.replicatorGroup.init(new NodeId(this.groupId, this.serverId), rgOpts);
    this.readOnlyService = new ReadOnlyServiceImpl();
    final ReadOnlyServiceOptions rosOpts = new ReadOnlyServiceOptions();
    rosOpts.setFsmCaller(this.fsmCaller);
    rosOpts.setNode(this);
    rosOpts.setRaftOptions(this.raftOptions);
    if (!this.readOnlyService.init(rosOpts)) {
        LOG.error("Fail to init readOnlyService.");
        return false;
    }
    // set state to follower
    this.state = State.STATE_FOLLOWER;
    if (LOG.isInfoEnabled()) {
        LOG.info("Node {} init, term={}, lastLogId={}, conf={}, oldConf={}.", getNodeId(), this.currTerm, this.logManager.getLastLogId(false), this.conf.getConf(), this.conf.getOldConf());
    }
    if (this.snapshotExecutor != null && this.options.getSnapshotIntervalSecs() > 0) {
        LOG.debug("Node {} start snapshot timer, term={}.", getNodeId(), this.currTerm);
        this.snapshotTimer.start();
    }
    if (!this.conf.isEmpty()) {
        stepDown(this.currTerm, false, new Status());
    }
    if (!NodeManager.getInstance().add(this)) {
        LOG.error("NodeManager add {} failed.", getNodeId());
        return false;
    }
    // Now the raft node is started , have to acquire the writeLock to avoid race
    // conditions
    this.writeLock.lock();
    if (this.conf.isStable() && this.conf.getConf().size() == 1 && this.conf.getConf().contains(this.serverId)) {
        // The group contains only this server which must be the LEADER, trigger
        // the timer immediately.
        electSelf();
    } else {
        this.writeLock.unlock();
    }
    return true;
}
Also used : BallotBoxOptions(com.alipay.sofa.jraft.option.BallotBoxOptions) ReadOnlyServiceOptions(com.alipay.sofa.jraft.option.ReadOnlyServiceOptions) RepeatedTimer(com.alipay.sofa.jraft.util.RepeatedTimer) ConfigurationManager(com.alipay.sofa.jraft.conf.ConfigurationManager) ConfigurationEntry(com.alipay.sofa.jraft.conf.ConfigurationEntry) Status(com.alipay.sofa.jraft.Status) BlockingWaitStrategy(com.lmax.disruptor.BlockingWaitStrategy) NamedThreadFactory(com.alipay.sofa.jraft.util.NamedThreadFactory) DisruptorMetricSet(com.alipay.sofa.jraft.util.DisruptorMetricSet) ReplicatorGroupOptions(com.alipay.sofa.jraft.option.ReplicatorGroupOptions) NodeId(com.alipay.sofa.jraft.entity.NodeId) DefaultRaftClientService(com.alipay.sofa.jraft.rpc.impl.core.DefaultRaftClientService) LogId(com.alipay.sofa.jraft.entity.LogId)

Example 2 with RepeatedTimer

use of com.alipay.sofa.jraft.util.RepeatedTimer in project sofa-jraft by sofastack.

the class NodeImpl method shutdown.

@Override
public void shutdown(Closure done) {
    List<RepeatedTimer> timers = null;
    this.writeLock.lock();
    try {
        LOG.info("Node {} shutdown, currTerm={} state={}.", getNodeId(), this.currTerm, this.state);
        if (this.state.compareTo(State.STATE_SHUTTING) < 0) {
            NodeManager.getInstance().remove(this);
            // If it is follower, call on_stop_following in step_down
            if (this.state.compareTo(State.STATE_FOLLOWER) <= 0) {
                stepDown(this.currTerm, this.state == State.STATE_LEADER, new Status(RaftError.ESHUTDOWN, "Raft node is going to quit."));
            }
            this.state = State.STATE_SHUTTING;
            // Stop all timers
            timers = stopAllTimers();
            if (this.readOnlyService != null) {
                this.readOnlyService.shutdown();
            }
            if (this.logManager != null) {
                this.logManager.shutdown();
            }
            if (this.metaStorage != null) {
                this.metaStorage.shutdown();
            }
            if (this.snapshotExecutor != null) {
                this.snapshotExecutor.shutdown();
            }
            if (this.wakingCandidate != null) {
                Replicator.stop(this.wakingCandidate);
            }
            if (this.fsmCaller != null) {
                this.fsmCaller.shutdown();
            }
            if (this.rpcService != null) {
                this.rpcService.shutdown();
            }
            if (this.applyQueue != null) {
                final CountDownLatch latch = new CountDownLatch(1);
                this.shutdownLatch = latch;
                Utils.runInThread(() -> this.applyQueue.publishEvent((event, sequence) -> event.shutdownLatch = latch));
            } else {
                final int num = GLOBAL_NUM_NODES.decrementAndGet();
                LOG.info("The number of active nodes decrement to {}.", num);
            }
            if (this.timerManager != null) {
                this.timerManager.shutdown();
            }
        }
        if (this.state != State.STATE_SHUTDOWN) {
            if (done != null) {
                this.shutdownContinuations.add(done);
                done = null;
            }
            return;
        }
    } finally {
        this.writeLock.unlock();
        // Destroy all timers out of lock
        if (timers != null) {
            destroyAllTimers(timers);
        }
        // Call join() asynchronously
        final Closure shutdownHook = done;
        Utils.runInThread(() -> {
            try {
                join();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                // a writeLock which is already held by the caller
                if (shutdownHook != null) {
                    shutdownHook.run(Status.OK());
                }
            }
        });
    }
}
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) RpcResponseClosure(com.alipay.sofa.jraft.rpc.RpcResponseClosure) CatchUpClosure(com.alipay.sofa.jraft.closure.CatchUpClosure) SynchronizedClosure(com.alipay.sofa.jraft.closure.SynchronizedClosure) RpcRequestClosure(com.alipay.sofa.jraft.rpc.RpcRequestClosure) ReadIndexClosure(com.alipay.sofa.jraft.closure.ReadIndexClosure) Closure(com.alipay.sofa.jraft.Closure) RepeatedTimer(com.alipay.sofa.jraft.util.RepeatedTimer) CountDownLatch(java.util.concurrent.CountDownLatch)

Aggregations

Status (com.alipay.sofa.jraft.Status)2 ConfigurationEntry (com.alipay.sofa.jraft.conf.ConfigurationEntry)2 ConfigurationManager (com.alipay.sofa.jraft.conf.ConfigurationManager)2 LogId (com.alipay.sofa.jraft.entity.LogId)2 NodeId (com.alipay.sofa.jraft.entity.NodeId)2 BallotBoxOptions (com.alipay.sofa.jraft.option.BallotBoxOptions)2 ReadOnlyServiceOptions (com.alipay.sofa.jraft.option.ReadOnlyServiceOptions)2 ReplicatorGroupOptions (com.alipay.sofa.jraft.option.ReplicatorGroupOptions)2 DefaultRaftClientService (com.alipay.sofa.jraft.rpc.impl.core.DefaultRaftClientService)2 DisruptorMetricSet (com.alipay.sofa.jraft.util.DisruptorMetricSet)2 NamedThreadFactory (com.alipay.sofa.jraft.util.NamedThreadFactory)2 RepeatedTimer (com.alipay.sofa.jraft.util.RepeatedTimer)2 BlockingWaitStrategy (com.lmax.disruptor.BlockingWaitStrategy)2 Closure (com.alipay.sofa.jraft.Closure)1 FSMCaller (com.alipay.sofa.jraft.FSMCaller)1 JRaftServiceFactory (com.alipay.sofa.jraft.JRaftServiceFactory)1 JRaftUtils (com.alipay.sofa.jraft.JRaftUtils)1 Node (com.alipay.sofa.jraft.Node)1 NodeManager (com.alipay.sofa.jraft.NodeManager)1 ReadOnlyService (com.alipay.sofa.jraft.ReadOnlyService)1