com.alipay.sofa.jraft.Closure Java Examples

The following examples show how to use com.alipay.sofa.jraft.Closure. 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: BallotBox.java    From sofa-jraft with Apache License 2.0 6 votes vote down vote up
/**
 * Called by leader, otherwise the behavior is undefined
 * Store application context before replication.
 *
 * @param conf      current configuration
 * @param oldConf   old configuration
 * @param done      callback
 * @return          returns true on success
 */
public boolean appendPendingTask(final Configuration conf, final Configuration oldConf, final Closure done) {
    final Ballot bl = new Ballot();
    if (!bl.init(conf, oldConf)) {
        LOG.error("Fail to init ballot.");
        return false;
    }
    final long stamp = this.stampedLock.writeLock();
    try {
        if (this.pendingIndex <= 0) {
            LOG.error("Fail to appendingTask, pendingIndex={}.", this.pendingIndex);
            return false;
        }
        this.pendingMetaQueue.add(bl);
        this.closureQueue.appendPendingClosure(done);
        return true;
    } finally {
        this.stampedLock.unlockWrite(stamp);
    }
}
 
Example #2
Source File: ClosureQueueTest.java    From sofa-jraft with Apache License 2.0 6 votes vote down vote up
@Test
public void testResetFirstIndex() {
    assertEquals(0, this.queue.getFirstIndex());
    this.queue.resetFirstIndex(10);
    assertEquals(10, this.queue.getFirstIndex());
    for (int i = 0; i < 10; i++) {
        this.queue.appendPendingClosure(mockClosure(null));
    }

    List<Closure> closures = new ArrayList<>();
    assertEquals(5, this.queue.popClosureUntil(4, closures));
    assertTrue(closures.isEmpty());
    assertEquals(4, this.queue.popClosureUntil(3, closures));
    assertTrue(closures.isEmpty());

    assertEquals(10, this.queue.popClosureUntil(19, closures));
    assertEquals(20, this.queue.getFirstIndex());
    assertEquals(10, closures.size());
    // empty ,return index+1
    assertEquals(21, this.queue.popClosureUntil(20, closures));
    assertTrue(closures.isEmpty());
}
 
Example #3
Source File: CounterStateMachine.java    From sofa-jraft with Apache License 2.0 6 votes vote down vote up
@Override
public void onSnapshotSave(final SnapshotWriter writer, final Closure done) {
  final long currVal = this.value.get();
  Utils.runInThread(() -> {
    final CounterSnapshotFile snapshot = new CounterSnapshotFile(writer.getPath() + File.separator + "data");
    if (snapshot.save(currVal)) {
      if (writer.addFile("data")) {
        done.run(Status.OK());
      } else {
        done.run(new Status(RaftError.EIO, "Fail to add file to writer"));
      }
    } else {
      done.run(new Status(RaftError.EIO, "Fail to save counter snapshot %s", snapshot.getPath()));
    }
  });
}
 
Example #4
Source File: AbstractKVStoreSnapshotFile.java    From sofa-jraft with Apache License 2.0 6 votes vote down vote up
protected void compressSnapshot(final SnapshotWriter writer, final LocalFileMeta.Builder metaBuilder,
                                final Closure done) {
    final String writerPath = writer.getPath();
    final String outputFile = Paths.get(writerPath, SNAPSHOT_ARCHIVE).toString();
    try {
        final Checksum checksum = new CRC64();
        ZipUtil.compress(writerPath, SNAPSHOT_DIR, outputFile, checksum);
        metaBuilder.setChecksum(Long.toHexString(checksum.getValue()));
        if (writer.addFile(SNAPSHOT_ARCHIVE, metaBuilder.build())) {
            done.run(Status.OK());
        } else {
            done.run(new Status(RaftError.EIO, "Fail to add snapshot file: %s", writerPath));
        }
    } catch (final Throwable t) {
        LOG.error("Fail to compress snapshot, path={}, file list={}, {}.", writerPath, writer.listFiles(),
            StackTraceUtil.stackTrace(t));
        done.run(new Status(RaftError.EIO, "Fail to compress snapshot at %s, error is %s", writerPath, t
            .getMessage()));
    }
}
 
