Search in sources :

Example 1 with RecordFileWriter

use of com.bonree.brfs.disknode.data.write.RecordFileWriter in project BRFS by zhangnianli.

the class FileRecoveryMessageHandler method handleMessage.

@Override
public void handleMessage(BaseMessage baseMessage, ResponseWriter<BaseResponse> writer) {
    FileRecoveryMessage message = ProtoStuffUtils.deserialize(baseMessage.getBody(), FileRecoveryMessage.class);
    if (message == null) {
        LOG.error("decode recover message error");
        writer.write(new BaseResponse(ResponseCode.ERROR_PROTOCOL));
        return;
    }
    String filePath = null;
    try {
        filePath = context.getConcreteFilePath(message.getFilePath());
        LOG.info("starting recover file[{}]", filePath);
        Pair<RecordFileWriter, WriteWorker> binding = writerManager.getBinding(filePath, false);
        if (binding == null) {
            writer.write(new BaseResponse(ResponseCode.ERROR));
            return;
        }
        binding.first().position(fileFormater.absoluteOffset(message.getOffset()));
        byte[] bytes = null;
        for (String stateString : message.getSources()) {
            FileObjectSyncState state = SyncStateCodec.fromString(stateString);
            Service service = serviceManager.getServiceById(state.getServiceGroup(), state.getServiceId());
            if (service == null) {
                LOG.error("can not get service with[{}:{}]", state.getServiceGroup(), state.getServiceId());
                continue;
            }
            DiskNodeClient client = null;
            try {
                LOG.info("get data from{} to recover...", service);
                TcpClient<ReadObject, FileContentPart> readClient = clientGroup.createClient(new AsyncFileReaderCreateConfig() {

                    @Override
                    public SocketAddress remoteAddress() {
                        return new InetSocketAddress(service.getHost(), service.getExtraPort());
                    }

                    @Override
                    public int connectTimeoutMillis() {
                        return 3000;
                    }

                    @Override
                    public int maxPendingRead() {
                        return 0;
                    }
                }, ForkJoinPool.commonPool());
                client = new TcpDiskNodeClient(null, readClient);
                long lackBytes = state.getFileLength() - message.getOffset();
                CompletableFuture<byte[]> byteFuture = new CompletableFuture<byte[]>();
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                client.readData(state.getFilePath(), message.getOffset(), (int) lackBytes, new ByteConsumer() {

                    @Override
                    public void error(Throwable e) {
                        byteFuture.completeExceptionally(e);
                    }

                    @Override
                    public void consume(byte[] bytes, boolean endOfConsume) {
                        try {
                            output.write(bytes);
                            if (endOfConsume) {
                                byteFuture.complete(output.toByteArray());
                                output.close();
                            }
                        } catch (Exception e) {
                            byteFuture.completeExceptionally(e);
                        }
                    }
                });
                bytes = byteFuture.get();
                if (bytes != null) {
                    LOG.info("read bytes length[{}], require[{}]", bytes.length, lackBytes);
                    break;
                }
            } catch (Exception e) {
                LOG.error("recover file[{}] error", filePath, e);
            } finally {
                CloseUtils.closeQuietly(client);
            }
        }
        if (bytes == null) {
            writer.write(new BaseResponse(ResponseCode.ERROR));
            return;
        }
        int offset = 0;
        int size = 0;
        while ((size = FileDecoder.getOffsets(offset, bytes)) > 0) {
            LOG.info("rewrite data[offset={}, size={}] to file[{}]", offset, size, filePath);
            binding.first().write(bytes, offset, size);
            offset += size;
            size = 0;
        }
        if (offset != bytes.length) {
            LOG.error("perhaps datas that being recoverd is not correct! get [{}], but recoverd[{}]", bytes.length, offset);
        }
        writer.write(new BaseResponse(ResponseCode.OK));
    } catch (Exception e) {
        LOG.error("recover file[{}] error", filePath, e);
        writer.write(new BaseResponse(ResponseCode.ERROR));
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) TcpDiskNodeClient(com.bonree.brfs.disknode.client.TcpDiskNodeClient) DiskNodeClient(com.bonree.brfs.disknode.client.DiskNodeClient) BaseResponse(com.bonree.brfs.common.net.tcp.BaseResponse) ByteConsumer(com.bonree.brfs.disknode.client.DiskNodeClient.ByteConsumer) CompletableFuture(java.util.concurrent.CompletableFuture) RecordFileWriter(com.bonree.brfs.disknode.data.write.RecordFileWriter) FileContentPart(com.bonree.brfs.common.net.tcp.file.client.FileContentPart) AsyncFileReaderCreateConfig(com.bonree.brfs.common.net.tcp.file.client.AsyncFileReaderCreateConfig) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) FileObjectSyncState(com.bonree.brfs.common.filesync.FileObjectSyncState) Service(com.bonree.brfs.common.service.Service) ByteArrayOutputStream(java.io.ByteArrayOutputStream) TcpDiskNodeClient(com.bonree.brfs.disknode.client.TcpDiskNodeClient) ReadObject(com.bonree.brfs.common.net.tcp.file.ReadObject) FileRecoveryMessage(com.bonree.brfs.disknode.server.tcp.handler.data.FileRecoveryMessage) WriteWorker(com.bonree.brfs.disknode.data.write.worker.WriteWorker)

