Search in sources :

Example 16 with ApolloConfigException

use of com.ctrip.framework.apollo.exceptions.ApolloConfigException in project apollo by ctripcorp.

the class LocalFileConfigRepository method checkLocalConfigCacheDir.

private void checkLocalConfigCacheDir(File baseDir) {
    if (baseDir.exists()) {
        return;
    }
    Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "createLocalConfigDir");
    transaction.addData("BaseDir", baseDir.getAbsolutePath());
    try {
        Files.createDirectory(baseDir.toPath());
        transaction.setStatus(Transaction.SUCCESS);
    } catch (IOException ex) {
        ApolloConfigException exception = new ApolloConfigException(String.format("Create local config directory %s failed", baseDir.getAbsolutePath()), ex);
        Tracer.logError(exception);
        transaction.setStatus(exception);
        logger.warn("Unable to create local config cache directory {}, reason: {}. Will not able to cache config file.", baseDir.getAbsolutePath(), ExceptionUtil.getDetailMessage(ex));
    } finally {
        transaction.complete();
    }
}
Also used : Transaction(com.ctrip.framework.apollo.tracer.spi.Transaction) IOException(java.io.IOException) ApolloConfigException(com.ctrip.framework.apollo.exceptions.ApolloConfigException)

Example 17 with ApolloConfigException

use of com.ctrip.framework.apollo.exceptions.ApolloConfigException in project apollo by ctripcorp.

the class LocalFileConfigRepository method sync.

@Override
protected void sync() {
    // sync with upstream immediately
    boolean syncFromUpstreamResultSuccess = trySyncFromUpstream();
    if (syncFromUpstreamResultSuccess) {
        return;
    }
    Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "syncLocalConfig");
    Throwable exception = null;
    try {
        transaction.addData("Basedir", m_baseDir.getAbsolutePath());
        m_fileProperties = this.loadFromLocalCacheFile(m_baseDir, m_namespace);
        m_sourceType = ConfigSourceType.LOCAL;
        transaction.setStatus(Transaction.SUCCESS);
    } catch (Throwable ex) {
        Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex));
        transaction.setStatus(ex);
        exception = ex;
    // ignore
    } finally {
        transaction.complete();
    }
    if (m_fileProperties == null) {
        m_sourceType = ConfigSourceType.NONE;
        throw new ApolloConfigException("Load config from local config failed!", exception);
    }
}
Also used : Transaction(com.ctrip.framework.apollo.tracer.spi.Transaction) ApolloConfigException(com.ctrip.framework.apollo.exceptions.ApolloConfigException)

Example 18 with ApolloConfigException

use of com.ctrip.framework.apollo.exceptions.ApolloConfigException in project apollo by ctripcorp.

the class RemoteConfigLongPollService method startLongPolling.

private void startLongPolling() {
    if (!m_longPollStarted.compareAndSet(false, true)) {
        // already started
        return;
    }
    try {
        final String appId = m_configUtil.getAppId();
        final String cluster = m_configUtil.getCluster();
        final String dataCenter = m_configUtil.getDataCenter();
        final String secret = m_configUtil.getAccessKeySecret();
        final long longPollingInitialDelayInMills = m_configUtil.getLongPollingInitialDelayInMills();
        m_longPollingService.submit(new Runnable() {

            @Override
            public void run() {
                if (longPollingInitialDelayInMills > 0) {
                    try {
                        logger.debug("Long polling will start in {} ms.", longPollingInitialDelayInMills);
                        TimeUnit.MILLISECONDS.sleep(longPollingInitialDelayInMills);
                    } catch (InterruptedException e) {
                    // ignore
                    }
                }
                doLongPollingRefresh(appId, cluster, dataCenter, secret);
            }
        });
    } catch (Throwable ex) {
        m_longPollStarted.set(false);
        ApolloConfigException exception = new ApolloConfigException("Schedule long polling refresh failed", ex);
        Tracer.logError(exception);
        logger.warn(ExceptionUtil.getDetailMessage(exception));
    }
}
Also used : ApolloConfigException(com.ctrip.framework.apollo.exceptions.ApolloConfigException)

Example 19 with ApolloConfigException

use of com.ctrip.framework.apollo.exceptions.ApolloConfigException in project apollo by ctripcorp.

the class ConfigServiceLocator method updateConfigServices.

private synchronized void updateConfigServices() {
    String url = assembleMetaServiceUrl();
    HttpRequest request = new HttpRequest(url);
    int maxRetries = 2;
    Throwable exception = null;
    for (int i = 0; i < maxRetries; i++) {
        Transaction transaction = Tracer.newTransaction("Apollo.MetaService", "getConfigService");
        transaction.addData("Url", url);
        try {
            HttpResponse<List<ServiceDTO>> response = m_httpClient.doGet(request, m_responseType);
            transaction.setStatus(Transaction.SUCCESS);
            List<ServiceDTO> services = response.getBody();
            if (services == null || services.isEmpty()) {
                logConfigService("Empty response!");
                continue;
            }
            setConfigServices(services);
            return;
        } catch (Throwable ex) {
            Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex));
            transaction.setStatus(ex);
            exception = ex;
        } finally {
            transaction.complete();
        }
        try {
            m_configUtil.getOnErrorRetryIntervalTimeUnit().sleep(m_configUtil.getOnErrorRetryInterval());
        } catch (InterruptedException ex) {
        // ignore
        }
    }
    throw new ApolloConfigException(String.format("Get config services failed from %s", url), exception);
}
Also used : HttpRequest(com.ctrip.framework.apollo.util.http.HttpRequest) Transaction(com.ctrip.framework.apollo.tracer.spi.Transaction) ServiceDTO(com.ctrip.framework.apollo.core.dto.ServiceDTO) List(java.util.List) ApolloConfigException(com.ctrip.framework.apollo.exceptions.ApolloConfigException)

