Search in sources :

Example 1 with ConnectionAlreadyClosedException

use of com.alibaba.nacos.common.remote.exception.ConnectionAlreadyClosedException in project nacos by alibaba.

the class ConnectionManager method loadSingle.

/**
 * send load request to spefic connetionId.
 *
 * @param connectionId    connection id of client.
 * @param redirectAddress server address to redirect.
 */
public void loadSingle(String connectionId, String redirectAddress) {
    Connection connection = getConnection(connectionId);
    if (connection != null) {
        if (connection.getMetaInfo().isSdkSource()) {
            ConnectResetRequest connectResetRequest = new ConnectResetRequest();
            if (StringUtils.isNotBlank(redirectAddress) && redirectAddress.contains(Constants.COLON)) {
                String[] split = redirectAddress.split(Constants.COLON);
                connectResetRequest.setServerIp(split[0]);
                connectResetRequest.setServerPort(split[1]);
            }
            try {
                connection.request(connectResetRequest, 3000L);
            } catch (ConnectionAlreadyClosedException e) {
                unregister(connectionId);
            } catch (Exception e) {
                Loggers.REMOTE.error("error occurs when expel connection, connectionId: {} ", connectionId, e);
            }
        }
    }
}
Also used : ConnectionAlreadyClosedException(com.alibaba.nacos.common.remote.exception.ConnectionAlreadyClosedException) ConnectResetRequest(com.alibaba.nacos.api.remote.request.ConnectResetRequest) ConnectionAlreadyClosedException(com.alibaba.nacos.common.remote.exception.ConnectionAlreadyClosedException) NacosException(com.alibaba.nacos.api.exception.NacosException) IOException(java.io.IOException)

Example 2 with ConnectionAlreadyClosedException

use of com.alibaba.nacos.common.remote.exception.ConnectionAlreadyClosedException in project nacos by alibaba.

the class ConnectionManager method start.

/**
 * Start Task:Expel the connection which active Time expire.
 */