Example 2 with RecordFileWriter

use of com.bonree.brfs.disknode.data.write.RecordFileWriter in project BRFS by zhangnianli.

the class OpenFileMessageHandler method handleMessage.

@Override
public void handleMessage(BaseMessage baseMessage, ResponseWriter<BaseResponse> writer) {
    OpenFileMessage message = ProtoStuffUtils.deserialize(baseMessage.getBody(), OpenFileMessage.class);
    if (message == null) {
        writer.write(new BaseResponse(ResponseCode.ERROR_PROTOCOL));
        return;
    }
    FileFormater fileFormater = new SimpleFileFormater(Math.min(message.getCapacity(), MAX_CAPACITY));
    String realPath = diskContext.getConcreteFilePath(message.getFilePath());
    LOG.info("open file [{}]", realPath);
    Pair<RecordFileWriter, WriteWorker> binding = writerManager.getBinding(realPath, true);
    if (binding == null) {
        LOG.error("get file writer for file[{}] error!", realPath);
        writer.write(new BaseResponse(ResponseCode.ERROR));
        return;
    }
    try {
        binding.first().write(fileFormater.fileHeader().getBytes());
        binding.first().flush();
        BaseResponse response = new BaseResponse(ResponseCode.OK);
        response.setBody(Longs.toByteArray(fileFormater.maxBodyLength()));
        writer.write(response);
    } catch (Exception e) {
        LOG.error("write header to file[{}] error!", realPath);
        writer.write(new BaseResponse(ResponseCode.ERROR));
    }
}
Also used : BaseResponse(com.bonree.brfs.common.net.tcp.BaseResponse) OpenFileMessage(com.bonree.brfs.disknode.server.tcp.handler.data.OpenFileMessage) FileFormater(com.bonree.brfs.disknode.fileformat.FileFormater) SimpleFileFormater(com.bonree.brfs.disknode.fileformat.impl.SimpleFileFormater) RecordFileWriter(com.bonree.brfs.disknode.data.write.RecordFileWriter) WriteWorker(com.bonree.brfs.disknode.data.write.worker.WriteWorker) SimpleFileFormater(com.bonree.brfs.disknode.fileformat.impl.SimpleFileFormater)

Example 3 with RecordFileWriter

use of com.bonree.brfs.disknode.data.write.RecordFileWriter in project BRFS by zhangnianli.

the class WriteFileMessageHandler method handleMessage.

@Override
public void handleMessage(BaseMessage baseMessage, ResponseWriter<BaseResponse> writer) {
    WriteFileMessage message = ProtoStuffUtils.deserialize(baseMessage.getBody(), WriteFileMessage.class);
    if (message == null) {
        writer.write(new BaseResponse(ResponseCode.ERROR_PROTOCOL));
        return;
    }
    try {
        String realPath = diskContext.getConcreteFilePath(message.getFilePath());
        LOG.debug("writing to file [{}]", realPath);
        Pair<RecordFileWriter, WriteWorker> binding = writerManager.getBinding(realPath, false);
        if (binding == null) {
            // 运行到这,可能时打开文件时失败,导致写数据节点找不到writer
            LOG.warn("no file writer is found, maybe the file[{}] is not opened.", realPath);
            writer.write(new BaseResponse(ResponseCode.ERROR));
            return;
        }
        binding.second().put(new DataWriteTask(binding, message, writer));
    } catch (Exception e) {
        LOG.error("EEEERRRRRR", e);
        writer.write(new BaseResponse(ResponseCode.ERROR));
    }
}
Also used : BaseResponse(com.bonree.brfs.common.net.tcp.BaseResponse) RecordFileWriter(com.bonree.brfs.disknode.data.write.RecordFileWriter) WriteFileMessage(com.bonree.brfs.disknode.server.tcp.handler.data.WriteFileMessage) WriteWorker(com.bonree.brfs.disknode.data.write.worker.WriteWorker) IOException(java.io.IOException)