Example #5
Source File: AbstractKVStoreSnapshotFile.java    From sofa-jraft with Apache License 2.0 6 votes vote down vote up
@Override
public void save(final SnapshotWriter writer, final Region region, final Closure done,
                 final ExecutorService executor) {
    final String writerPath = writer.getPath();
    final String snapshotPath = Paths.get(writerPath, SNAPSHOT_DIR).toString();
    try {
        doSnapshotSave(snapshotPath, region, executor).whenComplete((metaBuilder, throwable) -> {
            if (throwable == null) {
                executor.execute(() -> compressSnapshot(writer, metaBuilder, done));
            } else {
                LOG.error("Fail to save snapshot, path={}, file list={}, {}.", writerPath, writer.listFiles(),
                        StackTraceUtil.stackTrace(throwable));
                done.run(new Status(RaftError.EIO, "Fail to save snapshot at %s, error is %s", writerPath,
                        throwable.getMessage()));
            }
        });
    } catch (final Throwable t) {
        LOG.error("Fail to save snapshot, path={}, file list={}, {}.", writerPath, writer.listFiles(),
                StackTraceUtil.stackTrace(t));
        done.run(new Status(RaftError.EIO, "Fail to save snapshot at %s, error is %s", writerPath,
                t.getMessage()));
    }
}
 
Example #6
Source File: AbstractCliRequestProcessorTest.java    From sofa-jraft with 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 File: AtomicStateMachine.java    From sofa-jraft with Apache License 2.0 6 votes vote down vote up
@Override
public void onSnapshotSave(final SnapshotWriter writer, final Closure done) {
  final Map<String, Long> values = new HashMap<>();
  for (final Map.Entry<String, AtomicLong> entry : this.counters.entrySet()) {
    values.put(entry.getKey(), entry.getValue().get());
  }
  Utils.runInThread(() -> {
    final AtomicSnapshotFile snapshot = new AtomicSnapshotFile(writer.getPath() + File.separator + "data");
    if (snapshot.save(values)) {
      if (writer.addFile("data")) {
        done.run(Status.OK());
      } else {
        done.run(new Status(RaftError.EIO, "Fail to add file to writer"));
      }
    } else {
      done.run(new Status(RaftError.EIO, "Fail to save counter snapshot %s", snapshot.getPath()));
    }
  });
}
 
Example #8
Source File: NodeImpl.java    From sofa-jraft with Apache License 2.0 6 votes vote down vote up
private void afterShutdown() {
    List<Closure> savedDoneList = null;
    this.writeLock.lock();
    try {
        if (!this.shutdownContinuations.isEmpty()) {
            savedDoneList = new ArrayList<>(this.shutdownContinuations);
        }
        if (this.logStorage != null) {
            this.logStorage.shutdown();
        }
        this.state = State.STATE_SHUTDOWN;
    } finally {
        this.writeLock.unlock();
    }
    if (savedDoneList != null) {
        for (final Closure closure : savedDoneList) {
            Utils.runClosureInThread(closure);
        }
    }
}
 
Example #9
Source File: ClosureQueueImpl.java    From sofa-jraft with Apache License 2.0 6 votes vote down vote up
@Override
public void clear() {
    List<Closure> savedQueue;
    this.lock.lock();
    try {
        this.firstIndex = 0;
        savedQueue = this.queue;
        this.queue = new LinkedList<>();
    } finally {
        this.lock.unlock();
    }

    final Status status = new Status(RaftError.EPERM, "Leader stepped down");
    Utils.runInThread(() -> {
        for (final Closure done : savedQueue) {
            if (done != null) {
                done.run(status);
            }
        }
    });
}
 
Example #10
Source File: NodeImpl.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
@Override
public void resetLearners(final List<PeerId> learners, final Closure done) {
    checkPeers(learners);
    this.writeLock.lock();
    try {
        final Configuration newConf = new Configuration(this.conf.getConf());
        newConf.setLearners(new LinkedHashSet<>(learners));
        unsafeRegisterConfChange(this.conf.getConf(), newConf, done);
    } finally {
        this.writeLock.unlock();
    }
}
 
