Search in sources :

Example 1 with ConfigResponse

use of com.alibaba.nacos.client.config.filter.impl.ConfigResponse in project nacos by alibaba.

the class NacosConfigServiceTest method testGetConfigAndSignListener.

@Test
public void testGetConfigAndSignListener() throws NacosException {
    final String dataId = "1";
    final String group = "2";
    final String tenant = "";
    final String content = "123";
    final int timeout = 3000;
    final Listener listener = new Listener() {

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

        @Override
        public void receiveConfigInfo(String configInfo) {
        }
    };
    ConfigResponse response = new ConfigResponse();
    response.setContent(content);
    response.setConfigType("bb");
    Mockito.when(mockWoker.getServerConfig(dataId, group, "", timeout, false)).thenReturn(response);
    final String config = nacosConfigService.getConfigAndSignListener(dataId, group, timeout, listener);
    Assert.assertEquals(content, config);
    Mockito.verify(mockWoker, Mockito.times(1)).getServerConfig(dataId, group, tenant, timeout, false);
    Mockito.verify(mockWoker, Mockito.times(1)).addTenantListenersWithContent(dataId, group, content, Arrays.asList(listener));
}
Also used : Listener(com.alibaba.nacos.api.config.listener.Listener) ConfigResponse(com.alibaba.nacos.client.config.filter.impl.ConfigResponse) Test(org.junit.Test)

Example 2 with ConfigResponse

use of com.alibaba.nacos.client.config.filter.impl.ConfigResponse in project nacos by alibaba.

the class NacosConfigService method getConfigInner.

private String getConfigInner(String tenant, String dataId, String group, long timeoutMs) throws NacosException {
    group = blank2defaultGroup(group);
    ParamUtils.checkKeyParam(dataId, group);
    ConfigResponse cr = new ConfigResponse();
    cr.setDataId(dataId);
    cr.setTenant(tenant);
    cr.setGroup(group);
    // use local config first
    String content = LocalConfigInfoProcessor.getFailover(worker.getAgentName(), dataId, group, tenant);
    if (content != null) {
        LOGGER.warn("[{}] [get-config] get failover ok, dataId={}, group={}, tenant={}, config={}", worker.getAgentName(), dataId, group, tenant, ContentUtils.truncateContent(content));
        cr.setContent(content);
        String encryptedDataKey = LocalEncryptedDataKeyProcessor.getEncryptDataKeyFailover(agent.getName(), dataId, group, tenant);
        cr.setEncryptedDataKey(encryptedDataKey);
        configFilterChainManager.doFilter(null, cr);
        content = cr.getContent();
        return content;
    }
    try {
        ConfigResponse response = worker.getServerConfig(dataId, group, tenant, timeoutMs, false);
        cr.setContent(response.getContent());
        cr.setEncryptedDataKey(response.getEncryptedDataKey());
        configFilterChainManager.doFilter(null, cr);
        content = cr.getContent();
        return content;
    } catch (NacosException ioe) {
        if (NacosException.NO_RIGHT == ioe.getErrCode()) {
            throw ioe;
        }
        LOGGER.warn("[{}] [get-config] get from server error, dataId={}, group={}, tenant={}, msg={}", worker.getAgentName(), dataId, group, tenant, ioe.toString());
    }
    LOGGER.warn("[{}] [get-config] get snapshot ok, dataId={}, group={}, tenant={}, config={}", worker.getAgentName(), dataId, group, tenant, ContentUtils.truncateContent(content));
    content = LocalConfigInfoProcessor.getSnapshot(worker.getAgentName(), dataId, group, tenant);
    cr.setContent(content);
    String encryptedDataKey = LocalEncryptedDataKeyProcessor.getEncryptDataKeyFailover(agent.getName(), dataId, group, tenant);
    cr.setEncryptedDataKey(encryptedDataKey);
    configFilterChainManager.doFilter(null, cr);
    content = cr.getContent();
    return content;
}
Also used : ConfigResponse(com.alibaba.nacos.client.config.filter.impl.ConfigResponse) NacosException(com.alibaba.nacos.api.exception.NacosException)

Example 3 with ConfigResponse

use of com.alibaba.nacos.client.config.filter.impl.ConfigResponse in project nacos by alibaba.