Example 4 with RecordFileWriter

use of com.bonree.brfs.disknode.data.write.RecordFileWriter in project BRFS by zhangnianli.

the class RecoveryMessageHandler method handle.

@Override
public void handle(HttpMessage msg, HandleResultCallback callback) {
    HandleResult handleResult = new HandleResult();
    String filePath = null;
    try {
        filePath = context.getConcreteFilePath(msg.getPath());
        LOG.info("starting recover file[{}]", filePath);
        String lengthParam = msg.getParams().get("length");
        if (lengthParam == null) {
            handleResult.setSuccess(false);
            callback.completed(handleResult);
            return;
        }
        long fileLength = Long.parseLong(msg.getParams().get("length"));
        List<String> fullStates = Splitter.on(',').omitEmptyStrings().trimResults().splitToList(msg.getParams().get("fulls"));
        Pair<RecordFileWriter, WriteWorker> binding = writerManager.getBinding(filePath, false);
        if (binding == null) {
            handleResult.setSuccess(false);
            callback.completed(handleResult);
            return;
        }
        binding.first().position(fileFormater.absoluteOffset(fileLength));
        byte[] bytes = null;
        for (String stateString : fullStates) {
            FileObjectSyncState state = SyncStateCodec.fromString(stateString);
            Service service = serviceManager.getServiceById(state.getServiceGroup(), state.getServiceId());
            if (service == null) {
                LOG.error("can not get service with[{}:{}]", state.getServiceGroup(), state.getServiceId());
                continue;
            }
            DiskNodeClient client = null;
            try {
                LOG.info("get data from{} to recover...", service);
                client = new HttpDiskNodeClient(service.getHost(), service.getPort());
                long lackBytes = state.getFileLength() - fileLength;
                CompletableFuture<byte[]> byteFuture = new CompletableFuture<byte[]>();
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                client.readData(state.getFilePath(), fileLength, (int) lackBytes, new ByteConsumer() {

                    @Override
                    public void error(Throwable e) {
                        byteFuture.completeExceptionally(e);
                    }

                    @Override
                    public void consume(byte[] bytes, boolean endOfConsume) {
                        try {
                            output.write(bytes);
                            if (endOfConsume) {
                                byteFuture.complete(output.toByteArray());
                                output.close();
                            }
                        } catch (Exception e) {
                            byteFuture.completeExceptionally(e);
                        }
                    }
                });
                bytes = byteFuture.get();
                if (bytes != null) {
                    LOG.info("read bytes length[{}], require[{}]", bytes.length, lackBytes);
                    break;
                }
            } catch (Exception e) {
                LOG.error("recover file[{}] error", filePath, e);
            } finally {
                CloseUtils.closeQuietly(client);
            }
        }
        if (bytes == null) {
            handleResult.setSuccess(false);
            callback.completed(handleResult);
            return;
        }
        int offset = 0;
        int size = 0;
        while ((size = FileDecoder.getOffsets(offset, bytes)) > 0) {
            LOG.info("rewrite data[offset={}, size={}] to file[{}]", offset, size, filePath);
            binding.first().write(bytes, offset, size);
            offset += size;
            size = 0;
        }
        if (offset != bytes.length) {
            LOG.error("perhaps datas that being recoverd is not correct! get [{}], but recoverd[{}]", bytes.length, offset);
        }
        handleResult.setSuccess(true);
    } catch (Exception e) {
        LOG.error("recover file[{}] error", filePath, e);
        handleResult.setSuccess(false);
    } finally {
        callback.completed(handleResult);
    }
}
Also used : HttpDiskNodeClient(com.bonree.brfs.disknode.client.HttpDiskNodeClient) FileObjectSyncState(com.bonree.brfs.common.filesync.FileObjectSyncState) Service(com.bonree.brfs.common.service.Service) HandleResult(com.bonree.brfs.common.net.http.HandleResult) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DiskNodeClient(com.bonree.brfs.disknode.client.DiskNodeClient) HttpDiskNodeClient(com.bonree.brfs.disknode.client.HttpDiskNodeClient) ByteConsumer(com.bonree.brfs.disknode.client.DiskNodeClient.ByteConsumer) CompletableFuture(java.util.concurrent.CompletableFuture) RecordFileWriter(com.bonree.brfs.disknode.data.write.RecordFileWriter) WriteWorker(com.bonree.brfs.disknode.data.write.worker.WriteWorker)

