Search in sources :

Example 6 with ByteBufferCollector

use of org.apache.ignite.raft.jraft.util.ByteBufferCollector in project ignite-3 by apache.

the class AppendEntriesBenchmark method sendEntries1.

private byte[] sendEntries1() {
    final AppendEntriesRequestBuilder rb = msgFactory.appendEntriesRequest();
    fillCommonFields(rb);
    final ByteBufferCollector dataBuffer = ByteBufferCollector.allocate();
    for (int i = 0; i < entryCount; i++) {
        final byte[] bytes = new byte[sizeOfEntry];
        ThreadLocalRandom.current().nextBytes(bytes);
        final ByteBuffer buf = ByteBuffer.wrap(bytes);
        dataBuffer.put(buf.slice());
    }
    final ByteBuffer buf = dataBuffer.getBuffer();
    buf.flip();
    rb.data(new ByteString(buf));
    return Marshaller.DEFAULT.marshall(rb.build());
}
Also used : ByteBufferCollector(org.apache.ignite.raft.jraft.util.ByteBufferCollector) ByteString(org.apache.ignite.raft.jraft.util.ByteString) ByteBuffer(java.nio.ByteBuffer)

Example 7 with ByteBufferCollector

use of org.apache.ignite.raft.jraft.util.ByteBufferCollector in project ignite-3 by apache.

the class LocalFileReaderTest method testReadFile.

@Test
public void testReadFile() throws Exception {
    final ByteBufferCollector bufRef = ByteBufferCollector.allocate();
    try {
        this.fileReader.readFile(bufRef, "unfound", 0, 1024);
        fail();
    } catch (final FileNotFoundException e) {
    // Ignored.
    }
    final String data = writeData();
    assertReadResult(bufRef, data);
}
Also used : ByteBufferCollector(org.apache.ignite.raft.jraft.util.ByteBufferCollector) FileNotFoundException(java.io.FileNotFoundException) Test(org.junit.jupiter.api.Test) BaseStorageTest(org.apache.ignite.raft.jraft.storage.BaseStorageTest)

Example 8 with ByteBufferCollector

use of org.apache.ignite.raft.jraft.util.ByteBufferCollector in project ignite-3 by apache.

the class LocalFileReaderTest method testReadBigFile.

@Test
public void testReadBigFile() throws Exception {
    final ByteBufferCollector bufRef = ByteBufferCollector.allocate(2);
    final File file = new File(this.path + File.separator + "data");
    String data = "";
    for (int i = 0; i < 4096; i++) {
        data += i % 10;
    }
    Files.writeString(file.toPath(), data);
    int read = this.fileReader.readFile(bufRef, "data", 0, 1024);
    assertEquals(1024, read);
    read = this.fileReader.readFile(bufRef, "data", 1024, 1024);
    assertEquals(1024, read);
    read = this.fileReader.readFile(bufRef, "data", 1024 + 1024, 1024);
    assertEquals(1024, read);
    read = this.fileReader.readFile(bufRef, "data", 1024 + 1024 + 1024, 1024);
    assertEquals(-1, read);
    final ByteBuffer buf = bufRef.getBuffer();
    buf.flip();
    assertEquals(data.length(), buf.remaining());
    final byte[] bs = new byte[data.length()];
    buf.get(bs);
    assertEquals(data, new String(bs, UTF_8));
}
Also used : ByteBufferCollector(org.apache.ignite.raft.jraft.util.ByteBufferCollector) File(java.io.File) ByteBuffer(java.nio.ByteBuffer) Test(org.junit.jupiter.api.Test) BaseStorageTest(org.apache.ignite.raft.jraft.storage.BaseStorageTest)

Example 9 with ByteBufferCollector

use of org.apache.ignite.raft.jraft.util.ByteBufferCollector in project ignite-3 by apache.

the class Replicator method sendEntries.

/**
 * Send log entries to follower, returns true when success, otherwise false and unlock the id.
 *
 * @param nextSendingIndex next sending index
 * @return send result.
 */
