Search in sources :

Example 6 with ApolloConfig

use of com.ctrip.framework.apollo.core.dto.ApolloConfig in project apollo by ctripcorp.

the class ConfigControllerIntegrationTest method testQueryConfigFileWithNamespaceOK.

@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testQueryConfigFileWithNamespaceOK() throws Exception {
    ResponseEntity<ApolloConfig> response = restTemplate.getForEntity("http://{baseurl}/configs/{appId}/{clusterName}/{namespace}", ApolloConfig.class, getHostUrl(), someAppId, ConfigConsts.CLUSTER_NAME_DEFAULT, someNamespace + ".xml");
    ApolloConfig result = response.getBody();
    assertEquals(HttpStatus.OK, response.getStatusCode());
    assertEquals("TEST-RELEASE-KEY5", result.getReleaseKey());
    assertEquals("v1-file", result.getConfigurations().get("k1"));
    assertEquals("v2-file", result.getConfigurations().get("k2"));
}
Also used : ApolloConfig(com.ctrip.framework.apollo.core.dto.ApolloConfig) Test(org.junit.Test) Sql(org.springframework.test.context.jdbc.Sql)

Example 7 with ApolloConfig

use of com.ctrip.framework.apollo.core.dto.ApolloConfig in project apollo by ctripcorp.

the class ConfigControllerIntegrationTest method testQueryPublicGrayConfigWithNoOverride.

@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/test-gray-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testQueryPublicGrayConfigWithNoOverride() throws Exception {
    AtomicBoolean stop = new AtomicBoolean();
    periodicSendMessage(executorService, assembleKey(somePublicAppId, ConfigConsts.CLUSTER_NAME_DEFAULT, somePublicNamespace), stop);
    TimeUnit.MILLISECONDS.sleep(500);
    stop.set(true);
    ResponseEntity<ApolloConfig> response = restTemplate.getForEntity("http://{baseurl}/configs/{appId}/{clusterName}/{namespace}?ip={clientIp}", ApolloConfig.class, getHostUrl(), someAppId, someCluster, somePublicNamespace, someClientIp);
    ApolloConfig result = response.getBody();
    assertEquals(HttpStatus.OK, response.getStatusCode());
    assertEquals("TEST-GRAY-RELEASE-KEY2", result.getReleaseKey());
    assertEquals("gray-v1", result.getConfigurations().get("k1"));
    assertEquals("gray-v2", result.getConfigurations().get("k2"));
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ApolloConfig(com.ctrip.framework.apollo.core.dto.ApolloConfig) Test(org.junit.Test) Sql(org.springframework.test.context.jdbc.Sql)

Example 8 with ApolloConfig

use of com.ctrip.framework.apollo.core.dto.ApolloConfig in project apollo by ctripcorp.

the class ConfigControllerIntegrationTest method testQueryConfigWithDefaultClusterAndDefaultNamespaceAndIncorrectCase.

@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testQueryConfigWithDefaultClusterAndDefaultNamespaceAndIncorrectCase() throws Exception {
    ResponseEntity<ApolloConfig> response = restTemplate.getForEntity("http://{baseurl}/configs/{appId}/{clusterName}/{namespace}", ApolloConfig.class, getHostUrl(), someAppId, ConfigConsts.CLUSTER_NAME_DEFAULT, ConfigConsts.NAMESPACE_APPLICATION.toUpperCase());
    ApolloConfig result = response.getBody();
    assertEquals(HttpStatus.OK, response.getStatusCode());
    assertEquals("TEST-RELEASE-KEY1", result.getReleaseKey());
    assertEquals("v1", result.getConfigurations().get("k1"));
}
Also used : ApolloConfig(com.ctrip.framework.apollo.core.dto.ApolloConfig) Test(org.junit.Test) Sql(org.springframework.test.context.jdbc.Sql)

Example 9 with ApolloConfig

use of com.ctrip.framework.apollo.core.dto.ApolloConfig in project apollo by ctripcorp.

the class RemoteConfigRepository method loadApolloConfig.

private ApolloConfig loadApolloConfig() {
    if (!m_loadConfigRateLimiter.tryAcquire(5, TimeUnit.SECONDS)) {
        // wait at most 5 seconds
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
        }
    }
    String appId = m_configUtil.getAppId();
    String cluster = m_configUtil.getCluster();
    String dataCenter = m_configUtil.getDataCenter();
    String secret = m_configUtil.getAccessKeySecret();
    Tracer.logEvent("Apollo.Client.ConfigMeta", STRING_JOINER.join(appId, cluster, m_namespace));
    int maxRetries = m_configNeedForceRefresh.get() ? 2 : 1;
    // 0 means no sleep
    long onErrorSleepTime = 0;
    Throwable exception = null;
    List<ServiceDTO> configServices = getConfigServices();
    String url = null;
    retryLoopLabel: for (int i = 0; i < maxRetries; i++) {
        List<ServiceDTO> randomConfigServices = Lists.newLinkedList(configServices);
        Collections.shuffle(randomConfigServices);
        // Access the server which notifies the client first
        if (m_longPollServiceDto.get() != null) {
            randomConfigServices.add(0, m_longPollServiceDto.getAndSet(null));
        }
        for (ServiceDTO configService : randomConfigServices) {
            if (onErrorSleepTime > 0) {
                logger.warn("Load config failed, will retry in {} {}. appId: {}, cluster: {}, namespaces: {}", onErrorSleepTime, m_configUtil.getOnErrorRetryIntervalTimeUnit(), appId, cluster, m_namespace);
                try {
                    m_configUtil.getOnErrorRetryIntervalTimeUnit().sleep(onErrorSleepTime);
                } catch (InterruptedException e) {
                // ignore
                }
            }
            url = assembleQueryConfigUrl(configService.getHomepageUrl(), appId, cluster, m_namespace, dataCenter, m_remoteMessages.get(), m_configCache.get());
            logger.debug("Loading config from {}", url);
            HttpRequest request = new HttpRequest(url);
            if (!StringUtils.isBlank(secret)) {
                Map<String, String> headers = Signature.buildHttpHeaders(url, appId, secret);
                request.setHeaders(headers);
            }
            Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "queryConfig");
            transaction.addData("Url", url);
            try {
                HttpResponse<ApolloConfig> response = m_httpClient.doGet(request, ApolloConfig.class);
                m_configNeedForceRefresh.set(false);
                m_loadConfigFailSchedulePolicy.success();
                transaction.addData("StatusCode", response.getStatusCode());
                transaction.setStatus(Transaction.SUCCESS);
                if (response.getStatusCode() == 304) {
                    logger.debug("Config server responds with 304 HTTP status code.");
                    return m_configCache.get();
                }
                ApolloConfig result = response.getBody();
                logger.debug("Loaded config for {}: {}", m_namespace, result);
                return result;
            } catch (ApolloConfigStatusCodeException ex) {
                ApolloConfigStatusCodeException statusCodeException = ex;
                // config not found
                if (ex.getStatusCode() == 404) {
                    String message = String.format("Could not find config for namespace - appId: %s, cluster: %s, namespace: %s, " + "please check whether the configs are released in Apollo!", appId, cluster, m_namespace);
                    statusCodeException = new ApolloConfigStatusCodeException(ex.getStatusCode(), message);
                }
                Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(statusCodeException));
                transaction.setStatus(statusCodeException);
                exception = statusCodeException;
                if (ex.getStatusCode() == 404) {
                    break retryLoopLabel;
                }
            } catch (Throwable ex) {
                Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex));
                transaction.setStatus(ex);
                exception = ex;
            } finally {
                transaction.complete();
            }
            // if force refresh, do normal sleep, if normal config load, do exponential sleep
            onErrorSleepTime = m_configNeedForceRefresh.get() ? m_configUtil.getOnErrorRetryInterval() : m_loadConfigFailSchedulePolicy.fail();
        }
    }
    String message = String.format("Load Apollo Config failed - appId: %s, cluster: %s, namespace: %s, url: %s", appId, cluster, m_namespace, url);
    throw new ApolloConfigException(message, exception);
}
Also used : HttpRequest(com.ctrip.framework.apollo.util.http.HttpRequest) ApolloConfig(com.ctrip.framework.apollo.core.dto.ApolloConfig) ServiceDTO(com.ctrip.framework.apollo.core.dto.ServiceDTO) HttpResponse(com.ctrip.framework.apollo.util.http.HttpResponse) Transaction(com.ctrip.framework.apollo.tracer.spi.Transaction) List(java.util.List) ApolloConfigStatusCodeException(com.ctrip.framework.apollo.exceptions.ApolloConfigStatusCodeException) Map(java.util.Map) ApolloConfigException(com.ctrip.framework.apollo.exceptions.ApolloConfigException)