Example 5 with RecordFileWriter

use of com.bonree.brfs.disknode.data.write.RecordFileWriter in project BRFS by zhangnianli.

the class CloseMessageHandler method handle.

@Override
public void handle(HttpMessage msg, HandleResultCallback callback) {
    HandleResult result = new HandleResult();
    String filePath = null;
    try {
        filePath = diskContext.getConcreteFilePath(msg.getPath());
        LOG.info("CLOSE file[{}]", filePath);
        Pair<RecordFileWriter, WriteWorker> binding = writerManager.getBinding(filePath, false);
        if (binding == null) {
            LOG.info("no writer is found for file[{}], treat it as OK!", filePath);
            File dataFile = new File(filePath);
            if (!dataFile.exists()) {
                result.setData(Longs.toByteArray(0));
                result.setSuccess(true);
                return;
            }
            MappedByteBuffer buffer = Files.map(dataFile);
            try {
                buffer.position(fileFormater.fileHeader().length());
                buffer.limit(buffer.capacity() - fileFormater.fileTailer().length());
                result.setData(Longs.toByteArray(ByteUtils.crc(buffer)));
                result.setSuccess(true);
                return;
            } finally {
                BufferUtils.release(buffer);
            }
        }
        LOG.info("start writing file tailer for {}", filePath);
        binding.first().flush();
        byte[] fileBytes = DataFileReader.readFile(filePath, 2);
        long crcCode = ByteUtils.crc(fileBytes);
        LOG.info("final crc code[{}] by bytes[{}] of file[{}]", crcCode, fileBytes.length, filePath);
        byte[] tailer = Bytes.concat(FileEncoder.validate(crcCode), FileEncoder.tail());
        binding.first().write(tailer);
        binding.first().flush();
        LOG.info("close over for file[{}]", filePath);
        writerManager.close(filePath);
        result.setData(Longs.toByteArray(crcCode));
        result.setSuccess(true);
    } catch (IOException e) {
        result.setSuccess(false);
        LOG.error("close file[{}] error!", filePath, e);
    } finally {
        callback.completed(result);
    }
}
Also used : MappedByteBuffer(java.nio.MappedByteBuffer) RecordFileWriter(com.bonree.brfs.disknode.data.write.RecordFileWriter) HandleResult(com.bonree.brfs.common.net.http.HandleResult) IOException(java.io.IOException) File(java.io.File) WriteWorker(com.bonree.brfs.disknode.data.write.worker.WriteWorker)

Aggregations

RecordFileWriter (com.bonree.brfs.disknode.data.write.RecordFileWriter)10 WriteWorker (com.bonree.brfs.disknode.data.write.worker.WriteWorker)10 HandleResult (com.bonree.brfs.common.net.http.HandleResult)4 BaseResponse (com.bonree.brfs.common.net.tcp.BaseResponse)4 File (java.io.File)4 IOException (java.io.IOException)4 FileObjectSyncState (com.bonree.brfs.common.filesync.FileObjectSyncState)2 Service (com.bonree.brfs.common.service.Service)2 DiskNodeClient (com.bonree.brfs.disknode.client.DiskNodeClient)2 ByteConsumer (com.bonree.brfs.disknode.client.DiskNodeClient.ByteConsumer)2 RecordCollection (com.bonree.brfs.disknode.data.write.record.RecordCollection)2 RecordElement (com.bonree.brfs.disknode.data.write.record.RecordElement)2 RecordElementReader (com.bonree.brfs.disknode.data.write.record.RecordElementReader)2 FileFormater (com.bonree.brfs.disknode.fileformat.FileFormater)2 SimpleFileFormater (com.bonree.brfs.disknode.fileformat.impl.SimpleFileFormater)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 MappedByteBuffer (java.nio.MappedByteBuffer)2 CompletableFuture (java.util.concurrent.CompletableFuture)2 ReadObject (com.bonree.brfs.common.net.tcp.file.ReadObject)1 AsyncFileReaderCreateConfig (com.bonree.brfs.common.net.tcp.file.client.AsyncFileReaderCreateConfig)1