private boolean sendEntries(final long nextSendingIndex) {
    final AppendEntriesRequestBuilder rb = raftOptions.getRaftMessagesFactory().appendEntriesRequest();
    if (!fillCommonFields(rb, nextSendingIndex - 1, false)) {
        // unlock id in installSnapshot
        installSnapshot();
        return false;
    }
    ByteBufferCollector dataBuf = null;
    final int maxEntriesSize = this.raftOptions.getMaxEntriesSize();
    final RecyclableByteBufferList byteBufList = RecyclableByteBufferList.newInstance();
    try {
        List<RaftOutter.EntryMeta> entries = new ArrayList<>();
        for (int i = 0; i < maxEntriesSize; i++) {
            final EntryMetaBuilder emb = raftOptions.getRaftMessagesFactory().entryMeta();
            if (!prepareEntry(nextSendingIndex, i, emb, byteBufList)) {
                break;
            }
            entries.add(emb.build());
        }
        rb.entriesList(entries);
        if (entries.isEmpty()) {
            if (nextSendingIndex < this.options.getLogManager().getFirstLogIndex()) {
                installSnapshot();
                return false;
            }
            // _id is unlock in _wait_more
            waitMoreEntries(nextSendingIndex);
            return false;
        }
        if (byteBufList.getCapacity() > 0) {
            dataBuf = ByteBufferCollector.allocateByRecyclers(byteBufList.getCapacity());
            for (final ByteBuffer b : byteBufList) {
                dataBuf.put(b);
            }
            final ByteBuffer buf = dataBuf.getBuffer();
            buf.flip();
            rb.data(new ByteString(buf));
        }
    } finally {
        RecycleUtil.recycle(byteBufList);
    }
    final AppendEntriesRequest request = rb.build();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Node {} send AppendEntriesRequest to {} term {} lastCommittedIndex {} prevLogIndex {} prevLogTerm {} logIndex {} count {}", this.options.getNode().getNodeId(), this.options.getPeerId(), this.options.getTerm(), request.committedIndex(), request.prevLogIndex(), request.prevLogTerm(), nextSendingIndex, Utils.size(request.entriesList()));
    }
    this.statInfo.runningState = RunningState.APPENDING_ENTRIES;
    this.statInfo.firstLogIndex = request.prevLogIndex() + 1;
    this.statInfo.lastLogIndex = request.prevLogIndex() + Utils.size(request.entriesList());
    final Recyclable recyclable = dataBuf;
    final int v = this.version;
    final long monotonicSendTimeMs = Utils.monotonicMs();
    final int seq = getAndIncrementReqSeq();
    Future<Message> rpcFuture = null;
    try {
        rpcFuture = this.rpcService.appendEntries(this.options.getPeerId().getEndpoint(), request, -1, new RpcResponseClosureAdapter<AppendEntriesResponse>() {

            @Override
            public void run(final Status status) {
                if (status.isOk()) {
                    // TODO: recycle on send success, not response received IGNITE-14832.
                    // Also, this closure can be executed when rpcFuture was cancelled, but the request was not sent (meaning
                    // it's too early to recycle byte buffer)
                    RecycleUtil.recycle(recyclable);
                }
                onRpcReturned(Replicator.this.id, RequestType.AppendEntries, status, request, getResponse(), seq, v, monotonicSendTimeMs);
            }
        });
    } catch (final Throwable t) {
        RecycleUtil.recycle(recyclable);
        ThrowUtil.throwException(t);
    }
    addInflight(RequestType.AppendEntries, nextSendingIndex, Utils.size(request.entriesList()), request.data() == null ? 0 : request.data().size(), seq, rpcFuture);
    return true;
}
Also used : Status(org.apache.ignite.raft.jraft.Status) RecyclableByteBufferList(org.apache.ignite.raft.jraft.util.RecyclableByteBufferList) Message(org.apache.ignite.raft.jraft.rpc.Message) ByteString(org.apache.ignite.raft.jraft.util.ByteString) ArrayList(java.util.ArrayList) RpcResponseClosureAdapter(org.apache.ignite.raft.jraft.rpc.RpcResponseClosureAdapter) AppendEntriesRequest(org.apache.ignite.raft.jraft.rpc.RpcRequests.AppendEntriesRequest) ByteBuffer(java.nio.ByteBuffer) ByteBufferCollector(org.apache.ignite.raft.jraft.util.ByteBufferCollector) AppendEntriesRequestBuilder(org.apache.ignite.raft.jraft.rpc.AppendEntriesRequestBuilder) Recyclable(org.apache.ignite.raft.jraft.util.Recyclable) EntryMetaBuilder(org.apache.ignite.raft.jraft.entity.EntryMetaBuilder)

Example 10 with ByteBufferCollector