Example #11
Source File: DBStateMachine.java    From KitDB with Apache License 2.0 5 votes vote down vote up
@Override
public void onSnapshotSave(final SnapshotWriter writer, final Closure done) {
    try {
        String fileName = this.db.backupDB(writer.getPath(), spname);
        if (writer.addFile(spname + DB.BACK_FILE_SUFFIX)) {
            done.run(Status.OK());
        } else {
            done.run(new Status(RaftError.EIO, "Fail to add file to writer"));
        }
    } catch (Exception e) {
        done.run(new Status(RaftError.EIO, "Fail to save counter snapshot %s", writer.getPath()));
    }

}
 
Example #12
Source File: NodeImpl.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
private void doSnapshot(final Closure done) {
    if (this.snapshotExecutor != null) {
        this.snapshotExecutor.doSnapshot(done);
    } else {
        if (done != null) {
            final Status status = new Status(RaftError.EINVAL, "Snapshot is not supported");
            Utils.runClosureInThread(done, status);
        }
    }
}
 
Example #13
Source File: GetPeersRequestProcessorTest.java    From sofa-jraft with 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, GetPeersRequest.class.getName());
    assertNotNull(this.asyncContext.getResponseObject());
    assertEquals("[localhost:8081, localhost:8082, localhost:8083]", this.asyncContext.as(GetPeersResponse.class)
        .getPeersList().toString());
    assertEquals("[learner:8081, learner:8082, learner:8083]", this.asyncContext.as(GetPeersResponse.class)
        .getLearnersList().toString());
}
 
Example #14
Source File: RemoveLearnersRequestProcessorTest.java    From sofa-jraft with 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, RemoveLearnersRequest.class.getName());
    Mockito.verify(node).removeLearners(eq(Arrays.asList(new PeerId("learner", 8082), 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:8081, learner:8083]", this.asyncContext.as(LearnersOpResponse.class)
        .getNewLearnersList().toString());
}
 
Example #15
Source File: UtilsTest.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
@Test
public void testRunClosure() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    Utils.runClosureInThread(new Closure() {

        @Override
        public void run(Status status) {
            assertTrue(status.isOk());
            latch.countDown();
        }
    });
    latch.await();
}
 
Example #16
Source File: MockStateMachine.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
@Override
public void onSnapshotSave(final SnapshotWriter writer, final Closure done) {
    this.saveSnapshotTimes++;
    final String path = writer.getPath() + File.separator + "data";
    final File file = new File(path);
    try (FileOutputStream fout = new FileOutputStream(file);
            BufferedOutputStream out = new BufferedOutputStream(fout)) {
        this.lock.lock();
        try {
            for (final ByteBuffer buf : this.logs) {
                final byte[] bs = new byte[4];
                Bits.putInt(bs, 0, buf.remaining());
                out.write(bs);
                out.write(buf.array());
            }
            this.snapshotIndex = this.appliedIndex;
        } finally {
            this.lock.unlock();
        }
        System.out.println("Node<" + this.address + "> saved snapshot into " + file);
        writer.addFile("data");
        done.run(Status.OK());
    } catch (final IOException e) {
        e.printStackTrace();
        done.run(new Status(RaftError.EIO, "Fail to save snapshot"));
    }
}
 
Example #17
Source File: UtilsTest.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
@Test
public void testRunClosureWithStatus() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    Utils.runClosureInThread(new Closure() {

        @Override
        public void run(Status status) {
            assertFalse(status.isOk());
            Assert.assertEquals(RaftError.EACCES.getNumber(), status.getCode());
            assertEquals("test 99", status.getErrorMsg());
            latch.countDown();
        }
    }, new Status(RaftError.EACCES, "test %d", 99));
    latch.await();
}
 