the class CacheData method safeNotifyListener.

private void safeNotifyListener(final String dataId, final String group, final String content, final String type, final String md5, final String encryptedDataKey, final ManagerListenerWrap listenerWrap) {
    final Listener listener = listenerWrap.listener;
    if (listenerWrap.inNotifying) {
        LOGGER.warn("[{}] [notify-currentSkip] dataId={}, group={}, md5={}, listener={}, listener is not finish yet,will try next time.", name, dataId, group, md5, listener);
        return;
    }
    Runnable job = () -> {
        long start = System.currentTimeMillis();
        ClassLoader myClassLoader = Thread.currentThread().getContextClassLoader();
        ClassLoader appClassLoader = listener.getClass().getClassLoader();
        try {
            if (listener instanceof AbstractSharedListener) {
                AbstractSharedListener adapter = (AbstractSharedListener) listener;
                adapter.fillContext(dataId, group);
                LOGGER.info("[{}] [notify-context] dataId={}, group={}, md5={}", name, dataId, group, md5);
            }
            // Before executing the callback, set the thread classloader to the classloader of
            // the specific webapp to avoid exceptions or misuses when calling the spi interface in
            // the callback method (this problem occurs only in multi-application deployment).
            Thread.currentThread().setContextClassLoader(appClassLoader);
            ConfigResponse cr = new ConfigResponse();
            cr.setDataId(dataId);
            cr.setGroup(group);
            cr.setContent(content);
            cr.setEncryptedDataKey(encryptedDataKey);
            configFilterChainManager.doFilter(null, cr);
            String contentTmp = cr.getContent();
            listenerWrap.inNotifying = true;
            listener.receiveConfigInfo(contentTmp);
            // compare lastContent and content
            if (listener instanceof AbstractConfigChangeListener) {
                Map data = ConfigChangeHandler.getInstance().parseChangeData(listenerWrap.lastContent, content, type);
                ConfigChangeEvent event = new ConfigChangeEvent(data);
                ((AbstractConfigChangeListener) listener).receiveConfigChange(event);
                listenerWrap.lastContent = content;
            }
            listenerWrap.lastCallMd5 = md5;
            LOGGER.info("[{}] [notify-ok] dataId={}, group={}, md5={}, listener={} ,cost={} millis.", name, dataId, group, md5, listener, (System.currentTimeMillis() - start));
        } catch (NacosException ex) {
            LOGGER.error("[{}] [notify-error] dataId={}, group={}, md5={}, listener={} errCode={} errMsg={}", name, dataId, group, md5, listener, ex.getErrCode(), ex.getErrMsg());
        } catch (Throwable t) {
            LOGGER.error("[{}] [notify-error] dataId={}, group={}, md5={}, listener={} tx={}", name, dataId, group, md5, listener, t.getCause());
        } finally {
            listenerWrap.inNotifying = false;
            Thread.currentThread().setContextClassLoader(myClassLoader);
        }
    };
    final long startNotify = System.currentTimeMillis();
    try {
        if (null != listener.getExecutor()) {
            listener.getExecutor().execute(job);
        } else {
            try {
                INTERNAL_NOTIFIER.submit(job);
            } catch (RejectedExecutionException rejectedExecutionException) {
                LOGGER.warn("[{}] [notify-blocked] dataId={}, group={}, md5={}, listener={}, no available internal notifier,will sync notifier ", name, dataId, group, md5, listener);
                job.run();
            } catch (Throwable throwable) {
                LOGGER.error("[{}] [notify-blocked] dataId={}, group={}, md5={}, listener={}, submit internal async task fail,throwable= ", name, dataId, group, md5, listener, throwable);
                job.run();
            }
        }
    } catch (Throwable t) {
        LOGGER.error("[{}] [notify-error] dataId={}, group={}, md5={}, listener={} throwable={}", name, dataId, group, md5, listener, t.getCause());
    }
    final long finishNotify = System.currentTimeMillis();
    LOGGER.info("[{}] [notify-listener] time cost={}ms in ClientWorker, dataId={}, group={}, md5={}, listener={} ", name, (finishNotify - startNotify), dataId, group, md5, listener);
}
Also used : AbstractConfigChangeListener(com.alibaba.nacos.client.config.listener.impl.AbstractConfigChangeListener) AbstractSharedListener(com.alibaba.nacos.api.config.listener.AbstractSharedListener) Listener(com.alibaba.nacos.api.config.listener.Listener) ConfigResponse(com.alibaba.nacos.client.config.filter.impl.ConfigResponse) NacosException(com.alibaba.nacos.api.exception.NacosException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) AbstractSharedListener(com.alibaba.nacos.api.config.listener.AbstractSharedListener) ConfigChangeEvent(com.alibaba.nacos.api.config.ConfigChangeEvent) AbstractConfigChangeListener(com.alibaba.nacos.client.config.listener.impl.AbstractConfigChangeListener) Map(java.util.Map)