use of org.apache.ignite.raft.jraft.util.ByteBufferCollector in project ignite-3 by apache.

the class FileService method handleGetFile.

/**
 * Handle GetFileRequest, run the response or set the response with done.
 */
public Message handleGetFile(final GetFileRequest request, final RpcRequestClosure done) {
    if (request.count() <= 0 || request.offset() < 0) {
        return // 
        RaftRpcFactory.DEFAULT.newResponse(msgFactory, RaftError.EREQUEST, "Invalid request: %s", request);
    }
    final FileReader reader = this.fileReaderMap.get(request.readerId());
    if (LOG.isDebugEnabled()) {
        LOG.info("handleGetFile id={}, name={}, offset={}, cnt={}", request.readerId(), request.filename(), request.offset(), request.count());
    }
    if (reader == null) {
        return // 
        RaftRpcFactory.DEFAULT.newResponse(msgFactory, RaftError.ENOENT, "Fail to find reader=%d", request.readerId());
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("GetFile from {} path={} filename={} offset={} count={}", done.getRpcCtx().getRemoteAddress(), reader.getPath(), request.filename(), request.offset(), request.count());
    }
    final ByteBufferCollector dataBuffer = ByteBufferCollector.allocate();
    final GetFileResponseBuilder responseBuilder = msgFactory.getFileResponse();
    try {
        final int read = reader.readFile(dataBuffer, request.filename(), request.offset(), request.count());
        responseBuilder.readSize(read);
        responseBuilder.eof(read == FileReader.EOF);
        final ByteBuffer buf = dataBuffer.getBuffer();
        buf.flip();
        if (!buf.hasRemaining()) {
            // skip empty data
            responseBuilder.data(ByteString.EMPTY);
        } else {
            // TODO check hole https://issues.apache.org/jira/browse/IGNITE-14832
            responseBuilder.data(new ByteString(buf));
        }
        return responseBuilder.build();
    } catch (final RetryAgainException e) {
        return // 
        RaftRpcFactory.DEFAULT.newResponse(msgFactory, RaftError.EAGAIN, "Fail to read from path=%s filename=%s with error: %s", reader.getPath(), request.filename(), e.getMessage());
    } catch (final IOException e) {
        LOG.error("Fail to read file path={} filename={}", e, reader.getPath(), request.filename());
        return // 
        RaftRpcFactory.DEFAULT.newResponse(msgFactory, RaftError.EIO, "Fail to read from path=%s filename=%s", reader.getPath(), request.filename());
    }
}
Also used : ByteBufferCollector(org.apache.ignite.raft.jraft.util.ByteBufferCollector) GetFileResponseBuilder(org.apache.ignite.raft.jraft.rpc.GetFileResponseBuilder) ByteString(org.apache.ignite.raft.jraft.util.ByteString) FileReader(org.apache.ignite.raft.jraft.storage.io.FileReader) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) RetryAgainException(org.apache.ignite.raft.jraft.error.RetryAgainException)

Aggregations

ByteBufferCollector (org.apache.ignite.raft.jraft.util.ByteBufferCollector)14 ByteBuffer (java.nio.ByteBuffer)8 Test (org.junit.jupiter.api.Test)8 ByteString (org.apache.ignite.raft.jraft.util.ByteString)7 BaseStorageTest (org.apache.ignite.raft.jraft.storage.BaseStorageTest)5 Message (org.apache.ignite.raft.jraft.rpc.Message)3 FileNotFoundException (java.io.FileNotFoundException)2 CompletableFuture (java.util.concurrent.CompletableFuture)2 Status (org.apache.ignite.raft.jraft.Status)2 RpcRequests (org.apache.ignite.raft.jraft.rpc.RpcRequests)2 File (java.io.File)1 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 EntryMetaBuilder (org.apache.ignite.raft.jraft.entity.EntryMetaBuilder)1 LocalFileMetaOutter (org.apache.ignite.raft.jraft.entity.LocalFileMetaOutter)1 RetryAgainException (org.apache.ignite.raft.jraft.error.RetryAgainException)1 RaftOptions (org.apache.ignite.raft.jraft.option.RaftOptions)1 AppendEntriesRequestBuilder (org.apache.ignite.raft.jraft.rpc.AppendEntriesRequestBuilder)1 GetFileResponseBuilder (org.apache.ignite.raft.jraft.rpc.GetFileResponseBuilder)1