@PostConstruct
public void start() {
    // Start UnHealthy Connection Expel Task.
    RpcScheduledExecutor.COMMON_SERVER_EXECUTOR.scheduleWithFixedDelay(new Runnable() {

        @Override
        public void run() {
            try {
                int totalCount = connections.size();
                Loggers.REMOTE_DIGEST.info("Connection check task start");
                MetricsMonitor.getLongConnectionMonitor().set(totalCount);
                Set<Map.Entry<String, Connection>> entries = connections.entrySet();
                int currentSdkClientCount = currentSdkClientCount();
                boolean isLoaderClient = loadClient >= 0;
                int currentMaxClient = isLoaderClient ? loadClient : connectionLimitRule.countLimit;
                int expelCount = currentMaxClient < 0 ? 0 : Math.max(currentSdkClientCount - currentMaxClient, 0);
                Loggers.REMOTE_DIGEST.info("Total count ={}, sdkCount={},clusterCount={}, currentLimit={}, toExpelCount={}", totalCount, currentSdkClientCount, (totalCount - currentSdkClientCount), currentMaxClient + (isLoaderClient ? "(loaderCount)" : ""), expelCount);
                List<String> expelClient = new LinkedList<>();
                Map<String, AtomicInteger> expelForIp = new HashMap<>(16);
                // 1. calculate expel count  of ip.
                for (Map.Entry<String, Connection> entry : entries) {
                    Connection client = entry.getValue();
                    String appName = client.getMetaInfo().getAppName();
                    String clientIp = client.getMetaInfo().getClientIp();
                    if (client.getMetaInfo().isSdkSource() && !expelForIp.containsKey(clientIp)) {
                        // get limit for current ip.
                        int countLimitOfIp = connectionLimitRule.getCountLimitOfIp(clientIp);
                        if (countLimitOfIp < 0) {
                            int countLimitOfApp = connectionLimitRule.getCountLimitOfApp(appName);
                            countLimitOfIp = countLimitOfApp < 0 ? countLimitOfIp : countLimitOfApp;
                        }
                        if (countLimitOfIp < 0) {
                            countLimitOfIp = connectionLimitRule.getCountLimitPerClientIpDefault();
                        }
                        if (countLimitOfIp >= 0 && connectionForClientIp.containsKey(clientIp)) {
                            AtomicInteger currentCountIp = connectionForClientIp.get(clientIp);
                            if (currentCountIp != null && currentCountIp.get() > countLimitOfIp) {
                                expelForIp.put(clientIp, new AtomicInteger(currentCountIp.get() - countLimitOfIp));
                            }
                        }
                    }
                }
                Loggers.REMOTE_DIGEST.info("Check over limit for ip limit rule, over limit ip count={}", expelForIp.size());
                if (expelForIp.size() > 0) {
                    Loggers.REMOTE_DIGEST.info("Over limit ip expel info, {}", expelForIp);
                }
                Set<String> outDatedConnections = new HashSet<>();
                long now = System.currentTimeMillis();
                // 2.get expel connection for ip limit.
                for (Map.Entry<String, Connection> entry : entries) {
                    Connection client = entry.getValue();
                    String clientIp = client.getMetaInfo().getClientIp();
                    AtomicInteger integer = expelForIp.get(clientIp);
                    if (integer != null && integer.intValue() > 0) {
                        integer.decrementAndGet();
                        expelClient.add(client.getMetaInfo().getConnectionId());
                        expelCount--;
                    } else if (now - client.getMetaInfo().getLastActiveTime() >= KEEP_ALIVE_TIME) {
                        outDatedConnections.add(client.getMetaInfo().getConnectionId());
                    }
                }
                // 3. if total count is still over limit.
                if (expelCount > 0) {
                    for (Map.Entry<String, Connection> entry : entries) {
                        Connection client = entry.getValue();
                        if (!expelForIp.containsKey(client.getMetaInfo().clientIp) && client.getMetaInfo().isSdkSource() && expelCount > 0) {
                            expelClient.add(client.getMetaInfo().getConnectionId());
                            expelCount--;
                            outDatedConnections.remove(client.getMetaInfo().getConnectionId());
                        }
                    }
                }
                String serverIp = null;
                String serverPort = null;
                if (StringUtils.isNotBlank(redirectAddress) && redirectAddress.contains(Constants.COLON)) {
                    String[] split = redirectAddress.split(Constants.COLON);
                    serverIp = split[0];
                    serverPort = split[1];
                }
                for (String expelledClientId : expelClient) {
                    try {
                        Connection connection = getConnection(expelledClientId);
                        if (connection != null) {
                            ConnectResetRequest connectResetRequest = new ConnectResetRequest();
                            connectResetRequest.setServerIp(serverIp);
                            connectResetRequest.setServerPort(serverPort);
                            connection.asyncRequest(connectResetRequest, null);
                            Loggers.REMOTE_DIGEST.info("Send connection reset request , connection id = {},recommendServerIp={}, recommendServerPort={}", expelledClientId, connectResetRequest.getServerIp(), connectResetRequest.getServerPort());
                        }
                    } catch (ConnectionAlreadyClosedException e) {
                        unregister(expelledClientId);
                    } catch (Exception e) {
                        Loggers.REMOTE_DIGEST.error("Error occurs when expel connection, expelledClientId:{}", expelledClientId, e);
                    }
                }
                // 4.client active detection.
                Loggers.REMOTE_DIGEST.info("Out dated connection ,size={}", outDatedConnections.size());
                if (CollectionUtils.isNotEmpty(outDatedConnections)) {
                    Set<String> successConnections = new HashSet<>();
                    final CountDownLatch latch = new CountDownLatch(outDatedConnections.size());
                    for (String outDateConnectionId : outDatedConnections) {
                        try {
                            Connection connection = getConnection(outDateConnectionId);
                            if (connection != null) {
                                ClientDetectionRequest clientDetectionRequest = new ClientDetectionRequest();
                                connection.asyncRequest(clientDetectionRequest, new RequestCallBack() {

                                    @Override
                                    public Executor getExecutor() {
                                        return null;
                                    }

                                    @Override
                                    public long getTimeout() {
                                        return 1000L;
                                    }

                                    @Override
                                    public void onResponse(Response response) {
                                        latch.countDown();
                                        if (response != null && response.isSuccess()) {
                                            connection.freshActiveTime();
                                            successConnections.add(outDateConnectionId);
                                        }
                                    }

                                    @Override
                                    public void onException(Throwable e) {
                                        latch.countDown();
                                    }
                                });
                                Loggers.REMOTE_DIGEST.info("[{}]send connection active request ", outDateConnectionId);
                            } else {
                                latch.countDown();
                            }
                        } catch (ConnectionAlreadyClosedException e) {
                            latch.countDown();
                        } catch (Exception e) {
                            Loggers.REMOTE_DIGEST.error("[{}]Error occurs when check client active detection ,error={}", outDateConnectionId, e);
                            latch.countDown();
                        }
                    }
                    latch.await(3000L, TimeUnit.MILLISECONDS);
                    Loggers.REMOTE_DIGEST.info("Out dated connection check successCount={}", successConnections.size());
                    for (String outDateConnectionId : outDatedConnections) {
                        if (!successConnections.contains(outDateConnectionId)) {
                            Loggers.REMOTE_DIGEST.info("[{}]Unregister Out dated connection....", outDateConnectionId);
                            unregister(outDateConnectionId);
                        }
                    }
                }
                if (isLoaderClient) {
                    loadClient = -1;
                    redirectAddress = null;
                }
                Loggers.REMOTE_DIGEST.info("Connection check task end");
            } catch (Throwable e) {
                Loggers.REMOTE.error("Error occurs during connection check... ", e);
            }
        }
    }, 1000L, 3000L, TimeUnit.MILLISECONDS);
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) ConnectionAlreadyClosedException(com.alibaba.nacos.common.remote.exception.ConnectionAlreadyClosedException) ClientDetectionRequest(com.alibaba.nacos.api.remote.request.ClientDetectionRequest) RequestCallBack(com.alibaba.nacos.api.remote.RequestCallBack) CountDownLatch(java.util.concurrent.CountDownLatch) ConnectResetRequest(com.alibaba.nacos.api.remote.request.ConnectResetRequest) ConnectionAlreadyClosedException(com.alibaba.nacos.common.remote.exception.ConnectionAlreadyClosedException) NacosException(com.alibaba.nacos.api.exception.NacosException) IOException(java.io.IOException) Response(com.alibaba.nacos.api.remote.response.Response) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) PostConstruct(javax.annotation.PostConstruct)