Example 4 with ConfigResponse

use of com.alibaba.nacos.client.config.filter.impl.ConfigResponse in project nacos by alibaba.

the class ClientWorker method addCacheDataIfAbsent.

/**
 * Add cache data if absent.
 *
 * @param dataId data id if data
 * @param group  group of data
 * @param tenant tenant of data
 * @return cache data
 */
public CacheData addCacheDataIfAbsent(String dataId, String group, String tenant) throws NacosException {
    CacheData cache = getCache(dataId, group, tenant);
    if (null != cache) {
        return cache;
    }
    String key = GroupKey.getKeyTenant(dataId, group, tenant);
    synchronized (cacheMap) {
        CacheData cacheFromMap = getCache(dataId, group, tenant);
        // other listener thread beat me to set to cacheMap
        if (null != cacheFromMap) {
            cache = cacheFromMap;
            // reset so that server not hang this check
            cache.setInitializing(true);
        } else {
            cache = new CacheData(configFilterChainManager, agent.getName(), dataId, group, tenant);
            int taskId = cacheMap.get().size() / (int) ParamUtil.getPerTaskConfigSize();
            cache.setTaskId(taskId);
            // fix issue # 1317
            if (enableRemoteSyncConfig) {
                ConfigResponse response = getServerConfig(dataId, group, tenant, 3000L, false);
                cache.setContent(response.getContent());
            }
        }
        Map<String, CacheData> copy = new HashMap<>(this.cacheMap.get());
        copy.put(key, cache);
        cacheMap.set(copy);
    }
    LOGGER.info("[{}] [subscribe] {}", agent.getName(), key);
    MetricsMonitor.getListenConfigCountMonitor().set(cacheMap.get().size());
    return cache;
}
Also used : HashMap(java.util.HashMap) ConfigResponse(com.alibaba.nacos.client.config.filter.impl.ConfigResponse)

Example 5 with ConfigResponse

use of com.alibaba.nacos.client.config.filter.impl.ConfigResponse in project nacos by alibaba.

the class NacosConfigServiceTest method testGetConfig.

@Test
public void testGetConfig() throws NacosException {
    final String dataId = "1";
    final String group = "2";
    final String tenant = "";
    final int timeout = 3000;
    ConfigResponse response = new ConfigResponse();
    response.setContent("aa");
    response.setConfigType("bb");
    Mockito.when(mockWoker.getServerConfig(dataId, group, "", timeout, false)).thenReturn(response);
    final String config = nacosConfigService.getConfig(dataId, group, timeout);
    Assert.assertEquals("aa", config);
    Mockito.verify(mockWoker, Mockito.times(1)).getServerConfig(dataId, group, tenant, timeout, false);
}
Also used : ConfigResponse(com.alibaba.nacos.client.config.filter.impl.ConfigResponse) Test(org.junit.Test)

Aggregations

ConfigResponse (com.alibaba.nacos.client.config.filter.impl.ConfigResponse)6 NacosException (com.alibaba.nacos.api.exception.NacosException)3 Listener (com.alibaba.nacos.api.config.listener.Listener)2 Test (org.junit.Test)2 ConfigChangeEvent (com.alibaba.nacos.api.config.ConfigChangeEvent)1 AbstractSharedListener (com.alibaba.nacos.api.config.listener.AbstractSharedListener)1 AbstractConfigChangeListener (com.alibaba.nacos.client.config.listener.impl.AbstractConfigChangeListener)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)1