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);
}
}
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"));
}
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());
}
}
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;
}
Aggregations