Example 3 with ConnectionAlreadyClosedException

use of com.alibaba.nacos.common.remote.exception.ConnectionAlreadyClosedException in project nacos by alibaba.

the class GrpcConnection method sendRequestNoAck.

private void sendRequestNoAck(Request request) throws NacosException {
    try {
        // StreamObserver#onNext() is not thread-safe,synchronized is required to avoid direct memory leak.
        synchronized (streamObserver) {
            Payload payload = GrpcUtils.convert(request);
            traceIfNecessary(payload);
            streamObserver.onNext(payload);
        }
    } catch (Exception e) {
        if (e instanceof StatusRuntimeException) {
            throw new ConnectionAlreadyClosedException(e);
        }
        throw e;
    }
}
Also used : ConnectionAlreadyClosedException(com.alibaba.nacos.common.remote.exception.ConnectionAlreadyClosedException) StatusRuntimeException(io.grpc.StatusRuntimeException) Payload(com.alibaba.nacos.api.grpc.auto.Payload) StatusRuntimeException(io.grpc.StatusRuntimeException) ConnectionAlreadyClosedException(com.alibaba.nacos.common.remote.exception.ConnectionAlreadyClosedException) NacosException(com.alibaba.nacos.api.exception.NacosException)

Aggregations

NacosException (com.alibaba.nacos.api.exception.NacosException)3 ConnectionAlreadyClosedException (com.alibaba.nacos.common.remote.exception.ConnectionAlreadyClosedException)3 ConnectResetRequest (com.alibaba.nacos.api.remote.request.ConnectResetRequest)2 IOException (java.io.IOException)2 Payload (com.alibaba.nacos.api.grpc.auto.Payload)1 RequestCallBack (com.alibaba.nacos.api.remote.RequestCallBack)1 ClientDetectionRequest (com.alibaba.nacos.api.remote.request.ClientDetectionRequest)1 Response (com.alibaba.nacos.api.remote.response.Response)1 StatusRuntimeException (io.grpc.StatusRuntimeException)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 LinkedList (java.util.LinkedList)1 List (java.util.List)1 Map (java.util.Map)1 Set (java.util.Set)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 PostConstruct (javax.annotation.PostConstruct)1