Example #18
Source File: ClosureQueueTest.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("SameParameterValue")
private Closure mockClosure(final CountDownLatch latch) {
    return status -> {
        if (latch != null) {
            latch.countDown();
        }
    };
}
 
Example #19
Source File: AddLearnersRequestProcessorTest.java    From sofa-jraft with 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, AddLearnersRequest.class.getName());
    Mockito.verify(node).addLearners(
        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:8081, learner:8082, learner:8083, test:8182, test:8183]",
        this.asyncContext.as(LearnersOpResponse.class).getNewLearnersList().toString());
}
 
Example #20
Source File: RemovePeerRequestProcessorTest.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
@Override
public void verify(String interest, Node node, ArgumentCaptor<Closure> doneArg) {
    assertEquals(interest, RemovePeerRequest.class.getName());
    Mockito.verify(node).removePeer(eq(new PeerId("localhost", 8082)), doneArg.capture());
    Closure done = doneArg.getValue();
    assertNotNull(done);
    done.run(Status.OK());
    assertNotNull(this.asyncContext.getResponseObject());
    assertEquals("[localhost:8081, localhost:8082, localhost:8083]", this.asyncContext.as(RemovePeerResponse.class)
        .getOldPeersList().toString());
    assertEquals("[localhost:8081, localhost:8083]", this.asyncContext.as(RemovePeerResponse.class)
        .getNewPeersList().toString());
}
 
Example #21
Source File: NodeImpl.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
@Override
public void addLearners(final List<PeerId> learners, final Closure done) {
    checkPeers(learners);
    this.writeLock.lock();
    try {
        final Configuration newConf = new Configuration(this.conf.getConf());
        for (final PeerId peer : learners) {
            newConf.addLearner(peer);
        }
        unsafeRegisterConfChange(this.conf.getConf(), newConf, done);
    } finally {
        this.writeLock.unlock();
    }

}
 
Example #22
Source File: NodeImpl.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
@Override
public void changePeers(final Configuration newPeers, final Closure done) {
    Requires.requireNonNull(newPeers, "Null new peers");
    Requires.requireTrue(!newPeers.isEmpty(), "Empty new peers");
    this.writeLock.lock();
    try {
        LOG.info("Node {} change peers from {} to {}.", getNodeId(), this.conf.getConf(), newPeers);
        unsafeRegisterConfChange(this.conf.getConf(), newPeers, done);
    } finally {
        this.writeLock.unlock();
    }
}
 
Example #23
Source File: NodeImpl.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
@Override
public void removePeer(final PeerId peer, final Closure done) {
    Requires.requireNonNull(peer, "Null peer");
    this.writeLock.lock();
    try {
        Requires.requireTrue(this.conf.getConf().contains(peer), "Peer not found in current configuration");

        final Configuration newConf = new Configuration(this.conf.getConf());
        newConf.removePeer(peer);
        unsafeRegisterConfChange(this.conf.getConf(), newConf, done);
    } finally {
        this.writeLock.unlock();
    }
}
 
Example #24
Source File: NodeImpl.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
@Override
public void addPeer(final PeerId peer, final Closure done) {
    Requires.requireNonNull(peer, "Null peer");
    this.writeLock.lock();
    try {
        Requires.requireTrue(!this.conf.getConf().contains(peer), "Peer already exists in current configuration");

        final Configuration newConf = new Configuration(this.conf.getConf());
        newConf.addPeer(peer);
        unsafeRegisterConfChange(this.conf.getConf(), newConf, done);
    } finally {
        this.writeLock.unlock();
    }
}
 
