Java Code Examples for com.alipay.sofa.jraft.entity.PeerId

The following examples show how to use com.alipay.sofa.jraft.entity.PeerId. These examples are extracted from open source projects. 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 Project: sofa-jraft   Author: sofastack   File: AppendEntriesRequestProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@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 #2
Source Project: sofa-jraft   Author: sofastack   File: NodeTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 #3
Source Project: sofa-jraft   Author: sofastack   File: NodeTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 #4
Source Project: sofa-jraft   Author: sofastack   File: GrpcClient.java    License: Apache License 2.0 6 votes vote down vote up
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 #5
Source Project: sofa-jraft   Author: sofastack   File: NodeTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 #6
Source Project: sofa-jraft   Author: sofastack   File: AbstractCliRequestProcessorTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 #7
Source Project: sofa-jraft   Author: sofastack   File: TransferLeaderRequestProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@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 #8
Source Project: sofa-jraft   Author: sofastack   File: ConfigurationTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 #9
Source Project: sofa-jraft   Author: sofastack   File: BaseCliRequestProcessorTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 #10
Source Project: sofa-registry   Author: sofastack   File: RaftClient.java    License: Apache License 2.0 6 votes vote down vote up
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 #11
Source Project: sofa-jraft   Author: sofastack   File: ConfigurationTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 #12
Source Project: sofa-jraft   Author: sofastack   File: NodeImpl.java    License: Apache License 2.0 6 votes vote down vote up
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 #13
Source Project: sofa-jraft   Author: sofastack   File: NodeImpl.java    License: Apache License 2.0 6 votes vote down vote up
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 #14
Source Project: sofa-jraft   Author: sofastack   File: CliServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 #15
Source Project: sofa-jraft   Author: sofastack   File: CliServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 #16
Source Project: sofa-jraft   Author: sofastack   File: AtomicClient.java    License: Apache License 2.0 6 votes vote down vote up
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 #17
Source Project: sofa-jraft   Author: sofastack   File: JRaftHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static Peer toPeer(final PeerId peerId) {
    Requires.requireNonNull(peerId, "peerId");
    final Endpoint endpoint = peerId.getEndpoint();
    Requires.requireNonNull(endpoint, "peerId.endpoint");
    final Peer peer = new Peer();
    peer.setId(-1);
    peer.setStoreId(-1);
    peer.setEndpoint(endpoint.copy());
    return peer;
}
 
Example #18
Source Project: sofa-jraft   Author: sofastack   File: TestCluster.java    License: Apache License 2.0 5 votes vote down vote up
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 #19
Source Project: sofa-registry   Author: sofastack   File: RaftExchanger.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example #20
Source Project: sofa-jraft   Author: sofastack   File: CounterClient.java    License: Apache License 2.0 5 votes vote down vote up
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 #21
Source Project: sofa-jraft   Author: sofastack   File: CounterServer.java    License: Apache License 2.0 5 votes vote down vote up
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 #22
Source Project: sofa-registry   Author: sofastack   File: MetaStoreResource.java    License: Apache License 2.0 5 votes vote down vote up
@GET
@Path("queryPeer")
@Produces(MediaType.APPLICATION_JSON)
public List<String> getMetaList() {
    List<PeerId> peerIds = raftExchanger.getPeers();
    return peerIds.stream().map(PeerId::getIp).collect(Collectors.toList());
}
 
