Search in sources :

Example 11 with ByteBufferCollector

use of com.alipay.sofa.jraft.util.ByteBufferCollector in project sofa-jraft by sofastack.

the class AppendEntriesBenchmark method sendEntries2.

private static byte[] sendEntries2(final int entryCount, final int sizeOfEntry) {
    final AppendEntriesRequest.Builder rb = AppendEntriesRequest.newBuilder();
    fillCommonFields(rb);
    final ByteBufferCollector dataBuffer = ByteBufferCollector.allocateByRecyclers();
    try {
        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.setData(ZeroByteStringHelper.wrap(buf));
        return rb.build().toByteArray();
    } finally {
        RecycleUtil.recycle(dataBuffer);
    }
}
Also used : ByteBufferCollector(com.alipay.sofa.jraft.util.ByteBufferCollector) AppendEntriesRequest(com.alipay.sofa.jraft.rpc.RpcRequests.AppendEntriesRequest) ByteBuffer(java.nio.ByteBuffer)

Example 12 with ByteBufferCollector

use of com.alipay.sofa.jraft.util.ByteBufferCollector in project sofa-jraft by sofastack.

the class SnapshotFileReaderTest method testReadMetaFile.

@Test
public void testReadMetaFile() throws Exception {
    final ByteBufferCollector bufRef = ByteBufferCollector.allocate(1024);
    final LocalFileMetaOutter.LocalFileMeta meta = addDataMeta();
    assertEquals(-1, this.reader.readFile(bufRef, Snapshot.JRAFT_SNAPSHOT_META_FILE, 0, Integer.MAX_VALUE));
    final ByteBuffer buf = bufRef.getBuffer();
    buf.flip();
    final LocalSnapshotMetaTable newTable = new LocalSnapshotMetaTable(new RaftOptions());
    newTable.loadFromIoBufferAsRemote(buf);
    Assert.assertEquals(meta, newTable.getFileMeta("data"));
}
Also used : RaftOptions(com.alipay.sofa.jraft.option.RaftOptions) LocalFileMetaOutter(com.alipay.sofa.jraft.entity.LocalFileMetaOutter) ByteBufferCollector(com.alipay.sofa.jraft.util.ByteBufferCollector) ByteBuffer(java.nio.ByteBuffer) Test(org.junit.Test) BaseStorageTest(com.alipay.sofa.jraft.storage.BaseStorageTest)

Example 13 with ByteBufferCollector

use of com.alipay.sofa.jraft.util.ByteBufferCollector in project sofa-jraft by sofastack.

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.getCount() <= 0 || request.getOffset() < 0) {
        return // 
        RpcFactoryHelper.responseFactory().newResponse(GetFileResponse.getDefaultInstance(), RaftError.EREQUEST, "Invalid request: %s", request);
    }
    final FileReader reader = this.fileReaderMap.get(request.getReaderId());
    if (reader == null) {
        return // 
        RpcFactoryHelper.responseFactory().newResponse(GetFileResponse.getDefaultInstance(), RaftError.ENOENT, "Fail to find reader=%d", request.getReaderId());
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("GetFile from {} path={} filename={} offset={} count={}", done.getRpcCtx().getRemoteAddress(), reader.getPath(), request.getFilename(), request.getOffset(), request.getCount());
    }
    final ByteBufferCollector dataBuffer = ByteBufferCollector.allocate();
    final GetFileResponse.Builder responseBuilder = GetFileResponse.newBuilder();
    try {
        final int read = reader.readFile(dataBuffer, request.getFilename(), request.getOffset(), request.getCount());
        responseBuilder.setReadSize(read);
        responseBuilder.setEof(read == FileReader.EOF);
        final ByteBuffer buf = dataBuffer.getBuffer();
        buf.flip();
        if (!buf.hasRemaining()) {
            // skip empty data
            responseBuilder.setData(ByteString.EMPTY);
        } else {
            // TODO check hole
            responseBuilder.setData(ZeroByteStringHelper.wrap(buf));
        }
        return responseBuilder.build();
    } catch (final RetryAgainException e) {
        return // 
        RpcFactoryHelper.responseFactory().newResponse(GetFileResponse.getDefaultInstance(), RaftError.EAGAIN, "Fail to read from path=%s filename=%s with error: %s", reader.getPath(), request.getFilename(), e.getMessage());
    } catch (final IOException e) {
        LOG.error("Fail to read file path={} filename={}", reader.getPath(), request.getFilename(), e);
        return // 
        RpcFactoryHelper.responseFactory().newResponse(GetFileResponse.getDefaultInstance(), RaftError.EIO, "Fail to read from path=%s filename=%s", reader.getPath(), request.getFilename());
    }
}
Also used : ByteBufferCollector(com.alipay.sofa.jraft.util.ByteBufferCollector) GetFileResponse(com.alipay.sofa.jraft.rpc.RpcRequests.GetFileResponse) FileReader(com.alipay.sofa.jraft.storage.io.FileReader) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) RetryAgainException(com.alipay.sofa.jraft.error.RetryAgainException)

