use of com.alipay.sofa.jraft.storage.io.FileReader 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());
}
}
Aggregations