Example #25
Source File: NodeImpl.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
private void unsafeRegisterConfChange(final Configuration oldConf, final Configuration newConf, final Closure done) {

        Requires.requireTrue(newConf.isValid(), "Invalid new conf: %s", newConf);
        // The new conf entry(will be stored in log manager) should be valid
        Requires.requireTrue(new ConfigurationEntry(null, newConf, oldConf).isValid(), "Invalid conf entry: %s",
            newConf);

        if (this.state != State.STATE_LEADER) {
            LOG.warn("Node {} refused configuration changing as the state={}.", getNodeId(), this.state);
            if (done != null) {
                final Status status = new Status();
                if (this.state == State.STATE_TRANSFERRING) {
                    status.setError(RaftError.EBUSY, "Is transferring leadership.");
                } else {
                    status.setError(RaftError.EPERM, "Not leader");
                }
                Utils.runClosureInThread(done, status);
            }
            return;
        }
        // check concurrent conf change
        if (this.confCtx.isBusy()) {
            LOG.warn("Node {} refused configuration concurrent changing.", getNodeId());
            if (done != null) {
                Utils.runClosureInThread(done, new Status(RaftError.EBUSY, "Doing another configuration change."));
            }
            return;
        }
        // Return immediately when the new peers equals to current configuration
        if (this.conf.getConf().equals(newConf)) {
            Utils.runClosureInThread(done);
            return;
        }
        this.confCtx.start(oldConf, newConf, done);
    }
 
Example #26
Source File: NodeImpl.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
/**
 * Start change configuration.
 */
void start(final Configuration oldConf, final Configuration newConf, final Closure done) {
    if (isBusy()) {
        if (done != null) {
            Utils.runClosureInThread(done, new Status(RaftError.EBUSY, "Already in busy stage."));
        }
        throw new IllegalStateException("Busy stage");
    }
    if (this.done != null) {
        if (done != null) {
            Utils.runClosureInThread(done, new Status(RaftError.EINVAL, "Already have done closure."));
        }
        throw new IllegalArgumentException("Already have done closure");
    }
    this.done = done;
    this.stage = Stage.STAGE_CATCHING_UP;
    this.oldPeers = oldConf.listPeers();
    this.newPeers = newConf.listPeers();
    this.oldLearners = oldConf.listLearners();
    this.newLearners = newConf.listLearners();
    final Configuration adding = new Configuration();
    final Configuration removing = new Configuration();
    newConf.diff(oldConf, adding, removing);
    this.nchanges = adding.size() + removing.size();

    addNewLearners();
    if (adding.isEmpty()) {
        nextStage();
        return;
    }
    addNewPeers(adding);
}
 
Example #27
Source File: IteratorImpl.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
protected void runTheRestClosureWithError() {
    for (long i = Math.max(this.currentIndex, this.firstClosureIndex); i <= this.committedIndex; i++) {
        final Closure done = this.closures.get((int) (i - this.firstClosureIndex));
        if (done != null) {
            Requires.requireNonNull(this.error, "error");
            Requires.requireNonNull(this.error.getStatus(), "error.status");
            final Status status = this.error.getStatus();
            Utils.runClosureInThread(done, status);
        }
    }
}
 
Example #28
Source File: IteratorImpl.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
public IteratorImpl(final StateMachine fsm, final LogManager logManager, final List<Closure> closures,
                    final long firstClosureIndex, final long lastAppliedIndex, final long committedIndex,
                    final AtomicLong applyingIndex) {
    super();
    this.fsm = fsm;
    this.logManager = logManager;
    this.closures = closures;
    this.firstClosureIndex = firstClosureIndex;
    this.currentIndex = lastAppliedIndex;
    this.committedIndex = committedIndex;
    this.applyingIndex = applyingIndex;
    next();
}
 
Example #29
Source File: FSMCallerImpl.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
private boolean passByStatus(final Closure done) {
    final Status status = this.error.getStatus();
    if (!status.isOk()) {
        if (done != null) {
            done.run(new Status(RaftError.EINVAL, "FSMCaller is in bad status=`%s`", status));
            return false;
        }
    }
    return true;
}
 
Example #30
Source File: NodeImpl.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
@Override
public void removeLearners(final List<PeerId> learners, final Closure done) {
    checkPeers(learners);
    this.writeLock.lock();
    try {
        final Configuration newConf = new Configuration(this.conf.getConf());
        for (final PeerId peer : learners) {
            newConf.removeLearner(peer);
        }
        unsafeRegisterConfChange(this.conf.getConf(), newConf, done);
    } finally {
        this.writeLock.unlock();
    }
}