Example #23
Source Project: sofa-jraft   Author: sofastack   File: BaseLogEntryCodecFactoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testEncodeDecodeWithData() {
    ByteBuffer buf = ByteBuffer.wrap("hello".getBytes());
    LogEntry entry = new LogEntry(EnumOutter.EntryType.ENTRY_TYPE_NO_OP);
    entry.setId(new LogId(100, 3));
    entry.setData(buf);
    entry.setPeers(Arrays.asList(new PeerId("localhost", 99, 1), new PeerId("localhost", 100, 2)));
    assertEquals(buf, entry.getData());

    byte[] content = this.encoder.encode(entry);

    assertNotNull(content);
    assertTrue(content.length > 0);

    LogEntry nentry = this.decoder.decode(content);
    assertNotNull(nentry);

    assertEquals(100, nentry.getId().getIndex());
    assertEquals(3, nentry.getId().getTerm());

    assertEquals(2, nentry.getPeers().size());
    assertEquals("localhost:99:1", nentry.getPeers().get(0).toString());
    assertEquals("localhost:100:2", nentry.getPeers().get(1).toString());
    assertEquals(buf, nentry.getData());
    assertEquals(0, nentry.getData().position());
    assertEquals(5, nentry.getData().remaining());
    assertNull(nentry.getOldPeers());
}
 
Example #24
Source Project: sofa-jraft   Author: sofastack   File: NodeImpl.java    License: Apache License 2.0 5 votes vote down vote up
private List<PeerId> getAliveNodes(final Collection<PeerId> peers, final long monotonicNowMs) {
    final int leaderLeaseTimeoutMs = this.options.getLeaderLeaseTimeoutMs();
    final List<PeerId> alivePeers = new ArrayList<>();
    for (final PeerId peer : peers) {
        if (peer.equals(this.serverId)) {
            alivePeers.add(peer.copy());
            continue;
        }
        if (monotonicNowMs - this.replicatorGroup.getLastRpcSendTimestamp(peer) <= leaderLeaseTimeoutMs) {
            alivePeers.add(peer.copy());
        }
    }
    return alivePeers;
}
 
Example #25
Source Project: sofa-jraft   Author: sofastack   File: CliServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Status getLeader(final String groupId, final Configuration conf, final PeerId leaderId) {
    final PeerId ret = this.rebalancedLeaderIds.get(groupId);
    if (ret != null) {
        leaderId.parse(ret.toString());
    } else {
        leaderId.parse(this.initialLeaderId.toString());
    }
    return Status.OK();
}
 
Example #26
Source Project: sofa-jraft   Author: sofastack   File: NodeRequestProcessorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testOK() {
    Node node = Mockito.mock(Node.class, withSettings().extraInterfaces(RaftServerService.class));
    Mockito.when(node.getGroupId()).thenReturn("test");
    PeerId peerId = new PeerId("localhost", 8081);
    Mockito.when(node.getNodeId()).thenReturn(new NodeId("test", peerId));
    NodeManager.getInstance().addAddress(peerId.getEndpoint());
    NodeManager.getInstance().add(node);

    this.processor.handleRequest(asyncContext, TestUtils.createPingRequest());
    ErrorResponse resp = (ErrorResponse) asyncContext.getResponseObject();
    assertNotNull(resp);
    assertEquals(0, resp.getErrorCode());
}
 
Example #27
Source Project: distkv   Author: distkv-project   File: DmetaServer.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Get Redirect to new leader
 */
public String getRedirect() {
  if (this.node != null) {
    final PeerId leader = this.node.getLeaderId();
    if (leader != null) {
      return leader.toString();
    }
  }
  return new String();
}
 