Example 10 with ApolloConfig

use of com.ctrip.framework.apollo.core.dto.ApolloConfig in project apollo by ctripcorp.

the class EmbeddedApollo method loadConfigFor.

private String loadConfigFor(String namespace) {
    String filename = String.format("mockdata-%s.properties", namespace);
    final Properties prop = ResourceUtils.readConfigFile(filename, new Properties());
    Map<String, String> configurations = Maps.newHashMap();
    for (String propertyName : prop.stringPropertyNames()) {
        configurations.put(propertyName, prop.getProperty(propertyName));
    }
    ApolloConfig apolloConfig = new ApolloConfig("someAppId", "someCluster", namespace, "someReleaseKey");
    Map<String, String> mergedConfigurations = mergeOverriddenProperties(namespace, configurations);
    apolloConfig.setConfigurations(mergedConfigurations);
    return GSON.toJson(apolloConfig);
}
Also used : ApolloConfig(com.ctrip.framework.apollo.core.dto.ApolloConfig) Properties(java.util.Properties)

Aggregations

ApolloConfig (com.ctrip.framework.apollo.core.dto.ApolloConfig)57 Test (org.junit.Test)49 Sql (org.springframework.test.context.jdbc.Sql)17 HttpServletResponse (javax.servlet.http.HttpServletResponse)11 BaseIntegrationTest (com.ctrip.framework.apollo.BaseIntegrationTest)10 Config (com.ctrip.framework.apollo.Config)10 ContextHandler (org.eclipse.jetty.server.handler.ContextHandler)10 Properties (java.util.Properties)8 OrderedProperties (com.ctrip.framework.apollo.util.OrderedProperties)7 AppNamespace (com.ctrip.framework.apollo.common.entity.AppNamespace)6 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)5 ConfigChangeListener (com.ctrip.framework.apollo.ConfigChangeListener)4 ApolloConfigNotification (com.ctrip.framework.apollo.core.dto.ApolloConfigNotification)4 ConfigChangeEvent (com.ctrip.framework.apollo.model.ConfigChangeEvent)4 Map (java.util.Map)4 ApolloNotificationMessages (com.ctrip.framework.apollo.core.dto.ApolloNotificationMessages)3 HttpRequest (com.ctrip.framework.apollo.util.http.HttpRequest)3 ImmutableMap (com.google.common.collect.ImmutableMap)3 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)3 InvocationOnMock (org.mockito.invocation.InvocationOnMock)3