Example 20 with ApolloConfigException

use of com.ctrip.framework.apollo.exceptions.ApolloConfigException in project apollo by ctripcorp.

the class DefaultHttpClient method doGetWithSerializeFunction.

private <T> HttpResponse<T> doGetWithSerializeFunction(HttpRequest httpRequest, Function<String, T> serializeFunction) {
    InputStreamReader isr = null;
    InputStreamReader esr = null;
    int statusCode;
    try {
        HttpURLConnection conn = (HttpURLConnection) new URL(httpRequest.getUrl()).openConnection();
        conn.setRequestMethod("GET");
        Map<String, String> headers = httpRequest.getHeaders();
        if (headers != null && headers.size() > 0) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }
        int connectTimeout = httpRequest.getConnectTimeout();
        if (connectTimeout < 0) {
            connectTimeout = m_configUtil.getConnectTimeout();
        }
        int readTimeout = httpRequest.getReadTimeout();
        if (readTimeout < 0) {
            readTimeout = m_configUtil.getReadTimeout();
        }
        conn.setConnectTimeout(connectTimeout);
        conn.setReadTimeout(readTimeout);
        conn.connect();
        statusCode = conn.getResponseCode();
        String response;
        try {
            isr = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8);
            response = CharStreams.toString(isr);
        } catch (IOException ex) {
            /**
             * according to https://docs.oracle.com/javase/7/docs/technotes/guides/net/http-keepalive.html,
             * we should clean up the connection by reading the response body so that the connection
             * could be reused.
             */
            InputStream errorStream = conn.getErrorStream();
            if (errorStream != null) {
                esr = new InputStreamReader(errorStream, StandardCharsets.UTF_8);
                try {
                    CharStreams.toString(esr);
                } catch (IOException ioe) {
                // ignore
                }
            }
            // 200 and 304 should not trigger IOException, thus we must throw the original exception out
            if (statusCode == 200 || statusCode == 304) {
                throw ex;
            }
            // for status codes like 404, IOException is expected when calling conn.getInputStream()
            throw new ApolloConfigStatusCodeException(statusCode, ex);
        }
        if (statusCode == 200) {
            return new HttpResponse<>(statusCode, serializeFunction.apply(response));
        }
        if (statusCode == 304) {
            return new HttpResponse<>(statusCode, null);
        }
    } catch (ApolloConfigStatusCodeException ex) {
        throw ex;
    } catch (Throwable ex) {
        throw new ApolloConfigException("Could not complete get operation", ex);
    } finally {
        if (isr != null) {
            try {
                isr.close();
            } catch (IOException ex) {
            // ignore
            }
        }
        if (esr != null) {
            try {
                esr.close();
            } catch (IOException ex) {
            // ignore
            }
        }
    }
    throw new ApolloConfigStatusCodeException(statusCode, String.format("Get operation failed for %s", httpRequest.getUrl()));
}
Also used : InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) IOException(java.io.IOException) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) ApolloConfigStatusCodeException(com.ctrip.framework.apollo.exceptions.ApolloConfigStatusCodeException) Map(java.util.Map) ApolloConfigException(com.ctrip.framework.apollo.exceptions.ApolloConfigException)

Aggregations

ApolloConfigException (com.ctrip.framework.apollo.exceptions.ApolloConfigException)20 Transaction (com.ctrip.framework.apollo.tracer.spi.Transaction)10 IOException (java.io.IOException)9 ApolloConfigStatusCodeException (com.ctrip.framework.apollo.exceptions.ApolloConfigStatusCodeException)5 InputStream (java.io.InputStream)5 ServiceDTO (com.ctrip.framework.apollo.core.dto.ServiceDTO)4 HttpRequest (com.ctrip.framework.apollo.util.http.HttpRequest)4 File (java.io.File)4 List (java.util.List)4 Map (java.util.Map)4 Properties (java.util.Properties)4 InputStreamReader (java.io.InputStreamReader)3 HttpURLConnection (java.net.HttpURLConnection)3 URL (java.net.URL)3 ApolloConfig (com.ctrip.framework.apollo.core.dto.ApolloConfig)2 OrderedProperties (com.ctrip.framework.apollo.util.OrderedProperties)2 HttpResponse (com.ctrip.framework.apollo.util.http.HttpResponse)2 FileInputStream (java.io.FileInputStream)2 FileOutputStream (java.io.FileOutputStream)2 OutputStream (java.io.OutputStream)2