Search in sources :

Example 6 with Service

use of com.bonree.brfs.common.service.Service in project BRFS by zhangnianli.

the class TestService method main.

public static void main(String[] args) throws Exception {
    RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
    CuratorFramework client = CuratorFrameworkFactory.newClient("192.168.101.86:2181", 3000, 3000, retryPolicy);
    client.start();
    client.blockUntilConnected();
    ServiceManager sm = new DefaultServiceManager(client.usingNamespace("test"));
    sm.start();
    Service s = new Service();
    s.setServiceGroup("group");
    s.setServiceId("ser_" + ID);
    s.setHost("local");
    sm.registerService(s);
    Service tmp = sm.getServiceById(s.getServiceGroup(), s.getServiceId());
    System.out.println(tmp);
    sm.addServiceStateListener("group", new ServiceStateListener() {

        @Override
        public void serviceRemoved(Service service) {
            System.out.println("remove--" + service.getServiceId());
        }

        @Override
        public void serviceAdded(Service service) {
            System.out.println("add--" + service.getServiceId());
        }
    });
    System.out.println(sm.getServiceById(s.getServiceGroup(), s.getServiceId()));
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) DefaultServiceManager(com.bonree.brfs.common.service.impl.DefaultServiceManager) ServiceStateListener(com.bonree.brfs.common.service.ServiceStateListener) ExponentialBackoffRetry(org.apache.curator.retry.ExponentialBackoffRetry) DefaultServiceManager(com.bonree.brfs.common.service.impl.DefaultServiceManager) ServiceManager(com.bonree.brfs.common.service.ServiceManager) Service(com.bonree.brfs.common.service.Service) RetryPolicy(org.apache.curator.RetryPolicy)

Example 7 with Service

use of com.bonree.brfs.common.service.Service 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 8 with Service

use of com.bonree.brfs.common.service.Service 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 9 with Service

use of com.bonree.brfs.common.service.Service in project BRFS by zhangnianli.

the class DefaultBRFileSystem method deleteStorageName.

@Override
public boolean deleteStorageName(String storageName) {
    try {
        Service[] serviceList = regionNodeSelector.select(regionNodeSelector.serviceNum());
        if (serviceList.length == 0) {
            throw new BRFSException("none disknode!!!");
        }
        for (Service service : serviceList) {
            URI uri = new URIBuilder().setScheme(config.getUrlSchema()).setHost(service.getHost()).setPort(service.getPort()).setPath(config.getStorageUrlRoot() + "/" + storageName).build();
            HttpResponse response = null;
            try {
                response = httpClient.executeDelete(uri, defaultHeaders);
            } catch (Exception e) {
                LOG.warn("deleteStorageName http request failed", e);
                continue;
            }
            if (response == null) {
                throw new Exception("can not get response for deleteStorageName!");
            }
            if (response.isReponseOK()) {
                return true;
            }
        }
    } catch (Exception e) {
        LOG.error("deleteStorageName error", e);
    }
    return false;
}
Also used : Service(com.bonree.brfs.common.service.Service) HttpResponse(com.bonree.brfs.common.net.http.client.HttpResponse) BRFSException(com.bonree.brfs.common.exception.BRFSException) URI(java.net.URI) BRFSException(com.bonree.brfs.common.exception.BRFSException) IOException(java.io.IOException) URIBuilder(com.bonree.brfs.common.net.http.client.URIBuilder)

Example 10 with Service

use of com.bonree.brfs.common.service.Service in project BRFS by zhangnianli.

the class DefaultBRFileSystem method updateStorageName.

@Override
public boolean updateStorageName(String storageName, Map<String, Object> attrs) {
    try {
        Service[] serviceList = regionNodeSelector.select(regionNodeSelector.serviceNum());
        if (serviceList.length == 0) {
            throw new BRFSException("none disknode!!!");
        }
        for (Service service : serviceList) {
            URIBuilder uriBuilder = new URIBuilder().setScheme(config.getUrlSchema()).setHost(service.getHost()).setPort(service.getPort()).setPath(config.getStorageUrlRoot() + "/" + storageName);
            for (Entry<String, Object> attr : attrs.entrySet()) {
                uriBuilder.addParameter(attr.getKey(), String.valueOf(attr.getValue()));
            }
            HttpResponse response = null;
            try {
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("username", config.getName());
                headers.put("password", config.getPasswd());
                response = httpClient.executePost(uriBuilder.build(), headers);
            } catch (Exception e) {
                LOG.warn("updateStorageName http request failed", e);
                continue;
            }
            if (response == null) {
                throw new Exception("can not get response for updateStorageName!");
            }
            if (response.isReponseOK()) {
                return true;
            }
        }
    } catch (Exception e) {
        LOG.error("updateStorageName error", e);
    }
    return false;
}
Also used : HashMap(java.util.HashMap) Service(com.bonree.brfs.common.service.Service) HttpResponse(com.bonree.brfs.common.net.http.client.HttpResponse) BRFSException(com.bonree.brfs.common.exception.BRFSException) BRFSException(com.bonree.brfs.common.exception.BRFSException) IOException(java.io.IOException) URIBuilder(com.bonree.brfs.common.net.http.client.URIBuilder)

Aggregations

Service (com.bonree.brfs.common.service.Service)35 IOException (java.io.IOException)10 ExecutorService (java.util.concurrent.ExecutorService)8 BRFSException (com.bonree.brfs.common.exception.BRFSException)7 HttpResponse (com.bonree.brfs.common.net.http.client.HttpResponse)6 URIBuilder (com.bonree.brfs.common.net.http.client.URIBuilder)6 ServiceManager (com.bonree.brfs.common.service.ServiceManager)4 StorageRegion (com.bonree.brfs.duplication.storageregion.StorageRegion)4 URI (java.net.URI)4 ArrayList (java.util.ArrayList)4 ReturnCode (com.bonree.brfs.common.ReturnCode)3 HandleResult (com.bonree.brfs.common.net.http.HandleResult)3 DefaultServiceManager (com.bonree.brfs.common.service.impl.DefaultServiceManager)3 DiskNodeClient (com.bonree.brfs.disknode.client.DiskNodeClient)3 DiskNodeConnection (com.bonree.brfs.duplication.datastream.connection.DiskNodeConnection)3 DuplicateNode (com.bonree.brfs.duplication.filenode.duplicates.DuplicateNode)3 SimpleAuthentication (com.bonree.brfs.authentication.SimpleAuthentication)2 UserModel (com.bonree.brfs.authentication.model.UserModel)2 ZookeeperPaths (com.bonree.brfs.common.ZookeeperPaths)2 FileObjectSyncState (com.bonree.brfs.common.filesync.FileObjectSyncState)2