Example 14 with ByteBufferCollector

use of com.alipay.sofa.jraft.util.ByteBufferCollector in project sofa-jraft by sofastack.

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 AppendEntriesRequest.Builder rb = AppendEntriesRequest.newBuilder();
    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 {
        for (int i = 0; i < maxEntriesSize; i++) {
            final RaftOutter.EntryMeta.Builder emb = RaftOutter.EntryMeta.newBuilder();
            if (!prepareEntry(nextSendingIndex, i, emb, byteBufList)) {
                break;
            }
            rb.addEntries(emb.build());
        }
        if (rb.getEntriesCount() == 0) {
            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.setData(ZeroByteStringHelper.wrap(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.getCommittedIndex(), request.getPrevLogIndex(), request.getPrevLogTerm(), nextSendingIndex, request.getEntriesCount());
    }
    this.statInfo.runningState = RunningState.APPENDING_ENTRIES;
    this.statInfo.firstLogIndex = rb.getPrevLogIndex() + 1;
    this.statInfo.lastLogIndex = rb.getPrevLogIndex() + rb.getEntriesCount();
    final Recyclable recyclable = dataBuf;
    final int v = this.version;
    final long monotonicSendTimeMs = Utils.monotonicMs();
    final int seq = getAndIncrementReqSeq();
    this.appendEntriesCounter++;
    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) {
                // TODO: recycle on send success, not response received.
                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, request.getEntriesCount(), request.getData().size(), seq, rpcFuture);
    return true;
}
Also used : Status(com.alipay.sofa.jraft.Status) RecyclableByteBufferList(com.alipay.sofa.jraft.util.RecyclableByteBufferList) Message(com.google.protobuf.Message) RpcResponseClosureAdapter(com.alipay.sofa.jraft.rpc.RpcResponseClosureAdapter) AppendEntriesRequest(com.alipay.sofa.jraft.rpc.RpcRequests.AppendEntriesRequest) ByteBuffer(java.nio.ByteBuffer) ByteBufferCollector(com.alipay.sofa.jraft.util.ByteBufferCollector) Recyclable(com.alipay.sofa.jraft.util.Recyclable)

Aggregations

ByteBufferCollector (com.alipay.sofa.jraft.util.ByteBufferCollector)14 ByteBuffer (java.nio.ByteBuffer)8 Test (org.junit.Test)8 BaseStorageTest (com.alipay.sofa.jraft.storage.BaseStorageTest)5 AppendEntriesRequest (com.alipay.sofa.jraft.rpc.RpcRequests.AppendEntriesRequest)4 Message (com.google.protobuf.Message)3 Status (com.alipay.sofa.jraft.Status)2 FutureImpl (com.alipay.sofa.jraft.rpc.impl.FutureImpl)2 FileNotFoundException (java.io.FileNotFoundException)2 LocalFileMetaOutter (com.alipay.sofa.jraft.entity.LocalFileMetaOutter)1 RetryAgainException (com.alipay.sofa.jraft.error.RetryAgainException)1 RaftOptions (com.alipay.sofa.jraft.option.RaftOptions)1 GetFileResponse (com.alipay.sofa.jraft.rpc.RpcRequests.GetFileResponse)1 RpcResponseClosureAdapter (com.alipay.sofa.jraft.rpc.RpcResponseClosureAdapter)1 FileReader (com.alipay.sofa.jraft.storage.io.FileReader)1 Session (com.alipay.sofa.jraft.storage.snapshot.remote.Session)1 Recyclable (com.alipay.sofa.jraft.util.Recyclable)1 RecyclableByteBufferList (com.alipay.sofa.jraft.util.RecyclableByteBufferList)1 File (java.io.File)1 IOException (java.io.IOException)1