com.alipay.sofa.jraft.entity.PeerId Java Examples
The following examples show how to use
com.alipay.sofa.jraft.entity.PeerId.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CliServiceTest.java From sofa-jraft with Apache License 2.0 | 6 votes |
@Test public void testTransferLeader() throws Exception { final PeerId leader = this.cluster.getLeader().getNodeId().getPeerId().copy(); assertNotNull(leader); final Set<PeerId> peers = this.conf.getPeerSet(); PeerId targetPeer = null; for (final PeerId peer : peers) { if (!peer.equals(leader)) { targetPeer = peer; break; } } assertNotNull(targetPeer); assertTrue(this.cliService.transferLeader(this.groupId, this.conf, targetPeer).isOk()); this.cluster.waitLeader(); assertEquals(targetPeer, this.cluster.getLeader().getNodeId().getPeerId()); }
Example #2
Source File: AtomicClient.java From sofa-jraft with Apache License 2.0 | 6 votes |
public long addAndGet(PeerId peer, String key, long delta) throws InterruptedException { try { final IncrementAndGetCommand request = new IncrementAndGetCommand(); request.setKey(key); request.setDetal(delta); final Object response = this.rpcClient.invokeSync(peer.getEndpoint(), request, cliOptions.getRpcDefaultTimeout()); final BooleanCommand cmd = (BooleanCommand) response; if (cmd.isSuccess()) { return ((ValueCommand) cmd).getVlaue(); } else { throw new IllegalStateException("Server error:" + cmd.getErrorMsg()); } } catch (final Throwable t) { throw new IllegalStateException("Remoting error:" + t.getMessage()); } }
Example #3
Source File: NodeTest.java From sofa-jraft with Apache License 2.0 | 6 votes |
@Test public void testSetPeer1() throws Exception { final TestCluster cluster = new TestCluster("testSetPeer1", this.dataPath, new ArrayList<>()); final PeerId bootPeer = new PeerId(TestUtils.getMyIp(), TestUtils.INIT_PORT); assertTrue(cluster.start(bootPeer.getEndpoint())); final List<Node> nodes = cluster.getFollowers(); assertEquals(1, nodes.size()); final List<PeerId> peers = new ArrayList<>(); peers.add(bootPeer); // reset peers from empty assertTrue(nodes.get(0).resetPeers(new Configuration(peers)).isOk()); cluster.waitLeader(); assertNotNull(cluster.getLeader()); cluster.stopAll(); }
Example #4
Source File: AppendEntriesRequestProcessor.java From sofa-jraft with Apache License 2.0 | 6 votes |
@Override public void onClosed(final String remoteAddress, final Connection conn) { final PeerId peer = new PeerId(); final String peerAttr = (String) conn.getAttribute(PEER_ATTR); if (!StringUtils.isBlank(peerAttr) && peer.parse(peerAttr)) { // Clear request context when connection disconnected. for (final Map.Entry<String, ConcurrentMap<String, PeerRequestContext>> entry : this.peerRequestContexts .entrySet()) { final ConcurrentMap<String, PeerRequestContext> groupCtxs = entry.getValue(); synchronized (Utils.withLockObject(groupCtxs)) { final PeerRequestContext ctx = groupCtxs.remove(peer.toString()); if (ctx != null) { ctx.destroy(); } } } } else { LOG.info("Connection disconnected: {}", remoteAddress); } }
Example #5
Source File: NodeTest.java From sofa-jraft with Apache License 2.0 | 6 votes |
@Test public void testNodesWithSpecialPriorityElection() throws Exception { List<Integer> priorities = new ArrayList<Integer>(); priorities.add(0); priorities.add(0); priorities.add(-1); final List<PeerId> peers = TestUtils.generatePriorityPeers(3, priorities); final TestCluster cluster = new TestCluster("unittest", this.dataPath, peers); for (final PeerId peer : peers) { assertTrue(cluster.start(peer.getEndpoint(), peer.getPriority())); } // elect leader cluster.waitLeader(); // get leader final Node leader = cluster.getLeader(); assertNotNull(leader); assertEquals(3, leader.listPeers().size()); assertEquals(2, cluster.getFollowers().size()); cluster.stopAll(); }
Example #6
Source File: NodeTest.java From sofa-jraft with Apache License 2.0 | 6 votes |
@Test public void testNodesWithPartPriorityElection() throws Exception { List<Integer> priorities = new ArrayList<>(); priorities.add(100); priorities.add(40); priorities.add(-1); final List<PeerId> peers = TestUtils.generatePriorityPeers(3, priorities); final TestCluster cluster = new TestCluster("unittest", this.dataPath, peers); for (final PeerId peer : peers) { assertTrue(cluster.start(peer.getEndpoint(), peer.getPriority())); } // elect leader cluster.waitLeader(); // get leader final Node leader = cluster.getLeader(); assertNotNull(leader); assertEquals(3, leader.listPeers().size()); assertEquals(2, cluster.getFollowers().size()); cluster.stopAll(); }
Example #7
Source File: GrpcClient.java From sofa-jraft with Apache License 2.0 | 6 votes |
private Channel getChannel(final Endpoint endpoint) { return this.managedChannelPool.computeIfAbsent(endpoint, ep -> { final ManagedChannel ch = ManagedChannelBuilder.forAddress(ep.getIp(), ep.getPort()) // .usePlaintext() // .directExecutor() // .build(); // channel connection event ch.notifyWhenStateChanged(ConnectivityState.READY, () -> { final ReplicatorGroup rpGroup = replicatorGroup; if (rpGroup != null) { Utils.runInThread(() -> { final PeerId peer = new PeerId(); if (peer.parse(ep.toString())) { LOG.info("Peer {} is connected.", peer); rpGroup.checkReplicator(peer, true); } else { LOG.error("Fail to parse peer: {}.", ep); } }); } }); return ch; }); }
Example #8
Source File: AbstractCliRequestProcessorTest.java From sofa-jraft with Apache License 2.0 | 6 votes |
@Test public void testHandleRequest() { this.mockNodes(3); Mockito.when(this.node.getGroupId()).thenReturn(this.groupId); PeerId peerId = new PeerId(); peerId.parse(this.peerIdStr); Mockito.when(this.node.getOptions()).thenReturn(new NodeOptions()); Mockito.when(this.node.getNodeId()).thenReturn(new NodeId("test", peerId)); NodeManager.getInstance().addAddress(peerId.getEndpoint()); NodeManager.getInstance().add(this.node); BaseCliRequestProcessor<T> processor = newProcessor(); processor.handleRequest(this.asyncContext, createRequest(this.groupId, peerId)); ArgumentCaptor<Closure> doneArg = ArgumentCaptor.forClass(Closure.class); verify(processor.interest(), this.node, doneArg); }
Example #9
Source File: TransferLeaderRequestProcessor.java From sofa-jraft with Apache License 2.0 | 6 votes |
@Override protected Message processRequest0(final CliRequestContext ctx, final TransferLeaderRequest request, final RpcRequestClosure done) { final PeerId peer = new PeerId(); if (request.hasPeerId() && !peer.parse(request.getPeerId())) { return RpcFactoryHelper // .responseFactory() // .newResponse(defaultResp(), RaftError.EINVAL, "Fail to parse peer id %s", request.getPeerId()); } LOG.info("Receive TransferLeaderRequest to {} from {}, newLeader will be {}.", ctx.node.getNodeId(), done .getRpcCtx().getRemoteAddress(), peer); final Status st = ctx.node.transferLeadershipTo(peer); return RpcFactoryHelper // .responseFactory() // .newResponse(defaultResp(), st); }
Example #10
Source File: ConfigurationTest.java From sofa-jraft with Apache License 2.0 | 6 votes |
@Test public void testToStringParseStuff() { final String confStr = "localhost:8081,localhost:8082,localhost:8083"; final Configuration conf = JRaftUtils.getConfiguration(confStr); assertEquals(3, conf.size()); for (final PeerId peer : conf) { assertTrue(peer.toString().startsWith("localhost:80")); } assertFalse(conf.isEmpty()); assertEquals(confStr, conf.toString()); final Configuration newConf = new Configuration(); assertTrue(newConf.parse(conf.toString())); assertEquals(3, newConf.getPeerSet().size()); assertTrue(newConf.contains(new PeerId("localhost", 8081))); assertTrue(newConf.contains(new PeerId("localhost", 8082))); assertTrue(newConf.contains(new PeerId("localhost", 8083))); assertEquals(confStr, newConf.toString()); assertEquals(conf.hashCode(), newConf.hashCode()); assertEquals(conf, newConf); }
Example #11
Source File: BaseCliRequestProcessorTest.java From sofa-jraft with Apache License 2.0 | 6 votes |
@Test public void testManyNodes() { Node node1 = Mockito.mock(Node.class); Mockito.when(node1.getGroupId()).thenReturn("test"); Mockito.when(node1.getNodeId()).thenReturn(new NodeId("test", new PeerId("localhost", 8081))); NodeOptions opts = new NodeOptions(); Mockito.when(node1.getOptions()).thenReturn(opts); NodeManager.getInstance().addAddress(new Endpoint("localhost", 8081)); NodeManager.getInstance().add(node1); Node node2 = Mockito.mock(Node.class); Mockito.when(node2.getGroupId()).thenReturn("test"); Mockito.when(node2.getNodeId()).thenReturn(new NodeId("test", new PeerId("localhost", 8082))); Mockito.when(node2.getOptions()).thenReturn(opts); NodeManager.getInstance().addAddress(new Endpoint("localhost", 8082)); NodeManager.getInstance().add(node2); this.processor = new MockCliRequestProcessor(null, "test"); this.processor.handleRequest(asyncContext, TestUtils.createPingRequest()); ErrorResponse resp = (ErrorResponse) asyncContext.getResponseObject(); assertNotNull(resp); assertEquals(RaftError.EINVAL.getNumber(), resp.getErrorCode()); assertEquals("Peer must be specified since there're 2 nodes in group test", resp.getErrorMsg()); }
Example #12
Source File: RaftClient.java From sofa-registry with Apache License 2.0 | 6 votes |
public static PeerId refreshLeader(CliClientService cliClientService, String groupId, int timeout) { try { Status status = RouteTable.getInstance().refreshLeader(cliClientService, groupId, timeout); if (!status.isOk()) { throw new IllegalStateException(String.format("Refresh leader failed,error=%s", status.getErrorMsg())); } PeerId leader = RouteTable.getInstance().selectLeader(groupId); LOGGER.info("Leader is {}", leader); //avoid refresh leader config ip list must be current list,list maybe change by manage status = RouteTable.getInstance().refreshConfiguration(cliClientService, groupId, timeout); if (!status.isOk()) { throw new IllegalStateException(String.format( "Refresh configuration failed, error=%s", status.getErrorMsg())); } return leader; } catch (Exception e) { LOGGER.error("Refresh leader failed", e); throw new IllegalStateException("Refresh leader failed", e); } }
Example #13
Source File: ConfigurationTest.java From sofa-jraft with Apache License 2.0 | 6 votes |
@Test public void testToStringParseStuffWithPriorityAndNone() { final String confStr = "localhost:8081,localhost:8082,localhost:8083:1:100"; final Configuration conf = JRaftUtils.getConfiguration(confStr); assertEquals(3, conf.size()); for (final PeerId peer : conf) { assertTrue(peer.toString().startsWith("localhost:80")); if (peer.getIp().equals("localhost:8083")) { assertEquals(100, peer.getPriority()); assertEquals(1, peer.getIdx()); } } assertFalse(conf.isEmpty()); assertEquals(confStr, conf.toString()); final Configuration newConf = new Configuration(); assertTrue(newConf.parse(conf.toString())); assertEquals(3, newConf.getPeerSet().size()); assertTrue(newConf.contains(new PeerId("localhost", 8081))); assertTrue(newConf.contains(new PeerId("localhost", 8082))); assertTrue(newConf.contains(new PeerId("localhost", 8083, 1, 100))); assertEquals(confStr, newConf.toString()); assertEquals(conf.hashCode(), newConf.hashCode()); assertEquals(conf, newConf); }
Example #14
Source File: NodeImpl.java From sofa-jraft with Apache License 2.0 | 6 votes |
void onCaughtUp(final long version, final PeerId peer, final boolean success) { if (version != this.version) { LOG.warn("Ignore onCaughtUp message, mismatch configuration context version, expect {}, but is {}.", this.version, version); return; } Requires.requireTrue(this.stage == Stage.STAGE_CATCHING_UP, "Stage is not in STAGE_CATCHING_UP"); if (success) { this.addingPeers.remove(peer); if (this.addingPeers.isEmpty()) { nextStage(); return; } return; } LOG.warn("Node {} fail to catch up peer {} when trying to change peers from {} to {}.", this.node.getNodeId(), peer, this.oldPeers, this.newPeers); reset(new Status(RaftError.ECATCHUP, "Peer %s failed to catch up.", peer)); }
Example #15
Source File: NodeImpl.java From sofa-jraft with Apache License 2.0 | 6 votes |
private void addNewPeers(final Configuration adding) { this.addingPeers = adding.listPeers(); LOG.info("Adding peers: {}.", this.addingPeers); for (final PeerId newPeer : this.addingPeers) { if (!this.node.replicatorGroup.addReplicator(newPeer)) { LOG.error("Node {} start the replicator failed, peer={}.", this.node.getNodeId(), newPeer); onCaughtUp(this.version, newPeer, false); return; } final OnCaughtUp caughtUp = new OnCaughtUp(this.node, this.node.currTerm, newPeer, this.version); final long dueTime = Utils.nowMs() + this.node.options.getElectionTimeoutMs(); if (!this.node.replicatorGroup.waitCaughtUp(newPeer, this.node.options.getCatchupMargin(), dueTime, caughtUp)) { LOG.error("Node {} waitCaughtUp, peer={}.", this.node.getNodeId(), newPeer); onCaughtUp(this.version, newPeer, false); return; } } }
Example #16
Source File: CliServiceTest.java From sofa-jraft with Apache License 2.0 | 6 votes |
@Test public void testChangePeers() throws Exception { final List<PeerId> newPeers = TestUtils.generatePeers(10); newPeers.removeAll(this.conf.getPeerSet()); for (final PeerId peer : newPeers) { assertTrue(this.cluster.start(peer.getEndpoint())); } this.cluster.waitLeader(); final Node oldLeaderNode = this.cluster.getLeader(); assertNotNull(oldLeaderNode); final PeerId oldLeader = oldLeaderNode.getNodeId().getPeerId(); assertNotNull(oldLeader); assertTrue(this.cliService.changePeers(this.groupId, this.conf, new Configuration(newPeers)).isOk()); this.cluster.waitLeader(); final PeerId newLeader = this.cluster.getLeader().getNodeId().getPeerId(); assertNotEquals(oldLeader, newLeader); assertTrue(newPeers.contains(newLeader)); }
Example #17
Source File: TestUtils.java From sofa-jraft with Apache License 2.0 | 5 votes |
public static List<PeerId> generatePeers(final int n) { List<PeerId> ret = new ArrayList<>(); for (int i = 0; i < n; i++) { ret.add(new PeerId(getMyIp(), INIT_PORT + i)); } return ret; }
Example #18
Source File: BaseNodeRequestProcessorTest.java From sofa-jraft with Apache License 2.0 | 5 votes |
@Test public void testHandleRequest() { final PeerId peerId = mockNode(); final NodeRequestProcessor<T> processor = newProcessor(); processor.handleRequest(asyncContext, createRequest(groupId, peerId)); verify(processor.interest(), (RaftServerService) this.node, processor); }
Example #19
Source File: TestCluster.java From sofa-jraft with Apache License 2.0 | 5 votes |
public TestCluster(final String name, final String dataPath, final List<PeerId> peers, final LinkedHashSet<PeerId> learners, final int electionTimeoutMs) { super(); this.name = name; this.dataPath = dataPath; this.peers = peers; this.nodes = new ArrayList<>(this.peers.size()); this.fsms = new LinkedHashMap<>(this.peers.size()); this.electionTimeoutMs = electionTimeoutMs; this.learners = learners; CLUSTERS.add(this); }
Example #20
Source File: ReplicatorTest.java From sofa-jraft with Apache License 2.0 | 5 votes |
@Test public void testOnRpcReturnedLessLogs() { final Replicator r = getReplicator(); assertEquals(11, r.getRealNextIndex()); final RpcRequests.AppendEntriesRequest request = createEmptyEntriesRequest(); final RpcRequests.AppendEntriesResponse response = RpcRequests.AppendEntriesResponse.newBuilder() // .setSuccess(false) // .setLastLogIndex(8) // .setTerm(1) // .build(); this.id.unlock(); final Future<Message> rpcInFly = r.getRpcInFly(); assertNotNull(rpcInFly); Mockito.when(this.logManager.getTerm(8)).thenReturn(1L); final RpcRequests.AppendEntriesRequest newReq = RpcRequests.AppendEntriesRequest.newBuilder() // .setGroupId("test") // .setServerId(new PeerId("localhost", 8082).toString()) // .setPeerId(this.peerId.toString()) // .setTerm(1) // .setPrevLogIndex(8) // .setPrevLogTerm(1) // .setCommittedIndex(0) // .build(); Mockito.when(this.rpcService.appendEntries(eq(this.peerId.getEndpoint()), eq(newReq), eq(-1), Mockito.any())) .thenReturn(new FutureImpl<>()); Replicator.onRpcReturned(this.id, Replicator.RequestType.AppendEntries, Status.OK(), request, response, 0, 0, Utils.monotonicMs()); assertNotNull(r.getRpcInFly()); assertNotSame(r.getRpcInFly(), rpcInFly); assertEquals(r.statInfo.runningState, Replicator.RunningState.APPENDING_ENTRIES); this.id.unlock(); assertEquals(0, Replicator.getNextIndex(this.id)); assertEquals(9, r.getRealNextIndex()); }
Example #21
Source File: CliServiceImpl.java From sofa-jraft with Apache License 2.0 | 5 votes |
@Override public Status resetLearners(final String groupId, final Configuration conf, final List<PeerId> learners) { checkLearnersOpParams(groupId, conf, learners); final PeerId leaderId = new PeerId(); final Status st = getLeader(groupId, conf, leaderId); if (!st.isOk()) { return st; } if (!this.cliClientService.connect(leaderId.getEndpoint())) { return new Status(-1, "Fail to init channel to leader %s", leaderId); } final ResetLearnersRequest.Builder rb = ResetLearnersRequest.newBuilder() // .setGroupId(groupId) // .setLeaderId(leaderId.toString()); for (final PeerId peer : learners) { rb.addLearners(peer.toString()); } try { final Message result = this.cliClientService.resetLearners(leaderId.getEndpoint(), rb.build(), null).get(); return processLearnersOpResponse(groupId, result, "resetting learners: %s", learners); } catch (final Exception e) { return new Status(-1, e.getMessage()); } }
Example #22
Source File: RouteTableTest.java From sofa-jraft with Apache License 2.0 | 5 votes |
@Test public void testRefreshConfiguration() throws Exception { final RouteTable rt = RouteTable.getInstance(); final List<PeerId> partConf = new ArrayList<>(); partConf.add(cluster.getLeader().getLeaderId()); // part of peers conf, only contains leader peer rt.updateConfiguration(groupId, new Configuration(partConf)); // fetch all conf final Status st = rt.refreshConfiguration(cliClientService, groupId, 10000); assertTrue(st.isOk()); final Configuration newCnf = rt.getConfiguration(groupId); assertArrayEquals(new HashSet<>(cluster.getPeers()).toArray(), new HashSet<>(newCnf.getPeerSet()).toArray()); }
Example #23
Source File: CliServiceTest.java From sofa-jraft with Apache License 2.0 | 5 votes |
@Test public void testGetPeers() throws Exception { PeerId leader = this.cluster.getLeader().getNodeId().getPeerId(); assertNotNull(leader); assertArrayEquals(this.conf.getPeerSet().toArray(), new HashSet<>(this.cliService.getPeers(this.groupId, this.conf)).toArray()); // stop one peer final List<PeerId> peers = this.conf.getPeers(); this.cluster.stop(peers.get(0).getEndpoint()); this.cluster.waitLeader(); leader = this.cluster.getLeader().getNodeId().getPeerId(); assertNotNull(leader); assertArrayEquals(this.conf.getPeerSet().toArray(), new HashSet<>(this.cliService.getPeers(this.groupId, this.conf)).toArray()); this.cluster.stopAll(); try { this.cliService.getPeers(this.groupId, this.conf); fail(); } catch (final IllegalStateException e) { assertEquals("Fail to get leader of group " + this.groupId, e.getMessage()); } }
Example #24
Source File: BaseNodeRequestProcessorTest.java From sofa-jraft with Apache License 2.0 | 5 votes |
protected PeerId mockNode() { Mockito.when(node.getGroupId()).thenReturn(this.groupId); final PeerId peerId = new PeerId(); peerId.parse(this.peerIdStr); Mockito.when(node.getNodeId()).thenReturn(new NodeId(groupId, peerId)); NodeManager.getInstance().addAddress(peerId.getEndpoint()); NodeManager.getInstance().add(node); return peerId; }
Example #25
Source File: CounterClient.java From sofa-jraft with Apache License 2.0 | 5 votes |
public static void main(final String[] args) throws Exception { if (args.length != 2) { System.out.println("Useage : java com.alipay.sofa.jraft.example.counter.CounterClient {groupId} {conf}"); System.out .println("Example: java com.alipay.sofa.jraft.example.counter.CounterClient counter 127.0.0.1:8081,127.0.0.1:8082,127.0.0.1:8083"); System.exit(1); } final String groupId = args[0]; final String confStr = args[1]; final Configuration conf = new Configuration(); if (!conf.parse(confStr)) { throw new IllegalArgumentException("Fail to parse conf:" + confStr); } RouteTable.getInstance().updateConfiguration(groupId, conf); final CliClientServiceImpl cliClientService = new CliClientServiceImpl(); cliClientService.init(new CliOptions()); if (!RouteTable.getInstance().refreshLeader(cliClientService, groupId, 1000).isOk()) { throw new IllegalStateException("Refresh leader failed"); } final PeerId leader = RouteTable.getInstance().selectLeader(groupId); System.out.println("Leader is " + leader); final int n = 1000; final CountDownLatch latch = new CountDownLatch(n); final long start = System.currentTimeMillis(); for (int i = 0; i < n; i++) { incrementAndGet(cliClientService, leader, i, latch); } latch.await(); System.out.println(n + " ops, cost : " + (System.currentTimeMillis() - start) + " ms."); System.exit(0); }
Example #26
Source File: PreVoteRequestProcessorTest.java From sofa-jraft with Apache License 2.0 | 5 votes |
@Override public RequestVoteRequest createRequest(String groupId, PeerId peerId) { request = RequestVoteRequest.newBuilder().setGroupId(groupId). // setServerId("localhostL8082"). // setPeerId(peerId.toString()). // setTerm(0). // setLastLogIndex(0). // setLastLogTerm(0). // setPreVote(false).build(); return request; }
Example #27
Source File: RouteTableTest.java From sofa-jraft with Apache License 2.0 | 5 votes |
@Test public void testRefreshConfiguration() throws Exception { final RouteTable rt = RouteTable.getInstance(); final List<PeerId> partConf = new ArrayList<>(); partConf.add(cluster.getLeader().getLeaderId()); // part of peers conf, only contains leader peer rt.updateConfiguration(groupId, new Configuration(partConf)); // fetch all conf final Status st = rt.refreshConfiguration(cliClientService, groupId, 10000); assertTrue(st.isOk()); final Configuration newCnf = rt.getConfiguration(groupId); assertArrayEquals(new HashSet<>(cluster.getPeers()).toArray(), new HashSet<>(newCnf.getPeerSet()).toArray()); }
Example #28
Source File: CounterServer.java From sofa-jraft with Apache License 2.0 | 5 votes |
public CounterServer(final String dataPath, final String groupId, final PeerId serverId, final NodeOptions nodeOptions) throws IOException { // 初始化路径 FileUtils.forceMkdir(new File(dataPath)); // 这里让 raft RPC 和业务 RPC 使用同一个 RPC server, 通常也可以分开 final RpcServer rpcServer = RaftRpcServerFactory.createRaftRpcServer(serverId.getEndpoint()); // 注册业务处理器 CounterService counterService = new CounterServiceImpl(this); rpcServer.registerProcessor(new GetValueRequestProcessor(counterService)); rpcServer.registerProcessor(new IncrementAndGetRequestProcessor(counterService)); // 初始化状态机 this.fsm = new CounterStateMachine(); // 设置状态机到启动参数 nodeOptions.setFsm(this.fsm); // 设置存储路径 // 日志, 必须 nodeOptions.setLogUri(dataPath + File.separator + "log"); // 元信息, 必须 nodeOptions.setRaftMetaUri(dataPath + File.separator + "raft_meta"); // snapshot, 可选, 一般都推荐 nodeOptions.setSnapshotUri(dataPath + File.separator + "snapshot"); // 初始化 raft group 服务框架 this.raftGroupService = new RaftGroupService(groupId, serverId, nodeOptions, rpcServer); // 启动 this.node = this.raftGroupService.start(); }
Example #29
Source File: NodeImpl.java From sofa-jraft with Apache License 2.0 | 5 votes |
public void handleRequestVoteResponse(final PeerId peerId, final long term, final RequestVoteResponse response) { this.writeLock.lock(); try { if (this.state != State.STATE_CANDIDATE) { LOG.warn("Node {} received invalid RequestVoteResponse from {}, state not in STATE_CANDIDATE but {}.", getNodeId(), peerId, this.state); return; } // check stale term if (term != this.currTerm) { LOG.warn("Node {} received stale RequestVoteResponse from {}, term={}, currTerm={}.", getNodeId(), peerId, term, this.currTerm); return; } // check response term if (response.getTerm() > this.currTerm) { LOG.warn("Node {} received invalid RequestVoteResponse from {}, term={}, expect={}.", getNodeId(), peerId, response.getTerm(), this.currTerm); stepDown(response.getTerm(), false, new Status(RaftError.EHIGHERTERMRESPONSE, "Raft node receives higher term request_vote_response.")); return; } // check granted quorum? if (response.getGranted()) { this.voteCtx.grant(peerId); if (this.voteCtx.isGranted()) { becomeLeader(); } } } finally { this.writeLock.unlock(); } }
Example #30
Source File: RaftExchanger.java From sofa-registry with Apache License 2.0 | 5 votes |
/** * api for get all peers */ public List<PeerId> getPeers() { try { Configuration currentConf = getCurrentConfiguration(); return currentConf.getPeers(); } catch (Exception e) { String msg = "Get peers error:" + e.getMessage(); LOGGER.error(msg, e); throw new RuntimeException(msg, e); } }