Search in sources :

Example 1 with ConfigurationEntry

use of com.alipay.sofa.jraft.conf.ConfigurationEntry in project sofa-jraft by sofastack.

the class BaseLogStorageTest method testLoadWithConfigManager.

@Test
public void testLoadWithConfigManager() {
    assertTrue(this.confManager.getLastConfiguration().isEmpty());
    final LogEntry confEntry1 = new LogEntry(EnumOutter.EntryType.ENTRY_TYPE_CONFIGURATION);
    confEntry1.setId(new LogId(99, 1));
    confEntry1.setPeers(JRaftUtils.getConfiguration("localhost:8081,localhost:8082").listPeers());
    final LogEntry confEntry2 = new LogEntry(EnumOutter.EntryType.ENTRY_TYPE_CONFIGURATION);
    confEntry2.setId(new LogId(100, 2));
    confEntry2.setPeers(JRaftUtils.getConfiguration("localhost:8081,localhost:8082,localhost:8083").listPeers());
    assertTrue(this.logStorage.appendEntry(confEntry1));
    assertEquals(1, this.logStorage.appendEntries(Arrays.asList(confEntry2)));
    // reload log storage.
    this.logStorage.shutdown();
    this.logStorage = newLogStorage();
    this.logStorage.init(newLogStorageOptions());
    ConfigurationEntry conf = this.confManager.getLastConfiguration();
    assertNotNull(conf);
    assertFalse(conf.isEmpty());
    assertEquals("localhost:8081,localhost:8082,localhost:8083", conf.getConf().toString());
    conf = this.confManager.get(99);
    assertNotNull(conf);
    assertFalse(conf.isEmpty());
    assertEquals("localhost:8081,localhost:8082", conf.getConf().toString());
}
Also used : LogId(com.alipay.sofa.jraft.entity.LogId) ConfigurationEntry(com.alipay.sofa.jraft.conf.ConfigurationEntry) LogEntry(com.alipay.sofa.jraft.entity.LogEntry) Test(org.junit.Test) BaseStorageTest(com.alipay.sofa.jraft.storage.BaseStorageTest)

Example 2 with ConfigurationEntry

use of com.alipay.sofa.jraft.conf.ConfigurationEntry in project sofa-jraft by sofastack.

the class LogManagerTest method testGetConfiguration.

@Test
public void testGetConfiguration() throws Exception {
    assertTrue(this.logManager.getConfiguration(1).isEmpty());
    final List<LogEntry> entries = new ArrayList<>(2);
    final LogEntry confEntry1 = new LogEntry(EnumOutter.EntryType.ENTRY_TYPE_CONFIGURATION);
    confEntry1.setId(new LogId(0, 1));
    confEntry1.setPeers(JRaftUtils.getConfiguration("localhost:8081,localhost:8082").listPeers());
    final LogEntry confEntry2 = new LogEntry(EnumOutter.EntryType.ENTRY_TYPE_CONFIGURATION);
    confEntry2.setId(new LogId(0, 2));
    confEntry2.setPeers(JRaftUtils.getConfiguration("localhost:8081,localhost:8082,localhost:8083").listPeers());
    confEntry2.setOldPeers(confEntry1.getPeers());
    entries.add(confEntry1);
    entries.add(confEntry2);
    final CountDownLatch latch = new CountDownLatch(1);
    this.logManager.appendEntries(new ArrayList<>(entries), new LogManager.StableClosure() {

        @Override
        public void run(final Status status) {
            assertTrue(status.isOk());
            latch.countDown();
        }
    });
    latch.await();
    ConfigurationEntry entry = this.logManager.getConfiguration(1);
    assertEquals("localhost:8081,localhost:8082", entry.getConf().toString());
    assertTrue(entry.getOldConf().isEmpty());
    entry = this.logManager.getConfiguration(2);
    assertEquals("localhost:8081,localhost:8082,localhost:8083", entry.getConf().toString());
    assertEquals("localhost:8081,localhost:8082", entry.getOldConf().toString());
}
Also used : Status(com.alipay.sofa.jraft.Status) ArrayList(java.util.ArrayList) CountDownLatch(java.util.concurrent.CountDownLatch) LogId(com.alipay.sofa.jraft.entity.LogId) LogManager(com.alipay.sofa.jraft.storage.LogManager) ConfigurationEntry(com.alipay.sofa.jraft.conf.ConfigurationEntry) LogEntry(com.alipay.sofa.jraft.entity.LogEntry) Test(org.junit.Test) BaseStorageTest(com.alipay.sofa.jraft.storage.BaseStorageTest)