Example #28
Source Project: sofa-jraft   Author: sofastack   File: ChaosTestCluster.java    License: Apache License 2.0 5 votes vote down vote up
public synchronized void addPeer(final PeerId peerId) {
    if (this.peerIds.contains(peerId)) {
        throw new RuntimeException("peerId is exist: " + peerId);
    }
    this.peerIds.add(peerId);
    final Configuration conf = new Configuration(this.peerIds);
    final String initialServerList = conf.toString();
    final PlacementDriverOptions pdOpts = PlacementDriverOptionsConfigured.newConfigured().withFake(true) // use a fake pd
        .config();
    final StoreEngineOptions storeOpts = StoreEngineOptionsConfigured.newConfigured() //
        .withStorageType(this.storageType) //
        .withRocksDBOptions(RocksDBOptionsConfigured.newConfigured().withDbPath(DB_PATH).config()) //
        .withRaftDataPath(RAFT_DATA_PATH) //
        .withServerAddress(peerId.getEndpoint()) //
        .config();
    final RheaKVStoreOptions opts = RheaKVStoreOptionsConfigured.newConfigured() //
        .withClusterName("chaos_test") //
        .withInitialServerList(initialServerList).withStoreEngineOptions(storeOpts) //
        .withPlacementDriverOptions(pdOpts) //
        .config();
    BatchingOptions batchingOptions = opts.getBatchingOptions();
    if (batchingOptions == null) {
        batchingOptions = new BatchingOptions();
    }
    batchingOptions.setAllowBatching(this.allowBatching);
    opts.setBatchingOptions(batchingOptions);

    final RheaKVStore store = new DefaultRheaKVStore();
    if (!store.init(opts)) {
        throw new IllegalStateException("fail to init store with options: " + opts);
    }

    final RheaKVStore leader = getLeaderStore();
    final PlacementDriverClient pdClient = leader.getPlacementDriverClient();
    if (!pdClient.addReplica(Constants.DEFAULT_REGION_ID, JRaftHelper.toPeer(peerId), true)) {
        throw new RuntimeException("fail to add peer: " + peerId);
    }
    this.stores.add(store);
    awaitLeader();
}
 
Example #29
Source Project: sofa-jraft   Author: sofastack   File: ResetLearnersRequestProcessorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void verify(final String interest, final Node node, final ArgumentCaptor<Closure> doneArg) {
    assertEquals(interest, ResetLearnersRequest.class.getName());
    Mockito.verify(node).resetLearners(
        eq(Arrays.asList(new PeerId("learner", 8082), new PeerId("test", 8182), new PeerId("test", 8183))),
        doneArg.capture());
    Closure done = doneArg.getValue();
    assertNotNull(done);
    done.run(Status.OK());
    assertNotNull(this.asyncContext.getResponseObject());
    assertEquals("[learner:8081, learner:8082, learner:8083]", this.asyncContext.as(LearnersOpResponse.class)
        .getOldLearnersList().toString());
    assertEquals("[learner:8082, test:8182, test:8183]", this.asyncContext.as(LearnersOpResponse.class)
        .getNewLearnersList().toString());
}
 
Example #30
Source Project: sofa-jraft   Author: sofastack   File: AddPeerRequestProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Message processRequest0(final CliRequestContext ctx, final AddPeerRequest request, final RpcRequestClosure done) {
    final List<PeerId> oldPeers = ctx.node.listPeers();
    final String addingPeerIdStr = request.getPeerId();
    final PeerId addingPeer = new PeerId();
    if (addingPeer.parse(addingPeerIdStr)) {
        LOG.info("Receive AddPeerRequest to {} from {}, adding {}", ctx.node.getNodeId(), done.getRpcCtx()
            .getRemoteAddress(), addingPeerIdStr);
        ctx.node.addPeer(addingPeer, status -> {
            if (!status.isOk()) {
                done.run(status);
            } else {
                final AddPeerResponse.Builder rb = AddPeerResponse.newBuilder();
                boolean alreadyExists = false;
                for (final PeerId oldPeer : oldPeers) {
                    rb.addOldPeers(oldPeer.toString());
                    rb.addNewPeers(oldPeer.toString());
                    if (oldPeer.equals(addingPeer)) {
                        alreadyExists = true;
                    }
                }
                if (!alreadyExists) {
                    rb.addNewPeers(addingPeerIdStr);
                }
                done.sendResponse(rb.build());
            }
        });
    } else {
        return RpcFactoryHelper //
            .responseFactory() //
            .newResponse(defaultResp(), RaftError.EINVAL, "Fail to parse peer id %s", addingPeerIdStr);
    }

    return null;
}