Example 3 with ConfigurationEntry

use of com.alipay.sofa.jraft.conf.ConfigurationEntry in project sofa-jraft by sofastack.

the class LogManagerTest method testCheckAndSetConfiguration.

@Test
public void testCheckAndSetConfiguration() throws Exception {
    assertNull(this.logManager.checkAndSetConfiguration(null));
    final ConfigurationEntry entry = new ConfigurationEntry();
    entry.setId(new LogId(0, 1));
    entry.setConf(JRaftUtils.getConfiguration("localhost:8081,localhost:8082"));
    assertSame(entry, this.logManager.checkAndSetConfiguration(entry));
    testGetConfiguration();
    final ConfigurationEntry lastEntry = this.logManager.checkAndSetConfiguration(entry);
    assertNotSame(entry, lastEntry);
    assertEquals("localhost:8081,localhost:8082,localhost:8083", lastEntry.getConf().toString());
    assertEquals("localhost:8081,localhost:8082", lastEntry.getOldConf().toString());
}
Also used : ConfigurationEntry(com.alipay.sofa.jraft.conf.ConfigurationEntry) LogId(com.alipay.sofa.jraft.entity.LogId) Test(org.junit.Test) BaseStorageTest(com.alipay.sofa.jraft.storage.BaseStorageTest)

Example 4 with ConfigurationEntry

use of com.alipay.sofa.jraft.conf.ConfigurationEntry in project sofa-jraft by sofastack.

the class TestUtils method getConfEntry.

public static ConfigurationEntry getConfEntry(final String confStr, final String oldConfStr) {
    ConfigurationEntry entry = new ConfigurationEntry();
    entry.setConf(JRaftUtils.getConfiguration(confStr));
    entry.setOldConf(JRaftUtils.getConfiguration(oldConfStr));
    return entry;
}
Also used : ConfigurationEntry(com.alipay.sofa.jraft.conf.ConfigurationEntry)

Example 5 with ConfigurationEntry

use of com.alipay.sofa.jraft.conf.ConfigurationEntry 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)

Aggregations

ConfigurationEntry (com.alipay.sofa.jraft.conf.ConfigurationEntry)13 LogId (com.alipay.sofa.jraft.entity.LogId)6 Status (com.alipay.sofa.jraft.Status)5 Configuration (com.alipay.sofa.jraft.conf.Configuration)5 Test (org.junit.Test)5 LogEntry (com.alipay.sofa.jraft.entity.LogEntry)4 PeerId (com.alipay.sofa.jraft.entity.PeerId)3 BaseStorageTest (com.alipay.sofa.jraft.storage.BaseStorageTest)3 ConfigurationManager (com.alipay.sofa.jraft.conf.ConfigurationManager)1 NodeId (com.alipay.sofa.jraft.entity.NodeId)1 BallotBoxOptions (com.alipay.sofa.jraft.option.BallotBoxOptions)1 ReadOnlyServiceOptions (com.alipay.sofa.jraft.option.ReadOnlyServiceOptions)1 ReplicatorGroupOptions (com.alipay.sofa.jraft.option.ReplicatorGroupOptions)1 DefaultRaftClientService (com.alipay.sofa.jraft.rpc.impl.core.DefaultRaftClientService)1 LogManager (com.alipay.sofa.jraft.storage.LogManager)1 SnapshotWriter (com.alipay.sofa.jraft.storage.snapshot.SnapshotWriter)1 DisruptorMetricSet (com.alipay.sofa.jraft.util.DisruptorMetricSet)1 NamedThreadFactory (com.alipay.sofa.jraft.util.NamedThreadFactory)1 RepeatedTimer (com.alipay.sofa.jraft.util.RepeatedTimer)1 BlockingWaitStrategy (com.lmax.disruptor.BlockingWaitStrategy)1