index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/shared/transport
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/shared/transport/jersey2/Jersey2EurekaIdentityHeaderFilter.java
package com.netflix.discovery.shared.transport.jersey2; import com.netflix.appinfo.AbstractEurekaIdentity; import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.client.ClientRequestFilter; import java.io.IOException; public class Jersey2EurekaIdentityHeaderFilter implements ClientRequestFilter { private final AbstractEurekaIdentity authInfo; public Jersey2EurekaIdentityHeaderFilter(AbstractEurekaIdentity authInfo) { this.authInfo = authInfo; } @Override public void filter(ClientRequestContext requestContext) throws IOException { if (authInfo != null) { requestContext.getHeaders().putSingle(AbstractEurekaIdentity.AUTH_NAME_HEADER_KEY, authInfo.getName()); requestContext.getHeaders().putSingle(AbstractEurekaIdentity.AUTH_VERSION_HEADER_KEY, authInfo.getVersion()); if (authInfo.getId() != null) { requestContext.getHeaders().putSingle(AbstractEurekaIdentity.AUTH_ID_HEADER_KEY, authInfo.getId()); } } } }
6,600
0
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/shared/transport
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/shared/transport/jersey2/Jersey2ApplicationClient.java
package com.netflix.discovery.shared.transport.jersey2; import javax.ws.rs.client.Client; import javax.ws.rs.client.Invocation.Builder; import javax.ws.rs.core.MultivaluedMap; import java.util.List; import java.util.Map; /** * A version of Jersey2 {@link com.netflix.discovery.shared.transport.EurekaHttpClient} to be used by applications. * * @author David Liu */ public class Jersey2ApplicationClient extends AbstractJersey2EurekaHttpClient { private final MultivaluedMap<String, Object> additionalHeaders; public Jersey2ApplicationClient(Client jerseyClient, String serviceUrl, MultivaluedMap<String, Object> additionalHeaders) { super(jerseyClient, serviceUrl); this.additionalHeaders = additionalHeaders; } @Override protected void addExtraHeaders(Builder webResource) { if (additionalHeaders != null) { for (Map.Entry<String, List<Object>> entry: additionalHeaders.entrySet()) { webResource.header(entry.getKey(), entry.getValue()); } } } }
6,601
0
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/shared/transport
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/shared/transport/jersey2/EurekaJersey2ClientImpl.java
package com.netflix.discovery.shared.transport.jersey2; import static com.netflix.discovery.util.DiscoveryBuildInfo.buildVersion; import java.io.FileInputStream; import java.io.IOException; import java.security.KeyStore; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import org.apache.http.client.params.ClientPNames; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.params.CoreProtocolPNames; import org.glassfish.jersey.apache.connector.ApacheClientProperties; import org.glassfish.jersey.apache.connector.ApacheConnectorProvider; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.discovery.converters.wrappers.CodecWrappers; import com.netflix.discovery.converters.wrappers.DecoderWrapper; import com.netflix.discovery.converters.wrappers.EncoderWrapper; import com.netflix.discovery.provider.DiscoveryJerseyProvider; import com.netflix.servo.monitor.BasicCounter; import com.netflix.servo.monitor.BasicTimer; import com.netflix.servo.monitor.Counter; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.monitor.Monitors; import com.netflix.servo.monitor.Stopwatch; /** * @author Tomasz Bak */ public class EurekaJersey2ClientImpl implements EurekaJersey2Client { private static final Logger s_logger = LoggerFactory.getLogger(EurekaJersey2ClientImpl.class); private static final int HTTP_CONNECTION_CLEANER_INTERVAL_MS = 30 * 1000; private static final String PROTOCOL = "https"; private static final String PROTOCOL_SCHEME = "SSL"; private static final int HTTPS_PORT = 443; private static final String KEYSTORE_TYPE = "JKS"; private final Client apacheHttpClient; private final ConnectionCleanerTask connectionCleanerTask; ClientConfig jerseyClientConfig; private final ScheduledExecutorService eurekaConnCleaner = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { private final AtomicInteger threadNumber = new AtomicInteger(1); @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r, "Eureka-Jersey2Client-Conn-Cleaner" + threadNumber.incrementAndGet()); thread.setDaemon(true); return thread; } }); public EurekaJersey2ClientImpl( int connectionTimeout, int readTimeout, final int connectionIdleTimeout, ClientConfig clientConfig) { try { jerseyClientConfig = clientConfig; jerseyClientConfig.register(DiscoveryJerseyProvider.class); // Disable json autodiscovery, since json (de)serialization is provided by DiscoveryJerseyProvider jerseyClientConfig.property(ClientProperties.JSON_PROCESSING_FEATURE_DISABLE, Boolean.TRUE); jerseyClientConfig.property(ClientProperties.MOXY_JSON_FEATURE_DISABLE, Boolean.TRUE); jerseyClientConfig.connectorProvider(new ApacheConnectorProvider()); jerseyClientConfig.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout); jerseyClientConfig.property(ClientProperties.READ_TIMEOUT, readTimeout); apacheHttpClient = ClientBuilder.newClient(jerseyClientConfig); connectionCleanerTask = new ConnectionCleanerTask(connectionIdleTimeout); eurekaConnCleaner.scheduleWithFixedDelay( connectionCleanerTask, HTTP_CONNECTION_CLEANER_INTERVAL_MS, HTTP_CONNECTION_CLEANER_INTERVAL_MS, TimeUnit.MILLISECONDS); } catch (Throwable e) { throw new RuntimeException("Cannot create Jersey2 client", e); } } @Override public Client getClient() { return apacheHttpClient; } /** * Clean up resources. */ @Override public void destroyResources() { if (eurekaConnCleaner != null) { // Execute the connection cleaner one final time during shutdown eurekaConnCleaner.execute(connectionCleanerTask); eurekaConnCleaner.shutdown(); } if (apacheHttpClient != null) { apacheHttpClient.close(); } } public static class EurekaJersey2ClientBuilder { private boolean systemSSL; private String clientName; private int maxConnectionsPerHost; private int maxTotalConnections; private String trustStoreFileName; private String trustStorePassword; private String userAgent; private String proxyUserName; private String proxyPassword; private String proxyHost; private String proxyPort; private int connectionTimeout; private int readTimeout; private int connectionIdleTimeout; private EncoderWrapper encoderWrapper; private DecoderWrapper decoderWrapper; public EurekaJersey2ClientBuilder withClientName(String clientName) { this.clientName = clientName; return this; } public EurekaJersey2ClientBuilder withUserAgent(String userAgent) { this.userAgent = userAgent; return this; } public EurekaJersey2ClientBuilder withConnectionTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } public EurekaJersey2ClientBuilder withReadTimeout(int readTimeout) { this.readTimeout = readTimeout; return this; } public EurekaJersey2ClientBuilder withConnectionIdleTimeout(int connectionIdleTimeout) { this.connectionIdleTimeout = connectionIdleTimeout; return this; } public EurekaJersey2ClientBuilder withMaxConnectionsPerHost(int maxConnectionsPerHost) { this.maxConnectionsPerHost = maxConnectionsPerHost; return this; } public EurekaJersey2ClientBuilder withMaxTotalConnections(int maxTotalConnections) { this.maxTotalConnections = maxTotalConnections; return this; } public EurekaJersey2ClientBuilder withProxy(String proxyHost, String proxyPort, String user, String password) { this.proxyHost = proxyHost; this.proxyPort = proxyPort; this.proxyUserName = user; this.proxyPassword = password; return this; } public EurekaJersey2ClientBuilder withSystemSSLConfiguration() { this.systemSSL = true; return this; } public EurekaJersey2ClientBuilder withTrustStoreFile(String trustStoreFileName, String trustStorePassword) { this.trustStoreFileName = trustStoreFileName; this.trustStorePassword = trustStorePassword; return this; } public EurekaJersey2ClientBuilder withEncoder(String encoderName) { return this.withEncoderWrapper(CodecWrappers.getEncoder(encoderName)); } public EurekaJersey2ClientBuilder withEncoderWrapper(EncoderWrapper encoderWrapper) { this.encoderWrapper = encoderWrapper; return this; } public EurekaJersey2ClientBuilder withDecoder(String decoderName, String clientDataAccept) { return this.withDecoderWrapper(CodecWrappers.resolveDecoder(decoderName, clientDataAccept)); } public EurekaJersey2ClientBuilder withDecoderWrapper(DecoderWrapper decoderWrapper) { this.decoderWrapper = decoderWrapper; return this; } public EurekaJersey2Client build() { MyDefaultApacheHttpClient4Config config = new MyDefaultApacheHttpClient4Config(); try { return new EurekaJersey2ClientImpl( connectionTimeout, readTimeout, connectionIdleTimeout, config); } catch (Throwable e) { throw new RuntimeException("Cannot create Jersey client ", e); } } class MyDefaultApacheHttpClient4Config extends ClientConfig { MyDefaultApacheHttpClient4Config() { PoolingHttpClientConnectionManager cm; if (systemSSL) { cm = createSystemSslCM(); } else if (trustStoreFileName != null) { cm = createCustomSslCM(); } else { cm = new PoolingHttpClientConnectionManager(); } if (proxyHost != null) { addProxyConfiguration(); } DiscoveryJerseyProvider discoveryJerseyProvider = new DiscoveryJerseyProvider(encoderWrapper, decoderWrapper); // getSingletons().add(discoveryJerseyProvider); register(discoveryJerseyProvider); // Common properties to all clients cm.setDefaultMaxPerRoute(maxConnectionsPerHost); cm.setMaxTotal(maxTotalConnections); property(ApacheClientProperties.CONNECTION_MANAGER, cm); String fullUserAgentName = (userAgent == null ? clientName : userAgent) + "/v" + buildVersion(); property(CoreProtocolPNames.USER_AGENT, fullUserAgentName); // To pin a client to specific server in case redirect happens, we handle redirects directly // (see DiscoveryClient.makeRemoteCall methods). property(ClientProperties.FOLLOW_REDIRECTS, Boolean.FALSE); property(ClientPNames.HANDLE_REDIRECTS, Boolean.FALSE); } private void addProxyConfiguration() { if (proxyUserName != null && proxyPassword != null) { property(ClientProperties.PROXY_USERNAME, proxyUserName); property(ClientProperties.PROXY_PASSWORD, proxyPassword); } else { // Due to bug in apache client, user name/password must always be set. // Otherwise proxy configuration is ignored. property(ClientProperties.PROXY_USERNAME, "guest"); property(ClientProperties.PROXY_PASSWORD, "guest"); } property(ClientProperties.PROXY_URI, "http://" + proxyHost + ":" + proxyPort); } private PoolingHttpClientConnectionManager createSystemSslCM() { ConnectionSocketFactory socketFactory = SSLConnectionSocketFactory.getSystemSocketFactory(); Registry registry = RegistryBuilder.<ConnectionSocketFactory>create() .register(PROTOCOL, socketFactory) .build(); return new PoolingHttpClientConnectionManager(registry); } private PoolingHttpClientConnectionManager createCustomSslCM() { FileInputStream fin = null; try { SSLContext sslContext = SSLContext.getInstance(PROTOCOL_SCHEME); KeyStore sslKeyStore = KeyStore.getInstance(KEYSTORE_TYPE); fin = new FileInputStream(trustStoreFileName); sslKeyStore.load(fin, trustStorePassword.toCharArray()); TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); factory.init(sslKeyStore); TrustManager[] trustManagers = factory.getTrustManagers(); sslContext.init(null, trustManagers, null); ConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Registry registry = RegistryBuilder.<ConnectionSocketFactory>create() .register(PROTOCOL, socketFactory) .build(); return new PoolingHttpClientConnectionManager(registry); } catch (Exception ex) { throw new IllegalStateException("SSL configuration issue", ex); } finally { if (fin != null) { try { fin.close(); } catch (IOException ignore) { } } } } } } private class ConnectionCleanerTask implements Runnable { private final int connectionIdleTimeout; private final BasicTimer executionTimeStats; private final Counter cleanupFailed; private ConnectionCleanerTask(int connectionIdleTimeout) { this.connectionIdleTimeout = connectionIdleTimeout; MonitorConfig.Builder monitorConfigBuilder = MonitorConfig.builder("Eureka-Connection-Cleaner-Time"); executionTimeStats = new BasicTimer(monitorConfigBuilder.build()); cleanupFailed = new BasicCounter(MonitorConfig.builder("Eureka-Connection-Cleaner-Failure").build()); try { Monitors.registerObject(this); } catch (Exception e) { s_logger.error("Unable to register with servo.", e); } } @Override public void run() { Stopwatch start = executionTimeStats.start(); try { HttpClientConnectionManager cm = (HttpClientConnectionManager) apacheHttpClient .getConfiguration() .getProperty(ApacheClientProperties.CONNECTION_MANAGER); cm.closeIdleConnections(connectionIdleTimeout, TimeUnit.SECONDS); } catch (Throwable e) { s_logger.error("Cannot clean connections", e); cleanupFailed.increment(); } finally { if (null != start) { start.stop(); } } } } }
6,602
0
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/shared/transport
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/shared/transport/jersey2/AbstractJersey2EurekaHttpClient.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery.shared.transport.jersey2; import javax.ws.rs.client.Client; import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation.Builder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import java.net.URI; import java.net.URISyntaxException; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.InstanceStatus; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.EurekaHttpResponse; import com.netflix.discovery.shared.transport.EurekaHttpResponse.EurekaHttpResponseBuilder; import com.netflix.discovery.util.StringUtil; import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.netflix.discovery.shared.transport.EurekaHttpResponse.anEurekaHttpResponse; /** * @author Tomasz Bak */ public abstract class AbstractJersey2EurekaHttpClient implements EurekaHttpClient { private static final Logger logger = LoggerFactory.getLogger(AbstractJersey2EurekaHttpClient.class); protected final Client jerseyClient; protected final String serviceUrl; private final String userName; private final String password; public AbstractJersey2EurekaHttpClient(Client jerseyClient, String serviceUrl) { this.jerseyClient = jerseyClient; this.serviceUrl = serviceUrl; // Jersey2 does not read credentials from the URI. We extract it here and enable authentication feature. String localUserName = null; String localPassword = null; try { URI serviceURI = new URI(serviceUrl); if (serviceURI.getUserInfo() != null) { String[] credentials = serviceURI.getUserInfo().split(":"); if (credentials.length == 2) { localUserName = credentials[0]; localPassword = credentials[1]; } } } catch (URISyntaxException ignore) { } this.userName = localUserName; this.password = localPassword; } @Override public EurekaHttpResponse<Void> register(InstanceInfo info) { String urlPath = "apps/" + info.getAppName(); Response response = null; try { Builder resourceBuilder = jerseyClient.target(serviceUrl).path(urlPath).request(); addExtraProperties(resourceBuilder); addExtraHeaders(resourceBuilder); response = resourceBuilder .accept(MediaType.APPLICATION_JSON) .acceptEncoding("gzip") .post(Entity.json(info)); return anEurekaHttpResponse(response.getStatus()).headers(headersOf(response)).build(); } finally { if (logger.isDebugEnabled()) { logger.debug("Jersey2 HTTP POST {}/{} with instance {}; statusCode={}", serviceUrl, urlPath, info.getId(), response == null ? "N/A" : response.getStatus()); } if (response != null) { response.close(); } } } @Override public EurekaHttpResponse<Void> cancel(String appName, String id) { String urlPath = "apps/" + appName + '/' + id; Response response = null; try { Builder resourceBuilder = jerseyClient.target(serviceUrl).path(urlPath).request(); addExtraProperties(resourceBuilder); addExtraHeaders(resourceBuilder); response = resourceBuilder.delete(); return anEurekaHttpResponse(response.getStatus()).headers(headersOf(response)).build(); } finally { if (logger.isDebugEnabled()) { logger.debug("Jersey2 HTTP DELETE {}/{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus()); } if (response != null) { response.close(); } } } @Override public EurekaHttpResponse<InstanceInfo> sendHeartBeat(String appName, String id, InstanceInfo info, InstanceStatus overriddenStatus) { String urlPath = "apps/" + appName + '/' + id; Response response = null; try { WebTarget webResource = jerseyClient.target(serviceUrl) .path(urlPath) .queryParam("status", info.getStatus().toString()) .queryParam("lastDirtyTimestamp", info.getLastDirtyTimestamp().toString()); if (overriddenStatus != null) { webResource = webResource.queryParam("overriddenstatus", overriddenStatus.name()); } Builder requestBuilder = webResource.request(); addExtraProperties(requestBuilder); addExtraHeaders(requestBuilder); requestBuilder.accept(MediaType.APPLICATION_JSON_TYPE); response = requestBuilder.put(Entity.entity("{}", MediaType.APPLICATION_JSON_TYPE)); // Jersey2 refuses to handle PUT with no body EurekaHttpResponseBuilder<InstanceInfo> eurekaResponseBuilder = anEurekaHttpResponse(response.getStatus(), InstanceInfo.class).headers(headersOf(response)); if (response.hasEntity()) { eurekaResponseBuilder.entity(response.readEntity(InstanceInfo.class)); } return eurekaResponseBuilder.build(); } finally { if (logger.isDebugEnabled()) { logger.debug("Jersey2 HTTP PUT {}/{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus()); } if (response != null) { response.close(); } } } @Override public EurekaHttpResponse<Void> statusUpdate(String appName, String id, InstanceStatus newStatus, InstanceInfo info) { String urlPath = "apps/" + appName + '/' + id + "/status"; Response response = null; try { Builder requestBuilder = jerseyClient.target(serviceUrl) .path(urlPath) .queryParam("value", newStatus.name()) .queryParam("lastDirtyTimestamp", info.getLastDirtyTimestamp().toString()) .request(); addExtraProperties(requestBuilder); addExtraHeaders(requestBuilder); response = requestBuilder.put(Entity.entity("{}", MediaType.APPLICATION_JSON_TYPE)); // Jersey2 refuses to handle PUT with no body return anEurekaHttpResponse(response.getStatus()).headers(headersOf(response)).build(); } finally { if (logger.isDebugEnabled()) { logger.debug("Jersey2 HTTP PUT {}/{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus()); } if (response != null) { response.close(); } } } @Override public EurekaHttpResponse<Void> deleteStatusOverride(String appName, String id, InstanceInfo info) { String urlPath = "apps/" + appName + '/' + id + "/status"; Response response = null; try { Builder requestBuilder = jerseyClient.target(serviceUrl) .path(urlPath) .queryParam("lastDirtyTimestamp", info.getLastDirtyTimestamp().toString()) .request(); addExtraProperties(requestBuilder); addExtraHeaders(requestBuilder); response = requestBuilder.delete(); return anEurekaHttpResponse(response.getStatus()).headers(headersOf(response)).build(); } finally { if (logger.isDebugEnabled()) { logger.debug("Jersey2 HTTP DELETE {}/{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus()); } if (response != null) { response.close(); } } } @Override public EurekaHttpResponse<Applications> getApplications(String... regions) { return getApplicationsInternal("apps/", regions); } @Override public EurekaHttpResponse<Applications> getDelta(String... regions) { return getApplicationsInternal("apps/delta", regions); } @Override public EurekaHttpResponse<Applications> getVip(String vipAddress, String... regions) { return getApplicationsInternal("vips/" + vipAddress, regions); } @Override public EurekaHttpResponse<Applications> getSecureVip(String secureVipAddress, String... regions) { return getApplicationsInternal("svips/" + secureVipAddress, regions); } @Override public EurekaHttpResponse<Application> getApplication(String appName) { String urlPath = "apps/" + appName; Response response = null; try { Builder requestBuilder = jerseyClient.target(serviceUrl).path(urlPath).request(); addExtraProperties(requestBuilder); addExtraHeaders(requestBuilder); response = requestBuilder.accept(MediaType.APPLICATION_JSON_TYPE).get(); Application application = null; if (response.getStatus() == Status.OK.getStatusCode() && response.hasEntity()) { application = response.readEntity(Application.class); } return anEurekaHttpResponse(response.getStatus(), application).headers(headersOf(response)).build(); } finally { if (logger.isDebugEnabled()) { logger.debug("Jersey2 HTTP GET {}/{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus()); } if (response != null) { response.close(); } } } private EurekaHttpResponse<Applications> getApplicationsInternal(String urlPath, String[] regions) { Response response = null; try { WebTarget webTarget = jerseyClient.target(serviceUrl).path(urlPath); if (regions != null && regions.length > 0) { webTarget = webTarget.queryParam("regions", StringUtil.join(regions)); } Builder requestBuilder = webTarget.request(); addExtraProperties(requestBuilder); addExtraHeaders(requestBuilder); response = requestBuilder.accept(MediaType.APPLICATION_JSON_TYPE).get(); Applications applications = null; if (response.getStatus() == Status.OK.getStatusCode() && response.hasEntity()) { applications = response.readEntity(Applications.class); } return anEurekaHttpResponse(response.getStatus(), applications).headers(headersOf(response)).build(); } finally { if (logger.isDebugEnabled()) { logger.debug("Jersey2 HTTP GET {}/{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus()); } if (response != null) { response.close(); } } } @Override public EurekaHttpResponse<InstanceInfo> getInstance(String id) { return getInstanceInternal("instances/" + id); } @Override public EurekaHttpResponse<InstanceInfo> getInstance(String appName, String id) { return getInstanceInternal("apps/" + appName + '/' + id); } private EurekaHttpResponse<InstanceInfo> getInstanceInternal(String urlPath) { Response response = null; try { Builder requestBuilder = jerseyClient.target(serviceUrl).path(urlPath).request(); addExtraProperties(requestBuilder); addExtraHeaders(requestBuilder); response = requestBuilder.accept(MediaType.APPLICATION_JSON_TYPE).get(); InstanceInfo infoFromPeer = null; if (response.getStatus() == Status.OK.getStatusCode() && response.hasEntity()) { infoFromPeer = response.readEntity(InstanceInfo.class); } return anEurekaHttpResponse(response.getStatus(), infoFromPeer).headers(headersOf(response)).build(); } finally { if (logger.isDebugEnabled()) { logger.debug("Jersey2 HTTP GET {}/{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus()); } if (response != null) { response.close(); } } } @Override public void shutdown() { } protected void addExtraProperties(Builder webResource) { if (userName != null) { webResource.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, userName) .property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, password); } } protected abstract void addExtraHeaders(Builder webResource); private static Map<String, String> headersOf(Response response) { MultivaluedMap<String, String> jerseyHeaders = response.getStringHeaders(); if (jerseyHeaders == null || jerseyHeaders.isEmpty()) { return Collections.emptyMap(); } Map<String, String> headers = new HashMap<>(); for (Entry<String, List<String>> entry : jerseyHeaders.entrySet()) { if (!entry.getValue().isEmpty()) { headers.put(entry.getKey(), entry.getValue().get(0)); } } return headers; } }
6,603
0
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/shared/transport
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/shared/transport/jersey2/EurekaJersey2Client.java
package com.netflix.discovery.shared.transport.jersey2; import javax.ws.rs.client.Client; /** * @author David Liu */ public interface EurekaJersey2Client { Client getClient(); /** * Clean up resources. */ void destroyResources(); }
6,604
0
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/shared/transport
Create_ds/eureka/eureka-client-jersey2/src/main/java/com/netflix/discovery/shared/transport/jersey2/Jersey2ApplicationClientFactory.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery.shared.transport.jersey2; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.client.ClientRequestFilter; import javax.ws.rs.core.Feature; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; import java.io.FileInputStream; import java.io.IOException; import java.security.KeyStore; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; import com.netflix.appinfo.AbstractEurekaIdentity; import com.netflix.appinfo.EurekaAccept; import com.netflix.appinfo.EurekaClientIdentity; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.provider.DiscoveryJerseyProvider; import com.netflix.discovery.shared.resolver.EurekaEndpoint; import com.netflix.discovery.shared.transport.EurekaClientFactoryBuilder; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.TransportClientFactory; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; import org.glassfish.jersey.client.JerseyClient; import org.glassfish.jersey.message.GZipEncoder; import static com.netflix.discovery.util.DiscoveryBuildInfo.buildVersion; /** * @author Tomasz Bak */ public class Jersey2ApplicationClientFactory implements TransportClientFactory { public static final String HTTP_X_DISCOVERY_ALLOW_REDIRECT = "X-Discovery-AllowRedirect"; private static final String KEY_STORE_TYPE = "JKS"; private final Client jersey2Client; private final MultivaluedMap<String, Object> additionalHeaders; public Jersey2ApplicationClientFactory(Client jersey2Client, MultivaluedMap<String, Object> additionalHeaders) { this.jersey2Client = jersey2Client; this.additionalHeaders = additionalHeaders; } @Override public EurekaHttpClient newClient(EurekaEndpoint endpoint) { return new Jersey2ApplicationClient(jersey2Client, endpoint.getServiceUrl(), additionalHeaders); } @Override public void shutdown() { jersey2Client.close(); } public static Jersey2ApplicationClientFactory create(EurekaClientConfig clientConfig, Collection<ClientRequestFilter> additionalFilters, InstanceInfo myInstanceInfo, AbstractEurekaIdentity clientIdentity) { return create(clientConfig, additionalFilters, myInstanceInfo, clientIdentity, Optional.empty(), Optional.empty()); } public static Jersey2ApplicationClientFactory create(EurekaClientConfig clientConfig, Collection<ClientRequestFilter> additionalFilters, InstanceInfo myInstanceInfo, AbstractEurekaIdentity clientIdentity, Optional<SSLContext> sslContext, Optional<HostnameVerifier> hostnameVerifier) { Jersey2ApplicationClientFactoryBuilder clientBuilder = newBuilder(); clientBuilder.withAdditionalFilters(additionalFilters); clientBuilder.withMyInstanceInfo(myInstanceInfo); clientBuilder.withUserAgent("Java-EurekaClient"); clientBuilder.withClientConfig(clientConfig); clientBuilder.withClientIdentity(clientIdentity); sslContext.ifPresent(clientBuilder::withSSLContext); hostnameVerifier.ifPresent(clientBuilder::withHostnameVerifier); if ("true".equals(System.getProperty("com.netflix.eureka.shouldSSLConnectionsUseSystemSocketFactory"))) { clientBuilder.withClientName("DiscoveryClient-HTTPClient-System").withSystemSSLConfiguration(); } else if (clientConfig.getProxyHost() != null && clientConfig.getProxyPort() != null) { clientBuilder.withClientName("Proxy-DiscoveryClient-HTTPClient") .withProxy( clientConfig.getProxyHost(), Integer.parseInt(clientConfig.getProxyPort()), clientConfig.getProxyUserName(), clientConfig.getProxyPassword()); } else { clientBuilder.withClientName("DiscoveryClient-HTTPClient"); } return clientBuilder.build(); } public static Jersey2ApplicationClientFactoryBuilder newBuilder() { return new Jersey2ApplicationClientFactoryBuilder(); } public static class Jersey2ApplicationClientFactoryBuilder extends EurekaClientFactoryBuilder<Jersey2ApplicationClientFactory, Jersey2ApplicationClientFactoryBuilder> { private List<Feature> features = new ArrayList<>(); private List<ClientRequestFilter> additionalFilters = new ArrayList<>(); public Jersey2ApplicationClientFactoryBuilder withFeature(Feature feature) { features.add(feature); return this; } Jersey2ApplicationClientFactoryBuilder withAdditionalFilters(Collection<ClientRequestFilter> additionalFilters) { if (additionalFilters != null) { this.additionalFilters.addAll(additionalFilters); } return this; } @Override public Jersey2ApplicationClientFactory build() { ClientBuilder clientBuilder = ClientBuilder.newBuilder(); ClientConfig clientConfig = new ClientConfig(); for (ClientRequestFilter filter : additionalFilters) { clientConfig.register(filter); } for (Feature feature : features) { clientConfig.register(feature); } addProviders(clientConfig); addSSLConfiguration(clientBuilder); addProxyConfiguration(clientConfig); if (hostnameVerifier != null) { clientBuilder.hostnameVerifier(hostnameVerifier); } // Common properties to all clients final String fullUserAgentName = (userAgent == null ? clientName : userAgent) + "/v" + buildVersion(); clientBuilder.register(new ClientRequestFilter() { // Can we do it better, without filter? @Override public void filter(ClientRequestContext requestContext) { requestContext.getHeaders().put(HttpHeaders.USER_AGENT, Collections.<Object>singletonList(fullUserAgentName)); } }); clientConfig.property(ClientProperties.FOLLOW_REDIRECTS, allowRedirect); clientConfig.property(ClientProperties.READ_TIMEOUT, readTimeout); clientConfig.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout); clientBuilder.withConfig(clientConfig); // Add gzip content encoding support clientBuilder.register(new GZipEncoder()); // always enable client identity headers String ip = myInstanceInfo == null ? null : myInstanceInfo.getIPAddr(); final AbstractEurekaIdentity identity = clientIdentity == null ? new EurekaClientIdentity(ip) : clientIdentity; clientBuilder.register(new Jersey2EurekaIdentityHeaderFilter(identity)); JerseyClient jersey2Client = (JerseyClient) clientBuilder.build(); MultivaluedMap<String, Object> additionalHeaders = new MultivaluedHashMap<>(); if (allowRedirect) { additionalHeaders.add(HTTP_X_DISCOVERY_ALLOW_REDIRECT, "true"); } if (EurekaAccept.compact == eurekaAccept) { additionalHeaders.add(EurekaAccept.HTTP_X_EUREKA_ACCEPT, eurekaAccept.name()); } return new Jersey2ApplicationClientFactory(jersey2Client, additionalHeaders); } private void addSSLConfiguration(ClientBuilder clientBuilder) { FileInputStream fin = null; try { if (systemSSL) { clientBuilder.sslContext(SSLContext.getDefault()); } else if (trustStoreFileName != null) { KeyStore trustStore = KeyStore.getInstance(KEY_STORE_TYPE); fin = new FileInputStream(trustStoreFileName); trustStore.load(fin, trustStorePassword.toCharArray()); clientBuilder.trustStore(trustStore); } else if (sslContext != null) { clientBuilder.sslContext(sslContext); } } catch (Exception ex) { throw new IllegalArgumentException("Cannot setup SSL for Jersey2 client", ex); } finally { if (fin != null) { try { fin.close(); } catch (IOException ignore) { } } } } private void addProxyConfiguration(ClientConfig clientConfig) { if (proxyHost != null) { String proxyAddress = proxyHost; if (proxyPort > 0) { proxyAddress += ':' + proxyPort; } clientConfig.property(ClientProperties.PROXY_URI, proxyAddress); if (proxyUserName != null) { if (proxyPassword == null) { throw new IllegalArgumentException("Proxy user name provided but not password"); } clientConfig.property(ClientProperties.PROXY_USERNAME, proxyUserName); clientConfig.property(ClientProperties.PROXY_PASSWORD, proxyPassword); } } } private void addProviders(ClientConfig clientConfig) { DiscoveryJerseyProvider discoveryJerseyProvider = new DiscoveryJerseyProvider(encoderWrapper, decoderWrapper); clientConfig.register(discoveryJerseyProvider); // Disable json autodiscovery, since json (de)serialization is provided by DiscoveryJerseyProvider clientConfig.property(ClientProperties.JSON_PROCESSING_FEATURE_DISABLE, Boolean.TRUE); clientConfig.property(ClientProperties.MOXY_JSON_FEATURE_DISABLE, Boolean.TRUE); } } }
6,605
0
Create_ds/eureka/eureka-core-jersey2/src/test/java/com/netflix/eureka
Create_ds/eureka/eureka-core-jersey2/src/test/java/com/netflix/eureka/transport/Jersey2ReplicationClientTest.java
package com.netflix.eureka.transport; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response.Status; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.zip.GZIPOutputStream; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.InstanceStatus; import com.netflix.discovery.converters.EurekaJacksonCodec; import com.netflix.discovery.shared.transport.ClusterSampleData; import com.netflix.discovery.shared.transport.EurekaHttpResponse; import com.netflix.eureka.DefaultEurekaServerConfig; import com.netflix.eureka.EurekaServerConfig; import com.netflix.eureka.cluster.PeerEurekaNode; import com.netflix.eureka.resources.ASGResource.ASGStatus; import com.netflix.eureka.resources.DefaultServerCodecs; import com.netflix.eureka.resources.ServerCodecs; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockserver.client.server.MockServerClient; import org.mockserver.junit.MockServerRule; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.mockserver.model.Header.header; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; /** * Ideally we would test client/server REST layer together as an integration test, where server side has mocked * service layer. Right now server side REST has to much logic, so this test would be equal to testing everything. * Here we test only client side REST communication. * * @author Tomasz Bak */ public class Jersey2ReplicationClientTest { @Rule public MockServerRule serverMockRule = new MockServerRule(this); private MockServerClient serverMockClient; private Jersey2ReplicationClient replicationClient; private final EurekaServerConfig config = new DefaultEurekaServerConfig(); private final ServerCodecs serverCodecs = new DefaultServerCodecs(config); private final InstanceInfo instanceInfo = ClusterSampleData.newInstanceInfo(1); @Before public void setUp() throws Exception { replicationClient = Jersey2ReplicationClient.createReplicationClient( config, serverCodecs, "http://localhost:" + serverMockRule.getHttpPort() + "/eureka/v2" ); } @After public void tearDown() { if (serverMockClient != null) { serverMockClient.reset(); } } @Test public void testRegistrationReplication() throws Exception { serverMockClient.when( request() .withMethod("POST") .withHeader(header(PeerEurekaNode.HEADER_REPLICATION, "true")) .withPath("/eureka/v2/apps/" + instanceInfo.getAppName()) ).respond( response().withStatusCode(200) ); EurekaHttpResponse<Void> response = replicationClient.register(instanceInfo); assertThat(response.getStatusCode(), is(equalTo(200))); } @Test public void testCancelReplication() throws Exception { serverMockClient.when( request() .withMethod("DELETE") .withHeader(header(PeerEurekaNode.HEADER_REPLICATION, "true")) .withPath("/eureka/v2/apps/" + instanceInfo.getAppName() + '/' + instanceInfo.getId()) ).respond( response().withStatusCode(204) ); EurekaHttpResponse<Void> response = replicationClient.cancel(instanceInfo.getAppName(), instanceInfo.getId()); assertThat(response.getStatusCode(), is(equalTo(204))); } @Test public void testHeartbeatReplicationWithNoResponseBody() throws Exception { serverMockClient.when( request() .withMethod("PUT") .withHeader(header(PeerEurekaNode.HEADER_REPLICATION, "true")) .withPath("/eureka/v2/apps/" + instanceInfo.getAppName() + '/' + instanceInfo.getId()) ).respond( response().withStatusCode(200) ); EurekaHttpResponse<InstanceInfo> response = replicationClient.sendHeartBeat(instanceInfo.getAppName(), instanceInfo.getId(), instanceInfo, InstanceStatus.DOWN); assertThat(response.getStatusCode(), is(equalTo(200))); assertThat(response.getEntity(), is(nullValue())); } @Test public void testHeartbeatReplicationWithResponseBody() throws Exception { InstanceInfo remoteInfo = new InstanceInfo(this.instanceInfo); remoteInfo.setStatus(InstanceStatus.DOWN); byte[] responseBody = toGzippedJson(remoteInfo); serverMockClient.when( request() .withMethod("PUT") .withHeader(header(PeerEurekaNode.HEADER_REPLICATION, "true")) .withPath("/eureka/v2/apps/" + this.instanceInfo.getAppName() + '/' + this.instanceInfo.getId()) ).respond( response() .withStatusCode(Status.CONFLICT.getStatusCode()) .withHeader(header("Content-Type", MediaType.APPLICATION_JSON)) .withHeader(header("Content-Encoding", "gzip")) .withBody(responseBody) ); EurekaHttpResponse<InstanceInfo> response = replicationClient.sendHeartBeat(this.instanceInfo.getAppName(), this.instanceInfo.getId(), this.instanceInfo, null); assertThat(response.getStatusCode(), is(equalTo(Status.CONFLICT.getStatusCode()))); assertThat(response.getEntity(), is(notNullValue())); } @Test public void testAsgStatusUpdateReplication() throws Exception { serverMockClient.when( request() .withMethod("PUT") .withHeader(header(PeerEurekaNode.HEADER_REPLICATION, "true")) .withPath("/eureka/v2/asg/" + instanceInfo.getASGName() + "/status") ).respond( response().withStatusCode(200) ); EurekaHttpResponse<Void> response = replicationClient.statusUpdate(instanceInfo.getASGName(), ASGStatus.ENABLED); assertThat(response.getStatusCode(), is(equalTo(200))); } @Test public void testStatusUpdateReplication() throws Exception { serverMockClient.when( request() .withMethod("PUT") .withHeader(header(PeerEurekaNode.HEADER_REPLICATION, "true")) .withPath("/eureka/v2/apps/" + instanceInfo.getAppName() + '/' + instanceInfo.getId() + "/status") ).respond( response().withStatusCode(200) ); EurekaHttpResponse<Void> response = replicationClient.statusUpdate(instanceInfo.getAppName(), instanceInfo.getId(), InstanceStatus.DOWN, instanceInfo); assertThat(response.getStatusCode(), is(equalTo(200))); } @Test public void testDeleteStatusOverrideReplication() throws Exception { serverMockClient.when( request() .withMethod("DELETE") .withHeader(header(PeerEurekaNode.HEADER_REPLICATION, "true")) .withPath("/eureka/v2/apps/" + instanceInfo.getAppName() + '/' + instanceInfo.getId() + "/status") ).respond( response().withStatusCode(204) ); EurekaHttpResponse<Void> response = replicationClient.deleteStatusOverride(instanceInfo.getAppName(), instanceInfo.getId(), instanceInfo); assertThat(response.getStatusCode(), is(equalTo(204))); } private static byte[] toGzippedJson(InstanceInfo remoteInfo) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); GZIPOutputStream gos = new GZIPOutputStream(bos); EurekaJacksonCodec.getInstance().writeTo(remoteInfo, gos); gos.flush(); return bos.toByteArray(); } }
6,606
0
Create_ds/eureka/eureka-core-jersey2/src/main/java/com/netflix
Create_ds/eureka/eureka-core-jersey2/src/main/java/com/netflix/eureka/Jersey2EurekaBootStrap.java
package com.netflix.eureka; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.discovery.DiscoveryClient; import com.netflix.discovery.EurekaClientConfig; import com.netflix.eureka.cluster.Jersey2PeerEurekaNodes; import com.netflix.eureka.cluster.PeerEurekaNodes; import com.netflix.eureka.registry.PeerAwareInstanceRegistry; import com.netflix.eureka.resources.ServerCodecs; /** * Jersey2 eureka server bootstrapper * @author Matt Nelson */ public class Jersey2EurekaBootStrap extends EurekaBootStrap { public Jersey2EurekaBootStrap(DiscoveryClient discoveryClient) { super(discoveryClient); } @Override protected PeerEurekaNodes getPeerEurekaNodes(PeerAwareInstanceRegistry registry, EurekaServerConfig eurekaServerConfig, EurekaClientConfig eurekaClientConfig, ServerCodecs serverCodecs, ApplicationInfoManager applicationInfoManager) { PeerEurekaNodes peerEurekaNodes = new Jersey2PeerEurekaNodes( registry, eurekaServerConfig, eurekaClientConfig, serverCodecs, applicationInfoManager ); return peerEurekaNodes; } }
6,607
0
Create_ds/eureka/eureka-core-jersey2/src/main/java/com/netflix/eureka
Create_ds/eureka/eureka-core-jersey2/src/main/java/com/netflix/eureka/cluster/Jersey2PeerEurekaNodes.java
package com.netflix.eureka.cluster; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.discovery.EurekaClientConfig; import com.netflix.eureka.EurekaServerConfig; import com.netflix.eureka.registry.PeerAwareInstanceRegistry; import com.netflix.eureka.resources.ServerCodecs; import com.netflix.eureka.transport.Jersey2ReplicationClient; /** * Jersey2 implementation of PeerEurekaNodes that uses the Jersey2 replication client * @author Matt Nelson */ public class Jersey2PeerEurekaNodes extends PeerEurekaNodes { public Jersey2PeerEurekaNodes(PeerAwareInstanceRegistry registry, EurekaServerConfig serverConfig, EurekaClientConfig clientConfig, ServerCodecs serverCodecs, ApplicationInfoManager applicationInfoManager) { super(registry, serverConfig, clientConfig, serverCodecs, applicationInfoManager); } @Override protected PeerEurekaNode createPeerEurekaNode(String peerEurekaNodeUrl) { HttpReplicationClient replicationClient = Jersey2ReplicationClient.createReplicationClient(serverConfig, serverCodecs, peerEurekaNodeUrl); String targetHost = hostFromUrl(peerEurekaNodeUrl); if (targetHost == null) { targetHost = "host"; } return new PeerEurekaNode(registry, targetHost, peerEurekaNodeUrl, replicationClient, serverConfig); } }
6,608
0
Create_ds/eureka/eureka-core-jersey2/src/main/java/com/netflix/eureka
Create_ds/eureka/eureka-core-jersey2/src/main/java/com/netflix/eureka/transport/Jersey2DynamicGZIPContentEncodingFilter.java
package com.netflix.eureka.transport; import com.netflix.eureka.EurekaServerConfig; import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.client.ClientRequestFilter; import javax.ws.rs.client.ClientResponseContext; import javax.ws.rs.client.ClientResponseFilter; import javax.ws.rs.core.HttpHeaders; import java.io.IOException; public class Jersey2DynamicGZIPContentEncodingFilter implements ClientRequestFilter, ClientResponseFilter { private final EurekaServerConfig config; public Jersey2DynamicGZIPContentEncodingFilter(EurekaServerConfig config) { this.config = config; } @Override public void filter(ClientRequestContext requestContext) throws IOException { if (!requestContext.getHeaders().containsKey(HttpHeaders.ACCEPT_ENCODING)) { requestContext.getHeaders().add(HttpHeaders.ACCEPT_ENCODING, "gzip"); } if (hasEntity(requestContext) && isCompressionEnabled()) { Object contentEncoding = requestContext.getHeaders().getFirst(HttpHeaders.CONTENT_ENCODING); if (!"gzip".equals(contentEncoding)) { requestContext.getHeaders().add(HttpHeaders.CONTENT_ENCODING, "gzip"); } } } @Override public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { Object contentEncoding = responseContext.getHeaders().getFirst(HttpHeaders.CONTENT_ENCODING); if ("gzip".equals(contentEncoding)) { responseContext.getHeaders().remove(HttpHeaders.CONTENT_ENCODING); } } private boolean hasEntity(ClientRequestContext requestContext) { return false; } private boolean isCompressionEnabled() { return config.shouldEnableReplicatedRequestCompression(); } }
6,609
0
Create_ds/eureka/eureka-core-jersey2/src/main/java/com/netflix/eureka
Create_ds/eureka/eureka-core-jersey2/src/main/java/com/netflix/eureka/transport/Jersey2ReplicationClient.java
package com.netflix.eureka.transport; import static com.netflix.discovery.shared.transport.EurekaHttpResponse.anEurekaHttpResponse; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.URL; import java.net.UnknownHostException; import javax.ws.rs.client.Client; import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation.Builder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.InstanceStatus; import com.netflix.discovery.shared.transport.EurekaHttpResponse; import com.netflix.discovery.shared.transport.jersey2.AbstractJersey2EurekaHttpClient; import com.netflix.discovery.shared.transport.jersey2.EurekaIdentityHeaderFilter; import com.netflix.discovery.shared.transport.jersey2.EurekaJersey2Client; import com.netflix.discovery.shared.transport.jersey2.EurekaJersey2ClientImpl; import com.netflix.eureka.EurekaServerConfig; import com.netflix.eureka.EurekaServerIdentity; import com.netflix.eureka.cluster.HttpReplicationClient; import com.netflix.eureka.cluster.PeerEurekaNode; import com.netflix.eureka.cluster.protocol.ReplicationList; import com.netflix.eureka.cluster.protocol.ReplicationListResponse; import com.netflix.eureka.resources.ASGResource.ASGStatus; import com.netflix.eureka.resources.ServerCodecs; /** * @author Tomasz Bak */ public class Jersey2ReplicationClient extends AbstractJersey2EurekaHttpClient implements HttpReplicationClient { private static final Logger logger = LoggerFactory.getLogger(Jersey2ReplicationClient.class); private final EurekaJersey2Client eurekaJersey2Client; public Jersey2ReplicationClient(EurekaJersey2Client eurekaJersey2Client, String serviceUrl) { super(eurekaJersey2Client.getClient(), serviceUrl); this.eurekaJersey2Client = eurekaJersey2Client; } @Override protected void addExtraHeaders(Builder webResource) { webResource.header(PeerEurekaNode.HEADER_REPLICATION, "true"); } /** * Compared to regular heartbeat, in the replication channel the server may return a more up to date * instance copy. */ @Override public EurekaHttpResponse<InstanceInfo> sendHeartBeat(String appName, String id, InstanceInfo info, InstanceStatus overriddenStatus) { String urlPath = "apps/" + appName + '/' + id; Response response = null; try { WebTarget webResource = jerseyClient.target(serviceUrl) .path(urlPath) .queryParam("status", info.getStatus().toString()) .queryParam("lastDirtyTimestamp", info.getLastDirtyTimestamp().toString()); if (overriddenStatus != null) { webResource = webResource.queryParam("overriddenstatus", overriddenStatus.name()); } Builder requestBuilder = webResource.request(); addExtraHeaders(requestBuilder); response = requestBuilder.accept(MediaType.APPLICATION_JSON_TYPE).put(Entity.entity("{}", MediaType.APPLICATION_JSON_TYPE)); // Jersey2 refuses to handle PUT with no body InstanceInfo infoFromPeer = null; if (response.getStatus() == Status.CONFLICT.getStatusCode() && response.hasEntity()) { infoFromPeer = response.readEntity(InstanceInfo.class); } return anEurekaHttpResponse(response.getStatus(), infoFromPeer).type(MediaType.APPLICATION_JSON_TYPE).build(); } finally { if (logger.isDebugEnabled()) { logger.debug("[heartbeat] Jersey HTTP PUT {}; statusCode={}", urlPath, response == null ? "N/A" : response.getStatus()); } if (response != null) { response.close(); } } } @Override public EurekaHttpResponse<Void> statusUpdate(String asgName, ASGStatus newStatus) { Response response = null; try { String urlPath = "asg/" + asgName + "/status"; response = jerseyClient.target(serviceUrl) .path(urlPath) .queryParam("value", newStatus.name()) .request() .header(PeerEurekaNode.HEADER_REPLICATION, "true") .put(Entity.text("")); return EurekaHttpResponse.status(response.getStatus()); } finally { if (response != null) { response.close(); } } } @Override public EurekaHttpResponse<ReplicationListResponse> submitBatchUpdates(ReplicationList replicationList) { Response response = null; try { response = jerseyClient.target(serviceUrl) .path(PeerEurekaNode.BATCH_URL_PATH) .request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.json(replicationList)); if (!isSuccess(response.getStatus())) { return anEurekaHttpResponse(response.getStatus(), ReplicationListResponse.class).build(); } ReplicationListResponse batchResponse = response.readEntity(ReplicationListResponse.class); return anEurekaHttpResponse(response.getStatus(), batchResponse).type(MediaType.APPLICATION_JSON_TYPE).build(); } finally { if (response != null) { response.close(); } } } @Override public void shutdown() { super.shutdown(); eurekaJersey2Client.destroyResources(); } public static Jersey2ReplicationClient createReplicationClient(EurekaServerConfig config, ServerCodecs serverCodecs, String serviceUrl) { String name = Jersey2ReplicationClient.class.getSimpleName() + ": " + serviceUrl + "apps/: "; EurekaJersey2Client jerseyClient; try { String hostname; try { hostname = new URL(serviceUrl).getHost(); } catch (MalformedURLException e) { hostname = serviceUrl; } String jerseyClientName = "Discovery-PeerNodeClient-" + hostname; EurekaJersey2ClientImpl.EurekaJersey2ClientBuilder clientBuilder = new EurekaJersey2ClientImpl.EurekaJersey2ClientBuilder() .withClientName(jerseyClientName) .withUserAgent("Java-EurekaClient-Replication") .withEncoderWrapper(serverCodecs.getFullJsonCodec()) .withDecoderWrapper(serverCodecs.getFullJsonCodec()) .withConnectionTimeout(config.getPeerNodeConnectTimeoutMs()) .withReadTimeout(config.getPeerNodeReadTimeoutMs()) .withMaxConnectionsPerHost(config.getPeerNodeTotalConnectionsPerHost()) .withMaxTotalConnections(config.getPeerNodeTotalConnections()) .withConnectionIdleTimeout(config.getPeerNodeConnectionIdleTimeoutSeconds()); if (serviceUrl.startsWith("https://") && "true".equals(System.getProperty("com.netflix.eureka.shouldSSLConnectionsUseSystemSocketFactory"))) { clientBuilder.withSystemSSLConfiguration(); } jerseyClient = clientBuilder.build(); } catch (Throwable e) { throw new RuntimeException("Cannot Create new Replica Node :" + name, e); } String ip = null; try { ip = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { logger.warn("Cannot find localhost ip", e); } Client jerseyApacheClient = jerseyClient.getClient(); jerseyApacheClient.register(new Jersey2DynamicGZIPContentEncodingFilter(config)); EurekaServerIdentity identity = new EurekaServerIdentity(ip); jerseyApacheClient.register(new EurekaIdentityHeaderFilter(identity)); return new Jersey2ReplicationClient(jerseyClient, serviceUrl); } private static boolean isSuccess(int statusCode) { return statusCode >= 200 && statusCode < 300; } }
6,610
0
Create_ds/eureka/eureka-core-jersey2/src/main/java/com/netflix/eureka
Create_ds/eureka/eureka-core-jersey2/src/main/java/com/netflix/eureka/resources/EurekaServerContextBinder.java
package com.netflix.eureka.resources; import org.glassfish.hk2.api.Factory; import org.glassfish.hk2.utilities.binding.AbstractBinder; import com.netflix.eureka.EurekaServerContext; import com.netflix.eureka.EurekaServerContextHolder; /** * Jersey2 binder for the EurekaServerContext. Replaces the GuiceFilter in the server WAR web.xml * @author Matt Nelson */ public class EurekaServerContextBinder extends AbstractBinder { public class EurekaServerContextFactory implements Factory<EurekaServerContext> { @Override public EurekaServerContext provide() { return EurekaServerContextHolder.getInstance().getServerContext(); } @Override public void dispose(EurekaServerContext t) { } } /** * {@inheritDoc} */ @Override protected void configure() { bindFactory(new EurekaServerContextFactory()).to(EurekaServerContext.class); } }
6,611
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/EurekaEventListenerTest.java
package com.netflix.discovery; import static com.netflix.discovery.shared.transport.EurekaHttpResponse.anEurekaHttpResponse; import static com.netflix.discovery.util.EurekaEntityFunctions.toApplications; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.when; import java.io.IOException; import javax.ws.rs.core.MediaType; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.junit.resource.DiscoveryClientResource; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.EurekaHttpResponse; import com.netflix.discovery.shared.transport.SimpleEurekaHttpServer; public class EurekaEventListenerTest { private static final EurekaHttpClient requestHandler = mock(EurekaHttpClient.class); private static SimpleEurekaHttpServer eurekaHttpServer; @Rule public DiscoveryClientResource discoveryClientResource = DiscoveryClientResource.newBuilder() .withRegistration(true) .withRegistryFetch(true) .connectWith(eurekaHttpServer) .build(); /** * Share server stub by all tests. */ @BeforeClass public static void setUpClass() throws IOException { eurekaHttpServer = new SimpleEurekaHttpServer(requestHandler); } @AfterClass public static void tearDownClass() throws Exception { if (eurekaHttpServer != null) { eurekaHttpServer.shutdown(); } } @Before public void setUp() throws Exception { reset(requestHandler); when(requestHandler.register(any(InstanceInfo.class))).thenReturn(EurekaHttpResponse.status(204)); when(requestHandler.cancel(anyString(), anyString())).thenReturn(EurekaHttpResponse.status(200)); when(requestHandler.getDelta()).thenReturn( anEurekaHttpResponse(200, new Applications()).type(MediaType.APPLICATION_JSON_TYPE).build() ); } static class CapturingEurekaEventListener implements EurekaEventListener { private volatile EurekaEvent event; @Override public void onEvent(EurekaEvent event) { this.event = event; } } @Test public void testCacheRefreshEvent() throws Exception { CapturingEurekaEventListener listener = new CapturingEurekaEventListener(); Applications initialApps = toApplications(discoveryClientResource.getMyInstanceInfo()); when(requestHandler.getApplications()).thenReturn( anEurekaHttpResponse(200, initialApps).type(MediaType.APPLICATION_JSON_TYPE).build() ); DiscoveryClient client = (DiscoveryClient) discoveryClientResource.getClient(); client.registerEventListener(listener); client.refreshRegistry(); assertNotNull(listener.event); assertThat(listener.event, is(instanceOf(CacheRefreshedEvent.class))); } }
6,612
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/BaseDiscoveryClientTester.java
package com.netflix.discovery; import com.netflix.appinfo.AmazonInfo; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.LeaseInfo; import com.netflix.discovery.junit.resource.DiscoveryClientResource; import com.netflix.discovery.shared.Application; import org.junit.Rule; import javax.annotation.Nullable; import java.util.Arrays; import java.util.List; /** * @author Nitesh Kant */ public abstract class BaseDiscoveryClientTester { public static final String REMOTE_REGION = "myregion"; public static final String REMOTE_ZONE = "myzone"; public static final int CLIENT_REFRESH_RATE = 10; public static final String ALL_REGIONS_VIP1_ADDR = "myvip1"; public static final String REMOTE_REGION_APP1_INSTANCE1_HOSTNAME = "blah1-1"; public static final String REMOTE_REGION_APP1_INSTANCE2_HOSTNAME = "blah1-2"; public static final String LOCAL_REGION_APP1_NAME = "MYAPP1_LOC"; public static final String LOCAL_REGION_APP1_INSTANCE1_HOSTNAME = "blahloc1-1"; public static final String LOCAL_REGION_APP1_INSTANCE2_HOSTNAME = "blahloc1-2"; public static final String REMOTE_REGION_APP1_NAME = "MYAPP1"; public static final String ALL_REGIONS_VIP2_ADDR = "myvip2"; public static final String REMOTE_REGION_APP2_INSTANCE1_HOSTNAME = "blah2-1"; public static final String REMOTE_REGION_APP2_INSTANCE2_HOSTNAME = "blah2-2"; public static final String LOCAL_REGION_APP2_NAME = "MYAPP2_LOC"; public static final String LOCAL_REGION_APP2_INSTANCE1_HOSTNAME = "blahloc2-1"; public static final String LOCAL_REGION_APP2_INSTANCE2_HOSTNAME = "blahloc2-2"; public static final String REMOTE_REGION_APP2_NAME = "MYAPP2"; public static final String ALL_REGIONS_VIP3_ADDR = "myvip3"; public static final String LOCAL_REGION_APP3_NAME = "MYAPP3_LOC"; public static final String LOCAL_REGION_APP3_INSTANCE1_HOSTNAME = "blahloc3-1"; @Rule public MockRemoteEurekaServer mockLocalEurekaServer = new MockRemoteEurekaServer(); protected EurekaClient client; protected void setupProperties() { DiscoveryClientResource.setupDiscoveryClientConfig(mockLocalEurekaServer.getPort(), MockRemoteEurekaServer.EUREKA_API_BASE_PATH); } protected void setupDiscoveryClient() { client = getSetupDiscoveryClient(); } protected EurekaClient getSetupDiscoveryClient() { return getSetupDiscoveryClient(30); } protected EurekaClient getSetupDiscoveryClient(int renewalIntervalInSecs) { InstanceInfo instanceInfo = newInstanceInfoBuilder(renewalIntervalInSecs).build(); return DiscoveryClientResource.setupDiscoveryClient(instanceInfo); } protected InstanceInfo.Builder newInstanceInfoBuilder(int renewalIntervalInSecs) { return DiscoveryClientResource.newInstanceInfoBuilder(renewalIntervalInSecs); } protected void shutdownDiscoveryClient() { if (client != null) { client.shutdown(); } } protected void addLocalAppDelta() { Application myappDelta = new Application(LOCAL_REGION_APP3_NAME); InstanceInfo instanceInfo = createInstance(LOCAL_REGION_APP3_NAME, ALL_REGIONS_VIP3_ADDR, LOCAL_REGION_APP3_INSTANCE1_HOSTNAME, null); instanceInfo.setActionType(InstanceInfo.ActionType.ADDED); myappDelta.addInstance(instanceInfo); mockLocalEurekaServer.addLocalRegionAppsDelta(LOCAL_REGION_APP3_NAME, myappDelta); } protected void populateLocalRegistryAtStartup() { for (Application app : createLocalApps()) { mockLocalEurekaServer.addLocalRegionApps(app.getName(), app); } for (Application appDelta : createLocalAppsDelta()) { mockLocalEurekaServer.addLocalRegionAppsDelta(appDelta.getName(), appDelta); } } protected void populateRemoteRegistryAtStartup() { for (Application app : createRemoteApps()) { mockLocalEurekaServer.addRemoteRegionApps(app.getName(), app); } for (Application appDelta : createRemoteAppsDelta()) { mockLocalEurekaServer.addRemoteRegionAppsDelta(appDelta.getName(), appDelta); } } protected static List<Application> createRemoteApps() { Application myapp1 = new Application(REMOTE_REGION_APP1_NAME); InstanceInfo instanceInfo1 = createInstance(REMOTE_REGION_APP1_NAME, ALL_REGIONS_VIP1_ADDR, REMOTE_REGION_APP1_INSTANCE1_HOSTNAME, REMOTE_ZONE); myapp1.addInstance(instanceInfo1); Application myapp2 = new Application(REMOTE_REGION_APP2_NAME); InstanceInfo instanceInfo2 = createInstance(REMOTE_REGION_APP2_NAME, ALL_REGIONS_VIP2_ADDR, REMOTE_REGION_APP2_INSTANCE1_HOSTNAME, REMOTE_ZONE); myapp2.addInstance(instanceInfo2); return Arrays.asList(myapp1, myapp2); } protected static List<Application> createRemoteAppsDelta() { Application myapp1 = new Application(REMOTE_REGION_APP1_NAME); InstanceInfo instanceInfo1 = createInstance(REMOTE_REGION_APP1_NAME, ALL_REGIONS_VIP1_ADDR, REMOTE_REGION_APP1_INSTANCE2_HOSTNAME, REMOTE_ZONE); instanceInfo1.setActionType(InstanceInfo.ActionType.ADDED); myapp1.addInstance(instanceInfo1); Application myapp2 = new Application(REMOTE_REGION_APP2_NAME); InstanceInfo instanceInfo2 = createInstance(REMOTE_REGION_APP2_NAME, ALL_REGIONS_VIP2_ADDR, REMOTE_REGION_APP2_INSTANCE2_HOSTNAME, REMOTE_ZONE); instanceInfo2.setActionType(InstanceInfo.ActionType.ADDED); myapp2.addInstance(instanceInfo2); return Arrays.asList(myapp1, myapp2); } protected static List<Application> createLocalApps() { Application myapp1 = new Application(LOCAL_REGION_APP1_NAME); InstanceInfo instanceInfo1 = createInstance(LOCAL_REGION_APP1_NAME, ALL_REGIONS_VIP1_ADDR, LOCAL_REGION_APP1_INSTANCE1_HOSTNAME, null); myapp1.addInstance(instanceInfo1); Application myapp2 = new Application(LOCAL_REGION_APP2_NAME); InstanceInfo instanceInfo2 = createInstance(LOCAL_REGION_APP2_NAME, ALL_REGIONS_VIP2_ADDR, LOCAL_REGION_APP2_INSTANCE1_HOSTNAME, null); myapp2.addInstance(instanceInfo2); return Arrays.asList(myapp1, myapp2); } protected static List<Application> createLocalAppsDelta() { Application myapp1 = new Application(LOCAL_REGION_APP1_NAME); InstanceInfo instanceInfo1 = createInstance(LOCAL_REGION_APP1_NAME, ALL_REGIONS_VIP1_ADDR, LOCAL_REGION_APP1_INSTANCE2_HOSTNAME, null); instanceInfo1.setActionType(InstanceInfo.ActionType.ADDED); myapp1.addInstance(instanceInfo1); Application myapp2 = new Application(LOCAL_REGION_APP2_NAME); InstanceInfo instanceInfo2 = createInstance(LOCAL_REGION_APP2_NAME, ALL_REGIONS_VIP2_ADDR, LOCAL_REGION_APP2_INSTANCE2_HOSTNAME, null); instanceInfo2.setActionType(InstanceInfo.ActionType.ADDED); myapp2.addInstance(instanceInfo2); return Arrays.asList(myapp1, myapp2); } protected static InstanceInfo createInstance(String appName, String vipAddress, String instanceHostName, String zone) { InstanceInfo.Builder instanceBuilder = InstanceInfo.Builder.newBuilder(); instanceBuilder.setAppName(appName); instanceBuilder.setVIPAddress(vipAddress); instanceBuilder.setHostName(instanceHostName); instanceBuilder.setIPAddr("10.10.101.1"); AmazonInfo amazonInfo = getAmazonInfo(zone, instanceHostName); instanceBuilder.setDataCenterInfo(amazonInfo); instanceBuilder.setMetadata(amazonInfo.getMetadata()); instanceBuilder.setLeaseInfo(LeaseInfo.Builder.newBuilder().build()); return instanceBuilder.build(); } protected static AmazonInfo getAmazonInfo(@Nullable String availabilityZone, String instanceHostName) { AmazonInfo.Builder azBuilder = AmazonInfo.Builder.newBuilder(); azBuilder.addMetadata(AmazonInfo.MetaDataKey.availabilityZone, null == availabilityZone ? "us-east-1a" : availabilityZone); azBuilder.addMetadata(AmazonInfo.MetaDataKey.instanceId, instanceHostName); azBuilder.addMetadata(AmazonInfo.MetaDataKey.amiId, "XXX"); azBuilder.addMetadata(AmazonInfo.MetaDataKey.instanceType, "XXX"); azBuilder.addMetadata(AmazonInfo.MetaDataKey.localIpv4, "XXX"); azBuilder.addMetadata(AmazonInfo.MetaDataKey.publicIpv4, "XXX"); azBuilder.addMetadata(AmazonInfo.MetaDataKey.publicHostname, instanceHostName); return azBuilder.build(); } }
6,613
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/MockRemoteEurekaServer.java
package com.netflix.discovery; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedReader; import java.io.IOException; import java.util.*; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.netflix.appinfo.AbstractEurekaIdentity; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.EurekaClientIdentity; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.converters.XmlXStream; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import org.junit.Assert; import org.junit.rules.ExternalResource; import org.mortbay.jetty.Request; import org.mortbay.jetty.Server; import org.mortbay.jetty.handler.AbstractHandler; /** * @author Nitesh Kant */ public class MockRemoteEurekaServer extends ExternalResource { public static final String EUREKA_API_BASE_PATH = "/eureka/v2/"; private static Pattern HOSTNAME_PATTERN = Pattern.compile("\"hostName\"\\s?:\\s?\\\"([A-Za-z0-9\\.-]*)\\\""); private static Pattern STATUS_PATTERN = Pattern.compile("\"status\"\\s?:\\s?\\\"([A-Z_]*)\\\""); private int port; private final Map<String, Application> applicationMap = new HashMap<String, Application>(); private final Map<String, Application> remoteRegionApps = new HashMap<String, Application>(); private final Map<String, Application> remoteRegionAppsDelta = new HashMap<String, Application>(); private final Map<String, Application> applicationDeltaMap = new HashMap<String, Application>(); private Server server; private final AtomicBoolean sentDelta = new AtomicBoolean(); private final AtomicBoolean sentRegistry = new AtomicBoolean(); public final BlockingQueue<String> registrationStatusesQueue = new LinkedBlockingQueue<>(); public final List<String> registrationStatuses = new ArrayList<>(); public final AtomicLong registerCount = new AtomicLong(0); public final AtomicLong heartbeatCount = new AtomicLong(0); public final AtomicLong getFullRegistryCount = new AtomicLong(0); public final AtomicLong getSingleVipCount = new AtomicLong(0); public final AtomicLong getDeltaCount = new AtomicLong(0); @Override protected void before() throws Throwable { start(); } @Override protected void after() { try { stop(); } catch (Exception e) { Assert.fail(e.getMessage()); } } public void start() throws Exception { server = new Server(port); server.setHandler(new AppsResourceHandler()); server.start(); port = server.getConnectors()[0].getLocalPort(); } public int getPort() { return port; } public void stop() throws Exception { server.stop(); server = null; port = 0; registrationStatusesQueue.clear(); registrationStatuses.clear(); applicationMap.clear(); remoteRegionApps.clear(); remoteRegionAppsDelta.clear(); applicationDeltaMap.clear(); } public boolean isSentDelta() { return sentDelta.get(); } public boolean isSentRegistry() { return sentRegistry.get(); } public void addRemoteRegionApps(String appName, Application app) { remoteRegionApps.put(appName, app); } public void addRemoteRegionAppsDelta(String appName, Application app) { remoteRegionAppsDelta.put(appName, app); } public void addLocalRegionApps(String appName, Application app) { applicationMap.put(appName, app); } public void addLocalRegionAppsDelta(String appName, Application app) { applicationDeltaMap.put(appName, app); } public void waitForDeltaToBeRetrieved(int refreshRate) throws InterruptedException { int count = 0; while (count++ < 3 && !isSentDelta()) { System.out.println("Sleeping for " + refreshRate + " seconds to let the remote registry fetch delta. Attempt: " + count); Thread.sleep(3 * refreshRate * 1000); System.out.println("Done sleeping for 10 seconds to let the remote registry fetch delta. Delta fetched: " + isSentDelta()); } System.out.println("Sleeping for extra " + refreshRate + " seconds for the client to update delta in memory."); } // // A base default resource handler for the mock server // private class AppsResourceHandler extends AbstractHandler { @Override public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException { String authName = request.getHeader(AbstractEurekaIdentity.AUTH_NAME_HEADER_KEY); String authVersion = request.getHeader(AbstractEurekaIdentity.AUTH_VERSION_HEADER_KEY); String authId = request.getHeader(AbstractEurekaIdentity.AUTH_ID_HEADER_KEY); Assert.assertEquals(EurekaClientIdentity.DEFAULT_CLIENT_NAME, authName); Assert.assertNotNull(authVersion); Assert.assertNotNull(authId); String pathInfo = request.getPathInfo(); System.out.println("Eureka port: " + port + ". " + System.currentTimeMillis() + ". Eureka resource mock, received request on path: " + pathInfo + ". HTTP method: |" + request.getMethod() + '|' + ", query string: " + request.getQueryString()); boolean handled = false; if (null != pathInfo && pathInfo.startsWith("")) { pathInfo = pathInfo.substring(EUREKA_API_BASE_PATH.length()); boolean includeRemote = isRemoteRequest(request); if (pathInfo.startsWith("apps/delta")) { getDeltaCount.getAndIncrement(); Applications apps = new Applications(); apps.setVersion(100L); if (sentDelta.compareAndSet(false, true)) { addDeltaApps(includeRemote, apps); } else { System.out.println("Eureka port: " + port + ". " + System.currentTimeMillis() + ". Not including delta as it has already been sent."); } apps.setAppsHashCode(getDeltaAppsHashCode(includeRemote)); sendOkResponseWithContent((Request) request, response, apps); handled = true; } else if (pathInfo.equals("apps/")) { getFullRegistryCount.getAndIncrement(); Applications apps = new Applications(); apps.setVersion(100L); for (Application application : applicationMap.values()) { apps.addApplication(application); } if (includeRemote) { for (Application application : remoteRegionApps.values()) { apps.addApplication(application); } } if (sentDelta.get()) { addDeltaApps(includeRemote, apps); } else { System.out.println("Eureka port: " + port + ". " + System.currentTimeMillis() + ". Not including delta apps in /apps response, as delta has not been sent."); } apps.setAppsHashCode(apps.getReconcileHashCode()); sendOkResponseWithContent((Request) request, response, apps); sentRegistry.set(true); handled = true; } else if (pathInfo.startsWith("vips/")) { getSingleVipCount.getAndIncrement(); String vipAddress = pathInfo.substring("vips/".length()); Applications apps = new Applications(); apps.setVersion(-1l); for (Application application : applicationMap.values()) { Application retApp = new Application(application.getName()); for (InstanceInfo instance : application.getInstances()) { if (vipAddress.equals(instance.getVIPAddress())) { retApp.addInstance(instance); } } if (retApp.getInstances().size() > 0) { apps.addApplication(retApp); } } apps.setAppsHashCode(apps.getReconcileHashCode()); sendOkResponseWithContent((Request) request, response, apps); handled = true; } else if (pathInfo.startsWith("apps")) { // assume this is the renewal heartbeat if (request.getMethod().equals("PUT")) { // this is the renewal heartbeat heartbeatCount.getAndIncrement(); } else if (request.getMethod().equals("POST")) { // this is a register request registerCount.getAndIncrement(); String statusStr = null; String hostname = null; String line; BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { Matcher hostNameMatcher = HOSTNAME_PATTERN.matcher(line); if (hostname == null && hostNameMatcher.find()) { hostname = hostNameMatcher.group(1); // don't break here as we want to read the full buffer for a clean connection close } Matcher statusMatcher = STATUS_PATTERN.matcher(line); if (statusStr == null && statusMatcher.find()) { statusStr = statusMatcher.group(1); // don't break here as we want to read the full buffer for a clean connection close } } System.out.println("Matched status to: " + statusStr); registrationStatusesQueue.add(statusStr); registrationStatuses.add(statusStr); String appName = pathInfo.substring(5); if (!applicationMap.containsKey(appName)) { Application app = new Application(appName); InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder() .setAppName(appName) .setIPAddr("1.1.1.1") .setHostName(hostname) .setStatus(InstanceInfo.InstanceStatus.toEnum(statusStr)) .setDataCenterInfo(new DataCenterInfo() { @Override public Name getName() { return Name.MyOwn; } }) .build(); app.addInstance(instanceInfo); applicationMap.put(appName, app); } } Applications apps = new Applications(); apps.setAppsHashCode(""); sendOkResponseWithContent((Request) request, response, apps); handled = true; } else { System.out.println("Not handling request: " + pathInfo); } } if (!handled) { response.sendError(HttpServletResponse.SC_NOT_FOUND, "Request path: " + pathInfo + " not supported by eureka resource mock."); } } protected void addDeltaApps(boolean includeRemote, Applications apps) { for (Application application : applicationDeltaMap.values()) { apps.addApplication(application); } if (includeRemote) { for (Application application : remoteRegionAppsDelta.values()) { apps.addApplication(application); } } } protected String getDeltaAppsHashCode(boolean includeRemote) { Applications allApps = new Applications(); for (Application application : applicationMap.values()) { allApps.addApplication(application); } if (includeRemote) { for (Application application : remoteRegionApps.values()) { allApps.addApplication(application); } } addDeltaApps(includeRemote, allApps); return allApps.getReconcileHashCode(); } protected boolean isRemoteRequest(HttpServletRequest request) { String queryString = request.getQueryString(); if (queryString == null) { return false; } return queryString.contains("regions="); } protected void sendOkResponseWithContent(Request request, HttpServletResponse response, Applications apps) throws IOException { String content = XmlXStream.getInstance().toXML(apps); response.setContentType("application/xml"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println(content); response.getWriter().flush(); request.setHandled(true); System.out.println("Eureka port: " + port + ". " + System.currentTimeMillis() + ". Eureka resource mock, sent response for request path: " + request.getPathInfo() + ", apps count: " + apps.getRegisteredApplications().size()); } protected void sleep(int seconds) { try { Thread.sleep(seconds); } catch (InterruptedException e) { System.out.println("Interrupted: " + e); } } } }
6,614
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/DiscoveryClientCloseJerseyThreadTest.java
package com.netflix.discovery; import java.util.Set; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; public class DiscoveryClientCloseJerseyThreadTest extends AbstractDiscoveryClientTester { private static final String JERSEY_THREAD_NAME = "Eureka-JerseyClient-Conn-Cleaner"; private static final String APACHE_THREAD_NAME = "Apache-HttpClient-Conn-Cleaner"; @Test public void testThreadCount() throws InterruptedException { assertThat(containsClientThread(), equalTo(true)); client.shutdown(); // Give up control for cleaner thread to die Thread.sleep(5); assertThat(containsClientThread(), equalTo(false)); } private boolean containsClientThread() { Set<Thread> threads = Thread.getAllStackTraces().keySet(); for (Thread t : threads) { if (t.getName().contains(JERSEY_THREAD_NAME) || t.getName().contains(APACHE_THREAD_NAME)) { return true; } } return false; } }
6,615
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/InstanceInfoReplicatorTest.java
package com.netflix.discovery; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.HealthCheckHandler; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.LeaseInfo; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.UUID; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * @author David Liu */ public class InstanceInfoReplicatorTest { private final int burstSize = 2; private final int refreshRateSeconds = 2; private DiscoveryClient discoveryClient; private InstanceInfoReplicator replicator; @Before public void setUp() throws Exception { discoveryClient = mock(DiscoveryClient.class); InstanceInfo.Builder builder = InstanceInfo.Builder.newBuilder() .setIPAddr("10.10.101.00") .setHostName("Hosttt") .setAppName("EurekaTestApp-" + UUID.randomUUID()) .setDataCenterInfo(new DataCenterInfo() { @Override public Name getName() { return Name.MyOwn; } }) .setLeaseInfo(LeaseInfo.Builder.newBuilder().setRenewalIntervalInSecs(30).build()); InstanceInfo instanceInfo = builder.build(); instanceInfo.setStatus(InstanceInfo.InstanceStatus.DOWN); this.replicator = new InstanceInfoReplicator(discoveryClient, instanceInfo, refreshRateSeconds, burstSize); } @After public void tearDown() throws Exception { replicator.stop(); } @Test public void testOnDemandUpdate() throws Throwable { assertTrue(replicator.onDemandUpdate()); Thread.sleep(10); // give some time for execution assertTrue(replicator.onDemandUpdate()); Thread.sleep(1000 * refreshRateSeconds / 2); assertTrue(replicator.onDemandUpdate()); Thread.sleep(10); verify(discoveryClient, times(3)).refreshInstanceInfo(); verify(discoveryClient, times(1)).register(); } @Test public void testOnDemandUpdateRateLimiting() throws Throwable { assertTrue(replicator.onDemandUpdate()); Thread.sleep(10); // give some time for execution assertTrue(replicator.onDemandUpdate()); Thread.sleep(10); // give some time for execution assertFalse(replicator.onDemandUpdate()); Thread.sleep(1000); verify(discoveryClient, times(2)).refreshInstanceInfo(); verify(discoveryClient, times(1)).register(); } @Test public void testOnDemandUpdateResetAutomaticRefresh() throws Throwable { replicator.start(0); Thread.sleep(1000 * refreshRateSeconds / 2); assertTrue(replicator.onDemandUpdate()); Thread.sleep(1000 * refreshRateSeconds + 50); verify(discoveryClient, times(3)).refreshInstanceInfo(); // 1 initial refresh, 1 onDemand, 1 auto verify(discoveryClient, times(1)).register(); // all but 1 is no-op } @Test public void testOnDemandUpdateResetAutomaticRefreshWithInitialDelay() throws Throwable { replicator.start(1000 * refreshRateSeconds); assertTrue(replicator.onDemandUpdate()); Thread.sleep(1000 * refreshRateSeconds + 100); verify(discoveryClient, times(2)).refreshInstanceInfo(); // 1 onDemand, 1 auto verify(discoveryClient, times(1)).register(); // all but 1 is no-op } }
6,616
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/MockBackupRegistry.java
package com.netflix.discovery; import java.util.HashMap; import java.util.Map; import com.google.inject.Singleton; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; /** * @author Nitesh Kant */ @Singleton public class MockBackupRegistry implements BackupRegistry { private Map<String, Applications> remoteRegionVsApps = new HashMap<String, Applications>(); private Applications localRegionApps; @Override public Applications fetchRegistry() { if (null == localRegionApps) { return new Applications(); } return localRegionApps; } @Override public Applications fetchRegistry(String[] includeRemoteRegions) { Applications toReturn = new Applications(); for (Application application : localRegionApps.getRegisteredApplications()) { toReturn.addApplication(application); } for (String region : includeRemoteRegions) { Applications applications = remoteRegionVsApps.get(region); if (null != applications) { for (Application application : applications.getRegisteredApplications()) { toReturn.addApplication(application); } } } return toReturn; } public Applications getLocalRegionApps() { return localRegionApps; } public Map<String, Applications> getRemoteRegionVsApps() { return remoteRegionVsApps; } public void setRemoteRegionVsApps(Map<String, Applications> remoteRegionVsApps) { this.remoteRegionVsApps = remoteRegionVsApps; } public void setLocalRegionApps(Applications localRegionApps) { this.localRegionApps = localRegionApps; } }
6,617
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/DiscoveryClientRegisterUpdateTest.java
package com.netflix.discovery; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.LeaseInfo; import com.netflix.appinfo.MyDataCenterInstanceConfig; import com.netflix.config.ConfigurationManager; import com.netflix.discovery.util.InstanceInfoGenerator; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; /** * @author David Liu */ public class DiscoveryClientRegisterUpdateTest { private TestApplicationInfoManager applicationInfoManager; private MockRemoteEurekaServer mockLocalEurekaServer; private TestClient client; @Before public void setUp() throws Exception { mockLocalEurekaServer = new MockRemoteEurekaServer(); mockLocalEurekaServer.start(); ConfigurationManager.getConfigInstance().setProperty("eureka.name", "EurekaTestApp-" + UUID.randomUUID()); ConfigurationManager.getConfigInstance().setProperty("eureka.registration.enabled", "true"); ConfigurationManager.getConfigInstance().setProperty("eureka.appinfo.replicate.interval", 4); ConfigurationManager.getConfigInstance().setProperty("eureka.shouldFetchRegistry", "false"); ConfigurationManager.getConfigInstance().setProperty("eureka.serviceUrl.default", "http://localhost:" + mockLocalEurekaServer.getPort() + MockRemoteEurekaServer.EUREKA_API_BASE_PATH); InstanceInfo seed = InstanceInfoGenerator.takeOne(); LeaseInfo leaseSeed = seed.getLeaseInfo(); LeaseInfo leaseInfo = LeaseInfo.Builder.newBuilder() .setDurationInSecs(leaseSeed.getDurationInSecs()) .setEvictionTimestamp(leaseSeed.getEvictionTimestamp()) .setRegistrationTimestamp(leaseSeed.getRegistrationTimestamp()) .setServiceUpTimestamp(leaseSeed.getServiceUpTimestamp()) .setRenewalTimestamp(leaseSeed.getRenewalTimestamp()) .setRenewalIntervalInSecs(4) // make this more frequent for testing .build(); InstanceInfo instanceInfo = new InstanceInfo.Builder(seed) .setStatus(InstanceInfo.InstanceStatus.STARTING) .setLeaseInfo(leaseInfo) .build(); applicationInfoManager = new TestApplicationInfoManager(instanceInfo); client = Mockito.spy(new TestClient(applicationInfoManager, new DefaultEurekaClientConfig())); // force the initial registration to eagerly run InstanceInfoReplicator instanceInfoReplicator = ((DiscoveryClient) client).getInstanceInfoReplicator(); instanceInfoReplicator.run(); // give some execution time for the initial registration to process expectStatus(InstanceInfo.InstanceStatus.STARTING, 4000, TimeUnit.MILLISECONDS); mockLocalEurekaServer.registrationStatuses.clear(); // and then clear the validation list mockLocalEurekaServer.registerCount.set(0l); } @After public void tearDown() throws Exception { client.shutdown(); mockLocalEurekaServer.stop(); ConfigurationManager.getConfigInstance().clear(); } @Test public void registerUpdateLifecycleTest() throws Exception { applicationInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.UP); // give some execution time expectStatus(InstanceInfo.InstanceStatus.UP, 5, TimeUnit.SECONDS); applicationInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.UNKNOWN); // give some execution time expectStatus(InstanceInfo.InstanceStatus.UNKNOWN, 5, TimeUnit.SECONDS); applicationInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.DOWN); // give some execution time expectStatus(InstanceInfo.InstanceStatus.DOWN, 5, TimeUnit.SECONDS); Assert.assertTrue(mockLocalEurekaServer.registerCount.get() >= 3); // at least 3 } /** * This test is similar to the normal lifecycle test, but don't sleep between calls of setInstanceStatus */ @Test public void registerUpdateQuickLifecycleTest() throws Exception { applicationInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.UP); applicationInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.UNKNOWN); applicationInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.DOWN); expectStatus(InstanceInfo.InstanceStatus.DOWN, 5, TimeUnit.SECONDS); // this call will be rate limited, but will be transmitted by the automatic update after 10s applicationInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.UP); expectStatus(InstanceInfo.InstanceStatus.UP, 5, TimeUnit.SECONDS); Assert.assertTrue(mockLocalEurekaServer.registerCount.get() >= 2); // at least 2 } @Test public void registerUpdateShutdownTest() throws Exception { Assert.assertEquals(1, applicationInfoManager.getStatusChangeListeners().size()); client.shutdown(); Assert.assertEquals(0, applicationInfoManager.getStatusChangeListeners().size()); Mockito.verify(client, Mockito.times(1)).unregister(); } @Test public void testRegistrationDisabled() throws Exception { client.shutdown(); // shutdown the default @Before client first ConfigurationManager.getConfigInstance().setProperty("eureka.registration.enabled", "false"); client = new TestClient(applicationInfoManager, new DefaultEurekaClientConfig()); Assert.assertEquals(0, applicationInfoManager.getStatusChangeListeners().size()); applicationInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.DOWN); applicationInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.UP); Thread.sleep(400); client.shutdown(); Assert.assertEquals(0, applicationInfoManager.getStatusChangeListeners().size()); } @Test public void testDoNotUnregisterOnShutdown() throws Exception { client.shutdown(); // shutdown the default @Before client first ConfigurationManager.getConfigInstance().setProperty("eureka.shouldUnregisterOnShutdown", "false"); client = Mockito.spy(new TestClient(applicationInfoManager, new DefaultEurekaClientConfig())); client.shutdown(); Mockito.verify(client, Mockito.never()).unregister(); } public class TestApplicationInfoManager extends ApplicationInfoManager { TestApplicationInfoManager(InstanceInfo instanceInfo) { super(new MyDataCenterInstanceConfig(), instanceInfo, null); } Map<String, StatusChangeListener> getStatusChangeListeners() { return this.listeners; } } private void expectStatus(InstanceInfo.InstanceStatus expected, long timeout, TimeUnit timeUnit) throws InterruptedException { String status = mockLocalEurekaServer.registrationStatusesQueue.poll(timeout, timeUnit); Assert.assertEquals(expected.name(), status); } private static <T> T getLast(List<T> list) { return list.get(list.size() - 1); } private static class TestClient extends DiscoveryClient { public TestClient(ApplicationInfoManager applicationInfoManager, EurekaClientConfig config) { super(applicationInfoManager, config); } @Override public void unregister() { super.unregister(); } } }
6,618
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/DiscoveryClientStatsTest.java
package com.netflix.discovery; import org.junit.Assert; import org.junit.Test; /** * Tests for DiscoveryClient stats reported when initial registry fetch succeeds. */ public class DiscoveryClientStatsTest extends AbstractDiscoveryClientTester { @Test public void testNonEmptyInitLocalRegistrySize() throws Exception { Assert.assertTrue(client instanceof DiscoveryClient); DiscoveryClient clientImpl = (DiscoveryClient) client; Assert.assertEquals(createLocalApps().size(), clientImpl.getStats().initLocalRegistrySize()); } @Test public void testInitSucceeded() throws Exception { Assert.assertTrue(client instanceof DiscoveryClient); DiscoveryClient clientImpl = (DiscoveryClient) client; Assert.assertTrue(clientImpl.getStats().initSucceeded()); } }
6,619
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/Jersey1DiscoveryClientOptionalArgsTest.java
package com.netflix.discovery; import javax.inject.Provider; import com.netflix.discovery.shared.transport.jersey.Jersey1DiscoveryClientOptionalArgs; import org.junit.Before; import org.junit.Test; import com.netflix.appinfo.HealthCheckCallback; import com.netflix.appinfo.HealthCheckHandler; /** * @author Matt Nelson */ public class Jersey1DiscoveryClientOptionalArgsTest { private Jersey1DiscoveryClientOptionalArgs args; @Before public void before() { args = new Jersey1DiscoveryClientOptionalArgs(); } @Test public void testHealthCheckCallbackGuiceProvider() { args.setHealthCheckCallbackProvider(new GuiceProvider<HealthCheckCallback>()); } @Test public void testHealthCheckCallbackJavaxProvider() { args.setHealthCheckCallbackProvider(new JavaxProvider<HealthCheckCallback>()); } @Test public void testHealthCheckHandlerGuiceProvider() { args.setHealthCheckHandlerProvider(new GuiceProvider<HealthCheckHandler>()); } @Test public void testHealthCheckHandlerJavaxProvider() { args.setHealthCheckHandlerProvider(new JavaxProvider<HealthCheckHandler>()); } private class JavaxProvider<T> implements Provider<T> { @Override public T get() { return null; } } private class GuiceProvider<T> implements com.google.inject.Provider<T> { @Override public T get() { return null; } } }
6,620
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/EurekaClientLifecycleTest.java
package com.netflix.discovery; import javax.ws.rs.core.MediaType; import java.io.IOException; import java.util.Collections; import java.util.List; import com.google.inject.AbstractModule; import com.google.inject.Injector; import com.google.inject.ProvisionException; import com.google.inject.Scopes; import com.netflix.appinfo.EurekaInstanceConfig; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.PropertiesInstanceConfig; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.shared.resolver.EndpointRandomizer; import com.netflix.discovery.shared.resolver.ResolverUtils; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.EurekaHttpResponse; import com.netflix.discovery.shared.transport.SimpleEurekaHttpServer; import com.netflix.discovery.shared.transport.jersey.Jersey1DiscoveryClientOptionalArgs; import com.netflix.discovery.util.InstanceInfoGenerator; import com.netflix.governator.guice.LifecycleInjector; import com.netflix.governator.lifecycle.LifecycleManager; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import static com.netflix.discovery.shared.transport.EurekaHttpResponse.anEurekaHttpResponse; import static com.netflix.discovery.util.EurekaEntityFunctions.countInstances; import static java.util.Collections.singletonList; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class EurekaClientLifecycleTest { private static final String MY_APPLICATION_NAME = "MYAPPLICATION"; private static final String MY_INSTANCE_ID = "myInstanceId"; private static final Applications APPLICATIONS = InstanceInfoGenerator.newBuilder(1, 1).build().toApplications(); private static final Applications APPLICATIONS_DELTA = new Applications(APPLICATIONS.getAppsHashCode(), 1L, Collections.<Application>emptyList()); public static final int TIMEOUT_MS = 2 * 1000; public static final EurekaHttpClient requestHandler = mock(EurekaHttpClient.class); public static SimpleEurekaHttpServer eurekaHttpServer; @BeforeClass public static void setupClass() throws IOException { eurekaHttpServer = new SimpleEurekaHttpServer(requestHandler); when(requestHandler.register(any(InstanceInfo.class))).thenReturn(EurekaHttpResponse.status(204)); when(requestHandler.cancel(MY_APPLICATION_NAME, MY_INSTANCE_ID)).thenReturn(EurekaHttpResponse.status(200)); when(requestHandler.sendHeartBeat(MY_APPLICATION_NAME, MY_INSTANCE_ID, null, null)).thenReturn( anEurekaHttpResponse(200, InstanceInfo.class).build() ); when(requestHandler.getApplications()).thenReturn( anEurekaHttpResponse(200, APPLICATIONS).type(MediaType.APPLICATION_JSON_TYPE).build() ); when(requestHandler.getDelta()).thenReturn( anEurekaHttpResponse(200, APPLICATIONS_DELTA).type(MediaType.APPLICATION_JSON_TYPE).build() ); } @AfterClass public static void tearDownClass() { if (eurekaHttpServer != null) { eurekaHttpServer.shutdown(); } } @Test public void testEurekaClientLifecycle() throws Exception { Injector injector = LifecycleInjector.builder() .withModules( new AbstractModule() { @Override protected void configure() { bind(EurekaInstanceConfig.class).to(LocalEurekaInstanceConfig.class); bind(EurekaClientConfig.class).to(LocalEurekaClientConfig.class); bind(AbstractDiscoveryClientOptionalArgs.class).to(Jersey1DiscoveryClientOptionalArgs.class).in(Scopes.SINGLETON); bind(EndpointRandomizer.class).toInstance(ResolverUtils::randomize); } } ) .build().createInjector(); LifecycleManager lifecycleManager = injector.getInstance(LifecycleManager.class); lifecycleManager.start(); EurekaClient client = injector.getInstance(EurekaClient.class); // Check registration verify(requestHandler, timeout(TIMEOUT_MS).atLeast(1)).register(any(InstanceInfo.class)); // Check registry fetch verify(requestHandler, timeout(TIMEOUT_MS).times(1)).getApplications(); verify(requestHandler, timeout(TIMEOUT_MS).atLeast(1)).getDelta(); assertThat(countInstances(client.getApplications()), is(equalTo(1))); // Shutdown container, and check that unregister happens lifecycleManager.close(); verify(requestHandler, times(1)).cancel(MY_APPLICATION_NAME, MY_INSTANCE_ID); } @Test public void testBackupRegistryInjection() throws Exception { final BackupRegistry backupRegistry = mock(BackupRegistry.class); when(backupRegistry.fetchRegistry()).thenReturn(APPLICATIONS); Injector injector = LifecycleInjector.builder() .withModules( new AbstractModule() { @Override protected void configure() { bind(EurekaInstanceConfig.class).to(LocalEurekaInstanceConfig.class); bind(EurekaClientConfig.class).to(BadServerEurekaClientConfig1.class); bind(BackupRegistry.class).toInstance(backupRegistry); bind(AbstractDiscoveryClientOptionalArgs.class).to(Jersey1DiscoveryClientOptionalArgs.class).in(Scopes.SINGLETON); bind(EndpointRandomizer.class).toInstance(ResolverUtils::randomize); } } ) .build().createInjector(); LifecycleManager lifecycleManager = injector.getInstance(LifecycleManager.class); lifecycleManager.start(); EurekaClient client = injector.getInstance(EurekaClient.class); verify(backupRegistry, atLeast(1)).fetchRegistry(); assertThat(countInstances(client.getApplications()), is(equalTo(1))); } @Test(expected = ProvisionException.class) public void testEnforcingRegistrationOnInitFastFail() { Injector injector = LifecycleInjector.builder() .withModules( new AbstractModule() { @Override protected void configure() { bind(EurekaInstanceConfig.class).to(LocalEurekaInstanceConfig.class); bind(EurekaClientConfig.class).to(BadServerEurekaClientConfig2.class); bind(AbstractDiscoveryClientOptionalArgs.class).to(Jersey1DiscoveryClientOptionalArgs.class).in(Scopes.SINGLETON); bind(EndpointRandomizer.class).toInstance(ResolverUtils::randomize); } } ) .build().createInjector(); LifecycleManager lifecycleManager = injector.getInstance(LifecycleManager.class); try { lifecycleManager.start(); } catch (Exception e) { throw new RuntimeException(e); } // this will throw a Guice ProvisionException for the constructor failure EurekaClient client = injector.getInstance(EurekaClient.class); } private static class LocalEurekaInstanceConfig extends PropertiesInstanceConfig { @Override public String getInstanceId() { return MY_INSTANCE_ID; } @Override public String getAppname() { return MY_APPLICATION_NAME; } @Override public int getLeaseRenewalIntervalInSeconds() { return 1; } } private static class LocalEurekaClientConfig extends DefaultEurekaClientConfig { @Override public List<String> getEurekaServerServiceUrls(String myZone) { return singletonList(eurekaHttpServer.getServiceURI().toString()); } @Override public int getInitialInstanceInfoReplicationIntervalSeconds() { return 0; } @Override public int getInstanceInfoReplicationIntervalSeconds() { return 1; } @Override public int getRegistryFetchIntervalSeconds() { return 1; } } private static class BadServerEurekaClientConfig1 extends LocalEurekaClientConfig { @Override public List<String> getEurekaServerServiceUrls(String myZone) { return singletonList("http://localhost:1/v2/"); // Fail fast on bad port number } @Override public boolean shouldRegisterWithEureka() { return false; } } private static class BadServerEurekaClientConfig2 extends LocalEurekaClientConfig { @Override public List<String> getEurekaServerServiceUrls(String myZone) { return singletonList("http://localhost:1/v2/"); // Fail fast on bad port number } @Override public boolean shouldFetchRegistry() { return false; } @Override public boolean shouldEnforceRegistrationAtInit() { return true; } } }
6,621
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/EurekaClientLifecycleServerFailureTest.java
package com.netflix.discovery; import com.google.inject.AbstractModule; import com.google.inject.Injector; import com.google.inject.ProvisionException; import com.google.inject.Scopes; import com.netflix.appinfo.EurekaInstanceConfig; import com.netflix.appinfo.PropertiesInstanceConfig; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.shared.resolver.EndpointRandomizer; import com.netflix.discovery.shared.resolver.ResolverUtils; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.SimpleEurekaHttpServer; import com.netflix.discovery.shared.transport.jersey.Jersey1DiscoveryClientOptionalArgs; import com.netflix.discovery.util.InstanceInfoGenerator; import com.netflix.governator.guice.LifecycleInjector; import com.netflix.governator.lifecycle.LifecycleManager; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import javax.ws.rs.core.MediaType; import java.io.IOException; import java.util.Collections; import java.util.List; import static com.netflix.discovery.shared.transport.EurekaHttpResponse.anEurekaHttpResponse; import static java.util.Collections.singletonList; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Tests the `shouldEnforceFetchRegistryAtInit` configuration property, which throws an exception during `DiscoveryClient` * construction if set to `true` and both the primary and backup registry fail to return a successful response. */ public class EurekaClientLifecycleServerFailureTest { private static final String MY_APPLICATION_NAME = "MYAPPLICATION"; private static final String MY_INSTANCE_ID = "myInstanceId"; private static final Applications APPLICATIONS = InstanceInfoGenerator.newBuilder(1, 1).build().toApplications(); private static final Applications APPLICATIONS_DELTA = new Applications(APPLICATIONS.getAppsHashCode(), 1L, Collections.emptyList()); public static final EurekaHttpClient requestHandler = mock(EurekaHttpClient.class); public static SimpleEurekaHttpServer eurekaHttpServer; @BeforeClass public static void setupClass() throws IOException { eurekaHttpServer = new SimpleEurekaHttpServer(requestHandler); when(requestHandler.getApplications()).thenReturn( anEurekaHttpResponse(500, APPLICATIONS).type(MediaType.APPLICATION_JSON_TYPE).build() ); when(requestHandler.getDelta()).thenReturn( anEurekaHttpResponse(500, APPLICATIONS_DELTA).type(MediaType.APPLICATION_JSON_TYPE).build() ); } @AfterClass public static void tearDownClass() { if (eurekaHttpServer != null) { eurekaHttpServer.shutdown(); } } private static class LocalEurekaInstanceConfig extends PropertiesInstanceConfig { @Override public String getInstanceId() { return MY_INSTANCE_ID; } @Override public String getAppname() { return MY_APPLICATION_NAME; } @Override public int getLeaseRenewalIntervalInSeconds() { return 1; } } /** * EurekaClientConfig configured to enforce fetch registry at init */ private static class LocalEurekaClientConfig1 extends DefaultEurekaClientConfig { @Override public List<String> getEurekaServerServiceUrls(String myZone) { return singletonList(eurekaHttpServer.getServiceURI().toString()); } @Override public boolean shouldEnforceFetchRegistryAtInit() { return true; } } /** * EurekaClientConfig configured to enforce fetch registry at init but not to fetch registry */ private static class LocalEurekaClientConfig2 extends DefaultEurekaClientConfig { @Override public List<String> getEurekaServerServiceUrls(String myZone) { return singletonList(eurekaHttpServer.getServiceURI().toString()); } @Override public boolean shouldEnforceFetchRegistryAtInit() { return true; } @Override public boolean shouldFetchRegistry() { return false; } } /** * n.b. without a configured backup registry, the default backup registry is set to `NotImplementedRegistryImpl`, * which returns `null` for its list of applications and thus results in a failure to return a successful response * for registry data when used. */ @Test(expected = ProvisionException.class) public void testEnforceFetchRegistryAtInitPrimaryAndBackupFailure() { Injector injector = LifecycleInjector.builder() .withModules( new AbstractModule() { @Override protected void configure() { bind(EurekaInstanceConfig.class).to(LocalEurekaInstanceConfig.class); bind(EurekaClientConfig.class).to(LocalEurekaClientConfig1.class); bind(AbstractDiscoveryClientOptionalArgs.class).to(Jersey1DiscoveryClientOptionalArgs.class).in(Scopes.SINGLETON); bind(EndpointRandomizer.class).toInstance(ResolverUtils::randomize); } } ) .build().createInjector(); LifecycleManager lifecycleManager = injector.getInstance(LifecycleManager.class); try { lifecycleManager.start(); } catch (Exception e) { throw new RuntimeException(e); } // this will throw a Guice ProvisionException for the constructor failure injector.getInstance(EurekaClient.class); } @Test public void testEnforceFetchRegistryAtInitPrimaryFailureAndBackupSuccess() { Injector injector = LifecycleInjector.builder() .withModules( new AbstractModule() { @Override protected void configure() { bind(EurekaInstanceConfig.class).to(LocalEurekaInstanceConfig.class); bind(EurekaClientConfig.class).to(LocalEurekaClientConfig1.class); bind(AbstractDiscoveryClientOptionalArgs.class).to(Jersey1DiscoveryClientOptionalArgs.class).in(Scopes.SINGLETON); bind(EndpointRandomizer.class).toInstance(ResolverUtils::randomize); bind(BackupRegistry.class).toInstance(new MockBackupRegistry()); // returns empty list on registry fetch } } ) .build().createInjector(); LifecycleManager lifecycleManager = injector.getInstance(LifecycleManager.class); try { lifecycleManager.start(); } catch (Exception e) { throw new RuntimeException(e); } // this will not throw a Guice ProvisionException for the constructor failure EurekaClient client = injector.getInstance(EurekaClient.class); Assert.assertNotNull(client); } @Test public void testEnforceFetchRegistryAtInitPrimaryFailureNoop() { Injector injector = LifecycleInjector.builder() .withModules( new AbstractModule() { @Override protected void configure() { bind(EurekaInstanceConfig.class).to(LocalEurekaInstanceConfig.class); bind(EurekaClientConfig.class).to(LocalEurekaClientConfig2.class); bind(AbstractDiscoveryClientOptionalArgs.class).to(Jersey1DiscoveryClientOptionalArgs.class).in(Scopes.SINGLETON); bind(EndpointRandomizer.class).toInstance(ResolverUtils::randomize); } } ) .build().createInjector(); LifecycleManager lifecycleManager = injector.getInstance(LifecycleManager.class); try { lifecycleManager.start(); } catch (Exception e) { throw new RuntimeException(e); } // this will not throw a Guice ProvisionException for the constructor failure EurekaClient client = injector.getInstance(EurekaClient.class); Assert.assertNotNull(client); } }
6,622
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/BackUpRegistryTest.java
package com.netflix.discovery; import javax.annotation.Nullable; import java.util.List; import java.util.UUID; import com.google.inject.util.Providers; import com.netflix.appinfo.AmazonInfo; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.MyDataCenterInstanceConfig; import com.netflix.config.ConfigurationManager; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.shared.resolver.ResolverUtils; import org.junit.After; import org.junit.Assert; import org.junit.Test; /** * @author Nitesh Kant */ public class BackUpRegistryTest { public static final String ALL_REGIONS_VIP_ADDR = "myvip"; public static final String REMOTE_REGION_INSTANCE_1_HOSTNAME = "blah"; public static final String REMOTE_REGION_INSTANCE_2_HOSTNAME = "blah2"; public static final String LOCAL_REGION_APP_NAME = "MYAPP_LOC"; public static final String LOCAL_REGION_INSTANCE_1_HOSTNAME = "blahloc"; public static final String LOCAL_REGION_INSTANCE_2_HOSTNAME = "blahloc2"; public static final String REMOTE_REGION_APP_NAME = "MYAPP"; public static final String REMOTE_REGION = "myregion"; public static final String REMOTE_ZONE = "myzone"; public static final int CLIENT_REFRESH_RATE = 10; public static final int NOT_AVAILABLE_EUREKA_PORT = 756473; private EurekaClient client; private MockBackupRegistry backupRegistry; public void setUp(boolean enableRemote) throws Exception { ConfigurationManager.getConfigInstance().setProperty("eureka.client.refresh.interval", CLIENT_REFRESH_RATE); ConfigurationManager.getConfigInstance().setProperty("eureka.registration.enabled", "false"); if (enableRemote) { ConfigurationManager.getConfigInstance().setProperty("eureka.fetchRemoteRegionsRegistry", REMOTE_REGION); } ConfigurationManager.getConfigInstance().setProperty("eureka.myregion.availabilityZones", REMOTE_ZONE); ConfigurationManager.getConfigInstance().setProperty("eureka.backupregistry", MockBackupRegistry.class.getName()); ConfigurationManager.getConfigInstance().setProperty("eureka.serviceUrl.default", "http://localhost:" + NOT_AVAILABLE_EUREKA_PORT /*Should always be unavailable*/ + MockRemoteEurekaServer.EUREKA_API_BASE_PATH); InstanceInfo.Builder builder = InstanceInfo.Builder.newBuilder(); builder.setIPAddr("10.10.101.00"); builder.setHostName("Hosttt"); builder.setAppName("EurekaTestApp-" + UUID.randomUUID()); builder.setDataCenterInfo(new DataCenterInfo() { @Override public Name getName() { return Name.MyOwn; } }); ApplicationInfoManager applicationInfoManager = new ApplicationInfoManager(new MyDataCenterInstanceConfig(), builder.build()); backupRegistry = new MockBackupRegistry(); setupBackupMock(); client = new DiscoveryClient( applicationInfoManager, new DefaultEurekaClientConfig(), null, Providers.of((BackupRegistry)backupRegistry), ResolverUtils::randomize ); } @After public void tearDown() throws Exception { client.shutdown(); ConfigurationManager.getConfigInstance().clear(); } @Test public void testLocalOnly() throws Exception { setUp(false); Applications applications = client.getApplications(); List<Application> registeredApplications = applications.getRegisteredApplications(); System.out.println("***" + registeredApplications); Assert.assertNotNull("Local region apps not found.", registeredApplications); Assert.assertEquals("Local apps size not as expected.", 1, registeredApplications.size()); Assert.assertEquals("Local region apps not present.", LOCAL_REGION_APP_NAME, registeredApplications.get(0).getName()); } @Test public void testRemoteEnabledButLocalOnlyQueried() throws Exception { setUp(true); Applications applications = client.getApplications(); List<Application> registeredApplications = applications.getRegisteredApplications(); Assert.assertNotNull("Local region apps not found.", registeredApplications); Assert.assertEquals("Local apps size not as expected.", 2, registeredApplications.size()); // Remote region comes with no instances. Application localRegionApp = null; Application remoteRegionApp = null; for (Application registeredApplication : registeredApplications) { if (registeredApplication.getName().equals(LOCAL_REGION_APP_NAME)) { localRegionApp = registeredApplication; } else if (registeredApplication.getName().equals(REMOTE_REGION_APP_NAME)) { remoteRegionApp = registeredApplication; } } Assert.assertNotNull("Local region apps not present.", localRegionApp); Assert.assertTrue("Remote region instances returned for local query.", null == remoteRegionApp || remoteRegionApp.getInstances().isEmpty()); } @Test public void testRemoteEnabledAndQueried() throws Exception { setUp(true); Applications applications = client.getApplicationsForARegion(REMOTE_REGION); List<Application> registeredApplications = applications.getRegisteredApplications(); Assert.assertNotNull("Remote region apps not found.", registeredApplications); Assert.assertEquals("Remote apps size not as expected.", 1, registeredApplications.size()); Assert.assertEquals("Remote region apps not present.", REMOTE_REGION_APP_NAME, registeredApplications.get(0).getName()); } @Test public void testAppsHashCode() throws Exception { setUp(true); Applications applications = client.getApplications(); Assert.assertEquals("UP_1_", applications.getAppsHashCode()); } private void setupBackupMock() { Application localApp = createLocalApps(); Applications localApps = new Applications(); localApps.addApplication(localApp); backupRegistry.setLocalRegionApps(localApps); Application remoteApp = createRemoteApps(); Applications remoteApps = new Applications(); remoteApps.addApplication(remoteApp); backupRegistry.getRemoteRegionVsApps().put(REMOTE_REGION, remoteApps); } private Application createLocalApps() { Application myapp = new Application(LOCAL_REGION_APP_NAME); InstanceInfo instanceInfo = createLocalInstance(LOCAL_REGION_INSTANCE_1_HOSTNAME); myapp.addInstance(instanceInfo); return myapp; } private Application createRemoteApps() { Application myapp = new Application(REMOTE_REGION_APP_NAME); InstanceInfo instanceInfo = createRemoteInstance(REMOTE_REGION_INSTANCE_1_HOSTNAME); myapp.addInstance(instanceInfo); return myapp; } private InstanceInfo createRemoteInstance(String instanceHostName) { InstanceInfo.Builder instanceBuilder = InstanceInfo.Builder.newBuilder(); instanceBuilder.setAppName(REMOTE_REGION_APP_NAME); instanceBuilder.setVIPAddress(ALL_REGIONS_VIP_ADDR); instanceBuilder.setHostName(instanceHostName); instanceBuilder.setIPAddr("10.10.101.1"); AmazonInfo amazonInfo = getAmazonInfo(REMOTE_ZONE, instanceHostName); instanceBuilder.setDataCenterInfo(amazonInfo); instanceBuilder.setMetadata(amazonInfo.getMetadata()); return instanceBuilder.build(); } private InstanceInfo createLocalInstance(String instanceHostName) { InstanceInfo.Builder instanceBuilder = InstanceInfo.Builder.newBuilder(); instanceBuilder.setAppName(LOCAL_REGION_APP_NAME); instanceBuilder.setVIPAddress(ALL_REGIONS_VIP_ADDR); instanceBuilder.setHostName(instanceHostName); instanceBuilder.setIPAddr("10.10.101.1"); AmazonInfo amazonInfo = getAmazonInfo(null, instanceHostName); instanceBuilder.setDataCenterInfo(amazonInfo); instanceBuilder.setMetadata(amazonInfo.getMetadata()); return instanceBuilder.build(); } private AmazonInfo getAmazonInfo(@Nullable String availabilityZone, String instanceHostName) { AmazonInfo.Builder azBuilder = AmazonInfo.Builder.newBuilder(); azBuilder.addMetadata(AmazonInfo.MetaDataKey.availabilityZone, (null == availabilityZone) ? "us-east-1a" : availabilityZone); azBuilder.addMetadata(AmazonInfo.MetaDataKey.instanceId, instanceHostName); azBuilder.addMetadata(AmazonInfo.MetaDataKey.amiId, "XXX"); azBuilder.addMetadata(AmazonInfo.MetaDataKey.instanceType, "XXX"); azBuilder.addMetadata(AmazonInfo.MetaDataKey.localIpv4, "XXX"); azBuilder.addMetadata(AmazonInfo.MetaDataKey.publicIpv4, "XXX"); azBuilder.addMetadata(AmazonInfo.MetaDataKey.publicHostname, instanceHostName); return azBuilder.build(); } }
6,623
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/DiscoveryClientRedirectTest.java
package com.netflix.discovery; import javax.ws.rs.core.MediaType; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.converters.EntityBodyConverter; import com.netflix.discovery.junit.resource.DiscoveryClientResource; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.util.EurekaEntityFunctions; import com.netflix.discovery.util.InstanceInfoGenerator; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.mockserver.client.server.MockServerClient; import org.mockserver.junit.MockServerRule; import org.mockserver.matchers.Times; import org.mockserver.model.Header; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.verify.VerificationTimes.atLeast; import static org.mockserver.verify.VerificationTimes.exactly; /** * @author Tomasz Bak */ public class DiscoveryClientRedirectTest { static class MockClientHolder { MockServerClient client; } private final InstanceInfo myInstanceInfo = InstanceInfoGenerator.takeOne(); @Rule public MockServerRule redirectServerMockRule = new MockServerRule(this); private MockServerClient redirectServerMockClient; private MockClientHolder targetServerMockClient = new MockClientHolder(); @Rule public MockServerRule targetServerMockRule = new MockServerRule(targetServerMockClient); @Rule public DiscoveryClientResource registryFetchClientRule = DiscoveryClientResource.newBuilder() .withRegistration(false) .withRegistryFetch(true) .withPortResolver(new Callable<Integer>() { @Override public Integer call() throws Exception { return redirectServerMockRule.getHttpPort(); } }) .withInstanceInfo(myInstanceInfo) .build(); @Rule public DiscoveryClientResource registeringClientRule = DiscoveryClientResource.newBuilder() .withRegistration(true) .withRegistryFetch(false) .withPortResolver(new Callable<Integer>() { @Override public Integer call() throws Exception { return redirectServerMockRule.getHttpPort(); } }) .withInstanceInfo(myInstanceInfo) .build(); private String targetServerBaseUri; private final InstanceInfoGenerator dataGenerator = InstanceInfoGenerator.newBuilder(2, 1).withMetaData(true).build(); @Before public void setUp() throws Exception { targetServerBaseUri = "http://localhost:" + targetServerMockRule.getHttpPort(); } @After public void tearDown() { if (redirectServerMockClient != null) { redirectServerMockClient.reset(); } if (targetServerMockClient.client != null) { targetServerMockClient.client.reset(); } } @Test public void testClientQueryFollowsRedirectsAndPinsToTargetServer() throws Exception { Applications fullFetchApps = dataGenerator.takeDelta(1); String fullFetchJson = toJson(fullFetchApps); Applications deltaFetchApps = dataGenerator.takeDelta(1); String deltaFetchJson = toJson(deltaFetchApps); redirectServerMockClient.when( request() .withMethod("GET") .withPath("/eureka/v2/apps/") ).respond( response() .withStatusCode(302) .withHeader(new Header("Location", targetServerBaseUri + "/eureka/v2/apps/")) ); targetServerMockClient.client.when( request() .withMethod("GET") .withPath("/eureka/v2/apps/") ).respond( response() .withStatusCode(200) .withHeader(new Header("Content-Type", "application/json")) .withBody(fullFetchJson) ); targetServerMockClient.client.when( request() .withMethod("GET") .withPath("/eureka/v2/apps/delta") ).respond( response() .withStatusCode(200) .withHeader(new Header("Content-Type", "application/json")) .withBody(deltaFetchJson) ); final EurekaClient client = registryFetchClientRule.getClient(); await(new Callable<Boolean>() { @Override public Boolean call() throws Exception { List<Application> applicationList = client.getApplications().getRegisteredApplications(); return !applicationList.isEmpty() && applicationList.get(0).getInstances().size() == 2; } }, 1, TimeUnit.MINUTES); redirectServerMockClient.verify(request().withMethod("GET").withPath("/eureka/v2/apps/"), exactly(1)); redirectServerMockClient.verify(request().withMethod("GET").withPath("/eureka/v2/apps/delta"), exactly(0)); targetServerMockClient.client.verify(request().withMethod("GET").withPath("/eureka/v2/apps/"), exactly(1)); targetServerMockClient.client.verify(request().withMethod("GET").withPath("/eureka/v2/apps/delta"), atLeast(1)); } // There is an issue with using mock-server for this test case. For now it is verified manually that it works. @Ignore @Test public void testClientRegistrationFollowsRedirectsAndPinsToTargetServer() throws Exception { } @Test public void testClientFallsBackToOriginalServerOnError() throws Exception { Applications fullFetchApps1 = dataGenerator.takeDelta(1); String fullFetchJson1 = toJson(fullFetchApps1); Applications fullFetchApps2 = EurekaEntityFunctions.mergeApplications(fullFetchApps1, dataGenerator.takeDelta(1)); String fullFetchJson2 = toJson(fullFetchApps2); redirectServerMockClient.when( request() .withMethod("GET") .withPath("/eureka/v2/apps/") ).respond( response() .withStatusCode(302) .withHeader(new Header("Location", targetServerBaseUri + "/eureka/v2/apps/")) ); targetServerMockClient.client.when( request() .withMethod("GET") .withPath("/eureka/v2/apps/"), Times.exactly(1) ).respond( response() .withStatusCode(200) .withHeader(new Header("Content-Type", "application/json")) .withBody(fullFetchJson1) ); targetServerMockClient.client.when( request() .withMethod("GET") .withPath("/eureka/v2/apps/delta"), Times.exactly(1) ).respond( response() .withStatusCode(500) ); redirectServerMockClient.when( request() .withMethod("GET") .withPath("/eureka/v2/apps/delta") ).respond( response() .withStatusCode(200) .withHeader(new Header("Content-Type", "application/json")) .withBody(fullFetchJson2) ); final EurekaClient client = registryFetchClientRule.getClient(); await(new Callable<Boolean>() { @Override public Boolean call() throws Exception { List<Application> applicationList = client.getApplications().getRegisteredApplications(); return !applicationList.isEmpty() && applicationList.get(0).getInstances().size() == 2; } }, 1, TimeUnit.MINUTES); redirectServerMockClient.verify(request().withMethod("GET").withPath("/eureka/v2/apps/"), exactly(1)); redirectServerMockClient.verify(request().withMethod("GET").withPath("/eureka/v2/apps/delta"), exactly(1)); targetServerMockClient.client.verify(request().withMethod("GET").withPath("/eureka/v2/apps/"), exactly(1)); targetServerMockClient.client.verify(request().withMethod("GET").withPath("/eureka/v2/apps/delta"), exactly(1)); } private static String toJson(Applications applications) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); new EntityBodyConverter().write(applications, os, MediaType.APPLICATION_JSON_TYPE); os.close(); return os.toString(); } private static void await(Callable<Boolean> condition, long time, TimeUnit timeUnit) throws Exception { long timeout = System.currentTimeMillis() + timeUnit.toMillis(time); while (!condition.call()) { if (System.currentTimeMillis() >= timeout) { throw new TimeoutException(); } Thread.sleep(100); } } }
6,624
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/DiscoveryClientRegistryTest.java
package com.netflix.discovery; import javax.ws.rs.core.MediaType; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.InstanceStatus; import com.netflix.discovery.junit.resource.DiscoveryClientResource; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.EurekaHttpResponse; import com.netflix.discovery.shared.transport.SimpleEurekaHttpServer; import com.netflix.discovery.util.InstanceInfoGenerator; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import static com.netflix.discovery.shared.transport.EurekaHttpResponse.anEurekaHttpResponse; import static com.netflix.discovery.util.EurekaEntityFunctions.copyApplications; import static com.netflix.discovery.util.EurekaEntityFunctions.countInstances; import static com.netflix.discovery.util.EurekaEntityFunctions.mergeApplications; import static com.netflix.discovery.util.EurekaEntityFunctions.takeFirst; import static com.netflix.discovery.util.EurekaEntityFunctions.toApplications; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * @author Nitesh Kant */ public class DiscoveryClientRegistryTest { private static final String TEST_LOCAL_REGION = "us-east-1"; private static final String TEST_REMOTE_REGION = "us-west-2"; private static final String TEST_REMOTE_ZONE = "us-west-2c"; private static final EurekaHttpClient requestHandler = mock(EurekaHttpClient.class); private static SimpleEurekaHttpServer eurekaHttpServer; @Rule public DiscoveryClientResource discoveryClientResource = DiscoveryClientResource.newBuilder() .withRegistration(false) .withRegistryFetch(true) .withRemoteRegions(TEST_REMOTE_REGION) .connectWith(eurekaHttpServer) .build(); /** * Share server stub by all tests. */ @BeforeClass public static void setUpClass() throws IOException { eurekaHttpServer = new SimpleEurekaHttpServer(requestHandler); } @AfterClass public static void tearDownClass() throws Exception { if (eurekaHttpServer != null) { eurekaHttpServer.shutdown(); } } @Before public void setUp() throws Exception { reset(requestHandler); when(requestHandler.cancel(anyString(), anyString())).thenReturn(EurekaHttpResponse.status(200)); when(requestHandler.getDelta()).thenReturn( anEurekaHttpResponse(200, new Applications()).type(MediaType.APPLICATION_JSON_TYPE).build() ); } @Test public void testGetByVipInLocalRegion() throws Exception { Applications applications = InstanceInfoGenerator.newBuilder(4, "app1", "app2").build().toApplications(); InstanceInfo instance = applications.getRegisteredApplications("app1").getInstances().get(0); when(requestHandler.getApplications(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, applications).type(MediaType.APPLICATION_JSON_TYPE).build() ); List<InstanceInfo> result = discoveryClientResource.getClient().getInstancesByVipAddress(instance.getVIPAddress(), false); assertThat(result.size(), is(equalTo(2))); assertThat(result.get(0).getVIPAddress(), is(equalTo(instance.getVIPAddress()))); } @Test public void testGetAllKnownRegions() throws Exception { prepareRemoteRegionRegistry(); EurekaClient client = discoveryClientResource.getClient(); Set<String> allKnownRegions = client.getAllKnownRegions(); assertThat(allKnownRegions.size(), is(equalTo(2))); assertThat(allKnownRegions, hasItem(TEST_REMOTE_REGION)); } @Test public void testAllAppsForRegions() throws Exception { prepareRemoteRegionRegistry(); EurekaClient client = discoveryClientResource.getClient(); Applications appsForRemoteRegion = client.getApplicationsForARegion(TEST_REMOTE_REGION); assertThat(countInstances(appsForRemoteRegion), is(equalTo(4))); Applications appsForLocalRegion = client.getApplicationsForARegion(TEST_LOCAL_REGION); assertThat(countInstances(appsForLocalRegion), is(equalTo(4))); } @Test public void testCacheRefreshSingleAppForLocalRegion() throws Exception { InstanceInfoGenerator instanceGen = InstanceInfoGenerator.newBuilder(2, "testApp").build(); Applications initialApps = instanceGen.takeDelta(1); String vipAddress = initialApps.getRegisteredApplications().get(0).getInstances().get(0).getVIPAddress(); DiscoveryClientResource vipClientResource = discoveryClientResource.fork().withVipFetch(vipAddress).build(); // Take first portion when(requestHandler.getVip(vipAddress, TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, initialApps).type(MediaType.APPLICATION_JSON_TYPE).build() ); EurekaClient vipClient = vipClientResource.getClient(); assertThat(countInstances(vipClient.getApplications()), is(equalTo(1))); // Now second one when(requestHandler.getVip(vipAddress, TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, instanceGen.toApplications()).type(MediaType.APPLICATION_JSON_TYPE).build() ); assertThat(vipClientResource.awaitCacheUpdate(5, TimeUnit.SECONDS), is(true)); assertThat(countInstances(vipClient.getApplications()), is(equalTo(2))); } @Test public void testEurekaClientPeriodicHeartbeat() throws Exception { DiscoveryClientResource registeringClientResource = discoveryClientResource.fork().withRegistration(true).withRegistryFetch(false).build(); InstanceInfo instance = registeringClientResource.getMyInstanceInfo(); when(requestHandler.register(any(InstanceInfo.class))).thenReturn(EurekaHttpResponse.status(204)); when(requestHandler.sendHeartBeat(instance.getAppName(), instance.getId(), null, null)).thenReturn(anEurekaHttpResponse(200, InstanceInfo.class).build()); registeringClientResource.getClient(); // Initialize verify(requestHandler, timeout(5 * 1000).atLeast(2)).sendHeartBeat(instance.getAppName(), instance.getId(), null, null); } @Test public void testEurekaClientPeriodicCacheRefresh() throws Exception { InstanceInfoGenerator instanceGen = InstanceInfoGenerator.newBuilder(3, 1).build(); Applications initialApps = instanceGen.takeDelta(1); // Full fetch when(requestHandler.getApplications(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, initialApps).type(MediaType.APPLICATION_JSON_TYPE).build() ); EurekaClient client = discoveryClientResource.getClient(); assertThat(countInstances(client.getApplications()), is(equalTo(1))); // Delta 1 when(requestHandler.getDelta(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, instanceGen.takeDelta(1)).type(MediaType.APPLICATION_JSON_TYPE).build() ); assertThat(discoveryClientResource.awaitCacheUpdate(5, TimeUnit.SECONDS), is(true)); // Delta 2 when(requestHandler.getDelta(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, instanceGen.takeDelta(1)).type(MediaType.APPLICATION_JSON_TYPE).build() ); assertThat(discoveryClientResource.awaitCacheUpdate(5, TimeUnit.SECONDS), is(true)); assertThat(countInstances(client.getApplications()), is(equalTo(3))); } @Test public void testGetInvalidVIP() throws Exception { Applications applications = InstanceInfoGenerator.newBuilder(1, "testApp").build().toApplications(); when(requestHandler.getApplications(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, applications).type(MediaType.APPLICATION_JSON_TYPE).build() ); EurekaClient client = discoveryClientResource.getClient(); assertThat(countInstances(client.getApplications()), is(equalTo(1))); List<InstanceInfo> instancesByVipAddress = client.getInstancesByVipAddress("XYZ", false); assertThat(instancesByVipAddress.isEmpty(), is(true)); } @Test public void testGetInvalidVIPForRemoteRegion() throws Exception { prepareRemoteRegionRegistry(); EurekaClient client = discoveryClientResource.getClient(); List<InstanceInfo> instancesByVipAddress = client.getInstancesByVipAddress("XYZ", false, TEST_REMOTE_REGION); assertThat(instancesByVipAddress.isEmpty(), is(true)); } @Test public void testGetByVipInRemoteRegion() throws Exception { prepareRemoteRegionRegistry(); EurekaClient client = discoveryClientResource.getClient(); String vipAddress = takeFirst(client.getApplicationsForARegion(TEST_REMOTE_REGION)).getVIPAddress(); List<InstanceInfo> instancesByVipAddress = client.getInstancesByVipAddress(vipAddress, false, TEST_REMOTE_REGION); assertThat(instancesByVipAddress.size(), is(equalTo(2))); InstanceInfo instance = instancesByVipAddress.iterator().next(); assertThat(instance.getVIPAddress(), is(equalTo(vipAddress))); } @Test public void testAppsHashCodeAfterRefresh() throws Exception { InstanceInfoGenerator instanceGen = InstanceInfoGenerator.newBuilder(2, "testApp").build(); // Full fetch with one item InstanceInfo first = instanceGen.first(); Applications initial = toApplications(first); when(requestHandler.getApplications(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, initial).type(MediaType.APPLICATION_JSON_TYPE).build() ); EurekaClient client = discoveryClientResource.getClient(); assertThat(client.getApplications().getAppsHashCode(), is(equalTo("UP_1_"))); // Delta with one add InstanceInfo second = new InstanceInfo.Builder(instanceGen.take(1)).setStatus(InstanceStatus.DOWN).build(); Applications delta = toApplications(second); delta.setAppsHashCode("DOWN_1_UP_1_"); when(requestHandler.getDelta(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, delta).type(MediaType.APPLICATION_JSON_TYPE).build() ); assertThat(discoveryClientResource.awaitCacheUpdate(5, TimeUnit.SECONDS), is(true)); assertThat(client.getApplications().getAppsHashCode(), is(equalTo("DOWN_1_UP_1_"))); } @Test public void testApplyDeltaWithBadInstanceInfoDataCenterInfoAsNull() throws Exception { InstanceInfoGenerator instanceGen = InstanceInfoGenerator.newBuilder(2, "testApp").build(); // Full fetch with one item InstanceInfo first = instanceGen.first(); Applications initial = toApplications(first); when(requestHandler.getApplications(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, initial).type(MediaType.APPLICATION_JSON_TYPE).build() ); EurekaClient client = discoveryClientResource.getClient(); assertThat(client.getApplications().getAppsHashCode(), is(equalTo("UP_1_"))); // Delta with one add InstanceInfo second = new InstanceInfo.Builder(instanceGen.take(1)).setInstanceId("foo1").setStatus(InstanceStatus.DOWN).setDataCenterInfo(null).build(); InstanceInfo third = new InstanceInfo.Builder(instanceGen.take(1)).setInstanceId("foo2").setStatus(InstanceStatus.UP).setDataCenterInfo(new DataCenterInfo() { @Override public Name getName() { return null; } }).build(); Applications delta = toApplications(second, third); delta.setAppsHashCode("DOWN_1_UP_2_"); when(requestHandler.getDelta(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, delta).type(MediaType.APPLICATION_JSON_TYPE).build() ); assertThat(discoveryClientResource.awaitCacheUpdate(5, TimeUnit.SECONDS), is(true)); assertThat(client.getApplications().getAppsHashCode(), is(equalTo("DOWN_1_UP_2_"))); } @Test public void testEurekaClientPeriodicCacheRefreshForDelete() throws Exception { InstanceInfoGenerator instanceGen = InstanceInfoGenerator.newBuilder(3, 1).build(); Applications initialApps = instanceGen.takeDelta(2); Applications deltaForDelete = instanceGen.takeDeltaForDelete(true, 1); when(requestHandler.getApplications(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, initialApps).type(MediaType.APPLICATION_JSON_TYPE).build() ); EurekaClient client = discoveryClientResource.getClient(); assertThat(countInstances(client.getApplications()), is(equalTo(2))); when(requestHandler.getDelta(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, deltaForDelete).type(MediaType.APPLICATION_JSON_TYPE).build() ); assertThat(discoveryClientResource.awaitCacheUpdate(5, TimeUnit.SECONDS), is(true)); assertThat(client.getApplications().getRegisteredApplications().size(), is(equalTo(1))); assertThat(countInstances(client.getApplications()), is(equalTo(1))); } @Test public void testEurekaClientPeriodicCacheRefreshForDeleteAndNoApplication() throws Exception { InstanceInfoGenerator instanceGen = InstanceInfoGenerator.newBuilder(3, 1).build(); Applications initialApps = instanceGen.takeDelta(1); Applications deltaForDelete = instanceGen.takeDeltaForDelete(true, 1); when(requestHandler.getApplications(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, initialApps).type(MediaType.APPLICATION_JSON_TYPE).build() ); EurekaClient client = discoveryClientResource.getClient(); assertThat(countInstances(client.getApplications()), is(equalTo(1))); when(requestHandler.getDelta(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, deltaForDelete).type(MediaType.APPLICATION_JSON_TYPE).build() ); assertThat(discoveryClientResource.awaitCacheUpdate(5, TimeUnit.SECONDS), is(true)); assertEquals(client.getApplications().getRegisteredApplications(), new ArrayList<>()); } /** * There is a bug, because of which remote registry data structures are not initialized during full registry fetch, only during delta. */ private void prepareRemoteRegionRegistry() throws Exception { Applications localApplications = InstanceInfoGenerator.newBuilder(4, "app1", "app2").build().toApplications(); Applications remoteApplications = InstanceInfoGenerator.newBuilder(4, "remote1", "remote2").withZone(TEST_REMOTE_ZONE).build().toApplications(); Applications allApplications = mergeApplications(localApplications, remoteApplications); // Load remote data in delta, to go around exiting bug in DiscoveryClient Applications delta = copyApplications(remoteApplications); delta.setAppsHashCode(allApplications.getAppsHashCode()); when(requestHandler.getApplications(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, localApplications).type(MediaType.APPLICATION_JSON_TYPE).build() ); when(requestHandler.getDelta(TEST_REMOTE_REGION)).thenReturn( anEurekaHttpResponse(200, delta).type(MediaType.APPLICATION_JSON_TYPE).build() ); assertThat(discoveryClientResource.awaitCacheUpdate(5, TimeUnit.SECONDS), is(true)); } }
6,625
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/AbstractDiscoveryClientTester.java
package com.netflix.discovery; import com.netflix.discovery.junit.resource.DiscoveryClientResource; import org.junit.After; import org.junit.Before; /** * @author Nitesh Kant */ public abstract class AbstractDiscoveryClientTester extends BaseDiscoveryClientTester { @Before public void setUp() throws Exception { setupProperties(); populateLocalRegistryAtStartup(); populateRemoteRegistryAtStartup(); setupDiscoveryClient(); } @After public void tearDown() throws Exception { shutdownDiscoveryClient(); DiscoveryClientResource.clearDiscoveryClientConfig(); } }
6,626
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/InstanceRegionCheckerTest.java
package com.netflix.discovery; import com.netflix.appinfo.AmazonInfo; import com.netflix.appinfo.InstanceInfo; import com.netflix.config.ConfigurationManager; import org.junit.Assert; import org.junit.Test; /** * @author Nitesh Kant */ public class InstanceRegionCheckerTest { @Test public void testDefaults() throws Exception { PropertyBasedAzToRegionMapper azToRegionMapper = new PropertyBasedAzToRegionMapper( new DefaultEurekaClientConfig()); InstanceRegionChecker checker = new InstanceRegionChecker(azToRegionMapper, "us-east-1"); azToRegionMapper.setRegionsToFetch(new String[]{"us-east-1"}); AmazonInfo dcInfo = AmazonInfo.Builder.newBuilder().addMetadata(AmazonInfo.MetaDataKey.availabilityZone, "us-east-1c").build(); InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder().setAppName("app").setDataCenterInfo(dcInfo).build(); String instanceRegion = checker.getInstanceRegion(instanceInfo); Assert.assertEquals("Invalid instance region.", "us-east-1", instanceRegion); } @Test public void testDefaultOverride() throws Exception { ConfigurationManager.getConfigInstance().setProperty("eureka.us-east-1.availabilityZones", "abc,def"); PropertyBasedAzToRegionMapper azToRegionMapper = new PropertyBasedAzToRegionMapper(new DefaultEurekaClientConfig()); InstanceRegionChecker checker = new InstanceRegionChecker(azToRegionMapper, "us-east-1"); azToRegionMapper.setRegionsToFetch(new String[]{"us-east-1"}); AmazonInfo dcInfo = AmazonInfo.Builder.newBuilder().addMetadata(AmazonInfo.MetaDataKey.availabilityZone, "def").build(); InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder().setAppName("app").setDataCenterInfo( dcInfo).build(); String instanceRegion = checker.getInstanceRegion(instanceInfo); Assert.assertEquals("Invalid instance region.", "us-east-1", instanceRegion); } @Test public void testInstanceWithNoAZ() throws Exception { ConfigurationManager.getConfigInstance().setProperty("eureka.us-east-1.availabilityZones", "abc,def"); PropertyBasedAzToRegionMapper azToRegionMapper = new PropertyBasedAzToRegionMapper(new DefaultEurekaClientConfig()); InstanceRegionChecker checker = new InstanceRegionChecker(azToRegionMapper, "us-east-1"); azToRegionMapper.setRegionsToFetch(new String[]{"us-east-1"}); AmazonInfo dcInfo = AmazonInfo.Builder.newBuilder().addMetadata(AmazonInfo.MetaDataKey.availabilityZone, "").build(); InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder().setAppName("app").setDataCenterInfo( dcInfo).build(); String instanceRegion = checker.getInstanceRegion(instanceInfo); Assert.assertNull("Invalid instance region.", instanceRegion); } @Test public void testNotMappedAZ() throws Exception { ConfigurationManager.getConfigInstance().setProperty("eureka.us-east-1.availabilityZones", "abc,def"); PropertyBasedAzToRegionMapper azToRegionMapper = new PropertyBasedAzToRegionMapper(new DefaultEurekaClientConfig()); InstanceRegionChecker checker = new InstanceRegionChecker(azToRegionMapper, "us-east-1"); azToRegionMapper.setRegionsToFetch(new String[]{"us-east-1"}); AmazonInfo dcInfo = AmazonInfo.Builder.newBuilder().addMetadata(AmazonInfo.MetaDataKey.availabilityZone, "us-east-1x").build(); InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder().setAppName("abc").setDataCenterInfo(dcInfo).build(); String instanceRegion = checker.getInstanceRegion(instanceInfo); Assert.assertEquals("Invalid instance region.", "us-east-1", instanceRegion); } @Test public void testNotMappedAZNotFollowingFormat() throws Exception { ConfigurationManager.getConfigInstance().setProperty("eureka.us-east-1.availabilityZones", "abc,def"); PropertyBasedAzToRegionMapper azToRegionMapper = new PropertyBasedAzToRegionMapper(new DefaultEurekaClientConfig()); InstanceRegionChecker checker = new InstanceRegionChecker(azToRegionMapper, "us-east-1"); azToRegionMapper.setRegionsToFetch(new String[]{"us-east-1"}); AmazonInfo dcInfo = AmazonInfo.Builder.newBuilder().addMetadata(AmazonInfo.MetaDataKey.availabilityZone, "us-east-x").build(); InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder().setAppName("abc").setDataCenterInfo(dcInfo).build(); String instanceRegion = checker.getInstanceRegion(instanceInfo); Assert.assertNull("Invalid instance region.", instanceRegion); } }
6,627
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/DiscoveryClientDisableRegistryTest.java
package com.netflix.discovery; import java.util.UUID; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.MyDataCenterInstanceConfig; import com.netflix.config.ConfigurationManager; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * @author Nitesh Kant */ public class DiscoveryClientDisableRegistryTest { private EurekaClient client; private MockRemoteEurekaServer mockLocalEurekaServer; @Before public void setUp() throws Exception { mockLocalEurekaServer = new MockRemoteEurekaServer(); mockLocalEurekaServer.start(); ConfigurationManager.getConfigInstance().setProperty("eureka.registration.enabled", "false"); ConfigurationManager.getConfigInstance().setProperty("eureka.shouldFetchRegistry", "false"); ConfigurationManager.getConfigInstance().setProperty("eureka.serviceUrl.default", "http://localhost:" + mockLocalEurekaServer.getPort() + MockRemoteEurekaServer.EUREKA_API_BASE_PATH); InstanceInfo.Builder builder = InstanceInfo.Builder.newBuilder(); builder.setIPAddr("10.10.101.00"); builder.setHostName("Hosttt"); builder.setAppName("EurekaTestApp-" + UUID.randomUUID()); builder.setDataCenterInfo(new DataCenterInfo() { @Override public Name getName() { return Name.MyOwn; } }); ApplicationInfoManager applicationInfoManager = new ApplicationInfoManager(new MyDataCenterInstanceConfig(), builder.build()); client = new DiscoveryClient(applicationInfoManager, new DefaultEurekaClientConfig()); } @Test public void testDisableFetchRegistry() throws Exception { Assert.assertFalse("Registry fetch disabled but eureka server recieved a registry fetch.", mockLocalEurekaServer.isSentRegistry()); } }
6,628
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/TimedSupervisorTaskTest.java
package com.netflix.discovery; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class TimedSupervisorTaskTest { private static final int EXP_BACK_OFF_BOUND = 10; private ScheduledExecutorService scheduler; private ListeningExecutorService helperExecutor; private ThreadPoolExecutor executor; private AtomicLong testTaskStartCounter; private AtomicLong testTaskSuccessfulCounter; private AtomicLong testTaskInterruptedCounter; private AtomicLong maxConcurrentTestTasks; private AtomicLong testTaskCounter; @Before public void setUp() { scheduler = Executors.newScheduledThreadPool(4, new ThreadFactoryBuilder() .setNameFormat("DiscoveryClient-%d") .setDaemon(true) .build()); helperExecutor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10)); executor = new ThreadPoolExecutor( 1, // corePoolSize 3, // maxPoolSize 0, // keepAliveTime TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); // use direct handoff testTaskStartCounter = new AtomicLong(0); testTaskSuccessfulCounter = new AtomicLong(0); testTaskInterruptedCounter = new AtomicLong(0); maxConcurrentTestTasks = new AtomicLong(0); testTaskCounter = new AtomicLong(0); } @After public void tearDown() { if (executor != null) { executor.shutdownNow(); } if (helperExecutor != null) { helperExecutor.shutdownNow(); } if (scheduler != null) { scheduler.shutdownNow(); } } @Test public void testSupervisorTaskDefaultSingleTestTaskHappyCase() throws Exception { // testTask should never timeout TestTask testTask = new TestTask(1, false); TimedSupervisorTask supervisorTask = new TimedSupervisorTask("test", scheduler, executor, 5, TimeUnit.SECONDS, EXP_BACK_OFF_BOUND, testTask); helperExecutor.submit(supervisorTask).get(); Assert.assertEquals(1, maxConcurrentTestTasks.get()); Assert.assertEquals(0, testTaskCounter.get()); Assert.assertEquals(1, testTaskStartCounter.get()); Assert.assertEquals(1, testTaskSuccessfulCounter.get()); Assert.assertEquals(0, testTaskInterruptedCounter.get()); } @Test public void testSupervisorTaskCancelsTimedOutTask() throws Exception { // testTask will always timeout TestTask testTask = new TestTask(5, false); TimedSupervisorTask supervisorTask = new TimedSupervisorTask("test", scheduler, executor, 1, TimeUnit.SECONDS, EXP_BACK_OFF_BOUND, testTask); helperExecutor.submit(supervisorTask).get(); Thread.sleep(500); // wait a little bit for the subtask interrupt handler Assert.assertEquals(1, maxConcurrentTestTasks.get()); Assert.assertEquals(1, testTaskCounter.get()); Assert.assertEquals(1, testTaskStartCounter.get()); Assert.assertEquals(0, testTaskSuccessfulCounter.get()); Assert.assertEquals(1, testTaskInterruptedCounter.get()); } @Test public void testSupervisorRejectNewTasksIfThreadPoolIsFullForIncompleteTasks() throws Exception { // testTask should always timeout TestTask testTask = new TestTask(4, true); TimedSupervisorTask supervisorTask = new TimedSupervisorTask("test", scheduler, executor, 1, TimeUnit.MILLISECONDS, EXP_BACK_OFF_BOUND, testTask); scheduler.schedule(supervisorTask, 0, TimeUnit.SECONDS); Thread.sleep(500); // wait a little bit for the subtask interrupt handlers Assert.assertEquals(3, maxConcurrentTestTasks.get()); Assert.assertEquals(3, testTaskCounter.get()); Assert.assertEquals(3, testTaskStartCounter.get()); Assert.assertEquals(0, testTaskSuccessfulCounter.get()); Assert.assertEquals(0, testTaskInterruptedCounter.get()); } @Test public void testSupervisorTaskAsPeriodicScheduledJobHappyCase() throws Exception { // testTask should never timeout TestTask testTask = new TestTask(1, false); TimedSupervisorTask supervisorTask = new TimedSupervisorTask("test", scheduler, executor, 4, TimeUnit.SECONDS, EXP_BACK_OFF_BOUND, testTask); scheduler.schedule(supervisorTask, 0, TimeUnit.SECONDS); Thread.sleep(5000); // let the scheduler run for long enough for some results Assert.assertEquals(1, maxConcurrentTestTasks.get()); Assert.assertEquals(0, testTaskCounter.get()); Assert.assertEquals(0, testTaskInterruptedCounter.get()); } @Test public void testSupervisorTaskAsPeriodicScheduledJobTestTaskTimingOut() throws Exception { // testTask should always timeout TestTask testTask = new TestTask(5, false); TimedSupervisorTask supervisorTask = new TimedSupervisorTask("test", scheduler, executor, 2, TimeUnit.SECONDS, EXP_BACK_OFF_BOUND, testTask); scheduler.schedule(supervisorTask, 0, TimeUnit.SECONDS); Thread.sleep(5000); // let the scheduler run for long enough for some results Assert.assertEquals(1, maxConcurrentTestTasks.get()); Assert.assertTrue(0 != testTaskCounter.get()); // tasks are been cancelled Assert.assertEquals(0, testTaskSuccessfulCounter.get()); } private class TestTask implements Runnable { private final int runTimeSecs; private final boolean blockInterrupt; public TestTask(int runTimeSecs, boolean blockInterrupt) { this.runTimeSecs = runTimeSecs; this.blockInterrupt = blockInterrupt; } public void run() { testTaskStartCounter.incrementAndGet(); try { testTaskCounter.incrementAndGet(); synchronized (maxConcurrentTestTasks) { int activeCount = executor.getActiveCount(); if (maxConcurrentTestTasks.get() < activeCount) { maxConcurrentTestTasks.set(activeCount); } } long endTime = System.currentTimeMillis() + runTimeSecs * 1000; while (endTime >= System.currentTimeMillis()) { try { Thread.sleep(runTimeSecs * 1000); } catch (InterruptedException e) { if (!blockInterrupt) { throw e; } } } testTaskCounter.decrementAndGet(); testTaskSuccessfulCounter.incrementAndGet(); } catch (InterruptedException e) { testTaskInterruptedCounter.incrementAndGet(); } } } }
6,629
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/DiscoveryClientEventBusTest.java
package com.netflix.discovery; import javax.ws.rs.core.MediaType; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.junit.resource.DiscoveryClientResource; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.EurekaHttpResponse; import com.netflix.discovery.shared.transport.SimpleEurekaHttpServer; import com.netflix.discovery.util.InstanceInfoGenerator; import com.netflix.eventbus.spi.EventBus; import com.netflix.eventbus.spi.Subscribe; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import static com.netflix.discovery.shared.transport.EurekaHttpResponse.anEurekaHttpResponse; import static com.netflix.discovery.util.EurekaEntityFunctions.toApplications; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.when; /** * @author David Liu */ public class DiscoveryClientEventBusTest { private static final EurekaHttpClient requestHandler = mock(EurekaHttpClient.class); private static SimpleEurekaHttpServer eurekaHttpServer; @Rule public DiscoveryClientResource discoveryClientResource = DiscoveryClientResource.newBuilder() .withRegistration(false) // we don't need the registration thread for status change .withRegistryFetch(true) .connectWith(eurekaHttpServer) .build(); /** * Share server stub by all tests. */ @BeforeClass public static void setUpClass() throws IOException { eurekaHttpServer = new SimpleEurekaHttpServer(requestHandler); } @AfterClass public static void tearDownClass() throws Exception { if (eurekaHttpServer != null) { eurekaHttpServer.shutdown(); } } @Before public void setUp() throws Exception { reset(requestHandler); when(requestHandler.register(any(InstanceInfo.class))).thenReturn(EurekaHttpResponse.status(204)); when(requestHandler.cancel(anyString(), anyString())).thenReturn(EurekaHttpResponse.status(200)); when(requestHandler.getDelta()).thenReturn( anEurekaHttpResponse(200, new Applications()).type(MediaType.APPLICATION_JSON_TYPE).build() ); } @Test public void testStatusChangeEvent() throws Exception { final CountDownLatch eventLatch = new CountDownLatch(1); final List<StatusChangeEvent> receivedEvents = new ArrayList<>(); EventBus eventBus = discoveryClientResource.getEventBus(); eventBus.registerSubscriber(new Object() { @Subscribe public void consume(StatusChangeEvent event) { receivedEvents.add(event); eventLatch.countDown(); } }); Applications initialApps = toApplications(discoveryClientResource.getMyInstanceInfo()); when(requestHandler.getApplications()).thenReturn( anEurekaHttpResponse(200, initialApps).type(MediaType.APPLICATION_JSON_TYPE).build() ); discoveryClientResource.getClient(); // Activates the client assertThat(eventLatch.await(10, TimeUnit.SECONDS), is(true)); assertThat(receivedEvents.size(), is(equalTo(1))); assertThat(receivedEvents.get(0), is(notNullValue())); } @Test public void testCacheRefreshEvent() throws Exception { InstanceInfoGenerator instanceGen = InstanceInfoGenerator.newBuilder(2, "testApp").build(); // Initial full fetch Applications initialApps = instanceGen.takeDelta(1); when(requestHandler.getApplications()).thenReturn( anEurekaHttpResponse(200, initialApps).type(MediaType.APPLICATION_JSON_TYPE).build() ); discoveryClientResource.getClient(); // Activates the client // Delta update Applications delta = instanceGen.takeDelta(1); when(requestHandler.getDelta()).thenReturn( anEurekaHttpResponse(200, delta).type(MediaType.APPLICATION_JSON_TYPE).build() ); assertThat(discoveryClientResource.awaitCacheUpdate(10, TimeUnit.SECONDS), is(true)); } }
6,630
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/DiscoveryClientHealthTest.java
package com.netflix.discovery; import com.netflix.appinfo.HealthCheckCallback; import com.netflix.appinfo.HealthCheckHandler; import com.netflix.appinfo.InstanceInfo; import com.netflix.config.ConfigurationManager; import org.junit.Assert; import org.junit.Test; import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.stream.Stream; import static java.util.stream.Collectors.toList; import static java.util.stream.IntStream.range; /** * @author Nitesh Kant */ public class DiscoveryClientHealthTest extends AbstractDiscoveryClientTester { @Override protected void setupProperties() { super.setupProperties(); ConfigurationManager.getConfigInstance().setProperty("eureka.registration.enabled", "true"); // as the tests in this class triggers the instanceInfoReplicator explicitly, set the below config // so that it does not run as a background task ConfigurationManager.getConfigInstance().setProperty("eureka.appinfo.initial.replicate.time", Integer.MAX_VALUE); ConfigurationManager.getConfigInstance().setProperty("eureka.appinfo.replicate.interval", Integer.MAX_VALUE); } @Override protected InstanceInfo.Builder newInstanceInfoBuilder(int renewalIntervalInSecs) { InstanceInfo.Builder builder = super.newInstanceInfoBuilder(renewalIntervalInSecs); builder.setStatus(InstanceInfo.InstanceStatus.STARTING); return builder; } @Test public void testCallback() throws Exception { MyHealthCheckCallback myCallback = new MyHealthCheckCallback(true); Assert.assertTrue(client instanceof DiscoveryClient); DiscoveryClient clientImpl = (DiscoveryClient) client; InstanceInfoReplicator instanceInfoReplicator = clientImpl.getInstanceInfoReplicator(); instanceInfoReplicator.run(); Assert.assertEquals("Instance info status not as expected.", InstanceInfo.InstanceStatus.STARTING, clientImpl.getInstanceInfo().getStatus()); Assert.assertFalse("Healthcheck callback invoked when status is STARTING.", myCallback.isInvoked()); client.registerHealthCheckCallback(myCallback); clientImpl.getInstanceInfo().setStatus(InstanceInfo.InstanceStatus.OUT_OF_SERVICE); Assert.assertEquals("Instance info status not as expected.", InstanceInfo.InstanceStatus.OUT_OF_SERVICE, clientImpl.getInstanceInfo().getStatus()); myCallback.reset(); instanceInfoReplicator.run(); Assert.assertFalse("Healthcheck callback invoked when status is OOS.", myCallback.isInvoked()); clientImpl.getInstanceInfo().setStatus(InstanceInfo.InstanceStatus.DOWN); Assert.assertEquals("Instance info status not as expected.", InstanceInfo.InstanceStatus.DOWN, clientImpl.getInstanceInfo().getStatus()); myCallback.reset(); instanceInfoReplicator.run(); Assert.assertTrue("Healthcheck callback not invoked.", myCallback.isInvoked()); Assert.assertEquals("Instance info status not as expected.", InstanceInfo.InstanceStatus.UP, clientImpl.getInstanceInfo().getStatus()); } @Test public void testHandler() throws Exception { MyHealthCheckHandler myHealthCheckHandler = new MyHealthCheckHandler(InstanceInfo.InstanceStatus.UP); Assert.assertTrue(client instanceof DiscoveryClient); DiscoveryClient clientImpl = (DiscoveryClient) client; InstanceInfoReplicator instanceInfoReplicator = clientImpl.getInstanceInfoReplicator(); Assert.assertEquals("Instance info status not as expected.", InstanceInfo.InstanceStatus.STARTING, clientImpl.getInstanceInfo().getStatus()); client.registerHealthCheck(myHealthCheckHandler); instanceInfoReplicator.run(); Assert.assertTrue("Healthcheck callback not invoked when status is STARTING.", myHealthCheckHandler.isInvoked()); Assert.assertEquals("Instance info status not as expected post healthcheck.", InstanceInfo.InstanceStatus.UP, clientImpl.getInstanceInfo().getStatus()); clientImpl.getInstanceInfo().setStatus(InstanceInfo.InstanceStatus.OUT_OF_SERVICE); Assert.assertEquals("Instance info status not as expected.", InstanceInfo.InstanceStatus.OUT_OF_SERVICE, clientImpl.getInstanceInfo().getStatus()); myHealthCheckHandler.reset(); instanceInfoReplicator.run(); Assert.assertTrue("Healthcheck callback not invoked when status is OUT_OF_SERVICE.", myHealthCheckHandler.isInvoked()); Assert.assertEquals("Instance info status not as expected post healthcheck.", InstanceInfo.InstanceStatus.UP, clientImpl.getInstanceInfo().getStatus()); clientImpl.getInstanceInfo().setStatus(InstanceInfo.InstanceStatus.DOWN); Assert.assertEquals("Instance info status not as expected.", InstanceInfo.InstanceStatus.DOWN, clientImpl.getInstanceInfo().getStatus()); myHealthCheckHandler.reset(); instanceInfoReplicator.run(); Assert.assertTrue("Healthcheck callback not invoked when status is DOWN.", myHealthCheckHandler.isInvoked()); Assert.assertEquals("Instance info status not as expected post healthcheck.", InstanceInfo.InstanceStatus.UP, clientImpl.getInstanceInfo().getStatus()); clientImpl.getInstanceInfo().setStatus(InstanceInfo.InstanceStatus.UP); myHealthCheckHandler.reset(); myHealthCheckHandler.shouldException = true; instanceInfoReplicator.run(); Assert.assertTrue("Healthcheck callback not invoked when status is UP.", myHealthCheckHandler.isInvoked()); Assert.assertEquals("Instance info status not as expected post healthcheck.", InstanceInfo.InstanceStatus.DOWN, clientImpl.getInstanceInfo().getStatus()); } @Test public void shouldRegisterHealthCheckHandlerInConcurrentEnvironment() throws Exception { HealthCheckHandler myHealthCheckHandler = new MyHealthCheckHandler(InstanceInfo.InstanceStatus.UP); int testsCount = 20; int threadsCount = testsCount * 2; CountDownLatch starterLatch = new CountDownLatch(threadsCount); CountDownLatch finishLatch = new CountDownLatch(threadsCount); List<DiscoveryClient> discoveryClients = range(0, testsCount) .mapToObj(i -> (DiscoveryClient) getSetupDiscoveryClient()) .collect(toList()); Stream<Thread> registerCustomHandlerThreads = discoveryClients.stream().map(client -> new SimultaneousStarter(starterLatch, finishLatch, () -> client.registerHealthCheck(myHealthCheckHandler))); Stream<Thread> lazyInitOfDefaultHandlerThreads = discoveryClients.stream().map(client -> new SimultaneousStarter(starterLatch, finishLatch, client::getHealthCheckHandler)); List<Thread> threads = Stream.concat(registerCustomHandlerThreads, lazyInitOfDefaultHandlerThreads) .collect(toList()); Collections.shuffle(threads); threads.forEach(Thread::start); try { finishLatch.await(); discoveryClients.forEach(client -> Assert.assertSame("Healthcheck handler should be custom.", myHealthCheckHandler, client.getHealthCheckHandler())); } finally { //cleanup resources discoveryClients.forEach(DiscoveryClient::shutdown); } } public static class SimultaneousStarter extends Thread { private final CountDownLatch starterLatch; private final CountDownLatch finishLatch; private final Runnable runnable; public SimultaneousStarter(CountDownLatch starterLatch, CountDownLatch finishLatch, Runnable runnable) { this.starterLatch = starterLatch; this.finishLatch = finishLatch; this.runnable = runnable; } @Override public void run() { starterLatch.countDown(); try { starterLatch.await(); runnable.run(); finishLatch.countDown(); } catch (InterruptedException e) { throw new RuntimeException("Something went wrong..."); } } } private static class MyHealthCheckCallback implements HealthCheckCallback { private final boolean health; private volatile boolean invoked; private MyHealthCheckCallback(boolean health) { this.health = health; } @Override public boolean isHealthy() { invoked = true; return health; } public boolean isInvoked() { return invoked; } public void reset() { invoked = false; } } private static class MyHealthCheckHandler implements HealthCheckHandler { private final InstanceInfo.InstanceStatus health; private volatile boolean invoked; volatile boolean shouldException; private MyHealthCheckHandler(InstanceInfo.InstanceStatus health) { this.health = health; } public boolean isInvoked() { return invoked; } public void reset() { shouldException = false; invoked = false; } @Override public InstanceInfo.InstanceStatus getStatus(InstanceInfo.InstanceStatus currentStatus) { invoked = true; if (shouldException) { throw new RuntimeException("test induced exception"); } return health; } } }
6,631
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/DiscoveryClientStatsInitFailedTest.java
package com.netflix.discovery; import com.netflix.discovery.junit.resource.DiscoveryClientResource; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * Tests for DiscoveryClient stats reported when initial registry fetch fails. */ public class DiscoveryClientStatsInitFailedTest extends BaseDiscoveryClientTester { @Before public void setUp() throws Exception { setupProperties(); populateRemoteRegistryAtStartup(); setupDiscoveryClient(); } @After public void tearDown() throws Exception { shutdownDiscoveryClient(); DiscoveryClientResource.clearDiscoveryClientConfig(); } @Test public void testEmptyInitLocalRegistrySize() throws Exception { Assert.assertTrue(client instanceof DiscoveryClient); DiscoveryClient clientImpl = (DiscoveryClient) client; Assert.assertEquals(0, clientImpl.getStats().initLocalRegistrySize()); } @Test public void testInitFailed() throws Exception { Assert.assertTrue(client instanceof DiscoveryClient); DiscoveryClient clientImpl = (DiscoveryClient) client; Assert.assertFalse(clientImpl.getStats().initSucceeded()); } }
6,632
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/util/EurekaEntityFunctionsTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery.util; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; public class EurekaEntityFunctionsTest { private Application createSingleInstanceApp( String appId, String instanceId, InstanceInfo.ActionType actionType) { InstanceInfo instanceInfo = Mockito.mock(InstanceInfo.class); Mockito.when(instanceInfo.getId()).thenReturn(instanceId); Mockito.when(instanceInfo.getAppName()).thenReturn(instanceId); Mockito.when(instanceInfo.getStatus()) .thenReturn(InstanceInfo.InstanceStatus.UP); Mockito.when(instanceInfo.getActionType()).thenReturn(actionType); Application application = new Application(appId); application.addInstance(instanceInfo); return application; } private Applications createApplications(Application... applications) { return new Applications("appsHashCode", 1559658285l, new ArrayList<>(Arrays.asList(applications))); } @Test public void testSelectApplicationNamesIfNotNullReturnNameString() { Applications applications = createApplications(new Application("foo"), new Application("bar"), new Application("baz")); HashSet<String> strings = new HashSet<>(Arrays.asList("baz", "bar", "foo")); Assert.assertEquals(strings, EurekaEntityFunctions.selectApplicationNames(applications)); } @Test public void testSelectInstancesMappedByIdIfNotNullReturnMapOfInstances() { Application application = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); HashMap<String, InstanceInfo> hashMap = new HashMap<>(); hashMap.put("foo", application.getByInstanceId("foo")); Assert.assertEquals(hashMap, EurekaEntityFunctions.selectInstancesMappedById(application)); } @Test public void testSelectInstanceIfInstanceExistsReturnSelectedInstance() { Application application = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); Applications applications = createApplications(application); Assert.assertNull(EurekaEntityFunctions .selectInstance(new Applications(), "foo")); Assert.assertNull(EurekaEntityFunctions .selectInstance(new Applications(), "foo", "foo")); Assert.assertEquals(application.getByInstanceId("foo"), EurekaEntityFunctions.selectInstance(applications, "foo")); Assert.assertEquals(application.getByInstanceId("foo"), EurekaEntityFunctions.selectInstance(applications, "foo", "foo")); } @Test public void testTakeFirstIfNotNullReturnFirstInstance() { Application application = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); Applications applications = createApplications(application); applications.addApplication(application); Assert.assertNull(EurekaEntityFunctions.takeFirst(new Applications())); Assert.assertEquals(application.getByInstanceId("foo"), EurekaEntityFunctions.takeFirst(applications)); } @Test public void testSelectAllIfNotNullReturnAllInstances() { Application application = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); Applications applications = createApplications(application); applications.addApplication(application); Assert.assertEquals(new ArrayList<>(Arrays.asList( application.getByInstanceId("foo"), application.getByInstanceId("foo"))), EurekaEntityFunctions.selectAll(applications)); } @Test public void testToApplicationMapIfNotNullReturnMapOfApplication() { Application application = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); Assert.assertEquals(1, EurekaEntityFunctions.toApplicationMap( new ArrayList<>(Arrays.asList( application.getByInstanceId("foo")))).size()); } @Test public void testToApplicationsIfNotNullReturnApplicationsFromMapOfApplication() { HashMap<String, Application> hashMap = new HashMap<>(); hashMap.put("foo", new Application("foo")); hashMap.put("bar", new Application("bar")); hashMap.put("baz", new Application("baz")); Applications applications = createApplications(new Application("foo"), new Application("bar"), new Application("baz")); Assert.assertEquals(applications.size(), EurekaEntityFunctions.toApplications(hashMap).size()); } @Test public void testToApplicationsIfNotNullReturnApplicationsFromInstances() { InstanceInfo instanceInfo1 = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED).getByInstanceId("foo"); InstanceInfo instanceInfo2 = createSingleInstanceApp("bar", "bar", InstanceInfo.ActionType.ADDED).getByInstanceId("bar"); InstanceInfo instanceInfo3 = createSingleInstanceApp("baz", "baz", InstanceInfo.ActionType.ADDED).getByInstanceId("baz"); Assert.assertEquals(3, EurekaEntityFunctions.toApplications( instanceInfo1, instanceInfo2, instanceInfo3).size()); } @Test public void testCopyApplicationsIfNotNullReturnApplications() { Application application1 = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); Application application2 = createSingleInstanceApp("bar", "bar", InstanceInfo.ActionType.ADDED); Applications applications = createApplications(); applications.addApplication(application1); applications.addApplication(application2); Assert.assertEquals(2, EurekaEntityFunctions.copyApplications(applications).size()); } @Test public void testCopyApplicationIfNotNullReturnApplication() { Application application = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); Assert.assertEquals(1, EurekaEntityFunctions.copyApplication(application).size()); } @Test public void testCopyInstancesIfNotNullReturnCollectionOfInstanceInfo() { Application application = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); Assert.assertEquals(1, EurekaEntityFunctions.copyInstances( new ArrayList<>(Arrays.asList( application.getByInstanceId("foo"))), InstanceInfo.ActionType.ADDED).size()); } @Test public void testMergeApplicationsIfNotNullAndHasAppNameReturnApplications() { Application application = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); Applications applications = createApplications(application); Assert.assertEquals(1, EurekaEntityFunctions.mergeApplications( applications, applications).size()); } @Test public void testMergeApplicationsIfNotNullAndDoesNotHaveAppNameReturnApplications() { Application application1 = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); Applications applications1 = createApplications(application1); Application application2 = createSingleInstanceApp("bar", "bar", InstanceInfo.ActionType.ADDED); Applications applications2 = createApplications(application2); Assert.assertEquals(2, EurekaEntityFunctions.mergeApplications( applications1, applications2).size()); } @Test public void testMergeApplicationIfActionTypeAddedReturnApplication() { Application application = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); Assert.assertEquals(application.getInstances(), EurekaEntityFunctions.mergeApplication( application, application).getInstances()); } @Test public void testMergeApplicationIfActionTypeModifiedReturnApplication() { Application application = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.MODIFIED); Assert.assertEquals(application.getInstances(), EurekaEntityFunctions.mergeApplication( application, application).getInstances()); } @Test public void testMergeApplicationIfActionTypeDeletedReturnApplication() { Application application = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.DELETED); Assert.assertNotEquals(application.getInstances(), EurekaEntityFunctions.mergeApplication( application, application).getInstances()); } @Test public void testUpdateMetaIfNotNullReturnApplications() { Application application = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); Applications applications = createApplications(application); Assert.assertEquals(1l, (long) EurekaEntityFunctions.updateMeta(applications) .getVersion()); } @Test public void testCountInstancesIfApplicationsHasInstancesReturnSize() { Application application = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); Applications applications = createApplications(application); Assert.assertEquals(1, EurekaEntityFunctions.countInstances(applications)); } @Test public void testComparatorByAppNameAndIdIfNotNullReturnInt() { InstanceInfo instanceInfo1 = Mockito.mock(InstanceInfo.class); InstanceInfo instanceInfo2 = Mockito.mock(InstanceInfo.class); InstanceInfo instanceInfo3 = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED).getByInstanceId("foo"); InstanceInfo instanceInfo4 = createSingleInstanceApp("bar", "bar", InstanceInfo.ActionType.ADDED).getByInstanceId("bar"); Assert.assertTrue(EurekaEntityFunctions.comparatorByAppNameAndId() .compare(instanceInfo1, instanceInfo2) > 0); Assert.assertTrue(EurekaEntityFunctions.comparatorByAppNameAndId() .compare(instanceInfo3, instanceInfo2) > 0); Assert.assertTrue(EurekaEntityFunctions.comparatorByAppNameAndId() .compare(instanceInfo1, instanceInfo3) < 0); Assert.assertTrue(EurekaEntityFunctions.comparatorByAppNameAndId() .compare(instanceInfo3, instanceInfo4) > 0); Assert.assertTrue(EurekaEntityFunctions.comparatorByAppNameAndId() .compare(instanceInfo3, instanceInfo3) == 0); } }
6,633
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/util/EurekaUtilsTest.java
package com.netflix.discovery.util; import com.netflix.appinfo.AmazonInfo; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.InstanceInfo; import org.junit.Assert; import org.junit.Test; /** * @author David Liu */ public class EurekaUtilsTest { @Test public void testIsInEc2() { InstanceInfo instanceInfo1 = new InstanceInfo.Builder(InstanceInfoGenerator.takeOne()) .setDataCenterInfo(new DataCenterInfo() { @Override public Name getName() { return Name.MyOwn; } }) .build(); Assert.assertFalse(EurekaUtils.isInEc2(instanceInfo1)); InstanceInfo instanceInfo2 = InstanceInfoGenerator.takeOne(); Assert.assertTrue(EurekaUtils.isInEc2(instanceInfo2)); } @Test public void testIsInVpc() { InstanceInfo instanceInfo1 = new InstanceInfo.Builder(InstanceInfoGenerator.takeOne()) .setDataCenterInfo(new DataCenterInfo() { @Override public Name getName() { return Name.MyOwn; } }) .build(); Assert.assertFalse(EurekaUtils.isInVpc(instanceInfo1)); InstanceInfo instanceInfo2 = InstanceInfoGenerator.takeOne(); Assert.assertFalse(EurekaUtils.isInVpc(instanceInfo2)); InstanceInfo instanceInfo3 = InstanceInfoGenerator.takeOne(); ((AmazonInfo) instanceInfo3.getDataCenterInfo()).getMetadata() .put(AmazonInfo.MetaDataKey.vpcId.getName(), "vpc-123456"); Assert.assertTrue(EurekaUtils.isInVpc(instanceInfo3)); } }
6,634
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/util/RateLimiterTest.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery.util; import org.junit.Test; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * @author Tomasz Bak */ public class RateLimiterTest { private static final long START = 1000000; private static final int BURST_SIZE = 2; private static final int AVERAGE_RATE = 10; @Test public void testEvenLoad() { RateLimiter secondLimiter = new RateLimiter(TimeUnit.SECONDS); long secondStep = 1000 / AVERAGE_RATE; testEvenLoad(secondLimiter, START, BURST_SIZE, AVERAGE_RATE, secondStep); RateLimiter minuteLimiter = new RateLimiter(TimeUnit.MINUTES); long minuteStep = 60 * 1000 / AVERAGE_RATE; testEvenLoad(minuteLimiter, START, BURST_SIZE, AVERAGE_RATE, minuteStep); } private void testEvenLoad(RateLimiter rateLimiter, long start, int burstSize, int averageRate, long step) { long end = start + averageRate * step; for (long currentTime = start; currentTime < end; currentTime += step) { assertTrue(rateLimiter.acquire(burstSize, averageRate, currentTime)); } } @Test public void testBursts() { RateLimiter secondLimiter = new RateLimiter(TimeUnit.SECONDS); long secondStep = 1000 / AVERAGE_RATE; testBursts(secondLimiter, START, BURST_SIZE, AVERAGE_RATE, secondStep); RateLimiter minuteLimiter = new RateLimiter(TimeUnit.MINUTES); long minuteStep = 60 * 1000 / AVERAGE_RATE; testBursts(minuteLimiter, START, BURST_SIZE, AVERAGE_RATE, minuteStep); } private void testBursts(RateLimiter rateLimiter, long start, int burstSize, int averageRate, long step) { // Generate burst, and go above the limit assertTrue(rateLimiter.acquire(burstSize, averageRate, start)); assertTrue(rateLimiter.acquire(burstSize, averageRate, start)); assertFalse(rateLimiter.acquire(burstSize, averageRate, start)); // Now advance by 1.5 STEP assertTrue(rateLimiter.acquire(burstSize, averageRate, start + step + step / 2)); assertFalse(rateLimiter.acquire(burstSize, averageRate, start + step + step / 2)); assertTrue(rateLimiter.acquire(burstSize, averageRate, start + 2 * step)); } }
6,635
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/util/DiscoveryBuildInfoTest.java
package com.netflix.discovery.util; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; /** * @author Tomasz Bak */ public class DiscoveryBuildInfoTest { @Test public void testRequestedManifestIsLocatedAndLoaded() throws Exception { DiscoveryBuildInfo buildInfo = new DiscoveryBuildInfo(ObjectMapper.class); assertThat(buildInfo.getBuildVersion().contains("version_unknown"), is(false)); } }
6,636
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/util/DeserializerStringCacheTest.java
package com.netflix.discovery.util; import java.io.IOException; import java.util.Arrays; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.netflix.discovery.util.DeserializerStringCache.CacheScope; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class DeserializerStringCacheTest { @Test public void testUppercaseConversionWithLowercasePreset() throws IOException { DeserializationContext deserializationContext = mock(DeserializationContext.class); DeserializerStringCache deserializerStringCache = DeserializerStringCache.from(deserializationContext); String lowerCaseValue = deserializerStringCache.apply("value", CacheScope.APPLICATION_SCOPE); assertThat(lowerCaseValue, is("value")); JsonParser jsonParser = mock(JsonParser.class); when(jsonParser.getTextCharacters()).thenReturn(new char[] {'v', 'a', 'l', 'u', 'e'}); when(jsonParser.getTextLength()).thenReturn(5); String upperCaseValue = deserializerStringCache.apply(jsonParser, CacheScope.APPLICATION_SCOPE, () -> "VALUE"); assertThat(upperCaseValue, is("VALUE")); } @Test public void testUppercaseConversionWithLongString() throws IOException { DeserializationContext deserializationContext = mock(DeserializationContext.class); DeserializerStringCache deserializerStringCache = DeserializerStringCache.from(deserializationContext); char[] lowercaseValue = new char[1024]; Arrays.fill(lowercaseValue, 'a'); JsonParser jsonParser = mock(JsonParser.class); when(jsonParser.getText()).thenReturn(new String(lowercaseValue)); when(jsonParser.getTextCharacters()).thenReturn(lowercaseValue); when(jsonParser.getTextOffset()).thenReturn(0); when(jsonParser.getTextLength()).thenReturn(lowercaseValue.length); String upperCaseValue = deserializerStringCache.apply(jsonParser, CacheScope.APPLICATION_SCOPE, () -> { try { return jsonParser.getText().toUpperCase(); } catch(IOException ioe) { // not likely from mock above throw new IllegalStateException("mock threw unexpected exception", ioe); } }); char[] expectedValueChars = new char[1024]; Arrays.fill(expectedValueChars, 'A'); String expectedValue = new String(expectedValueChars); assertThat(upperCaseValue, is(expectedValue)); } }
6,637
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/providers/DefaultEurekaClientConfigProviderTest.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery.providers; import java.util.List; import com.google.inject.Injector; import com.netflix.config.ConfigurationManager; import com.netflix.discovery.CommonConstants; import com.netflix.discovery.DefaultEurekaClientConfig; import com.netflix.discovery.EurekaNamespace; import com.netflix.governator.guice.BootstrapBinder; import com.netflix.governator.guice.BootstrapModule; import com.netflix.governator.guice.LifecycleInjector; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; /** * @author Tomasz Bak */ public class DefaultEurekaClientConfigProviderTest { private static final String SERVICE_URI = "http://my.eureka.server:8080/"; @Test public void testNameSpaceInjection() throws Exception { ConfigurationManager.getConfigInstance().setProperty("testnamespace.serviceUrl.default", SERVICE_URI); Injector injector = LifecycleInjector.builder() .withBootstrapModule(new BootstrapModule() { @Override public void configure(BootstrapBinder binder) { binder.bind(String.class).annotatedWith(EurekaNamespace.class).toInstance("testnamespace."); } }) .build() .createInjector(); DefaultEurekaClientConfig clientConfig = injector.getInstance(DefaultEurekaClientConfig.class); List<String> serviceUrls = clientConfig.getEurekaServerServiceUrls("default"); assertThat(serviceUrls.get(0), is(equalTo(SERVICE_URI))); } @Test public void testURLSeparator() throws Exception { testURLSeparator(","); testURLSeparator(" ,"); testURLSeparator(", "); testURLSeparator(" , "); testURLSeparator(" , "); } private void testURLSeparator(String separator) { ConfigurationManager.getConfigInstance().setProperty(CommonConstants.DEFAULT_CONFIG_NAMESPACE + ".serviceUrl.default", SERVICE_URI + separator + SERVICE_URI); DefaultEurekaClientConfig clientConfig = new DefaultEurekaClientConfig(); List<String> serviceUrls = clientConfig.getEurekaServerServiceUrls("default"); assertThat(serviceUrls.get(0), is(equalTo(SERVICE_URI))); assertThat(serviceUrls.get(1), is(equalTo(SERVICE_URI))); } }
6,638
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/guice/EurekaModuleTest.java
package com.netflix.discovery.guice; import com.google.inject.AbstractModule; import com.google.inject.Binding; import com.google.inject.Key; import com.google.inject.Scopes; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.EurekaInstanceConfig; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.providers.MyDataCenterInstanceConfigProvider; import com.netflix.config.ConfigurationManager; import com.netflix.discovery.DiscoveryClient; import com.netflix.discovery.DiscoveryManager; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.shared.transport.jersey.TransportClientFactories; import com.netflix.governator.InjectorBuilder; import com.netflix.governator.LifecycleInjector; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * @author David Liu */ public class EurekaModuleTest { private LifecycleInjector injector; @Before public void setUp() throws Exception { ConfigurationManager.getConfigInstance().setProperty("eureka.region", "default"); ConfigurationManager.getConfigInstance().setProperty("eureka.shouldFetchRegistry", "false"); ConfigurationManager.getConfigInstance().setProperty("eureka.registration.enabled", "false"); ConfigurationManager.getConfigInstance().setProperty("eureka.serviceUrl.default", "http://localhost:8080/eureka/v2"); injector = InjectorBuilder .fromModule(new EurekaModule()) .overrideWith(new AbstractModule() { @Override protected void configure() { // the default impl of EurekaInstanceConfig is CloudInstanceConfig, which we only want in an AWS // environment. Here we override that by binding MyDataCenterInstanceConfig to EurekaInstanceConfig. bind(EurekaInstanceConfig.class).toProvider(MyDataCenterInstanceConfigProvider.class).in(Scopes.SINGLETON); } }) .createInjector(); } @After public void tearDown() { if (injector != null) { injector.shutdown(); } ConfigurationManager.getConfigInstance().clear(); } @SuppressWarnings("deprecation") @Test public void testDI() { InstanceInfo instanceInfo = injector.getInstance(InstanceInfo.class); Assert.assertEquals(ApplicationInfoManager.getInstance().getInfo(), instanceInfo); EurekaClient eurekaClient = injector.getInstance(EurekaClient.class); DiscoveryClient discoveryClient = injector.getInstance(DiscoveryClient.class); Assert.assertEquals(DiscoveryManager.getInstance().getEurekaClient(), eurekaClient); Assert.assertEquals(DiscoveryManager.getInstance().getDiscoveryClient(), discoveryClient); Assert.assertEquals(eurekaClient, discoveryClient); EurekaClientConfig eurekaClientConfig = injector.getInstance(EurekaClientConfig.class); Assert.assertEquals(DiscoveryManager.getInstance().getEurekaClientConfig(), eurekaClientConfig); EurekaInstanceConfig eurekaInstanceConfig = injector.getInstance(EurekaInstanceConfig.class); Assert.assertEquals(DiscoveryManager.getInstance().getEurekaInstanceConfig(), eurekaInstanceConfig); Binding<TransportClientFactories> binding = injector.getExistingBinding(Key.get(TransportClientFactories.class)); Assert.assertNull(binding); // no bindings so defaulting to default of jersey1 } }
6,639
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/provider/DiscoveryJerseyProviderTest.java
/* * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery.provider; import javax.ws.rs.core.MediaType; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.converters.wrappers.CodecWrappers; import com.netflix.discovery.util.InstanceInfoGenerator; import org.apache.commons.io.output.ByteArrayOutputStream; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; /** */ public class DiscoveryJerseyProviderTest { private static final InstanceInfo INSTANCE = InstanceInfoGenerator.takeOne(); private final DiscoveryJerseyProvider jerseyProvider = new DiscoveryJerseyProvider( CodecWrappers.getEncoder(CodecWrappers.JacksonJson.class), CodecWrappers.getDecoder(CodecWrappers.JacksonJson.class) ); @Test public void testJsonEncodingDecoding() throws Exception { testEncodingDecoding(MediaType.APPLICATION_JSON_TYPE); } @Test public void testXmlEncodingDecoding() throws Exception { testEncodingDecoding(MediaType.APPLICATION_XML_TYPE); } @Test public void testDecodingWithUtf8CharsetExplicitlySet() throws Exception { Map<String, String> params = new HashMap<>(); params.put("charset", "UTF-8"); testEncodingDecoding(new MediaType("application", "json", params)); } private void testEncodingDecoding(MediaType mediaType) throws IOException { // Write assertThat(jerseyProvider.isWriteable(InstanceInfo.class, InstanceInfo.class, null, mediaType), is(true)); ByteArrayOutputStream out = new ByteArrayOutputStream(); jerseyProvider.writeTo(INSTANCE, InstanceInfo.class, InstanceInfo.class, null, mediaType, null, out); // Read assertThat(jerseyProvider.isReadable(InstanceInfo.class, InstanceInfo.class, null, mediaType), is(true)); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); InstanceInfo decodedInstance = (InstanceInfo) jerseyProvider.readFrom(InstanceInfo.class, InstanceInfo.class, null, mediaType, null, in); assertThat(decodedInstance, is(equalTo(INSTANCE))); } @Test public void testNonUtf8CharsetIsNotAccepted() throws Exception { Map<String, String> params = new HashMap<>(); params.put("charset", "ISO-8859"); MediaType mediaTypeWithNonSupportedCharset = new MediaType("application", "json", params); assertThat(jerseyProvider.isReadable(InstanceInfo.class, InstanceInfo.class, null, mediaTypeWithNonSupportedCharset), is(false)); } }
6,640
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/converters/XmlXStreamTest.java
package com.netflix.discovery.converters; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.util.EurekaEntityComparators; import com.netflix.discovery.util.InstanceInfoGenerator; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.security.ForbiddenClassException; import org.junit.Test; /** * @author Tomasz Bak */ public class XmlXStreamTest { @Test public void testEncodingDecodingWithoutMetaData() throws Exception { Applications applications = InstanceInfoGenerator.newBuilder(10, 2).withMetaData(false).build().toApplications(); XStream xstream = XmlXStream.getInstance(); String xmlDocument = xstream.toXML(applications); Applications decodedApplications = (Applications) xstream.fromXML(xmlDocument); assertThat(EurekaEntityComparators.equal(decodedApplications, applications), is(true)); } @Test public void testEncodingDecodingWithMetaData() throws Exception { Applications applications = InstanceInfoGenerator.newBuilder(10, 2).withMetaData(true).build().toApplications(); XStream xstream = XmlXStream.getInstance(); String xmlDocument = xstream.toXML(applications); Applications decodedApplications = (Applications) xstream.fromXML(xmlDocument); assertThat(EurekaEntityComparators.equal(decodedApplications, applications), is(true)); } /** * Tests: http://x-stream.github.io/CVE-2017-7957.html */ @Test(expected=ForbiddenClassException.class, timeout=5000) public void testVoidElementUnmarshalling() throws Exception { XStream xstream = XmlXStream.getInstance(); xstream.fromXML("<void/>"); } /** * Tests: http://x-stream.github.io/CVE-2017-7957.html */ @Test(expected=ForbiddenClassException.class, timeout=5000) public void testVoidAttributeUnmarshalling() throws Exception { XStream xstream = XmlXStream.getInstance(); xstream.fromXML("<string class='void'>Hello, world!</string>"); } }
6,641
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/converters/StringCacheTest.java
package com.netflix.discovery.converters; import com.netflix.discovery.util.StringCache; import org.junit.Test; import static org.junit.Assert.assertTrue; /** * @author Tomasz Bak */ public class StringCacheTest { public static final int CACHE_SIZE = 100000; @Test public void testVerifyStringsAreGarbageCollectedIfNotReferenced() throws Exception { StringCache cache = new StringCache(); for (int i = 0; i < CACHE_SIZE; i++) { cache.cachedValueOf("id#" + i); } gc(); // Testing GC behavior is unpredictable, so we set here low target level // The tests run on desktop show that all strings are removed actually. assertTrue(cache.size() < CACHE_SIZE * 0.1); } public static void gc() { System.gc(); System.runFinalization(); try { Thread.sleep(1000); } catch (InterruptedException e) { // IGNORE } } }
6,642
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/converters/EurekaJacksonCodecIntegrationTest.java
package com.netflix.discovery.converters; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.file.StandardCopyOption; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.junit.Test; import com.netflix.discovery.shared.Applications; /** * this integration test parses the response of a Eureka discovery server, * specified by url via system property 'discovery.url'. It's useful for memory * utilization and performance tests, but since it's environment specific, the * tests below are @Ignore'd. * */ @org.junit.Ignore public class EurekaJacksonCodecIntegrationTest { private static final int UNREASONABLE_TIMEOUT_MS = 500; private final EurekaJacksonCodec codec = new EurekaJacksonCodec("", ""); /** * parse discovery response in a long-running loop with a delay * * @throws Exception */ @Test public void testRealDecode() throws Exception { Applications applications; File localDiscovery = new File("/var/folders/6j/qy6n1npj11x5j2j_9ng2wzmw0000gp/T/discovery-data-6054758555577530004.json"); //downloadRegistration(System.getProperty("discovery.url")); long testStart = System.currentTimeMillis(); for (int i = 0; i < 60; i++) { try (InputStream is = new FileInputStream(localDiscovery)) { long start = System.currentTimeMillis(); applications = codec.readValue(Applications.class, is); System.out.println("found some applications: " + applications.getRegisteredApplications().size() + " et: " + (System.currentTimeMillis() - start)); } } System.out.println("test time: " + " et: " + (System.currentTimeMillis() - testStart)); } @Test public void testCuriosity() { char[] arr1 = "test".toCharArray(); char[] arr2 = new char[] {'t', 'e', 's', 't'}; System.out.println("array equals" + arr1.equals(arr2)); } /** * parse discovery response with an unreasonable timeout, so that the * parsing job is cancelled * * @throws Exception */ @Test public void testDecodeTimeout() throws Exception { ExecutorService executor = Executors.newFixedThreadPool(5); File localDiscovery = downloadRegistration(System.getProperty("discovery.url")); Callable<Applications> task = () -> { try (InputStream is = new FileInputStream(localDiscovery)) { return codec.readValue(Applications.class, is); } }; final int cancelAllButNthTask = 3; for (int i = 0; i < 30; i++) { Future<Applications> appsFuture = executor.submit(task); if (i % cancelAllButNthTask < cancelAllButNthTask - 1) { Thread.sleep(UNREASONABLE_TIMEOUT_MS); System.out.println("cancelling..." + " i: " + i + " - " + (i % 3)); appsFuture.cancel(true); } try { Applications apps = appsFuture.get(); System.out.println("found some applications: " + apps.toString() + ":" + apps.getRegisteredApplications().size() + " i: " + i + " - " + (i % 3)); } catch (Exception e) { System.out.println(e + " cause: " + " i: " + i + " - " + (i % 3)); } } } /** * low-tech http downloader */ private static File downloadRegistration(String discoveryUrl) throws IOException { if (discoveryUrl == null) { throw new IllegalArgumentException("null value not allowed for parameter discoveryUrl"); } File localFile = File.createTempFile("discovery-data-", ".json"); URL url = new URL(discoveryUrl); System.out.println("downloading registration data from " + url + " to " + localFile); HttpURLConnection hurlConn = (HttpURLConnection) url.openConnection(); hurlConn.setDoOutput(true); hurlConn.setRequestProperty("accept", "application/json"); hurlConn.connect(); try (InputStream is = hurlConn.getInputStream()) { java.nio.file.Files.copy(is, localFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } return localFile; } }
6,643
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/converters/CodecLoadTester.java
package com.netflix.discovery.converters; import javax.ws.rs.core.MediaType; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.converters.jackson.AbstractEurekaJacksonCodec; import com.netflix.discovery.converters.jackson.EurekaJsonJacksonCodec; import com.netflix.discovery.converters.jackson.EurekaXmlJacksonCodec; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.util.InstanceInfoGenerator; /** * @author Tomasz Bak */ public class CodecLoadTester { private final List<InstanceInfo> instanceInfoList = new ArrayList<>(); private final List<Application> applicationList = new ArrayList<>(); private final Applications applications; private final EntityBodyConverter xstreamCodec = new EntityBodyConverter(); private final EurekaJacksonCodec legacyJacksonCodec = new EurekaJacksonCodec(); private final EurekaJsonJacksonCodec jsonCodecNG = new EurekaJsonJacksonCodec(); private final EurekaJsonJacksonCodec jsonCodecNgCompact = new EurekaJsonJacksonCodec(KeyFormatter.defaultKeyFormatter(), true); private final EurekaXmlJacksonCodec xmlCodecNG = new EurekaXmlJacksonCodec(); private final EurekaXmlJacksonCodec xmlCodecNgCompact = new EurekaXmlJacksonCodec(KeyFormatter.defaultKeyFormatter(), true); static class FirstHolder { Applications value; } static class SecondHolder { Applications value; } private FirstHolder firstHolder = new FirstHolder(); private SecondHolder secondHolder = new SecondHolder(); public CodecLoadTester(int instanceCount, int appCount) { Iterator<InstanceInfo> instanceIt = InstanceInfoGenerator.newBuilder(instanceCount, appCount) .withMetaData(true).build().serviceIterator(); applications = new Applications(); int appIdx = 0; while (instanceIt.hasNext()) { InstanceInfo next = instanceIt.next(); instanceInfoList.add(next); if (applicationList.size() <= appIdx) { applicationList.add(new Application(next.getAppName())); } applicationList.get(appIdx).addInstance(next); appIdx = (appIdx + 1) % appCount; } for (Application app : applicationList) { applications.addApplication(app); } applications.setAppsHashCode(applications.getReconcileHashCode()); firstHolder.value = applications; } public CodecLoadTester(String[] args) throws Exception { if (args.length != 1) { System.err.println("ERROR: too many command line arguments; file name expected only"); throw new IllegalArgumentException(); } String fileName = args[0]; Applications applications; try { System.out.println("Attempting to load " + fileName + " in XML format..."); applications = loadWithCodec(fileName, MediaType.APPLICATION_XML_TYPE); } catch (Exception e) { System.out.println("Attempting to load " + fileName + " in JSON format..."); applications = loadWithCodec(fileName, MediaType.APPLICATION_JSON_TYPE); } this.applications = applications; long totalInstances = 0; for (Application a : applications.getRegisteredApplications()) { totalInstances += a.getInstances().size(); } System.out.printf("Loaded %d applications with %d instances\n", applications.getRegisteredApplications().size(), totalInstances); firstHolder.value = applications; } private Applications loadWithCodec(String fileName, MediaType mediaType) throws IOException { FileInputStream fis = new FileInputStream(fileName); BufferedInputStream bis = new BufferedInputStream(fis); return (Applications) xstreamCodec.read(bis, Applications.class, mediaType); } public void runApplicationsLoadTest(int loops, Func0<Applications> action) { long size = 0; for (int i = 0; i < loops; i++) { size += action.call(applications); } System.out.println("Average applications object size=" + formatSize(size / loops)); } public void runApplicationLoadTest(int loops, Func0<Application> action) { for (int i = 0; i < loops; i++) { action.call(applicationList.get(i % applicationList.size())); } } public void runInstanceInfoLoadTest(int loops, Func0<InstanceInfo> action) { for (int i = 0; i < loops; i++) { action.call(instanceInfoList.get(i % instanceInfoList.size())); } } public void runInstanceInfoIntervalTest(int batch, int intervalMs, long durationSec, Func0 action) { long startTime = System.currentTimeMillis(); long endTime = startTime + durationSec * 1000; long now; do { now = System.currentTimeMillis(); runInstanceInfoLoadTest(batch, action); long waiting = intervalMs - (System.currentTimeMillis() - now); System.out.println("Waiting " + waiting + "ms"); if (waiting > 0) { try { Thread.sleep(waiting); } catch (InterruptedException e) { // IGNORE } } } while (now < endTime); } public void runApplicationIntervalTest(int batch, int intervalMs, long durationSec, Func0 action) { long startTime = System.currentTimeMillis(); long endTime = startTime + durationSec * 1000; long now; do { now = System.currentTimeMillis(); runApplicationLoadTest(batch, action); long waiting = intervalMs - (System.currentTimeMillis() - now); System.out.println("Waiting " + waiting + "ms"); if (waiting > 0) { try { Thread.sleep(waiting); } catch (InterruptedException e) { // IGNORE } } } while (now < endTime); } private static String formatSize(long size) { if (size < 1000) { return String.format("%d [bytes]", size); } if (size < 1024 * 1024) { return String.format("%.2f [KB]", size / 1024f); } return String.format("%.2f [MB]", size / (1024f * 1024f)); } interface Func0<T> { int call(T data); } Func0 legacyJacksonAction = new Func0<Object>() { @Override public int call(Object object) { ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); try { legacyJacksonCodec.writeTo(object, captureStream); byte[] bytes = captureStream.toByteArray(); InputStream source = new ByteArrayInputStream(bytes); legacyJacksonCodec.readValue(object.getClass(), source); return bytes.length; } catch (IOException e) { throw new RuntimeException("unexpected", e); } } }; Func0 xstreamJsonAction = new Func0<Object>() { @Override public int call(Object object) { ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); try { xstreamCodec.write(object, captureStream, MediaType.APPLICATION_JSON_TYPE); byte[] bytes = captureStream.toByteArray(); InputStream source = new ByteArrayInputStream(bytes); xstreamCodec.read(source, InstanceInfo.class, MediaType.APPLICATION_JSON_TYPE); return bytes.length; } catch (IOException e) { throw new RuntimeException("unexpected", e); } } }; Func0 xstreamXmlAction = new Func0<Object>() { @Override public int call(Object object) { ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); try { xstreamCodec.write(object, captureStream, MediaType.APPLICATION_XML_TYPE); byte[] bytes = captureStream.toByteArray(); InputStream source = new ByteArrayInputStream(bytes); xstreamCodec.read(source, InstanceInfo.class, MediaType.APPLICATION_XML_TYPE); return bytes.length; } catch (IOException e) { throw new RuntimeException("unexpected", e); } } }; Func0 createJacksonNgAction(final MediaType mediaType, final boolean compact) { return new Func0<Object>() { @Override public int call(Object object) { AbstractEurekaJacksonCodec codec; if (mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) { codec = compact ? jsonCodecNgCompact : jsonCodecNG; } else { codec = compact ? xmlCodecNgCompact : xmlCodecNG; } ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); try { codec.writeTo(object, captureStream); byte[] bytes = captureStream.toByteArray(); InputStream source = new ByteArrayInputStream(bytes); Applications readValue = codec.getObjectMapper(object.getClass()).readValue(source, Applications.class); secondHolder.value = readValue; return bytes.length; } catch (IOException e) { throw new RuntimeException("unexpected", e); } } }; } public void runFullSpeed() { int loop = 5; System.gc(); long start = System.currentTimeMillis(); // runInstanceInfoLoadTest(loop, legacyJacksonAction); // runInstanceInfoLoadTest(loop, xstreamAction); // runApplicationLoadTest(loop, legacyJacksonAction); // runApplicationLoadTest(loop, xstreamAction); // ---------------------------------------------------------------- // Applications // runApplicationsLoadTest(loop, xstreamJsonAction); // runApplicationsLoadTest(loop, xstreamXmlAction); // runApplicationsLoadTest(loop, legacyJacksonAction); runApplicationsLoadTest(loop, createJacksonNgAction(MediaType.APPLICATION_JSON_TYPE, false)); long executionTime = System.currentTimeMillis() - start; System.out.printf("Execution time: %d[ms]\n", executionTime); } public void runIntervals() { int batch = 1500; int intervalMs = 1000; long durationSec = 600; // runInstanceInfoIntervalTest(batch, intervalMs, durationSec, legacyJacksonAction); runInstanceInfoIntervalTest(batch, intervalMs, durationSec, xstreamJsonAction); // runApplicationIntervalTest(batch, intervalMs, durationSec, legacyJacksonAction); // runApplicationIntervalTest(batch, intervalMs, durationSec, xstreamAction); } public static void main(String[] args) throws Exception { CodecLoadTester loadTester; if (args.length == 0) { loadTester = new CodecLoadTester(2000, 40); } else { loadTester = new CodecLoadTester(args); } loadTester.runFullSpeed(); Thread.sleep(100000); } }
6,644
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/converters/EnumLookupTest.java
package com.netflix.discovery.converters; import org.junit.Assert; import org.junit.Test; public class EnumLookupTest { enum TestEnum { VAL_ONE("one"), VAL_TWO("two"), VAL_THREE("three"); private final String name; private TestEnum(String name) { this.name = name; } } @Test public void testLookup() { EnumLookup<TestEnum> lookup = new EnumLookup<>(TestEnum.class, v->v.name.toCharArray()); char[] buffer = "zeroonetwothreefour".toCharArray(); Assert.assertSame(TestEnum.VAL_ONE, lookup.find(buffer, 4, 3)); Assert.assertSame(TestEnum.VAL_TWO, lookup.find(buffer, 7, 3)); Assert.assertSame(TestEnum.VAL_THREE, lookup.find(buffer, 10, 5)); } }
6,645
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/converters/EurekaJacksonCodecTest.java
package com.netflix.discovery.converters; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.nio.charset.Charset; import java.util.Iterator; import javax.ws.rs.core.MediaType; import org.junit.Test; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.ActionType; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.util.EurekaEntityComparators; import com.netflix.discovery.util.InstanceInfoGenerator; /** * @author Tomasz Bak */ public class EurekaJacksonCodecTest { public static final InstanceInfo INSTANCE_INFO_1_A1; public static final InstanceInfo INSTANCE_INFO_2_A1; public static final InstanceInfo INSTANCE_INFO_1_A2; public static final InstanceInfo INSTANCE_INFO_2_A2; public static final Application APPLICATION_1; public static final Application APPLICATION_2; public static final Applications APPLICATIONS; static { Iterator<InstanceInfo> infoIterator = InstanceInfoGenerator.newBuilder(4, 2).withMetaData(true).build().serviceIterator(); INSTANCE_INFO_1_A1 = infoIterator.next(); INSTANCE_INFO_1_A1.setActionType(ActionType.ADDED); INSTANCE_INFO_1_A2 = infoIterator.next(); INSTANCE_INFO_1_A2.setActionType(ActionType.ADDED); INSTANCE_INFO_2_A1 = infoIterator.next(); INSTANCE_INFO_1_A2.setActionType(ActionType.ADDED); INSTANCE_INFO_2_A2 = infoIterator.next(); INSTANCE_INFO_2_A2.setActionType(ActionType.ADDED); APPLICATION_1 = new Application(INSTANCE_INFO_1_A1.getAppName()); APPLICATION_1.addInstance(INSTANCE_INFO_1_A1); APPLICATION_1.addInstance(INSTANCE_INFO_2_A1); APPLICATION_2 = new Application(INSTANCE_INFO_1_A2.getAppName()); APPLICATION_2.addInstance(INSTANCE_INFO_1_A2); APPLICATION_2.addInstance(INSTANCE_INFO_2_A2); APPLICATIONS = new Applications(); APPLICATIONS.addApplication(APPLICATION_1); APPLICATIONS.addApplication(APPLICATION_2); } private final EurekaJacksonCodec codec = new EurekaJacksonCodec(); @Test public void testInstanceInfoJacksonEncodeDecode() throws Exception { // Encode ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); codec.writeTo(INSTANCE_INFO_1_A1, captureStream); byte[] encoded = captureStream.toByteArray(); // Decode InputStream source = new ByteArrayInputStream(encoded); InstanceInfo decoded = codec.readValue(InstanceInfo.class, source); assertTrue(EurekaEntityComparators.equal(decoded, INSTANCE_INFO_1_A1)); } @Test public void testInstanceInfoJacksonEncodeDecodeWithoutMetaData() throws Exception { InstanceInfo noMetaDataInfo = InstanceInfoGenerator.newBuilder(1, 1).withMetaData(false).build().serviceIterator().next(); // Encode ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); codec.writeTo(noMetaDataInfo, captureStream); byte[] encoded = captureStream.toByteArray(); // Decode InputStream source = new ByteArrayInputStream(encoded); InstanceInfo decoded = codec.readValue(InstanceInfo.class, source); assertTrue(EurekaEntityComparators.equal(decoded, noMetaDataInfo)); } @Test public void testInstanceInfoXStreamEncodeJacksonDecode() throws Exception { InstanceInfo original = INSTANCE_INFO_1_A1; // Encode ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); new EntityBodyConverter().write(original, captureStream, MediaType.APPLICATION_JSON_TYPE); byte[] encoded = captureStream.toByteArray(); // Decode InputStream source = new ByteArrayInputStream(encoded); InstanceInfo decoded = codec.readValue(InstanceInfo.class, source); assertTrue(EurekaEntityComparators.equal(decoded, original)); } @Test public void testInstanceInfoJacksonEncodeXStreamDecode() throws Exception { // Encode ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); codec.writeTo(INSTANCE_INFO_1_A1, captureStream); byte[] encoded = captureStream.toByteArray(); // Decode InputStream source = new ByteArrayInputStream(encoded); InstanceInfo decoded = (InstanceInfo) new EntityBodyConverter().read(source, InstanceInfo.class, MediaType.APPLICATION_JSON_TYPE); assertTrue(EurekaEntityComparators.equal(decoded, INSTANCE_INFO_1_A1)); } @Test public void testApplicationJacksonEncodeDecode() throws Exception { // Encode ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); codec.writeTo(APPLICATION_1, captureStream); byte[] encoded = captureStream.toByteArray(); // Decode InputStream source = new ByteArrayInputStream(encoded); Application decoded = codec.readValue(Application.class, source); assertTrue(EurekaEntityComparators.equal(decoded, APPLICATION_1)); } @Test public void testApplicationXStreamEncodeJacksonDecode() throws Exception { Application original = APPLICATION_1; // Encode ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); new EntityBodyConverter().write(original, captureStream, MediaType.APPLICATION_JSON_TYPE); byte[] encoded = captureStream.toByteArray(); // Decode InputStream source = new ByteArrayInputStream(encoded); Application decoded = codec.readValue(Application.class, source); assertTrue(EurekaEntityComparators.equal(decoded, original)); } @Test public void testApplicationJacksonEncodeXStreamDecode() throws Exception { // Encode ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); codec.writeTo(APPLICATION_1, captureStream); byte[] encoded = captureStream.toByteArray(); // Decode InputStream source = new ByteArrayInputStream(encoded); Application decoded = (Application) new EntityBodyConverter().read(source, Application.class, MediaType.APPLICATION_JSON_TYPE); assertTrue(EurekaEntityComparators.equal(decoded, APPLICATION_1)); } @Test public void testApplicationsJacksonEncodeDecode() throws Exception { // Encode ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); codec.writeTo(APPLICATIONS, captureStream); byte[] encoded = captureStream.toByteArray(); // Decode InputStream source = new ByteArrayInputStream(encoded); Applications decoded = codec.readValue(Applications.class, source); assertTrue(EurekaEntityComparators.equal(decoded, APPLICATIONS)); } @Test public void testApplicationsXStreamEncodeJacksonDecode() throws Exception { Applications original = APPLICATIONS; // Encode ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); new EntityBodyConverter().write(original, captureStream, MediaType.APPLICATION_JSON_TYPE); byte[] encoded = captureStream.toByteArray(); String encodedString = new String(encoded); // Decode InputStream source = new ByteArrayInputStream(encoded); Applications decoded = codec.readValue(Applications.class, source); assertTrue(EurekaEntityComparators.equal(decoded, original)); } @Test public void testApplicationsJacksonEncodeXStreamDecode() throws Exception { // Encode ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); codec.writeTo(APPLICATIONS, captureStream); byte[] encoded = captureStream.toByteArray(); // Decode InputStream source = new ByteArrayInputStream(encoded); Applications decoded = (Applications) new EntityBodyConverter().read(source, Applications.class, MediaType.APPLICATION_JSON_TYPE); assertTrue(EurekaEntityComparators.equal(decoded, APPLICATIONS)); } @Test public void testJacksonWriteToString() throws Exception { String jsonValue = codec.writeToString(INSTANCE_INFO_1_A1); InstanceInfo decoded = codec.readValue(InstanceInfo.class, new ByteArrayInputStream(jsonValue.getBytes(Charset.defaultCharset()))); assertTrue(EurekaEntityComparators.equal(decoded, INSTANCE_INFO_1_A1)); } @Test public void testJacksonWrite() throws Exception { // Encode ByteArrayOutputStream captureStream = new ByteArrayOutputStream(); codec.writeTo(INSTANCE_INFO_1_A1, captureStream); byte[] encoded = captureStream.toByteArray(); // Decode value InputStream source = new ByteArrayInputStream(encoded); InstanceInfo decoded = codec.readValue(InstanceInfo.class, source); assertTrue(EurekaEntityComparators.equal(decoded, INSTANCE_INFO_1_A1)); } }
6,646
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/converters/EurekaCodecCompatibilityTest.java
package com.netflix.discovery.converters; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.MyDataCenterInfo; import com.netflix.discovery.converters.wrappers.CodecWrapper; import com.netflix.discovery.converters.wrappers.CodecWrappers; import com.netflix.discovery.converters.wrappers.DecoderWrapper; import com.netflix.discovery.converters.wrappers.EncoderWrapper; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.util.EurekaEntityComparators; import com.netflix.discovery.util.InstanceInfoGenerator; import com.netflix.eureka.cluster.protocol.ReplicationInstance; import com.netflix.eureka.cluster.protocol.ReplicationInstanceResponse; import com.netflix.eureka.cluster.protocol.ReplicationList; import com.netflix.eureka.cluster.protocol.ReplicationListResponse; import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl.Action; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; /** * @author Tomasz Bak */ public class EurekaCodecCompatibilityTest { private static final List<CodecWrapper> availableJsonWrappers = new ArrayList<>(); private static final List<CodecWrapper> availableXmlWrappers = new ArrayList<>(); static { availableJsonWrappers.add(new CodecWrappers.XStreamJson()); availableJsonWrappers.add(new CodecWrappers.LegacyJacksonJson()); availableJsonWrappers.add(new CodecWrappers.JacksonJson()); availableXmlWrappers.add(new CodecWrappers.JacksonXml()); availableXmlWrappers.add(new CodecWrappers.XStreamXml()); } private final InstanceInfoGenerator infoGenerator = InstanceInfoGenerator.newBuilder(4, 2).withMetaData(true).build(); private final Iterator<InstanceInfo> infoIterator = infoGenerator.serviceIterator(); interface Action2 { void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException; } /** * @deprecated see to do note in {@link com.netflix.appinfo.LeaseInfo} and delete once legacy is removed */ @Deprecated @Test public void testInstanceInfoEncodeDecodeLegacyJacksonToJackson() throws Exception { final InstanceInfo instanceInfo = infoIterator.next(); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(instanceInfo); // convert the field from the json string to what the legacy json would encode as encodedString = encodedString.replaceFirst("lastRenewalTimestamp", "renewalTimestamp"); InstanceInfo decodedValue = decodingCodec.decode(encodedString, InstanceInfo.class); assertThat(EurekaEntityComparators.equal(instanceInfo, decodedValue, new EurekaEntityComparators.RawIdEqualFunc()), is(true)); assertThat(EurekaEntityComparators.equal(instanceInfo, decodedValue), is(true)); } }; verifyForPair( codingAction, InstanceInfo.class, new CodecWrappers.LegacyJacksonJson(), new CodecWrappers.JacksonJson() ); } @Test public void testInstanceInfoEncodeDecodeJsonWithEmptyMetadataMap() throws Exception { final InstanceInfo base = infoIterator.next(); final InstanceInfo instanceInfo = new InstanceInfo.Builder(base) .setMetadata(Collections.EMPTY_MAP) .build(); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(instanceInfo); InstanceInfo decodedValue = decodingCodec.decode(encodedString, InstanceInfo.class); assertThat(EurekaEntityComparators.equal(instanceInfo, decodedValue), is(true)); } }; verifyAllPairs(codingAction, Application.class, availableJsonWrappers); verifyAllPairs(codingAction, Application.class, availableXmlWrappers); } /** * During deserialization process in compact mode not all fields might be filtered out. If JVM memory * is an issue, compact version of the encoder should be used on the server side. */ @Test public void testInstanceInfoFullEncodeMiniDecodeJackson() throws Exception { final InstanceInfo instanceInfo = infoIterator.next(); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(instanceInfo); InstanceInfo decodedValue = decodingCodec.decode(encodedString, InstanceInfo.class); assertThat(EurekaEntityComparators.equalMini(instanceInfo, decodedValue), is(true)); } }; verifyForPair( codingAction, InstanceInfo.class, new CodecWrappers.JacksonJson(), new CodecWrappers.JacksonJsonMini() ); } @Test public void testInstanceInfoFullEncodeMiniDecodeJacksonWithMyOwnDataCenterInfo() throws Exception { final InstanceInfo base = infoIterator.next(); final InstanceInfo instanceInfo = new InstanceInfo.Builder(base) .setDataCenterInfo(new MyDataCenterInfo(DataCenterInfo.Name.MyOwn)) .build(); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(instanceInfo); InstanceInfo decodedValue = decodingCodec.decode(encodedString, InstanceInfo.class); assertThat(EurekaEntityComparators.equalMini(instanceInfo, decodedValue), is(true)); } }; verifyForPair( codingAction, InstanceInfo.class, new CodecWrappers.JacksonJson(), new CodecWrappers.JacksonJsonMini() ); } @Test public void testInstanceInfoMiniEncodeMiniDecodeJackson() throws Exception { final InstanceInfo instanceInfo = infoIterator.next(); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(instanceInfo); InstanceInfo decodedValue = decodingCodec.decode(encodedString, InstanceInfo.class); assertThat(EurekaEntityComparators.equalMini(instanceInfo, decodedValue), is(true)); } }; verifyForPair( codingAction, InstanceInfo.class, new CodecWrappers.JacksonJsonMini(), new CodecWrappers.JacksonJsonMini() ); } @Test public void testInstanceInfoEncodeDecode() throws Exception { final InstanceInfo instanceInfo = infoIterator.next(); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(instanceInfo); InstanceInfo decodedValue = decodingCodec.decode(encodedString, InstanceInfo.class); assertThat(EurekaEntityComparators.equal(instanceInfo, decodedValue), is(true)); assertThat(EurekaEntityComparators.equal(instanceInfo, decodedValue, new EurekaEntityComparators.RawIdEqualFunc()), is(true)); } }; verifyAllPairs(codingAction, InstanceInfo.class, availableJsonWrappers); verifyAllPairs(codingAction, InstanceInfo.class, availableXmlWrappers); } // https://github.com/Netflix/eureka/issues/1051 // test going from camel case to lower case @Test public void testInstanceInfoEncodeDecodeCompatibilityDueToOverriddenStatusRenamingV1() throws Exception { final InstanceInfo instanceInfo = infoIterator.next(); new InstanceInfo.Builder(instanceInfo).setOverriddenStatus(InstanceInfo.InstanceStatus.OUT_OF_SERVICE); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(instanceInfo); // sed to older naming to test encodedString = encodedString.replace("overriddenStatus", "overriddenstatus"); InstanceInfo decodedValue = decodingCodec.decode(encodedString, InstanceInfo.class); assertThat(EurekaEntityComparators.equal(instanceInfo, decodedValue), is(true)); assertThat(EurekaEntityComparators.equal(instanceInfo, decodedValue, new EurekaEntityComparators.RawIdEqualFunc()), is(true)); } }; verifyAllPairs(codingAction, Application.class, availableJsonWrappers); verifyAllPairs(codingAction, Application.class, availableXmlWrappers); } // same as the above, but go from lower case to camel case @Test public void testInstanceInfoEncodeDecodeCompatibilityDueToOverriddenStatusRenamingV2() throws Exception { final InstanceInfo instanceInfo = infoIterator.next(); new InstanceInfo.Builder(instanceInfo).setOverriddenStatus(InstanceInfo.InstanceStatus.OUT_OF_SERVICE); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(instanceInfo); // sed to older naming to test encodedString = encodedString.replace("overriddenstatus", "overriddenStatus"); InstanceInfo decodedValue = decodingCodec.decode(encodedString, InstanceInfo.class); assertThat(EurekaEntityComparators.equal(instanceInfo, decodedValue), is(true)); assertThat(EurekaEntityComparators.equal(instanceInfo, decodedValue, new EurekaEntityComparators.RawIdEqualFunc()), is(true)); } }; verifyAllPairs(codingAction, Application.class, availableJsonWrappers); verifyAllPairs(codingAction, Application.class, availableXmlWrappers); } @Test public void testApplicationEncodeDecode() throws Exception { final Application application = new Application("testApp"); application.addInstance(infoIterator.next()); application.addInstance(infoIterator.next()); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(application); Application decodedValue = decodingCodec.decode(encodedString, Application.class); assertThat(EurekaEntityComparators.equal(application, decodedValue), is(true)); } }; verifyAllPairs(codingAction, Application.class, availableJsonWrappers); verifyAllPairs(codingAction, Application.class, availableXmlWrappers); } @Test public void testApplicationsEncodeDecode() throws Exception { final Applications applications = infoGenerator.takeDelta(2); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(applications); Applications decodedValue = decodingCodec.decode(encodedString, Applications.class); assertThat(EurekaEntityComparators.equal(applications, decodedValue), is(true)); } }; verifyAllPairs(codingAction, Applications.class, availableJsonWrappers); verifyAllPairs(codingAction, Applications.class, availableXmlWrappers); } /** * For backward compatibility with LegacyJacksonJson codec single item arrays shall not be unwrapped. */ @Test public void testApplicationsJsonEncodeDecodeWithSingleAppItem() throws Exception { final Applications applications = infoGenerator.takeDelta(1); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(applications); assertThat(encodedString.contains("\"application\":[{"), is(true)); Applications decodedValue = decodingCodec.decode(encodedString, Applications.class); assertThat(EurekaEntityComparators.equal(applications, decodedValue), is(true)); } }; List<CodecWrapper> jsonCodes = Arrays.asList( new CodecWrappers.LegacyJacksonJson(), new CodecWrappers.JacksonJson() ); verifyAllPairs(codingAction, Applications.class, jsonCodes); } @Test public void testBatchRequestEncoding() throws Exception { InstanceInfo instance = InstanceInfoGenerator.takeOne(); List<ReplicationInstance> replicationInstances = new ArrayList<>(); replicationInstances.add(new ReplicationInstance( instance.getAppName(), instance.getId(), System.currentTimeMillis(), null, instance.getStatus().name(), instance, Action.Register )); final ReplicationList replicationList = new ReplicationList(replicationInstances); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(replicationList); ReplicationList decodedValue = decodingCodec.decode(encodedString, ReplicationList.class); assertThat(decodedValue.getReplicationList().size(), is(equalTo(1))); } }; // In replication channel we use JSON only List<CodecWrapper> jsonCodes = Arrays.asList( new CodecWrappers.JacksonJson(), new CodecWrappers.LegacyJacksonJson() ); verifyAllPairs(codingAction, ReplicationList.class, jsonCodes); } @Test public void testBatchResponseEncoding() throws Exception { List<ReplicationInstanceResponse> responseList = new ArrayList<>(); responseList.add(new ReplicationInstanceResponse(200, InstanceInfoGenerator.takeOne())); final ReplicationListResponse replicationListResponse = new ReplicationListResponse(responseList); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(replicationListResponse); ReplicationListResponse decodedValue = decodingCodec.decode(encodedString, ReplicationListResponse.class); assertThat(decodedValue.getResponseList().size(), is(equalTo(1))); } }; // In replication channel we use JSON only List<CodecWrapper> jsonCodes = Arrays.asList( new CodecWrappers.JacksonJson(), new CodecWrappers.LegacyJacksonJson() ); verifyAllPairs(codingAction, ReplicationListResponse.class, jsonCodes); } public void verifyAllPairs(Action2 codingAction, Class<?> typeToEncode, List<CodecWrapper> codecHolders) throws Exception { for (EncoderWrapper encodingCodec : codecHolders) { for (DecoderWrapper decodingCodec : codecHolders) { String pair = "{" + encodingCodec.codecName() + ',' + decodingCodec.codecName() + '}'; System.out.println("Encoding " + typeToEncode.getSimpleName() + " using " + pair); try { codingAction.call(encodingCodec, decodingCodec); } catch (Exception ex) { throw new Exception("Encoding failure for codec pair " + pair, ex); } } } } public void verifyForPair(Action2 codingAction, Class<?> typeToEncode, EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws Exception { String pair = "{" + encodingCodec.codecName() + ',' + decodingCodec.codecName() + '}'; System.out.println("Encoding " + typeToEncode.getSimpleName() + " using " + pair); try { codingAction.call(encodingCodec, decodingCodec); } catch (Exception ex) { throw new Exception("Encoding failure for codec pair " + pair, ex); } } }
6,647
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/converters/EurekaJsonAndXmlJacksonCodecTest.java
package com.netflix.discovery.converters; import java.util.Iterator; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.netflix.appinfo.AmazonInfo; import com.netflix.appinfo.AmazonInfo.MetaDataKey; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.DataCenterInfo.Name; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.LeaseInfo; import com.netflix.discovery.converters.jackson.AbstractEurekaJacksonCodec; import com.netflix.discovery.converters.jackson.EurekaJsonJacksonCodec; import com.netflix.discovery.converters.jackson.EurekaXmlJacksonCodec; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.util.EurekaEntityComparators; import com.netflix.discovery.util.InstanceInfoGenerator; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; /** * @author Tomasz Bak */ public class EurekaJsonAndXmlJacksonCodecTest { private final InstanceInfoGenerator infoGenerator = InstanceInfoGenerator.newBuilder(4, 2).withMetaData(true).build(); private final Iterator<InstanceInfo> infoIterator = infoGenerator.serviceIterator(); @Test public void testAmazonInfoEncodeDecodeWithJson() throws Exception { doAmazonInfoEncodeDecodeTest(new EurekaJsonJacksonCodec()); } @Test public void testAmazonInfoEncodeDecodeWithXml() throws Exception { doAmazonInfoEncodeDecodeTest(new EurekaXmlJacksonCodec()); } private void doAmazonInfoEncodeDecodeTest(AbstractEurekaJacksonCodec codec) throws Exception { AmazonInfo amazonInfo = (AmazonInfo) infoIterator.next().getDataCenterInfo(); String encodedString = codec.getObjectMapper(DataCenterInfo.class).writeValueAsString(amazonInfo); DataCenterInfo decodedValue = codec.getObjectMapper(DataCenterInfo.class).readValue(encodedString, DataCenterInfo.class); assertThat(EurekaEntityComparators.equal(amazonInfo, decodedValue), is(true)); } @Test public void testAmazonInfoCompactEncodeDecodeWithJson() throws Exception { doAmazonInfoCompactEncodeDecodeTest(new EurekaJsonJacksonCodec(KeyFormatter.defaultKeyFormatter(), true)); } @Test public void testAmazonInfoCompactEncodeDecodeWithXml() throws Exception { doAmazonInfoCompactEncodeDecodeTest(new EurekaXmlJacksonCodec(KeyFormatter.defaultKeyFormatter(), true)); } private void doAmazonInfoCompactEncodeDecodeTest(AbstractEurekaJacksonCodec codec) throws Exception { AmazonInfo amazonInfo = (AmazonInfo) infoIterator.next().getDataCenterInfo(); String encodedString = codec.getObjectMapper(DataCenterInfo.class).writeValueAsString(amazonInfo); AmazonInfo decodedValue = (AmazonInfo) codec.getObjectMapper(DataCenterInfo.class).readValue(encodedString, DataCenterInfo.class); assertThat(decodedValue.get(MetaDataKey.publicHostname), is(equalTo(amazonInfo.get(MetaDataKey.publicHostname)))); } @Test public void testMyDataCenterInfoEncodeDecodeWithJson() throws Exception { doMyDataCenterInfoEncodeDecodeTest(new EurekaJsonJacksonCodec()); } @Test public void testMyDataCenterInfoEncodeDecodeWithXml() throws Exception { doMyDataCenterInfoEncodeDecodeTest(new EurekaXmlJacksonCodec()); } private void doMyDataCenterInfoEncodeDecodeTest(AbstractEurekaJacksonCodec codec) throws Exception { DataCenterInfo myDataCenterInfo = new DataCenterInfo() { @Override public Name getName() { return Name.MyOwn; } }; String encodedString = codec.getObjectMapper(DataCenterInfo.class).writeValueAsString(myDataCenterInfo); DataCenterInfo decodedValue = codec.getObjectMapper(DataCenterInfo.class).readValue(encodedString, DataCenterInfo.class); assertThat(decodedValue.getName(), is(equalTo(Name.MyOwn))); } @Test public void testLeaseInfoEncodeDecodeWithJson() throws Exception { doLeaseInfoEncodeDecode(new EurekaJsonJacksonCodec()); } @Test public void testLeaseInfoEncodeDecodeWithXml() throws Exception { doLeaseInfoEncodeDecode(new EurekaXmlJacksonCodec()); } private void doLeaseInfoEncodeDecode(AbstractEurekaJacksonCodec codec) throws Exception { LeaseInfo leaseInfo = infoIterator.next().getLeaseInfo(); String encodedString = codec.getObjectMapper(LeaseInfo.class).writeValueAsString(leaseInfo); LeaseInfo decodedValue = codec.getObjectMapper(LeaseInfo.class).readValue(encodedString, LeaseInfo.class); assertThat(EurekaEntityComparators.equal(leaseInfo, decodedValue), is(true)); } @Test public void testInstanceInfoEncodeDecodeWithJson() throws Exception { doInstanceInfoEncodeDecode(new EurekaJsonJacksonCodec()); } @Test public void testInstanceInfoEncodeDecodeWithXml() throws Exception { doInstanceInfoEncodeDecode(new EurekaXmlJacksonCodec()); } private void doInstanceInfoEncodeDecode(AbstractEurekaJacksonCodec codec) throws Exception { InstanceInfo instanceInfo = infoIterator.next(); String encodedString = codec.getObjectMapper(InstanceInfo.class).writeValueAsString(instanceInfo); InstanceInfo decodedValue = codec.getObjectMapper(InstanceInfo.class).readValue(encodedString, InstanceInfo.class); assertThat(EurekaEntityComparators.equal(instanceInfo, decodedValue), is(true)); } @Test public void testInstanceInfoCompactEncodeDecodeWithJson() throws Exception { doInstanceInfoCompactEncodeDecode(new EurekaJsonJacksonCodec(KeyFormatter.defaultKeyFormatter(), true), true); } @Test public void testInstanceInfoCompactEncodeDecodeWithXml() throws Exception { doInstanceInfoCompactEncodeDecode(new EurekaXmlJacksonCodec(KeyFormatter.defaultKeyFormatter(), true), false); } private void doInstanceInfoCompactEncodeDecode(AbstractEurekaJacksonCodec codec, boolean isJson) throws Exception { InstanceInfo instanceInfo = infoIterator.next(); String encodedString = codec.getObjectMapper(InstanceInfo.class).writeValueAsString(instanceInfo); if (isJson) { JsonNode metadataNode = new ObjectMapper().readTree(encodedString).get("instance").get("metadata"); assertThat(metadataNode, is(nullValue())); } InstanceInfo decodedValue = codec.getObjectMapper(InstanceInfo.class).readValue(encodedString, InstanceInfo.class); assertThat(decodedValue.getId(), is(equalTo(instanceInfo.getId()))); assertThat(decodedValue.getMetadata().isEmpty(), is(true)); } @Test public void testInstanceInfoIgnoredFieldsAreFilteredOutDuringDeserializationProcessWithJson() throws Exception { doInstanceInfoIgnoredFieldsAreFilteredOutDuringDeserializationProcess( new EurekaJsonJacksonCodec(), new EurekaJsonJacksonCodec(KeyFormatter.defaultKeyFormatter(), true) ); } @Test public void testInstanceInfoIgnoredFieldsAreFilteredOutDuringDeserializationProcessWithXml() throws Exception { doInstanceInfoIgnoredFieldsAreFilteredOutDuringDeserializationProcess( new EurekaXmlJacksonCodec(), new EurekaXmlJacksonCodec(KeyFormatter.defaultKeyFormatter(), true) ); } public void doInstanceInfoIgnoredFieldsAreFilteredOutDuringDeserializationProcess(AbstractEurekaJacksonCodec fullCodec, AbstractEurekaJacksonCodec compactCodec) throws Exception { InstanceInfo instanceInfo = infoIterator.next(); // We use regular codec here to have all fields serialized String encodedString = fullCodec.getObjectMapper(InstanceInfo.class).writeValueAsString(instanceInfo); InstanceInfo decodedValue = compactCodec.getObjectMapper(InstanceInfo.class).readValue(encodedString, InstanceInfo.class); assertThat(decodedValue.getId(), is(equalTo(instanceInfo.getId()))); assertThat(decodedValue.getAppName(), is(equalTo(instanceInfo.getAppName()))); assertThat(decodedValue.getIPAddr(), is(equalTo(instanceInfo.getIPAddr()))); assertThat(decodedValue.getVIPAddress(), is(equalTo(instanceInfo.getVIPAddress()))); assertThat(decodedValue.getSecureVipAddress(), is(equalTo(instanceInfo.getSecureVipAddress()))); assertThat(decodedValue.getHostName(), is(equalTo(instanceInfo.getHostName()))); assertThat(decodedValue.getStatus(), is(equalTo(instanceInfo.getStatus()))); assertThat(decodedValue.getActionType(), is(equalTo(instanceInfo.getActionType()))); assertThat(decodedValue.getASGName(), is(equalTo(instanceInfo.getASGName()))); assertThat(decodedValue.getLastUpdatedTimestamp(), is(equalTo(instanceInfo.getLastUpdatedTimestamp()))); AmazonInfo sourceAmazonInfo = (AmazonInfo) instanceInfo.getDataCenterInfo(); AmazonInfo decodedAmazonInfo = (AmazonInfo) decodedValue.getDataCenterInfo(); assertThat(decodedAmazonInfo.get(MetaDataKey.accountId), is(equalTo(sourceAmazonInfo.get(MetaDataKey.accountId)))); } @Test public void testInstanceInfoWithNoMetaEncodeDecodeWithJson() throws Exception { doInstanceInfoWithNoMetaEncodeDecode(new EurekaJsonJacksonCodec(), true); } @Test public void testInstanceInfoWithNoMetaEncodeDecodeWithXml() throws Exception { doInstanceInfoWithNoMetaEncodeDecode(new EurekaXmlJacksonCodec(), false); } private void doInstanceInfoWithNoMetaEncodeDecode(AbstractEurekaJacksonCodec codec, boolean json) throws Exception { InstanceInfo noMetaDataInfo = new InstanceInfo.Builder(infoIterator.next()).setMetadata(null).build(); String encodedString = codec.getObjectMapper(InstanceInfo.class).writeValueAsString(noMetaDataInfo); // Backward compatibility with old codec if (json) { assertThat(encodedString.contains("\"@class\":\"java.util.Collections$EmptyMap\""), is(true)); } InstanceInfo decodedValue = codec.getObjectMapper(InstanceInfo.class).readValue(encodedString, InstanceInfo.class); assertThat(decodedValue.getId(), is(equalTo(noMetaDataInfo.getId()))); assertThat(decodedValue.getMetadata().isEmpty(), is(true)); } @Test public void testApplicationEncodeDecodeWithJson() throws Exception { doApplicationEncodeDecode(new EurekaJsonJacksonCodec()); } @Test public void testApplicationEncodeDecodeWithXml() throws Exception { doApplicationEncodeDecode(new EurekaXmlJacksonCodec()); } private void doApplicationEncodeDecode(AbstractEurekaJacksonCodec codec) throws Exception { Application application = new Application("testApp"); application.addInstance(infoIterator.next()); application.addInstance(infoIterator.next()); String encodedString = codec.getObjectMapper(Application.class).writeValueAsString(application); Application decodedValue = codec.getObjectMapper(Application.class).readValue(encodedString, Application.class); assertThat(EurekaEntityComparators.equal(application, decodedValue), is(true)); } @Test public void testApplicationsEncodeDecodeWithJson() throws Exception { doApplicationsEncodeDecode(new EurekaJsonJacksonCodec()); } @Test public void testApplicationsEncodeDecodeWithXml() throws Exception { doApplicationsEncodeDecode(new EurekaXmlJacksonCodec()); } private void doApplicationsEncodeDecode(AbstractEurekaJacksonCodec codec) throws Exception { Applications applications = infoGenerator.takeDelta(2); String encodedString = codec.getObjectMapper(Applications.class).writeValueAsString(applications); Applications decodedValue = codec.getObjectMapper(Applications.class).readValue(encodedString, Applications.class); assertThat(EurekaEntityComparators.equal(applications, decodedValue), is(true)); } }
6,648
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/converters/JsonXStreamTest.java
package com.netflix.discovery.converters; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import com.thoughtworks.xstream.security.ForbiddenClassException; import org.junit.Test; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.util.EurekaEntityComparators; import com.netflix.discovery.util.InstanceInfoGenerator; import com.thoughtworks.xstream.XStream; /** * @author Borja Lafuente */ public class JsonXStreamTest { @Test public void testEncodingDecodingWithoutMetaData() throws Exception { Applications applications = InstanceInfoGenerator.newBuilder(10, 2).withMetaData(false).build().toApplications(); XStream xstream = JsonXStream.getInstance(); String jsonDocument = xstream.toXML(applications); Applications decodedApplications = (Applications) xstream.fromXML(jsonDocument); assertThat(EurekaEntityComparators.equal(decodedApplications, applications), is(true)); } @Test public void testEncodingDecodingWithMetaData() throws Exception { Applications applications = InstanceInfoGenerator.newBuilder(10, 2).withMetaData(true).build().toApplications(); XStream xstream = JsonXStream.getInstance(); String jsonDocument = xstream.toXML(applications); Applications decodedApplications = (Applications) xstream.fromXML(jsonDocument); assertThat(EurekaEntityComparators.equal(decodedApplications, applications), is(true)); } /** * Tests: http://x-stream.github.io/CVE-2017-7957.html */ @Test(expected=ForbiddenClassException.class, timeout=5000) public void testVoidElementUnmarshalling() throws Exception { XStream xstream = JsonXStream.getInstance(); xstream.fromXML("{'void':null}"); } }
6,649
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/converters
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/converters/wrappers/CodecWrappersTest.java
package com.netflix.discovery.converters.wrappers; import junit.framework.Assert; import org.junit.Test; import javax.ws.rs.core.MediaType; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * @author David Liu */ public class CodecWrappersTest { private static String testWrapperName = "FOO_WRAPPER"; @Test public void testRegisterNewWrapper() { Assert.assertNull(CodecWrappers.getEncoder(testWrapperName)); Assert.assertNull(CodecWrappers.getDecoder(testWrapperName)); CodecWrappers.registerWrapper(new TestWrapper()); Assert.assertNotNull(CodecWrappers.getEncoder(testWrapperName)); Assert.assertNotNull(CodecWrappers.getDecoder(testWrapperName)); } private final class TestWrapper implements CodecWrapper { @Override public <T> T decode(String textValue, Class<T> type) throws IOException { return null; } @Override public <T> T decode(InputStream inputStream, Class<T> type) throws IOException { return null; } @Override public <T> String encode(T object) throws IOException { return null; } @Override public <T> void encode(T object, OutputStream outputStream) throws IOException { } @Override public String codecName() { return testWrapperName; } @Override public boolean support(MediaType mediaType) { return false; } } }
6,650
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/converters/jackson
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/converters/jackson/builder/StringInterningAmazonInfoBuilderTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery.converters.jackson.builder; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.exc.InvalidTypeIdException; import com.fasterxml.jackson.databind.module.SimpleModule; import com.netflix.appinfo.AmazonInfo; import org.junit.Assert; import org.junit.Test; import java.io.IOException; import java.util.HashMap; public class StringInterningAmazonInfoBuilderTest { private ObjectMapper newMapper() { SimpleModule module = new SimpleModule() .addDeserializer(AmazonInfo.class, new StringInterningAmazonInfoBuilder()); return new ObjectMapper().registerModule(module); } /** * Convert to AmazonInfo with a simple map instead of a compact map. The compact map * doesn't have a custom toString and makes it hard to understand diffs in assertions. */ private AmazonInfo nonCompact(AmazonInfo info) { return new AmazonInfo(info.getName().name(), new HashMap<>(info.getMetadata())); } @Test(expected = InvalidTypeIdException.class) public void payloadThatIsEmpty() throws IOException { newMapper().readValue("{}", AmazonInfo.class); } @Test public void payloadWithJustClass() throws IOException { String json = "{" + "\"@class\": \"com.netflix.appinfo.AmazonInfo\"" + "}"; AmazonInfo info = newMapper().readValue(json, AmazonInfo.class); Assert.assertEquals(new AmazonInfo(), info); } @Test public void payloadWithClassAndMetadata() throws IOException { String json = "{" + " \"@class\": \"com.netflix.appinfo.AmazonInfo\"," + " \"metadata\": {" + " \"instance-id\": \"i-12345\"" + " }" + "}"; AmazonInfo info = newMapper().readValue(json, AmazonInfo.class); AmazonInfo expected = AmazonInfo.Builder.newBuilder() .addMetadata(AmazonInfo.MetaDataKey.instanceId, "i-12345") .build(); Assert.assertEquals(expected, nonCompact(info)); } @Test public void payloadWithClassAfterMetadata() throws IOException { String json = "{" + " \"metadata\": {" + " \"instance-id\": \"i-12345\"" + " }," + " \"@class\": \"com.netflix.appinfo.AmazonInfo\"" + "}"; AmazonInfo info = newMapper().readValue(json, AmazonInfo.class); AmazonInfo expected = AmazonInfo.Builder.newBuilder() .addMetadata(AmazonInfo.MetaDataKey.instanceId, "i-12345") .build(); Assert.assertEquals(expected, nonCompact(info)); } @Test public void payloadWithNameBeforeMetadata() throws IOException { String json = "{" + " \"@class\": \"com.netflix.appinfo.AmazonInfo\"," + " \"name\": \"Amazon\"," + " \"metadata\": {" + " \"instance-id\": \"i-12345\"" + " }" + "}"; AmazonInfo info = newMapper().readValue(json, AmazonInfo.class); AmazonInfo expected = AmazonInfo.Builder.newBuilder() .addMetadata(AmazonInfo.MetaDataKey.instanceId, "i-12345") .build(); Assert.assertEquals(expected, nonCompact(info)); } @Test public void payloadWithNameAfterMetadata() throws IOException { String json = "{" + " \"@class\": \"com.netflix.appinfo.AmazonInfo\"," + " \"metadata\": {" + " \"instance-id\": \"i-12345\"" + " }," + " \"name\": \"Amazon\"" + "}"; AmazonInfo info = newMapper().readValue(json, AmazonInfo.class); AmazonInfo expected = AmazonInfo.Builder.newBuilder() .addMetadata(AmazonInfo.MetaDataKey.instanceId, "i-12345") .build(); Assert.assertEquals(expected, nonCompact(info)); } @Test public void payloadWithOtherStuffBeforeAndAfterMetadata() throws IOException { String json = "{" + " \"@class\": \"com.netflix.appinfo.AmazonInfo\"," + " \"foo\": \"bar\"," + " \"metadata\": {" + " \"instance-id\": \"i-12345\"" + " }," + " \"bar\": \"baz\"," + " \"name\": \"Amazon\"" + "}"; AmazonInfo info = newMapper().readValue(json, AmazonInfo.class); AmazonInfo expected = AmazonInfo.Builder.newBuilder() .addMetadata(AmazonInfo.MetaDataKey.instanceId, "i-12345") .build(); Assert.assertEquals(expected, nonCompact(info)); } }
6,651
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/ApplicationsTest.java
package com.netflix.discovery.shared; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.lang.reflect.Constructor; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; import com.google.common.collect.Iterables; import com.netflix.appinfo.AmazonInfo; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.AmazonInfo.MetaDataKey; import com.netflix.appinfo.InstanceInfo.InstanceStatus; import com.netflix.discovery.AzToRegionMapper; import com.netflix.discovery.DefaultEurekaClientConfig; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.InstanceRegionChecker; import com.netflix.discovery.InstanceRegionCheckerTest; import com.netflix.discovery.PropertyBasedAzToRegionMapper; public class ApplicationsTest { @Test public void testVersionAndAppHash() { Applications apps = new Applications(); assertEquals(-1L, (long)apps.getVersion()); assertNull(apps.getAppsHashCode()); apps.setVersion(101L); apps.setAppsHashCode("UP_5_DOWN_6_"); assertEquals(101L, (long)apps.getVersion()); assertEquals("UP_5_DOWN_6_", apps.getAppsHashCode()); } /** * Test that instancesMap in Application and shuffleVirtualHostNameMap in * Applications are correctly updated when the last instance is removed from * an application and shuffleInstances has been run. */ @Test public void shuffleVirtualHostNameMapLastInstanceTest() { DataCenterInfo myDCI = new DataCenterInfo() { public DataCenterInfo.Name getName() { return DataCenterInfo.Name.MyOwn; } }; InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder().setAppName("test") .setVIPAddress("test.testname:1").setDataCenterInfo(myDCI).setHostName("test.hostname").build(); Application application = new Application("TestApp"); application.addInstance(instanceInfo); Applications applications = new Applications(); applications.addApplication(application); applications.shuffleInstances(true); List<InstanceInfo> testApp = applications.getInstancesByVirtualHostName("test.testname:1"); assertEquals(Iterables.getOnlyElement(testApp), application.getByInstanceId("test.hostname")); application.removeInstance(instanceInfo); assertEquals(0, applications.size()); applications.shuffleInstances(true); testApp = applications.getInstancesByVirtualHostName("test.testname:1"); assertTrue(testApp.isEmpty()); assertNull(application.getByInstanceId("test.hostname")); } /** * Test that instancesMap in Application and shuffleVirtualHostNameMap in * Applications are correctly updated when the last instance is removed from * an application and shuffleInstances has been run. */ @Test public void shuffleSecureVirtualHostNameMapLastInstanceTest() { DataCenterInfo myDCI = new DataCenterInfo() { public DataCenterInfo.Name getName() { return DataCenterInfo.Name.MyOwn; } }; InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder().setAppName("test") .setVIPAddress("test.testname:1").setSecureVIPAddress("securetest.testname:7102") .setDataCenterInfo(myDCI).setHostName("test.hostname").build(); Application application = new Application("TestApp"); application.addInstance(instanceInfo); Applications applications = new Applications(); assertEquals(0, applications.size()); applications.addApplication(application); assertEquals(1, applications.size()); applications.shuffleInstances(true); List<InstanceInfo> testApp = applications.getInstancesByVirtualHostName("test.testname:1"); assertEquals(Iterables.getOnlyElement(testApp), application.getByInstanceId("test.hostname")); application.removeInstance(instanceInfo); assertNull(application.getByInstanceId("test.hostname")); assertEquals(0, applications.size()); applications.shuffleInstances(true); testApp = applications.getInstancesBySecureVirtualHostName("securetest.testname:7102"); assertTrue(testApp.isEmpty()); assertNull(application.getByInstanceId("test.hostname")); } /** * Test that instancesMap in Application and shuffleVirtualHostNameMap in * Applications are correctly updated when the last instance is removed from * an application and shuffleInstances has been run. */ @Test public void shuffleRemoteRegistryTest() throws Exception { AmazonInfo ai1 = AmazonInfo.Builder.newBuilder() .addMetadata(MetaDataKey.availabilityZone, "us-east-1a") .build(); InstanceInfo instanceInfo1 = InstanceInfo.Builder.newBuilder().setAppName("test") .setVIPAddress("test.testname:1") .setSecureVIPAddress("securetest.testname:7102") .setDataCenterInfo(ai1) .setAppName("TestApp") .setHostName("test.east.hostname") .build(); AmazonInfo ai2 = AmazonInfo.Builder.newBuilder() .addMetadata(MetaDataKey.availabilityZone, "us-west-2a") .build(); InstanceInfo instanceInfo2 = InstanceInfo.Builder.newBuilder().setAppName("test") .setVIPAddress("test.testname:1") .setSecureVIPAddress("securetest.testname:7102") .setDataCenterInfo(ai2) .setAppName("TestApp") .setHostName("test.west.hostname") .build(); Application application = new Application("TestApp"); application.addInstance(instanceInfo1); application.addInstance(instanceInfo2); Applications applications = new Applications(); assertEquals(0, applications.size()); applications.addApplication(application); assertEquals(2, applications.size()); EurekaClientConfig clientConfig = Mockito.mock(EurekaClientConfig.class); Mockito.when(clientConfig.getAvailabilityZones("us-east-1")).thenReturn(new String[] {"us-east-1a", "us-east-1b", "us-east-1c", "us-east-1d", "us-east-1e", "us-east-1f"}); Mockito.when(clientConfig.getAvailabilityZones("us-west-2")).thenReturn(new String[] {"us-west-2a", "us-west-2b", "us-west-2c"}); Mockito.when(clientConfig.getRegion()).thenReturn("us-east-1"); Constructor<?> ctor = InstanceRegionChecker.class.getDeclaredConstructor(AzToRegionMapper.class, String.class); ctor.setAccessible(true); PropertyBasedAzToRegionMapper azToRegionMapper = new PropertyBasedAzToRegionMapper(clientConfig); azToRegionMapper.setRegionsToFetch(new String[] {"us-east-1", "us-west-2"}); InstanceRegionChecker instanceRegionChecker = (InstanceRegionChecker)ctor.newInstance(azToRegionMapper, "us-west-2"); Map<String, Applications> remoteRegionsRegistry = new HashMap<>(); remoteRegionsRegistry.put("us-east-1", new Applications()); applications.shuffleAndIndexInstances(remoteRegionsRegistry, clientConfig, instanceRegionChecker); assertNotNull(remoteRegionsRegistry.get("us-east-1").getRegisteredApplications("TestApp").getByInstanceId("test.east.hostname")); assertNull(applications.getRegisteredApplications("TestApp").getByInstanceId("test.east.hostname")); assertNull(remoteRegionsRegistry.get("us-east-1").getRegisteredApplications("TestApp").getByInstanceId("test.west.hostname")); assertNotNull(applications.getRegisteredApplications("TestApp").getByInstanceId("test.west.hostname")); } @Test public void testInfoDetailApplications(){ DataCenterInfo myDCI = new DataCenterInfo() { public DataCenterInfo.Name getName() { return DataCenterInfo.Name.MyOwn; } }; InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder() .setInstanceId("test.id") .setAppName("test") .setHostName("test.hostname") .setStatus(InstanceStatus.UP) .setIPAddr("test.testip:1") .setPort(8080) .setSecurePort(443) .setDataCenterInfo(myDCI) .build(); Application application = new Application("Test App"); application.addInstance(instanceInfo); Applications applications = new Applications(); applications.addApplication(application); List<InstanceInfo> instanceInfos = application.getInstances(); Assert.assertEquals(1, instanceInfos.size()); Assert.assertTrue(instanceInfos.contains(instanceInfo)); List<Application> appsList = applications.getRegisteredApplications(); Assert.assertEquals(1, appsList.size()); Assert.assertTrue(appsList.contains(application)); Assert.assertEquals(application, applications.getRegisteredApplications(application.getName())); } @Test public void testRegisteredApplications() { DataCenterInfo myDCI = new DataCenterInfo() { public DataCenterInfo.Name getName() { return DataCenterInfo.Name.MyOwn; } }; InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder() .setAppName("test") .setVIPAddress("test.testname:1") .setSecureVIPAddress("securetest.testname:7102") .setDataCenterInfo(myDCI) .setHostName("test.hostname") .build(); Application application = new Application("TestApp"); application.addInstance(instanceInfo); Applications applications = new Applications(); applications.addApplication(application); List<Application> appsList = applications.getRegisteredApplications(); Assert.assertEquals(1, appsList.size()); Assert.assertTrue(appsList.contains(application)); Assert.assertEquals(application, applications.getRegisteredApplications(application.getName())); } @Test public void testRegisteredApplicationsConstructor() { DataCenterInfo myDCI = new DataCenterInfo() { public DataCenterInfo.Name getName() { return DataCenterInfo.Name.MyOwn; } }; InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder() .setAppName("test") .setVIPAddress("test.testname:1") .setSecureVIPAddress("securetest.testname:7102") .setDataCenterInfo(myDCI) .setHostName("test.hostname") .build(); Application application = new Application("TestApp"); application.addInstance(instanceInfo); Applications applications = new Applications("UP_1_", -1L, Arrays.asList(application)); List<Application> appsList = applications.getRegisteredApplications(); Assert.assertEquals(1, appsList.size()); Assert.assertTrue(appsList.contains(application)); Assert.assertEquals(application, applications.getRegisteredApplications(application.getName())); } @Test public void testApplicationsHashAndVersion() { Applications applications = new Applications("appsHashCode", 1L, Collections.emptyList()); assertEquals(1L, (long)applications.getVersion()); assertEquals("appsHashCode", applications.getAppsHashCode()); } @Test public void testPopulateInstanceCount() { DataCenterInfo myDCI = new DataCenterInfo() { public DataCenterInfo.Name getName() { return DataCenterInfo.Name.MyOwn; } }; InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder() .setAppName("test") .setVIPAddress("test.testname:1") .setSecureVIPAddress("securetest.testname:7102") .setDataCenterInfo(myDCI) .setHostName("test.hostname") .setStatus(InstanceStatus.UP) .build(); Application application = new Application("TestApp"); application.addInstance(instanceInfo); Applications applications = new Applications(); applications.addApplication(application); TreeMap<String, AtomicInteger> instanceCountMap = new TreeMap<>(); applications.populateInstanceCountMap(instanceCountMap); assertEquals(1, instanceCountMap.size()); assertNotNull(instanceCountMap.get(InstanceStatus.UP.name())); assertEquals(1, instanceCountMap.get(InstanceStatus.UP.name()).get()); } @Test public void testGetNextIndex() { DataCenterInfo myDCI = new DataCenterInfo() { public DataCenterInfo.Name getName() { return DataCenterInfo.Name.MyOwn; } }; InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder() .setAppName("test") .setVIPAddress("test.testname:1") .setSecureVIPAddress("securetest.testname:7102") .setDataCenterInfo(myDCI) .setHostName("test.hostname") .setStatus(InstanceStatus.UP) .build(); Application application = new Application("TestApp"); application.addInstance(instanceInfo); Applications applications = new Applications(); applications.addApplication(application); assertNotNull(applications.getNextIndex("test.testname:1", false)); assertEquals(0L, applications.getNextIndex("test.testname:1", false).get()); assertNotNull(applications.getNextIndex("securetest.testname:7102", true)); assertEquals(0L, applications.getNextIndex("securetest.testname:7102", true).get()); assertNotSame(applications.getNextIndex("test.testname:1", false), applications.getNextIndex("securetest.testname:7102", true)); } @Test public void testReconcileHashcode() { DataCenterInfo myDCI = new DataCenterInfo() { public DataCenterInfo.Name getName() { return DataCenterInfo.Name.MyOwn; } }; InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder() .setAppName("test") .setVIPAddress("test.testname:1") .setSecureVIPAddress("securetest.testname:7102") .setDataCenterInfo(myDCI) .setHostName("test.hostname") .setStatus(InstanceStatus.UP) .build(); Application application = new Application("TestApp"); application.addInstance(instanceInfo); Applications applications = new Applications(); String hashCode = applications.getReconcileHashCode(); assertTrue(hashCode.isEmpty()); applications.addApplication(application); hashCode = applications.getReconcileHashCode(); assertFalse(hashCode.isEmpty()); assertEquals("UP_1_", hashCode); } @Test public void testInstanceFiltering() { DataCenterInfo myDCI = new DataCenterInfo() { public DataCenterInfo.Name getName() { return DataCenterInfo.Name.MyOwn; } }; InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder() .setAppName("test") .setVIPAddress("test.testname:1") .setSecureVIPAddress("securetest.testname:7102") .setDataCenterInfo(myDCI) .setHostName("test.hostname") .setStatus(InstanceStatus.DOWN) .build(); Application application = new Application("TestApp"); application.addInstance(instanceInfo); Applications applications = new Applications(); applications.addApplication(application); applications.shuffleInstances(true); assertNotNull(applications.getRegisteredApplications("TestApp").getByInstanceId("test.hostname")); assertTrue(applications.getInstancesBySecureVirtualHostName("securetest.testname:7102").isEmpty()); assertTrue(applications.getInstancesBySecureVirtualHostName("test.testname:1").isEmpty()); } }
6,652
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/transport/EurekaHttpClientsTest.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery.shared.transport; import javax.ws.rs.core.HttpHeaders; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.EurekaInstanceConfig; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.shared.resolver.ClosableResolver; import com.netflix.discovery.shared.resolver.ClusterResolver; import com.netflix.discovery.shared.resolver.DefaultEndpoint; import com.netflix.discovery.shared.resolver.EndpointRandomizer; import com.netflix.discovery.shared.resolver.EurekaEndpoint; import com.netflix.discovery.shared.resolver.ResolverUtils; import com.netflix.discovery.shared.resolver.StaticClusterResolver; import com.netflix.discovery.shared.resolver.aws.ApplicationsResolver; import com.netflix.discovery.shared.resolver.aws.AwsEndpoint; import com.netflix.discovery.shared.resolver.aws.EurekaHttpResolver; import com.netflix.discovery.shared.resolver.aws.TestEurekaHttpResolver; import com.netflix.discovery.shared.transport.jersey.Jersey1TransportClientFactories; import com.netflix.discovery.util.EurekaEntityComparators; import com.netflix.discovery.util.InstanceInfoGenerator; import com.sun.jersey.api.client.ClientHandlerException; import com.sun.jersey.api.client.ClientRequest; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.filter.ClientFilter; import org.junit.After; import org.junit.Before; import org.junit.Test; import static com.netflix.discovery.shared.transport.EurekaHttpResponse.anEurekaHttpResponse; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * @author Tomasz Bak */ public class EurekaHttpClientsTest { private static final InstanceInfo MY_INSTANCE = InstanceInfoGenerator.newBuilder(1, "myApp").build().first(); private final EurekaInstanceConfig instanceConfig = mock(EurekaInstanceConfig.class); private final ApplicationInfoManager applicationInfoManager = new ApplicationInfoManager(instanceConfig, MY_INSTANCE); private final EurekaHttpClient writeRequestHandler = mock(EurekaHttpClient.class); private final EurekaHttpClient readRequestHandler = mock(EurekaHttpClient.class); private EurekaClientConfig clientConfig; private EurekaTransportConfig transportConfig; private SimpleEurekaHttpServer writeServer; private SimpleEurekaHttpServer readServer; private ClusterResolver<EurekaEndpoint> clusterResolver; private EndpointRandomizer randomizer; private EurekaHttpClientFactory clientFactory; private String readServerURI; private final InstanceInfoGenerator instanceGen = InstanceInfoGenerator.newBuilder(2, 1).build(); @Before public void setUp() throws IOException { clientConfig = mock(EurekaClientConfig.class); transportConfig = mock(EurekaTransportConfig.class); randomizer = ResolverUtils::randomize; when(clientConfig.getEurekaServerTotalConnectionsPerHost()).thenReturn(10); when(clientConfig.getEurekaServerTotalConnections()).thenReturn(10); when(transportConfig.getSessionedClientReconnectIntervalSeconds()).thenReturn(10); writeServer = new SimpleEurekaHttpServer(writeRequestHandler); clusterResolver = new StaticClusterResolver<EurekaEndpoint>("regionA", new DefaultEndpoint("localhost", writeServer.getServerPort(), false, "/v2/")); readServer = new SimpleEurekaHttpServer(readRequestHandler); readServerURI = "http://localhost:" + readServer.getServerPort(); clientFactory = EurekaHttpClients.canonicalClientFactory( "test", transportConfig, clusterResolver, new Jersey1TransportClientFactories().newTransportClientFactory( clientConfig, Collections.<ClientFilter>emptyList(), applicationInfoManager.getInfo() )); } @After public void tearDown() throws Exception { if (writeServer != null) { writeServer.shutdown(); } if (readServer != null) { readServer.shutdown(); } if (clientFactory != null) { clientFactory.shutdown(); } } @Test public void testCanonicalClient() throws Exception { Applications apps = instanceGen.toApplications(); when(writeRequestHandler.getApplications()).thenReturn( anEurekaHttpResponse(302, Applications.class).headers("Location", readServerURI + "/v2/apps").build() ); when(readRequestHandler.getApplications()).thenReturn( anEurekaHttpResponse(200, apps).headers(HttpHeaders.CONTENT_TYPE, "application/json").build() ); EurekaHttpClient eurekaHttpClient = clientFactory.newClient(); EurekaHttpResponse<Applications> result = eurekaHttpClient.getApplications(); assertThat(result.getStatusCode(), is(equalTo(200))); assertThat(EurekaEntityComparators.equal(result.getEntity(), apps), is(true)); } @Test public void testCompositeBootstrapResolver() throws Exception { Applications applications = InstanceInfoGenerator.newBuilder(5, "eurekaWrite", "someOther").build().toApplications(); Applications applications2 = InstanceInfoGenerator.newBuilder(2, "eurekaWrite", "someOther").build().toApplications(); String vipAddress = applications.getRegisteredApplications("eurekaWrite").getInstances().get(0).getVIPAddress(); // setup client config to use fixed root ips for testing when(clientConfig.shouldUseDnsForFetchingServiceUrls()).thenReturn(false); when(clientConfig.getEurekaServerServiceUrls(anyString())).thenReturn(Arrays.asList("http://foo:0")); // can use anything here when(clientConfig.getRegion()).thenReturn("us-east-1"); when(transportConfig.getWriteClusterVip()).thenReturn(vipAddress); when(transportConfig.getAsyncExecutorThreadPoolSize()).thenReturn(4); when(transportConfig.getAsyncResolverRefreshIntervalMs()).thenReturn(400); when(transportConfig.getAsyncResolverWarmUpTimeoutMs()).thenReturn(400); ApplicationsResolver.ApplicationsSource applicationsSource = mock(ApplicationsResolver.ApplicationsSource.class); when(applicationsSource.getApplications(anyInt(), eq(TimeUnit.SECONDS))) .thenReturn(null) // first time .thenReturn(applications) // second time .thenReturn(null); // subsequent times EurekaHttpClient mockHttpClient = mock(EurekaHttpClient.class); when(mockHttpClient.getVip(eq(vipAddress))) .thenReturn(anEurekaHttpResponse(200, applications).build()) .thenReturn(anEurekaHttpResponse(200, applications2).build()); // contains diff number of servers TransportClientFactory transportClientFactory = mock(TransportClientFactory.class); when(transportClientFactory.newClient(any(EurekaEndpoint.class))).thenReturn(mockHttpClient); ClosableResolver<AwsEndpoint> resolver = null; try { resolver = EurekaHttpClients.compositeBootstrapResolver( clientConfig, transportConfig, transportClientFactory, applicationInfoManager.getInfo(), applicationsSource, randomizer ); List endpoints = resolver.getClusterEndpoints(); assertThat(endpoints.size(), equalTo(applications.getInstancesByVirtualHostName(vipAddress).size())); // wait for the second cycle that hits the app source verify(applicationsSource, timeout(3000).times(2)).getApplications(anyInt(), eq(TimeUnit.SECONDS)); endpoints = resolver.getClusterEndpoints(); assertThat(endpoints.size(), equalTo(applications.getInstancesByVirtualHostName(vipAddress).size())); // wait for the third cycle that triggers the mock http client (which is the third resolver cycle) // for the third cycle we have mocked the application resolver to return null data so should fall back // to calling the remote resolver again (which should return applications2) verify(mockHttpClient, timeout(3000).times(3)).getVip(anyString()); endpoints = resolver.getClusterEndpoints(); assertThat(endpoints.size(), equalTo(applications2.getInstancesByVirtualHostName(vipAddress).size())); } finally { if (resolver != null) { resolver.shutdown(); } } } @Test public void testCanonicalResolver() throws Exception { when(clientConfig.getEurekaServerURLContext()).thenReturn("context"); when(clientConfig.getRegion()).thenReturn("region"); when(transportConfig.getAsyncExecutorThreadPoolSize()).thenReturn(3); when(transportConfig.getAsyncResolverRefreshIntervalMs()).thenReturn(400); when(transportConfig.getAsyncResolverWarmUpTimeoutMs()).thenReturn(400); Applications applications = InstanceInfoGenerator.newBuilder(5, "eurekaRead", "someOther").build().toApplications(); String vipAddress = applications.getRegisteredApplications("eurekaRead").getInstances().get(0).getVIPAddress(); ApplicationsResolver.ApplicationsSource applicationsSource = mock(ApplicationsResolver.ApplicationsSource.class); when(applicationsSource.getApplications(anyInt(), eq(TimeUnit.SECONDS))) .thenReturn(null) // first time .thenReturn(applications); // subsequent times EurekaHttpClientFactory remoteResolverClientFactory = mock(EurekaHttpClientFactory.class); EurekaHttpClient httpClient = mock(EurekaHttpClient.class); when(remoteResolverClientFactory.newClient()).thenReturn(httpClient); when(httpClient.getVip(vipAddress)).thenReturn(EurekaHttpResponse.anEurekaHttpResponse(200, applications).build()); EurekaHttpResolver remoteResolver = spy(new TestEurekaHttpResolver(clientConfig, transportConfig, remoteResolverClientFactory, vipAddress)); when(transportConfig.getReadClusterVip()).thenReturn(vipAddress); ApplicationsResolver localResolver = spy(new ApplicationsResolver( clientConfig, transportConfig, applicationsSource, transportConfig.getReadClusterVip())); ClosableResolver resolver = null; try { resolver = EurekaHttpClients.compositeQueryResolver( remoteResolver, localResolver, clientConfig, transportConfig, applicationInfoManager.getInfo(), randomizer ); List endpoints = resolver.getClusterEndpoints(); assertThat(endpoints.size(), equalTo(applications.getInstancesByVirtualHostName(vipAddress).size())); verify(remoteResolver, times(1)).getClusterEndpoints(); verify(localResolver, times(1)).getClusterEndpoints(); // wait for the second cycle that hits the app source verify(applicationsSource, timeout(3000).times(2)).getApplications(anyInt(), eq(TimeUnit.SECONDS)); endpoints = resolver.getClusterEndpoints(); assertThat(endpoints.size(), equalTo(applications.getInstancesByVirtualHostName(vipAddress).size())); verify(remoteResolver, times(1)).getClusterEndpoints(); verify(localResolver, times(2)).getClusterEndpoints(); } finally { if (resolver != null) { resolver.shutdown(); } } } @Test public void testAddingAdditionalFilters() throws Exception { TestFilter testFilter = new TestFilter(); Collection<ClientFilter> additionalFilters = Arrays.<ClientFilter>asList(testFilter); TransportClientFactory transportClientFactory = new Jersey1TransportClientFactories().newTransportClientFactory( clientConfig, additionalFilters, MY_INSTANCE ); EurekaHttpClient client = transportClientFactory.newClient(clusterResolver.getClusterEndpoints().get(0)); client.getApplication("foo"); assertThat(testFilter.await(30, TimeUnit.SECONDS), is(true)); } private static class TestFilter extends ClientFilter { private final CountDownLatch latch = new CountDownLatch(1); @Override public ClientResponse handle(ClientRequest cr) throws ClientHandlerException { latch.countDown(); return mock(ClientResponse.class); } public boolean await(long timeout, TimeUnit unit) throws Exception { return latch.await(timeout, unit); } } }
6,653
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/transport
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/transport/jersey/JerseyApplicationClientTest.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery.shared.transport.jersey; import java.net.URI; import com.google.common.base.Preconditions; import com.netflix.discovery.shared.resolver.DefaultEndpoint; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.EurekaHttpClientCompatibilityTestSuite; import com.netflix.discovery.shared.transport.TransportClientFactory; import org.junit.After; public class JerseyApplicationClientTest extends EurekaHttpClientCompatibilityTestSuite { private JerseyApplicationClient jerseyHttpClient; @Override @After public void tearDown() throws Exception { if (jerseyHttpClient != null) { jerseyHttpClient.shutdown(); } super.tearDown(); } @Override protected EurekaHttpClient getEurekaHttpClient(URI serviceURI) { Preconditions.checkState(jerseyHttpClient == null, "EurekaHttpClient has been already created"); TransportClientFactory clientFactory = JerseyEurekaHttpClientFactory.newBuilder() .withClientName("compatibilityTestClient") .build(); jerseyHttpClient = (JerseyApplicationClient) clientFactory.newClient(new DefaultEndpoint(serviceURI.toString())); return jerseyHttpClient; } }
6,654
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/transport
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/transport/jersey/UnexpectedContentTypeTest.java
package com.netflix.discovery.shared.transport.jersey; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.shared.resolver.DefaultEndpoint; import com.netflix.discovery.shared.transport.EurekaHttpResponse; import com.netflix.discovery.shared.transport.TransportClientFactory; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.util.UUID; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * @author rbolles on 12/19/19. */ public class UnexpectedContentTypeTest { protected static final String CLIENT_APP_NAME = "unexpectedContentTypeTest"; private JerseyApplicationClient jerseyHttpClient; @Rule public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort().dynamicHttpsPort()); // No-args constructor defaults to port 8080 @Before public void setUp() throws Exception { TransportClientFactory clientFactory = JerseyEurekaHttpClientFactory.newBuilder() .withClientName(CLIENT_APP_NAME) .build(); String uri = String.format("http://localhost:%s/v2/", wireMockRule.port()); jerseyHttpClient = (JerseyApplicationClient) clientFactory.newClient(new DefaultEndpoint(uri)); } @Test public void testSendHeartBeatReceivesUnexpectedHtmlResponse() { long lastDirtyTimestamp = System.currentTimeMillis(); String uuid = UUID.randomUUID().toString(); stubFor(put(urlPathEqualTo("/v2/apps/" + CLIENT_APP_NAME + "/" + uuid)) .withQueryParam("status", equalTo("UP")) .withQueryParam("lastDirtyTimestamp", equalTo(lastDirtyTimestamp + "")) .willReturn(aResponse() .withStatus(502) .withHeader("Content-Type", "text/HTML") .withBody("<html><body>Something went wrong in Apacache</body></html>"))); InstanceInfo instanceInfo = mock(InstanceInfo.class); when(instanceInfo.getStatus()).thenReturn(InstanceInfo.InstanceStatus.UP); when(instanceInfo.getLastDirtyTimestamp()).thenReturn(lastDirtyTimestamp); EurekaHttpResponse<InstanceInfo> response = jerseyHttpClient.sendHeartBeat(CLIENT_APP_NAME, uuid, instanceInfo, null); verify(putRequestedFor(urlPathEqualTo("/v2/apps/" + CLIENT_APP_NAME + "/" + uuid)) .withQueryParam("status", equalTo("UP")) .withQueryParam("lastDirtyTimestamp", equalTo(lastDirtyTimestamp + "")) ); assertThat(response.getStatusCode()).as("status code").isEqualTo(502); assertThat(response.getEntity()).as("instance info").isNull(); } @After public void tearDown() throws Exception { if (jerseyHttpClient != null) { jerseyHttpClient.shutdown(); } } }
6,655
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/transport
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/transport/decorator/RetryableEurekaHttpClientTest.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery.shared.transport.decorator; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import com.netflix.discovery.shared.resolver.ClusterResolver; import com.netflix.discovery.shared.resolver.EurekaEndpoint; import com.netflix.discovery.shared.resolver.aws.SampleCluster; import com.netflix.discovery.shared.resolver.aws.AwsEndpoint; import com.netflix.discovery.shared.transport.DefaultEurekaTransportConfig; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.EurekaHttpResponse; import com.netflix.discovery.shared.transport.EurekaTransportConfig; import com.netflix.discovery.shared.transport.TransportClientFactory; import com.netflix.discovery.shared.transport.TransportException; import com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.RequestExecutor; import com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.RequestType; import org.junit.Before; import org.junit.Test; import org.mockito.Matchers; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * @author Tomasz Bak */ public class RetryableEurekaHttpClientTest { private static final int NUMBER_OF_RETRIES = 2; private static final int CLUSTER_SIZE = 3; public static final RequestType TEST_REQUEST_TYPE = RequestType.Register; private static final List<AwsEndpoint> CLUSTER_ENDPOINTS = SampleCluster.UsEast1a.builder().withServerPool(CLUSTER_SIZE).build(); private final EurekaTransportConfig transportConfig = mock(EurekaTransportConfig.class); private final ClusterResolver clusterResolver = mock(ClusterResolver.class); private final TransportClientFactory clientFactory = mock(TransportClientFactory.class); private final ServerStatusEvaluator serverStatusEvaluator = ServerStatusEvaluators.legacyEvaluator(); private final RequestExecutor<Void> requestExecutor = mock(RequestExecutor.class); private RetryableEurekaHttpClient retryableClient; private List<EurekaHttpClient> clusterDelegates; @Before public void setUp() throws Exception { when(transportConfig.getRetryableClientQuarantineRefreshPercentage()).thenReturn(0.66); retryableClient = new RetryableEurekaHttpClient( "test", transportConfig, clusterResolver, clientFactory, serverStatusEvaluator, NUMBER_OF_RETRIES); clusterDelegates = new ArrayList<>(CLUSTER_SIZE); for (int i = 0; i < CLUSTER_SIZE; i++) { clusterDelegates.add(mock(EurekaHttpClient.class)); } when(clusterResolver.getClusterEndpoints()).thenReturn(CLUSTER_ENDPOINTS); } @Test public void testRequestsReuseSameConnectionIfThereIsNoError() throws Exception { when(clientFactory.newClient(Matchers.<EurekaEndpoint>anyVararg())).thenReturn(clusterDelegates.get(0)); when(requestExecutor.execute(clusterDelegates.get(0))).thenReturn(EurekaHttpResponse.status(200)); // First request creates delegate, second reuses it for (int i = 0; i < 3; i++) { EurekaHttpResponse<Void> httpResponse = retryableClient.execute(requestExecutor); assertThat(httpResponse.getStatusCode(), is(equalTo(200))); } verify(clientFactory, times(1)).newClient(Matchers.<EurekaEndpoint>anyVararg()); verify(requestExecutor, times(3)).execute(clusterDelegates.get(0)); } @Test public void testRequestIsRetriedOnConnectionError() throws Exception { when(clientFactory.newClient(Matchers.<EurekaEndpoint>anyVararg())).thenReturn(clusterDelegates.get(0), clusterDelegates.get(1)); when(requestExecutor.execute(clusterDelegates.get(0))).thenThrow(new TransportException("simulated network error")); when(requestExecutor.execute(clusterDelegates.get(1))).thenReturn(EurekaHttpResponse.status(200)); EurekaHttpResponse<Void> httpResponse = retryableClient.execute(requestExecutor); assertThat(httpResponse.getStatusCode(), is(equalTo(200))); verify(clientFactory, times(2)).newClient(Matchers.<EurekaEndpoint>anyVararg()); verify(requestExecutor, times(1)).execute(clusterDelegates.get(0)); verify(requestExecutor, times(1)).execute(clusterDelegates.get(1)); } @Test(expected = TransportException.class) public void testErrorResponseIsReturnedIfRetryLimitIsReached() throws Exception { simulateTransportError(0, NUMBER_OF_RETRIES + 1); retryableClient.execute(requestExecutor); } @Test public void testQuarantineListIsResetWhenNoMoreServerAreAvailable() throws Exception { // First two call fail simulateTransportError(0, CLUSTER_SIZE); for (int i = 0; i < 2; i++) { executeWithTransportErrorExpectation(); } // Second call, should reset cluster quarantine list, and hit health node 0 when(clientFactory.newClient(Matchers.<EurekaEndpoint>anyVararg())).thenReturn(clusterDelegates.get(0)); reset(requestExecutor); when(requestExecutor.execute(clusterDelegates.get(0))).thenReturn(EurekaHttpResponse.status(200)); retryableClient.execute(requestExecutor); } @Test public void test5xxStatusCodeResultsInRequestRetry() throws Exception { when(clientFactory.newClient(Matchers.<EurekaEndpoint>anyVararg())).thenReturn(clusterDelegates.get(0), clusterDelegates.get(1)); when(requestExecutor.execute(clusterDelegates.get(0))).thenReturn(EurekaHttpResponse.status(500)); when(requestExecutor.execute(clusterDelegates.get(1))).thenReturn(EurekaHttpResponse.status(200)); EurekaHttpResponse<Void> httpResponse = retryableClient.execute(requestExecutor); assertThat(httpResponse.getStatusCode(), is(equalTo(200))); verify(requestExecutor, times(1)).execute(clusterDelegates.get(0)); verify(requestExecutor, times(1)).execute(clusterDelegates.get(1)); } @Test(timeout = 10000) public void testConcurrentRequestsLeaveLastSuccessfulDelegate() throws Exception { when(clientFactory.newClient(Matchers.<EurekaEndpoint>anyVararg())).thenReturn(clusterDelegates.get(0), clusterDelegates.get(1)); BlockingRequestExecutor executor0 = new BlockingRequestExecutor(); BlockingRequestExecutor executor1 = new BlockingRequestExecutor(); Thread thread0 = new Thread(new RequestExecutorRunner(executor0)); Thread thread1 = new Thread(new RequestExecutorRunner(executor1)); // Run parallel requests thread0.start(); executor0.awaitReady(); thread1.start(); executor1.awaitReady(); // Complete request, first thread first, second afterwards executor0.complete(); thread0.join(); executor1.complete(); thread1.join(); // Verify subsequent request done on delegate1 when(requestExecutor.execute(clusterDelegates.get(1))).thenReturn(EurekaHttpResponse.status(200)); EurekaHttpResponse<Void> httpResponse = retryableClient.execute(requestExecutor); assertThat(httpResponse.getStatusCode(), is(equalTo(200))); verify(clientFactory, times(2)).newClient(Matchers.<EurekaEndpoint>anyVararg()); verify(requestExecutor, times(0)).execute(clusterDelegates.get(0)); verify(requestExecutor, times(1)).execute(clusterDelegates.get(1)); } private void simulateTransportError(int delegateFrom, int count) { for (int i = 0; i < count; i++) { int delegateId = delegateFrom + i; when(clientFactory.newClient(Matchers.<EurekaEndpoint>anyVararg())).thenReturn(clusterDelegates.get(delegateId)); when(requestExecutor.execute(clusterDelegates.get(delegateId))).thenThrow(new TransportException("simulated network error")); } } private void executeWithTransportErrorExpectation() { try { retryableClient.execute(requestExecutor); fail("TransportException expected"); } catch (TransportException ignore) { } } class RequestExecutorRunner implements Runnable { private final RequestExecutor<Void> requestExecutor; RequestExecutorRunner(RequestExecutor<Void> requestExecutor) { this.requestExecutor = requestExecutor; } @Override public void run() { retryableClient.execute(requestExecutor); } } static class BlockingRequestExecutor implements RequestExecutor<Void> { private final CountDownLatch readyLatch = new CountDownLatch(1); private final CountDownLatch completeLatch = new CountDownLatch(1); @Override public EurekaHttpResponse<Void> execute(EurekaHttpClient delegate) { readyLatch.countDown(); try { completeLatch.await(); } catch (InterruptedException e) { throw new IllegalStateException("never released"); } return EurekaHttpResponse.status(200); } @Override public RequestType getRequestType() { return TEST_REQUEST_TYPE; } void awaitReady() { try { readyLatch.await(); } catch (InterruptedException e) { throw new IllegalStateException("never released"); } } void complete() { completeLatch.countDown(); } } }
6,656
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/transport
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/transport/decorator/RedirectingEurekaHttpClientTest.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery.shared.transport.decorator; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.shared.dns.DnsService; import com.netflix.discovery.shared.resolver.EurekaEndpoint; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.TransportClientFactory; import com.netflix.discovery.shared.transport.TransportException; import org.junit.Test; import org.mockito.Matchers; import static com.netflix.discovery.shared.transport.EurekaHttpResponse.anEurekaHttpResponse; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * @author Tomasz Bak */ public class RedirectingEurekaHttpClientTest { private static final String SERVICE_URL = "http://mydiscovery.test"; private final TransportClientFactory factory = mock(TransportClientFactory.class); private final EurekaHttpClient sourceClient = mock(EurekaHttpClient.class); private final EurekaHttpClient redirectedClient = mock(EurekaHttpClient.class); private final DnsService dnsService = mock(DnsService.class); public void setupRedirect() { when(factory.newClient(Matchers.<EurekaEndpoint>anyVararg())).thenReturn(sourceClient, redirectedClient); when(sourceClient.getApplications()).thenReturn( anEurekaHttpResponse(302, Applications.class) .headers(HttpHeaders.LOCATION, "http://another.discovery.test/eureka/v2/apps") .build() ); when(dnsService.resolveIp("another.discovery.test")).thenReturn("192.168.0.1"); when(redirectedClient.getApplications()).thenReturn( anEurekaHttpResponse(200, new Applications()).type(MediaType.APPLICATION_JSON_TYPE).build() ); } @Test public void testNonRedirectedRequestsAreServedByFirstClient() throws Exception { when(factory.newClient(Matchers.<EurekaEndpoint>anyVararg())).thenReturn(sourceClient); when(sourceClient.getApplications()).thenReturn( anEurekaHttpResponse(200, new Applications()).type(MediaType.APPLICATION_JSON_TYPE).build() ); RedirectingEurekaHttpClient httpClient = new RedirectingEurekaHttpClient(SERVICE_URL, factory, dnsService); httpClient.getApplications(); verify(factory, times(1)).newClient(Matchers.<EurekaEndpoint>anyVararg()); verify(sourceClient, times(1)).getApplications(); } @Test public void testRedirectsAreFollowedAndClientIsPinnedToTheLastServer() throws Exception { setupRedirect(); RedirectingEurekaHttpClient httpClient = new RedirectingEurekaHttpClient(SERVICE_URL, factory, dnsService); // First call pins client to resolved IP httpClient.getApplications(); verify(factory, times(2)).newClient(Matchers.<EurekaEndpoint>anyVararg()); verify(sourceClient, times(1)).getApplications(); verify(dnsService, times(1)).resolveIp("another.discovery.test"); verify(redirectedClient, times(1)).getApplications(); // Second call goes straight to the same address httpClient.getApplications(); verify(factory, times(2)).newClient(Matchers.<EurekaEndpoint>anyVararg()); verify(sourceClient, times(1)).getApplications(); verify(dnsService, times(1)).resolveIp("another.discovery.test"); verify(redirectedClient, times(2)).getApplications(); } @Test public void testOnConnectionErrorPinnedClientIsDestroyed() throws Exception { setupRedirect(); RedirectingEurekaHttpClient httpClient = new RedirectingEurekaHttpClient(SERVICE_URL, factory, dnsService); // First call pins client to resolved IP httpClient.getApplications(); verify(redirectedClient, times(1)).getApplications(); // Trigger connection error when(redirectedClient.getApplications()).thenThrow(new TransportException("simulated network error")); try { httpClient.getApplications(); fail("Expected transport error"); } catch (Exception ignored) { } // Subsequent connection shall create new httpClient reset(factory, sourceClient, dnsService, redirectedClient); setupRedirect(); httpClient.getApplications(); verify(factory, times(2)).newClient(Matchers.<EurekaEndpoint>anyVararg()); verify(sourceClient, times(1)).getApplications(); verify(dnsService, times(1)).resolveIp("another.discovery.test"); verify(redirectedClient, times(1)).getApplications(); } }
6,657
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/transport
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/transport/decorator/SessionedEurekaHttpClientTest.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery.shared.transport.decorator; import java.util.concurrent.atomic.AtomicReference; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.EurekaHttpClientFactory; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * @author Tomasz Bak */ public class SessionedEurekaHttpClientTest { private final EurekaHttpClient firstClient = mock(EurekaHttpClient.class); private final EurekaHttpClient secondClient = mock(EurekaHttpClient.class); private final EurekaHttpClientFactory factory = mock(EurekaHttpClientFactory.class); @Test public void testReconnectIsEnforcedAtConfiguredInterval() throws Exception { final AtomicReference<EurekaHttpClient> clientRef = new AtomicReference<>(firstClient); when(factory.newClient()).thenAnswer(new Answer<EurekaHttpClient>() { @Override public EurekaHttpClient answer(InvocationOnMock invocation) throws Throwable { return clientRef.get(); } }); SessionedEurekaHttpClient httpClient = null; try { httpClient = new SessionedEurekaHttpClient("test", factory, 1); httpClient.getApplications(); verify(firstClient, times(1)).getApplications(); clientRef.set(secondClient); Thread.sleep(2); httpClient.getApplications(); verify(secondClient, times(1)).getApplications(); } finally { if (httpClient != null) { httpClient.shutdown(); } } } }
6,658
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver/StaticClusterResolverTest.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery.shared.resolver; import java.net.URL; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; /** * @author Tomasz Bak */ public class StaticClusterResolverTest { @Test public void testClusterResolverFromURL() throws Exception { verifyEqual( StaticClusterResolver.fromURL("regionA", new URL("http://eureka.test:8080/eureka/v2/apps")), new DefaultEndpoint("eureka.test", 8080, false, "/eureka/v2/apps") ); verifyEqual( StaticClusterResolver.fromURL("regionA", new URL("https://eureka.test:8081/eureka/v2/apps")), new DefaultEndpoint("eureka.test", 8081, true, "/eureka/v2/apps") ); verifyEqual( StaticClusterResolver.fromURL("regionA", new URL("http://eureka.test/eureka/v2/apps")), new DefaultEndpoint("eureka.test", 80, false, "/eureka/v2/apps") ); verifyEqual( StaticClusterResolver.fromURL("regionA", new URL("https://eureka.test/eureka/v2/apps")), new DefaultEndpoint("eureka.test", 443, true, "/eureka/v2/apps") ); } private static void verifyEqual(ClusterResolver<EurekaEndpoint> actual, EurekaEndpoint expected) { assertThat(actual.getClusterEndpoints().get(0), is(equalTo(expected))); } }
6,659
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver/ResolverUtilsTest.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery.shared.resolver; import java.util.List; import com.netflix.appinfo.AmazonInfo; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.MyDataCenterInfo; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.shared.resolver.aws.AwsEndpoint; import com.netflix.discovery.shared.resolver.aws.SampleCluster; import com.netflix.discovery.shared.transport.EurekaTransportConfig; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * @author Tomasz Bak */ public class ResolverUtilsTest { @Test public void testSplitByZone() throws Exception { List<AwsEndpoint> endpoints = SampleCluster.merge(SampleCluster.UsEast1a, SampleCluster.UsEast1b, SampleCluster.UsEast1c); List<AwsEndpoint>[] parts = ResolverUtils.splitByZone(endpoints, "us-east-1b"); List<AwsEndpoint> myZoneServers = parts[0]; List<AwsEndpoint> remainingServers = parts[1]; assertThat(myZoneServers, is(equalTo(SampleCluster.UsEast1b.build()))); assertThat(remainingServers, is(equalTo(SampleCluster.merge(SampleCluster.UsEast1a, SampleCluster.UsEast1c)))); } @Test public void testExtractZoneFromHostName() throws Exception { assertThat(ResolverUtils.extractZoneFromHostName("us-east-1c.myservice.net"), is(equalTo("us-east-1c"))); assertThat(ResolverUtils.extractZoneFromHostName("txt.us-east-1c.myservice.net"), is(equalTo("us-east-1c"))); } @Test public void testRandomizeProperlyRandomizesList() throws Exception { boolean success = false; for (int i = 0; i < 100; i++) { List<AwsEndpoint> firstList = SampleCluster.UsEast1a.builder().withServerPool(100).build(); List<AwsEndpoint> secondList = ResolverUtils.randomize(firstList); try { assertThat(firstList, is(not(equalTo(secondList)))); success = true; break; }catch(AssertionError e) { } } if(!success) { throw new AssertionError("ResolverUtils::randomize returned the same list 100 times, this is more than likely a bug."); } } @Test public void testRandomizeReturnsACopyOfTheMethodParameter() throws Exception { List<AwsEndpoint> firstList = SampleCluster.UsEast1a.builder().withServerPool(1).build(); List<AwsEndpoint> secondList = ResolverUtils.randomize(firstList); assertThat(firstList, is(not(sameInstance(secondList)))); } @Test public void testIdentical() throws Exception { List<AwsEndpoint> firstList = SampleCluster.UsEast1a.builder().withServerPool(10).build(); List<AwsEndpoint> secondList = ResolverUtils.randomize(firstList); assertThat(ResolverUtils.identical(firstList, secondList), is(true)); secondList.set(0, SampleCluster.UsEast1b.build().get(0)); assertThat(ResolverUtils.identical(firstList, secondList), is(false)); } @Test public void testInstanceInfoToEndpoint() throws Exception { EurekaClientConfig clientConfig = mock(EurekaClientConfig.class); when(clientConfig.getEurekaServerURLContext()).thenReturn("/eureka"); when(clientConfig.getRegion()).thenReturn("region"); EurekaTransportConfig transportConfig = mock(EurekaTransportConfig.class); when(transportConfig.applicationsResolverUseIp()).thenReturn(false); AmazonInfo amazonInfo = AmazonInfo.Builder.newBuilder().addMetadata(AmazonInfo.MetaDataKey.availabilityZone, "us-east-1c").build(); InstanceInfo instanceWithAWSInfo = InstanceInfo.Builder.newBuilder().setAppName("appName") .setHostName("hostName").setPort(8080).setDataCenterInfo(amazonInfo).build(); AwsEndpoint awsEndpoint = ResolverUtils.instanceInfoToEndpoint(clientConfig, transportConfig, instanceWithAWSInfo); assertEquals("zone not equals.", "us-east-1c", awsEndpoint.getZone()); MyDataCenterInfo myDataCenterInfo = new MyDataCenterInfo(DataCenterInfo.Name.MyOwn); InstanceInfo instanceWithMyDataInfo = InstanceInfo.Builder.newBuilder().setAppName("appName") .setHostName("hostName").setPort(8080).setDataCenterInfo(myDataCenterInfo) .add("zone", "us-east-1c").build(); awsEndpoint = ResolverUtils.instanceInfoToEndpoint(clientConfig, transportConfig, instanceWithMyDataInfo); assertEquals("zone not equals.", "us-east-1c", awsEndpoint.getZone()); } }
6,660
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver/AsyncResolverTest.java
package com.netflix.discovery.shared.resolver; import com.netflix.discovery.shared.resolver.aws.SampleCluster; import com.netflix.discovery.shared.transport.EurekaTransportConfig; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyLong; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * @author David Liu */ public class AsyncResolverTest { private final EurekaTransportConfig transportConfig = mock(EurekaTransportConfig.class); private final ClusterResolver delegateResolver = mock(ClosableResolver.class); private AsyncResolver resolver; @Before public void setUp() { when(transportConfig.getAsyncExecutorThreadPoolSize()).thenReturn(3); when(transportConfig.getAsyncResolverRefreshIntervalMs()).thenReturn(200); when(transportConfig.getAsyncResolverWarmUpTimeoutMs()).thenReturn(100); resolver = spy(new AsyncResolver( "test", delegateResolver, transportConfig.getAsyncExecutorThreadPoolSize(), transportConfig.getAsyncResolverRefreshIntervalMs(), transportConfig.getAsyncResolverWarmUpTimeoutMs() )); } @After public void shutDown() { resolver.shutdown(); } @Test public void testHappyCase() { List delegateReturns1 = new ArrayList(SampleCluster.UsEast1a.builder().withServerPool(2).build()); List delegateReturns2 = new ArrayList(SampleCluster.UsEast1b.builder().withServerPool(3).build()); when(delegateResolver.getClusterEndpoints()) .thenReturn(delegateReturns1) .thenReturn(delegateReturns2); List endpoints = resolver.getClusterEndpoints(); assertThat(endpoints.size(), equalTo(delegateReturns1.size())); verify(delegateResolver, times(1)).getClusterEndpoints(); verify(resolver, times(1)).doWarmUp(); // try again, should be async endpoints = resolver.getClusterEndpoints(); assertThat(endpoints.size(), equalTo(delegateReturns1.size())); verify(delegateResolver, times(1)).getClusterEndpoints(); verify(resolver, times(1)).doWarmUp(); // wait for the next async update cycle verify(delegateResolver, timeout(1000).times(2)).getClusterEndpoints(); endpoints = resolver.getClusterEndpoints(); assertThat(endpoints.size(), equalTo(delegateReturns2.size())); verify(delegateResolver, times(2)).getClusterEndpoints(); verify(resolver, times(1)).doWarmUp(); } @Test public void testDelegateFailureAtWarmUp() { when(delegateResolver.getClusterEndpoints()) .thenReturn(null); // override the scheduling which will be triggered immediately if warmUp fails (as is intended). // do this to avoid thread race conditions for a more predictable test doNothing().when(resolver).scheduleTask(anyLong()); List endpoints = resolver.getClusterEndpoints(); assertThat(endpoints.isEmpty(), is(true)); verify(delegateResolver, times(1)).getClusterEndpoints(); verify(resolver, times(1)).doWarmUp(); } }
6,661
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver/ReloadingClusterResolverTest.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery.shared.resolver; import java.util.List; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicReference; import com.netflix.discovery.shared.resolver.aws.AwsEndpoint; import com.netflix.discovery.shared.resolver.aws.SampleCluster; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; /** * @author Tomasz Bak */ public class ReloadingClusterResolverTest { private final InjectableFactory factory = new InjectableFactory(); private ReloadingClusterResolver<AwsEndpoint> resolver; @Test(timeout = 30000) public void testDataAreReloadedPeriodically() throws Exception { List<AwsEndpoint> firstEndpointList = SampleCluster.UsEast1a.build(); factory.setEndpoints(firstEndpointList); // First endpoint list is loaded eagerly resolver = new ReloadingClusterResolver<>(factory, 1); assertThat(resolver.getClusterEndpoints(), is(equalTo(firstEndpointList))); // Swap with a different one List<AwsEndpoint> secondEndpointList = SampleCluster.UsEast1b.build(); factory.setEndpoints(secondEndpointList); assertThat(awaitUpdate(resolver, secondEndpointList), is(true)); } @Test(timeout = 30000) public void testIdenticalListsDoNotCauseReload() throws Exception { List<AwsEndpoint> firstEndpointList = SampleCluster.UsEast1a.build(); factory.setEndpoints(firstEndpointList); // First endpoint list is loaded eagerly resolver = new ReloadingClusterResolver(factory, 1); assertThat(resolver.getClusterEndpoints(), is(equalTo(firstEndpointList))); // Now inject the same one but in the different order List<AwsEndpoint> snapshot = resolver.getClusterEndpoints(); factory.setEndpoints(ResolverUtils.randomize(firstEndpointList)); Thread.sleep(5); assertThat(resolver.getClusterEndpoints(), is(equalTo(snapshot))); // Now inject different list List<AwsEndpoint> secondEndpointList = SampleCluster.UsEast1b.build(); factory.setEndpoints(secondEndpointList); assertThat(awaitUpdate(resolver, secondEndpointList), is(true)); } private static boolean awaitUpdate(ReloadingClusterResolver<AwsEndpoint> resolver, List<AwsEndpoint> expected) throws Exception { long deadline = System.currentTimeMillis() + 5 * 1000; do { List<AwsEndpoint> current = resolver.getClusterEndpoints(); if (ResolverUtils.identical(current, expected)) { return true; } Thread.sleep(1); } while (System.currentTimeMillis() < deadline); throw new TimeoutException("Endpoint list not reloaded on time"); } static class InjectableFactory implements ClusterResolverFactory<AwsEndpoint> { private final AtomicReference<List<AwsEndpoint>> currentEndpointsRef = new AtomicReference<>(); @Override public ClusterResolver<AwsEndpoint> createClusterResolver() { return new StaticClusterResolver<>("regionA", currentEndpointsRef.get()); } void setEndpoints(List<AwsEndpoint> endpoints) { currentEndpointsRef.set(endpoints); } } }
6,662
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver/aws/ZoneAffinityClusterResolverTest.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery.shared.resolver.aws; import java.util.List; import com.netflix.discovery.shared.resolver.ResolverUtils; import com.netflix.discovery.shared.resolver.StaticClusterResolver; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; /** * @author Tomasz Bak */ public class ZoneAffinityClusterResolverTest { @Test public void testApplicationZoneIsFirstOnTheList() throws Exception { List<AwsEndpoint> endpoints = SampleCluster.merge(SampleCluster.UsEast1a, SampleCluster.UsEast1b, SampleCluster.UsEast1c); ZoneAffinityClusterResolver resolver = new ZoneAffinityClusterResolver( new StaticClusterResolver<>("regionA", endpoints), "us-east-1b", true, ResolverUtils::randomize); List<AwsEndpoint> result = resolver.getClusterEndpoints(); assertThat(result.size(), is(equalTo(endpoints.size()))); assertThat(result.get(0).getZone(), is(equalTo("us-east-1b"))); } @Test public void testAntiAffinity() throws Exception { List<AwsEndpoint> endpoints = SampleCluster.merge(SampleCluster.UsEast1a, SampleCluster.UsEast1b); ZoneAffinityClusterResolver resolver = new ZoneAffinityClusterResolver(new StaticClusterResolver<>("regionA", endpoints), "us-east-1b", false, ResolverUtils::randomize); List<AwsEndpoint> result = resolver.getClusterEndpoints(); assertThat(result.size(), is(equalTo(endpoints.size()))); assertThat(result.get(0).getZone(), is(equalTo("us-east-1a"))); } @Test public void testUnrecognizedZoneIsIgnored() throws Exception { List<AwsEndpoint> endpoints = SampleCluster.merge(SampleCluster.UsEast1a, SampleCluster.UsEast1b); ZoneAffinityClusterResolver resolver = new ZoneAffinityClusterResolver(new StaticClusterResolver<>("regionA", endpoints), "us-east-1c", true, ResolverUtils::randomize); List<AwsEndpoint> result = resolver.getClusterEndpoints(); assertThat(result.size(), is(equalTo(endpoints.size()))); } }
6,663
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver/aws/ConfigClusterResolverTest.java
package com.netflix.discovery.shared.resolver.aws; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.MyDataCenterInfo; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.util.InstanceInfoGenerator; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import java.util.List; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * @author David Liu */ public class ConfigClusterResolverTest { private final EurekaClientConfig clientConfig = mock(EurekaClientConfig.class); private final List<String> endpointsC = Arrays.asList( "http://1.1.1.1:8000/eureka/v2/", "http://1.1.1.2:8000/eureka/v2/", "http://1.1.1.3:8000/eureka/v2/" ); private final List<String> endpointsD = Arrays.asList( "http://1.1.2.1:8000/eureka/v2/", "http://1.1.2.2:8000/eureka/v2/" ); private final List<String> endpointsWithBasicAuth = Arrays.asList( "https://myuser:mypassword@1.1.3.1/eureka/v2/" ); private ConfigClusterResolver resolver; @Before public void setUp() { when(clientConfig.shouldUseDnsForFetchingServiceUrls()).thenReturn(false); when(clientConfig.getRegion()).thenReturn("us-east-1"); when(clientConfig.getAvailabilityZones("us-east-1")).thenReturn(new String[]{"us-east-1c", "us-east-1d", "us-east-1e"}); when(clientConfig.getEurekaServerServiceUrls("us-east-1c")).thenReturn(endpointsC); when(clientConfig.getEurekaServerServiceUrls("us-east-1d")).thenReturn(endpointsD); when(clientConfig.getEurekaServerServiceUrls("us-east-1e")).thenReturn(endpointsWithBasicAuth); InstanceInfo instanceInfo = new InstanceInfo.Builder(InstanceInfoGenerator.takeOne()) .setDataCenterInfo(new MyDataCenterInfo(DataCenterInfo.Name.MyOwn)) .build(); resolver = new ConfigClusterResolver(clientConfig, instanceInfo); } @Test public void testReadFromConfig() { List<AwsEndpoint> endpoints = resolver.getClusterEndpoints(); assertThat(endpoints.size(), equalTo(6)); for (AwsEndpoint endpoint : endpoints) { if (endpoint.getZone().equals("us-east-1e")) { assertThat("secure was wrong", endpoint.isSecure(), is(true)); assertThat("serviceUrl contains -1", endpoint.getServiceUrl().contains("-1"), is(false)); assertThat("BASIC auth credentials expected", endpoint.getServiceUrl().contains("myuser:mypassword"), is(true)); } } } }
6,664
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver/aws/SampleCluster.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery.shared.resolver.aws; import java.util.ArrayList; import java.util.List; /** * @author Tomasz Bak */ public enum SampleCluster { UsEast1a() { @Override public SampleClusterBuilder builder() { return new SampleClusterBuilder("us-east-1", "us-east-1a", "10.10.10."); } }, UsEast1b() { @Override public SampleClusterBuilder builder() { return new SampleClusterBuilder("us-east-1", "us-east-1b", "10.10.20."); } }, UsEast1c() { @Override public SampleClusterBuilder builder() { return new SampleClusterBuilder("us-east-1", "us-east-1c", "10.10.30."); } }; public abstract SampleClusterBuilder builder(); public List<AwsEndpoint> build() { return builder().build(); } public static List<AwsEndpoint> merge(SampleCluster... sampleClusters) { List<AwsEndpoint> endpoints = new ArrayList<>(); for (SampleCluster cluster : sampleClusters) { endpoints.addAll(cluster.build()); } return endpoints; } public static class SampleClusterBuilder { private final String region; private final String zone; private final String networkPrefix; private int serverPoolSize = 2; public SampleClusterBuilder(String region, String zone, String networkPrefix) { this.region = region; this.zone = zone; this.networkPrefix = networkPrefix; } public SampleClusterBuilder withServerPool(int serverPoolSize) { this.serverPoolSize = serverPoolSize; return this; } public List<AwsEndpoint> build() { List<AwsEndpoint> endpoints = new ArrayList<>(); for (int i = 0; i < serverPoolSize; i++) { String hostName = networkPrefix + i; endpoints.add(new AwsEndpoint( hostName, 80, false, "/eureka/v2", region, zone )); } return endpoints; } } }
6,665
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver/aws/EurekaHttpResolverTest.java
package com.netflix.discovery.shared.resolver.aws; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.EurekaHttpClientFactory; import com.netflix.discovery.shared.transport.EurekaHttpResponse; import com.netflix.discovery.shared.transport.EurekaTransportConfig; import com.netflix.discovery.util.InstanceInfoGenerator; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.List; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * @author David Liu */ public class EurekaHttpResolverTest { private final EurekaClientConfig clientConfig = mock(EurekaClientConfig.class); private final EurekaTransportConfig transportConfig = mock(EurekaTransportConfig.class); private final EurekaHttpClientFactory clientFactory = mock(EurekaHttpClientFactory.class); private final EurekaHttpClient httpClient = mock(EurekaHttpClient.class); private Applications applications; private String vipAddress; private EurekaHttpResolver resolver; @Before public void setUp() { when(clientConfig.getEurekaServerURLContext()).thenReturn("context"); when(clientConfig.getRegion()).thenReturn("region"); applications = InstanceInfoGenerator.newBuilder(5, "eurekaRead", "someOther").build().toApplications(); vipAddress = applications.getRegisteredApplications("eurekaRead").getInstances().get(0).getVIPAddress(); when(clientFactory.newClient()).thenReturn(httpClient); when(httpClient.getVip(vipAddress)).thenReturn(EurekaHttpResponse.anEurekaHttpResponse(200, applications).build()); resolver = new EurekaHttpResolver(clientConfig, transportConfig, clientFactory, vipAddress); } @After public void tearDown() { } @Test public void testHappyCase() { List<AwsEndpoint> endpoints = resolver.getClusterEndpoints(); assertThat(endpoints.size(), equalTo(applications.getInstancesByVirtualHostName(vipAddress).size())); verify(httpClient, times(1)).shutdown(); } @Test public void testNoValidDataFromRemoteServer() { Applications newApplications = new Applications(); for (Application application : applications.getRegisteredApplications()) { if (!application.getInstances().get(0).getVIPAddress().equals(vipAddress)) { newApplications.addApplication(application); } } when(httpClient.getVip(vipAddress)).thenReturn(EurekaHttpResponse.anEurekaHttpResponse(200, newApplications).build()); List<AwsEndpoint> endpoints = resolver.getClusterEndpoints(); assertThat(endpoints.isEmpty(), is(true)); verify(httpClient, times(1)).shutdown(); } @Test public void testErrorResponseFromRemoteServer() { when(httpClient.getVip(vipAddress)).thenReturn(EurekaHttpResponse.anEurekaHttpResponse(500, (Applications)null).build()); List<AwsEndpoint> endpoints = resolver.getClusterEndpoints(); assertThat(endpoints.isEmpty(), is(true)); verify(httpClient, times(1)).shutdown(); } }
6,666
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver/aws/ApplicationsResolverTest.java
package com.netflix.discovery.shared.resolver.aws; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.shared.resolver.aws.ApplicationsResolver.ApplicationsSource; import com.netflix.discovery.shared.transport.EurekaTransportConfig; import com.netflix.discovery.util.InstanceInfoGenerator; import org.junit.Before; import org.junit.Test; import java.util.List; import java.util.concurrent.TimeUnit; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * @author David Liu */ public class ApplicationsResolverTest { private final EurekaClientConfig clientConfig = mock(EurekaClientConfig.class); private final EurekaTransportConfig transportConfig = mock(EurekaTransportConfig.class); private final ApplicationsSource applicationsSource = mock(ApplicationsSource.class); private Applications applications; private String vipAddress; private ApplicationsResolver resolver; @Before public void setUp() { when(clientConfig.getEurekaServerURLContext()).thenReturn("context"); when(clientConfig.getRegion()).thenReturn("region"); when(transportConfig.getApplicationsResolverDataStalenessThresholdSeconds()).thenReturn(1); applications = InstanceInfoGenerator.newBuilder(5, "eurekaRead", "someOther").build().toApplications(); vipAddress = applications.getRegisteredApplications("eurekaRead").getInstances().get(0).getVIPAddress(); when(transportConfig.getReadClusterVip()).thenReturn(vipAddress); resolver = new ApplicationsResolver( clientConfig, transportConfig, applicationsSource, transportConfig.getReadClusterVip() ); } @Test public void testHappyCase() { when(applicationsSource.getApplications(anyInt(), eq(TimeUnit.SECONDS))).thenReturn(applications); List<AwsEndpoint> endpoints = resolver.getClusterEndpoints(); assertThat(endpoints.size(), equalTo(applications.getInstancesByVirtualHostName(vipAddress).size())); } @Test public void testVipDoesNotExist() { vipAddress = "doNotExist"; when(transportConfig.getReadClusterVip()).thenReturn(vipAddress); resolver = new ApplicationsResolver( // recreate the resolver as desired config behaviour has changed clientConfig, transportConfig, applicationsSource, transportConfig.getReadClusterVip() ); when(applicationsSource.getApplications(anyInt(), eq(TimeUnit.SECONDS))).thenReturn(applications); List<AwsEndpoint> endpoints = resolver.getClusterEndpoints(); assertThat(endpoints.isEmpty(), is(true)); } @Test public void testStaleData() { when(applicationsSource.getApplications(anyInt(), eq(TimeUnit.SECONDS))).thenReturn(null); // stale contract List<AwsEndpoint> endpoints = resolver.getClusterEndpoints(); assertThat(endpoints.isEmpty(), is(true)); } }
6,667
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver
Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver/aws/TestEurekaHttpResolver.java
package com.netflix.discovery.shared.resolver.aws; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.shared.transport.EurekaHttpClientFactory; import com.netflix.discovery.shared.transport.EurekaTransportConfig; /** * Used to expose test constructor to other packages * * @author David Liu */ public class TestEurekaHttpResolver extends EurekaHttpResolver { public TestEurekaHttpResolver(EurekaClientConfig clientConfig, EurekaTransportConfig transportConfig, EurekaHttpClientFactory clientFactory, String vipAddress) { super(clientConfig, transportConfig, clientFactory, vipAddress); } }
6,668
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/appinfo/ApplicationInfoManagerTest.java
package com.netflix.appinfo; import com.netflix.discovery.CommonConstants; import com.netflix.discovery.util.InstanceInfoGenerator; import org.junit.Before; import org.junit.Test; import static com.netflix.appinfo.AmazonInfo.MetaDataKey.localIpv4; import static com.netflix.appinfo.AmazonInfo.MetaDataKey.publicHostname; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; /** * @author David Liu */ public class ApplicationInfoManagerTest { private CloudInstanceConfig config; private String dummyDefault = "dummyDefault"; private InstanceInfo instanceInfo; private ApplicationInfoManager applicationInfoManager; @Before public void setUp() { AmazonInfo initialAmazonInfo = AmazonInfo.Builder.newBuilder().build(); config = spy(new CloudInstanceConfig(initialAmazonInfo)); instanceInfo = InstanceInfoGenerator.takeOne(); this.applicationInfoManager = new ApplicationInfoManager(config, instanceInfo, null); when(config.getDefaultAddressResolutionOrder()).thenReturn(new String[]{ publicHostname.name(), localIpv4.name() }); when(config.getHostName(anyBoolean())).thenReturn(dummyDefault); } @Test public void testRefreshDataCenterInfoWithAmazonInfo() { String newPublicHostname = "newValue"; assertThat(instanceInfo.getHostName(), is(not(newPublicHostname))); ((AmazonInfo)config.getDataCenterInfo()).getMetadata().put(publicHostname.getName(), newPublicHostname); applicationInfoManager.refreshDataCenterInfoIfRequired(); assertThat(instanceInfo.getHostName(), is(newPublicHostname)); } @Test public void testSpotInstanceTermination() { AmazonInfo initialAmazonInfo = AmazonInfo.Builder.newBuilder().build(); RefreshableAmazonInfoProvider refreshableAmazonInfoProvider = spy(new RefreshableAmazonInfoProvider(initialAmazonInfo, new Archaius1AmazonInfoConfig(CommonConstants.DEFAULT_CONFIG_NAMESPACE))); config = spy(new CloudInstanceConfig(CommonConstants.DEFAULT_CONFIG_NAMESPACE, refreshableAmazonInfoProvider)); this.applicationInfoManager = new ApplicationInfoManager(config, instanceInfo, null); String terminationTime = "2015-01-05T18:02:00Z"; String spotInstanceAction = "{\"action\": \"terminate\", \"time\": \"2017-09-18T08:22:00Z\"}"; AmazonInfo newAmazonInfo = AmazonInfo.Builder.newBuilder() .addMetadata(AmazonInfo.MetaDataKey.spotTerminationTime, terminationTime) // new property on refresh .addMetadata(AmazonInfo.MetaDataKey.spotInstanceAction, spotInstanceAction) // new property refresh .addMetadata(AmazonInfo.MetaDataKey.publicHostname, instanceInfo.getHostName()) // unchanged .addMetadata(AmazonInfo.MetaDataKey.instanceId, instanceInfo.getInstanceId()) // unchanged .addMetadata(AmazonInfo.MetaDataKey.localIpv4, instanceInfo.getIPAddr()) // unchanged .build(); when(refreshableAmazonInfoProvider.getNewAmazonInfo()).thenReturn(newAmazonInfo); applicationInfoManager.refreshDataCenterInfoIfRequired(); assertThat(((AmazonInfo)instanceInfo.getDataCenterInfo()).getMetadata().get(AmazonInfo.MetaDataKey.spotTerminationTime.getName()), is(terminationTime)); assertThat(((AmazonInfo)instanceInfo.getDataCenterInfo()).getMetadata().get(AmazonInfo.MetaDataKey.spotInstanceAction.getName()), is(spotInstanceAction)); } @Test public void testCustomInstanceStatusMapper() { ApplicationInfoManager.OptionalArgs optionalArgs = new ApplicationInfoManager.OptionalArgs(); optionalArgs.setInstanceStatusMapper(new ApplicationInfoManager.InstanceStatusMapper() { @Override public InstanceInfo.InstanceStatus map(InstanceInfo.InstanceStatus prev) { return InstanceInfo.InstanceStatus.UNKNOWN; } }); applicationInfoManager = new ApplicationInfoManager(config, instanceInfo, optionalArgs); InstanceInfo.InstanceStatus existingStatus = applicationInfoManager.getInfo().getStatus(); assertNotEquals(existingStatus, InstanceInfo.InstanceStatus.UNKNOWN); applicationInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.UNKNOWN); existingStatus = applicationInfoManager.getInfo().getStatus(); assertEquals(existingStatus, InstanceInfo.InstanceStatus.UNKNOWN); } @Test public void testNullResultInstanceStatusMapper() { ApplicationInfoManager.OptionalArgs optionalArgs = new ApplicationInfoManager.OptionalArgs(); optionalArgs.setInstanceStatusMapper(new ApplicationInfoManager.InstanceStatusMapper() { @Override public InstanceInfo.InstanceStatus map(InstanceInfo.InstanceStatus prev) { return null; } }); applicationInfoManager = new ApplicationInfoManager(config, instanceInfo, optionalArgs); InstanceInfo.InstanceStatus existingStatus1 = applicationInfoManager.getInfo().getStatus(); assertNotEquals(existingStatus1, InstanceInfo.InstanceStatus.UNKNOWN); applicationInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.UNKNOWN); InstanceInfo.InstanceStatus existingStatus2 = applicationInfoManager.getInfo().getStatus(); assertEquals(existingStatus2, existingStatus1); } }
6,669
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/appinfo/RefreshableAmazonInfoProviderTest.java
package com.netflix.appinfo; import com.netflix.discovery.util.InstanceInfoGenerator; import org.junit.Before; import org.junit.Test; import static com.netflix.appinfo.AmazonInfo.MetaDataKey.amiId; import static com.netflix.appinfo.AmazonInfo.MetaDataKey.instanceId; import static com.netflix.appinfo.AmazonInfo.MetaDataKey.localIpv4; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; /** * @author David Liu */ public class RefreshableAmazonInfoProviderTest { private InstanceInfo instanceInfo; @Before public void setUp() { instanceInfo = InstanceInfoGenerator.takeOne(); } @Test public void testAmazonInfoNoUpdateIfEqual() { AmazonInfo oldInfo = (AmazonInfo) instanceInfo.getDataCenterInfo(); AmazonInfo newInfo = copyAmazonInfo(instanceInfo); assertThat(RefreshableAmazonInfoProvider.shouldUpdate(newInfo, oldInfo), is(false)); } @Test public void testAmazonInfoNoUpdateIfEmpty() { AmazonInfo oldInfo = (AmazonInfo) instanceInfo.getDataCenterInfo(); AmazonInfo newInfo = new AmazonInfo(); assertThat(RefreshableAmazonInfoProvider.shouldUpdate(newInfo, oldInfo), is(false)); } @Test public void testAmazonInfoNoUpdateIfNoInstanceId() { AmazonInfo oldInfo = (AmazonInfo) instanceInfo.getDataCenterInfo(); AmazonInfo newInfo = copyAmazonInfo(instanceInfo); newInfo.getMetadata().remove(instanceId.getName()); assertThat(newInfo.getId(), is(nullValue())); assertThat(newInfo.get(instanceId), is(nullValue())); assertThat(CloudInstanceConfig.shouldUpdate(newInfo, oldInfo), is(false)); newInfo.getMetadata().put(instanceId.getName(), ""); assertThat(newInfo.getId(), is("")); assertThat(newInfo.get(instanceId), is("")); assertThat(RefreshableAmazonInfoProvider.shouldUpdate(newInfo, oldInfo), is(false)); } @Test public void testAmazonInfoNoUpdateIfNoLocalIpv4() { AmazonInfo oldInfo = (AmazonInfo) instanceInfo.getDataCenterInfo(); AmazonInfo newInfo = copyAmazonInfo(instanceInfo); newInfo.getMetadata().remove(localIpv4.getName()); assertThat(newInfo.get(localIpv4), is(nullValue())); assertThat(CloudInstanceConfig.shouldUpdate(newInfo, oldInfo), is(false)); newInfo.getMetadata().put(localIpv4.getName(), ""); assertThat(newInfo.get(localIpv4), is("")); assertThat(RefreshableAmazonInfoProvider.shouldUpdate(newInfo, oldInfo), is(false)); } @Test public void testAmazonInfoUpdatePositiveCase() { AmazonInfo oldInfo = (AmazonInfo) instanceInfo.getDataCenterInfo(); AmazonInfo newInfo = copyAmazonInfo(instanceInfo); newInfo.getMetadata().remove(amiId.getName()); assertThat(newInfo.getMetadata().size(), is(oldInfo.getMetadata().size() - 1)); assertThat(RefreshableAmazonInfoProvider.shouldUpdate(newInfo, oldInfo), is(true)); String newKey = "someNewKey"; newInfo.getMetadata().put(newKey, "bar"); assertThat(newInfo.getMetadata().size(), is(oldInfo.getMetadata().size())); assertThat(RefreshableAmazonInfoProvider.shouldUpdate(newInfo, oldInfo), is(true)); } private static AmazonInfo copyAmazonInfo(InstanceInfo instanceInfo) { AmazonInfo currInfo = (AmazonInfo) instanceInfo.getDataCenterInfo(); AmazonInfo copyInfo = new AmazonInfo(); for (String key : currInfo.getMetadata().keySet()) { copyInfo.getMetadata().put(key, currInfo.getMetadata().get(key)); } return copyInfo; } }
6,670
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/appinfo/InstanceInfoTest.java
package com.netflix.appinfo; import com.netflix.appinfo.InstanceInfo.Builder; import com.netflix.appinfo.InstanceInfo.PortType; import com.netflix.config.ConcurrentCompositeConfiguration; import com.netflix.config.ConfigurationManager; import com.netflix.discovery.util.InstanceInfoGenerator; import org.junit.After; import org.junit.Assert; import org.junit.Test; import static com.netflix.appinfo.InstanceInfo.Builder.newBuilder; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertThat; /** * Created by jzarfoss on 2/12/14. */ public class InstanceInfoTest { @After public void tearDown() throws Exception { ((ConcurrentCompositeConfiguration) ConfigurationManager.getConfigInstance()).clearOverrideProperty("NETFLIX_APP_GROUP"); ((ConcurrentCompositeConfiguration) ConfigurationManager.getConfigInstance()).clearOverrideProperty("eureka.appGroup"); } // contrived test to check copy constructor and verify behavior of builder for InstanceInfo @Test public void testCopyConstructor() { DataCenterInfo myDCI = new DataCenterInfo() { public DataCenterInfo.Name getName() { return DataCenterInfo.Name.MyOwn; } }; InstanceInfo smallII1 = newBuilder().setAppName("test").setDataCenterInfo(myDCI).build(); InstanceInfo smallII2 = new InstanceInfo(smallII1); assertNotSame(smallII1, smallII2); Assert.assertEquals(smallII1, smallII2); InstanceInfo fullII1 = newBuilder().setMetadata(null) .setOverriddenStatus(InstanceInfo.InstanceStatus.UNKNOWN) .setHostName("localhost") .setSecureVIPAddress("testSecureVIP:22") .setStatus(InstanceInfo.InstanceStatus.UNKNOWN) .setStatusPageUrl("relative", "explicit/relative") .setVIPAddress("testVIP:21") .setAppName("test").setASGName("testASG").setDataCenterInfo(myDCI) .setHealthCheckUrls("relative", "explicit/relative", "secureExplicit/relative") .setHomePageUrl("relativeHP", "explicitHP/relativeHP") .setIPAddr("127.0.0.1") .setPort(21).setSecurePort(22).build(); InstanceInfo fullII2 = new InstanceInfo(fullII1); assertNotSame(fullII1, fullII2); Assert.assertEquals(fullII1, fullII2); } @Test public void testAppGroupNameSystemProp() throws Exception { String appGroup = "testAppGroupSystemProp"; ((ConcurrentCompositeConfiguration) ConfigurationManager.getConfigInstance()).setOverrideProperty("NETFLIX_APP_GROUP", appGroup); MyDataCenterInstanceConfig config = new MyDataCenterInstanceConfig(); Assert.assertEquals("Unexpected app group name", appGroup, config.getAppGroupName()); } @Test public void testAppGroupName() throws Exception { String appGroup = "testAppGroup"; ((ConcurrentCompositeConfiguration) ConfigurationManager.getConfigInstance()).setOverrideProperty("eureka.appGroup", appGroup); MyDataCenterInstanceConfig config = new MyDataCenterInstanceConfig(); Assert.assertEquals("Unexpected app group name", appGroup, config.getAppGroupName()); } @Test public void testHealthCheckSetContainsValidUrlEntries() throws Exception { Builder builder = newBuilder() .setAppName("test") .setNamespace("eureka.") .setHostName("localhost") .setPort(80) .setSecurePort(443) .enablePort(PortType.SECURE, true); // No health check URLs InstanceInfo noHealtcheckInstanceInfo = builder.build(); assertThat(noHealtcheckInstanceInfo.getHealthCheckUrls().size(), is(equalTo(0))); // Now when health check is defined InstanceInfo instanceInfo = builder .setHealthCheckUrls("/healthcheck", "http://${eureka.hostname}/healthcheck", "https://${eureka.hostname}/healthcheck") .build(); assertThat(instanceInfo.getHealthCheckUrls().size(), is(equalTo(2))); } @Test public void testNullUrlEntries() throws Exception { Builder builder = newBuilder() .setAppName("test") .setNamespace("eureka.") .setHostName("localhost") .setPort(80) .setSecurePort(443) .setHealthCheckUrls(null, null, null) .setStatusPageUrl(null, null) .setHomePageUrl(null, null) .enablePort(PortType.SECURE, true); // No URLs for healthcheck , status , homepage InstanceInfo noHealtcheckInstanceInfo = builder.build(); assertThat(noHealtcheckInstanceInfo.getHealthCheckUrls().size(), is(equalTo(0))); assertThat(noHealtcheckInstanceInfo.getStatusPageUrl(), nullValue()); assertThat(noHealtcheckInstanceInfo.getHomePageUrl(), nullValue()); } @Test public void testGetIdWithInstanceIdUsed() { InstanceInfo baseline = InstanceInfoGenerator.takeOne(); String dataCenterInfoId = ((UniqueIdentifier) baseline.getDataCenterInfo()).getId(); assertThat(baseline.getInstanceId(), is(baseline.getId())); assertThat(dataCenterInfoId, is(baseline.getId())); String customInstanceId = "someId"; InstanceInfo instanceInfo = new InstanceInfo.Builder(baseline).setInstanceId(customInstanceId).build(); dataCenterInfoId = ((UniqueIdentifier) instanceInfo.getDataCenterInfo()).getId(); assertThat(instanceInfo.getInstanceId(), is(instanceInfo.getId())); assertThat(customInstanceId, is(instanceInfo.getId())); assertThat(dataCenterInfoId, is(not(baseline.getId()))); } // test case for backwards compatibility @Test public void testGetIdWithInstanceIdNotUsed() { InstanceInfo baseline = InstanceInfoGenerator.takeOne(); // override the sid with "" InstanceInfo instanceInfo1 = new InstanceInfo.Builder(baseline).setInstanceId("").build(); String dataCenterInfoId = ((UniqueIdentifier) baseline.getDataCenterInfo()).getId(); assertThat(instanceInfo1.getInstanceId().isEmpty(), is(true)); assertThat(instanceInfo1.getInstanceId(), is(not(instanceInfo1.getId()))); assertThat(dataCenterInfoId, is(instanceInfo1.getId())); // override the sid with null InstanceInfo instanceInfo2 = new InstanceInfo.Builder(baseline).setInstanceId(null).build(); dataCenterInfoId = ((UniqueIdentifier) baseline.getDataCenterInfo()).getId(); assertThat(instanceInfo2.getInstanceId(), is(nullValue())); assertThat(instanceInfo2.getInstanceId(), is(not(instanceInfo2.getId()))); assertThat(dataCenterInfoId, is(instanceInfo2.getId())); } }
6,671
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/appinfo/CloudInstanceConfigTest.java
package com.netflix.appinfo; import com.netflix.discovery.util.InstanceInfoGenerator; import org.junit.Before; import org.junit.Test; import static com.netflix.appinfo.AmazonInfo.MetaDataKey.ipv6; import static com.netflix.appinfo.AmazonInfo.MetaDataKey.localIpv4; import static com.netflix.appinfo.AmazonInfo.MetaDataKey.publicHostname; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertEquals; /** * @author David Liu */ public class CloudInstanceConfigTest { private CloudInstanceConfig config; private String dummyDefault = "dummyDefault"; private InstanceInfo instanceInfo; @Before public void setUp() { instanceInfo = InstanceInfoGenerator.takeOne(); } @Test public void testResolveDefaultAddress() { AmazonInfo info = (AmazonInfo) instanceInfo.getDataCenterInfo(); config = createConfig(info); assertThat(config.resolveDefaultAddress(false), is(info.get(publicHostname))); info.getMetadata().remove(publicHostname.getName()); config = createConfig(info); assertThat(config.resolveDefaultAddress(false), is(info.get(localIpv4))); info.getMetadata().remove(localIpv4.getName()); config = createConfig(info); assertThat(config.resolveDefaultAddress(false), is(info.get(ipv6))); info.getMetadata().remove(ipv6.getName()); config = createConfig(info); assertThat(config.resolveDefaultAddress(false), is(dummyDefault)); } @Test public void testBroadcastPublicIpv4Address() { AmazonInfo info = (AmazonInfo) instanceInfo.getDataCenterInfo(); config = createConfig(info); // this should work because the test utils class sets the ipAddr to the public IP of the instance assertEquals(instanceInfo.getIPAddr(), config.getIpAddress()); } @Test public void testBroadcastPublicIpv4Address_usingPublicIpv4s() { AmazonInfo info = (AmazonInfo) instanceInfo.getDataCenterInfo(); info.getMetadata().remove(AmazonInfo.MetaDataKey.publicIpv4.getName()); info.getMetadata().put(AmazonInfo.MetaDataKey.publicIpv4s.getName(), "10.0.0.1"); config = createConfig(info); assertEquals("10.0.0.1", config.getIpAddress()); } private CloudInstanceConfig createConfig(AmazonInfo info) { return new CloudInstanceConfig(info) { @Override public String[] getDefaultAddressResolutionOrder() { return new String[] { publicHostname.name(), localIpv4.name(), ipv6.name() }; } @Override public String getHostName(boolean refresh) { return dummyDefault; } @Override public boolean shouldBroadcastPublicIpv4Addr() { return true; } }; } }
6,672
0
Create_ds/eureka/eureka-client/src/test/java/com/netflix
Create_ds/eureka/eureka-client/src/test/java/com/netflix/appinfo/AmazonInfoTest.java
package com.netflix.appinfo; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.net.URL; import com.netflix.discovery.internal.util.AmazonInfoUtils; import org.junit.Test; import org.mockito.MockedStatic; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.anyInt; import static org.mockito.Mockito.when; import static org.mockito.Mockito.mockStatic; import static org.junit.Assert.assertEquals; /** * @author David Liu */ public class AmazonInfoTest { @Test public void testExtractAccountId() throws Exception { String json = "{\n" + " \"imageId\" : \"ami-someId\",\n" + " \"instanceType\" : \"m1.small\",\n" + " \"version\" : \"2000-00-00\",\n" + " \"architecture\" : \"x86_64\",\n" + " \"accountId\" : \"1111111111\",\n" + " \"instanceId\" : \"i-someId\",\n" + " \"billingProducts\" : null,\n" + " \"pendingTime\" : \"2000-00-00T00:00:00Z\",\n" + " \"availabilityZone\" : \"us-east-1c\",\n" + " \"region\" : \"us-east-1\",\n" + " \"kernelId\" : \"aki-someId\",\n" + " \"ramdiskId\" : null,\n" + " \"privateIp\" : \"1.1.1.1\"\n" + "}"; InputStream inputStream = new ByteArrayInputStream(json.getBytes()); String accountId = AmazonInfo.MetaDataKey.accountId.read(inputStream); assertEquals("1111111111", accountId); } @Test public void testExtractMacs_SingleMac() throws Exception { String body = "0d:c2:9a:3c:18:2b"; InputStream inputStream = new ByteArrayInputStream(body.getBytes()); String macs = AmazonInfo.MetaDataKey.macs.read(inputStream); assertEquals("0d:c2:9a:3c:18:2b", macs); } @Test public void testExtractMacs_MultipleMacs() throws Exception { String body = "0d:c2:9a:3c:18:2b\n4c:31:99:7e:26:d6"; InputStream inputStream = new ByteArrayInputStream(body.getBytes()); String macs = AmazonInfo.MetaDataKey.macs.read(inputStream); assertEquals("0d:c2:9a:3c:18:2b\n4c:31:99:7e:26:d6", macs); } @Test public void testExtractPublicIPv4s_SingleAddress() throws Exception { String body = "10.0.0.1"; InputStream inputStream = new ByteArrayInputStream(body.getBytes()); String publicIPv4s = AmazonInfo.MetaDataKey.publicIpv4s.read(inputStream); assertEquals("10.0.0.1", publicIPv4s); } @Test public void testExtractPublicIPv4s_MultipleAddresses() throws Exception { String body = "10.0.0.1\n10.0.0.2"; InputStream inputStream = new ByteArrayInputStream(body.getBytes()); String publicIPv4s = AmazonInfo.MetaDataKey.publicIpv4s.read(inputStream); assertEquals("10.0.0.1", publicIPv4s); } @Test public void testAutoBuild() throws Exception { try (MockedStatic<AmazonInfoUtils> mockUtils = mockStatic(AmazonInfoUtils.class)) { mockUtils.when( () -> AmazonInfoUtils.readEc2MetadataUrl(any(AmazonInfo.MetaDataKey.class), any(URL.class), anyInt(), anyInt()) ).thenReturn(null); mockUtils.when( () -> AmazonInfoUtils.readEc2MetadataUrl(any(AmazonInfo.MetaDataKey.class), any(URL.class), anyInt(), anyInt()) ).thenReturn(null); URL macsUrl = AmazonInfo.MetaDataKey.macs.getURL(null, null); mockUtils.when( () -> AmazonInfoUtils.readEc2MetadataUrl(eq(AmazonInfo.MetaDataKey.macs), eq(macsUrl), anyInt(), anyInt()) ).thenReturn("0d:c2:9a:3c:18:2b\n4c:31:99:7e:26:d6"); URL firstMacPublicIPv4sUrl = AmazonInfo.MetaDataKey.publicIpv4s.getURL(null, "0d:c2:9a:3c:18:2b"); mockUtils.when( () -> AmazonInfoUtils.readEc2MetadataUrl(eq(AmazonInfo.MetaDataKey.publicIpv4s), eq(firstMacPublicIPv4sUrl), anyInt(), anyInt()) ).thenReturn(null); URL secondMacPublicIPv4sUrl = AmazonInfo.MetaDataKey.publicIpv4s.getURL(null, "4c:31:99:7e:26:d6"); mockUtils.when( () -> AmazonInfoUtils.readEc2MetadataUrl(eq(AmazonInfo.MetaDataKey.publicIpv4s), eq(secondMacPublicIPv4sUrl), anyInt(), anyInt()) ).thenReturn("10.0.0.1"); AmazonInfoConfig config = mock(AmazonInfoConfig.class); when(config.getNamespace()).thenReturn("test_namespace"); when(config.getConnectTimeout()).thenReturn(10); when(config.getNumRetries()).thenReturn(1); when(config.getReadTimeout()).thenReturn(10); when(config.shouldLogAmazonMetadataErrors()).thenReturn(false); when(config.shouldValidateInstanceId()).thenReturn(false); when(config.shouldFailFastOnFirstLoad()).thenReturn(false); AmazonInfo info = AmazonInfo.Builder.newBuilder().withAmazonInfoConfig(config).autoBuild("test_namespace"); assertEquals("10.0.0.1", info.get(AmazonInfo.MetaDataKey.publicIpv4s)); } } }
6,673
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/DNSBasedAzToRegionMapper.java
package com.netflix.discovery; import com.netflix.discovery.endpoint.EndpointUtils; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; /** * DNS-based region mapper that discovers regions via DNS TXT records. * @author Nitesh Kant */ public class DNSBasedAzToRegionMapper extends AbstractAzToRegionMapper { public DNSBasedAzToRegionMapper(EurekaClientConfig clientConfig) { super(clientConfig); } @Override protected Set<String> getZonesForARegion(String region) { Map<String, List<String>> zoneBasedDiscoveryUrlsFromRegion = EndpointUtils .getZoneBasedDiscoveryUrlsFromRegion(clientConfig, region); if (null != zoneBasedDiscoveryUrlsFromRegion) { return zoneBasedDiscoveryUrlsFromRegion.keySet(); } return Collections.emptySet(); } }
6,674
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/EurekaUpStatusResolver.java
package com.netflix.discovery; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.inject.Singleton; import java.util.concurrent.atomic.AtomicLong; import com.google.inject.Inject; import com.netflix.appinfo.InstanceInfo; import com.netflix.eventbus.spi.EventBus; import com.netflix.eventbus.spi.InvalidSubscriberException; import com.netflix.eventbus.spi.Subscribe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Singleton that manages the state of @UpStatus/@DownStatus Supplier<Boolean> * and emits status changes to @UpStatus Observable<Boolean>. * * @author elandau * */ @Singleton public class EurekaUpStatusResolver { private static Logger LOG = LoggerFactory.getLogger(EurekaUpStatusResolver.class); private volatile InstanceInfo.InstanceStatus currentStatus = InstanceInfo.InstanceStatus.UNKNOWN; private final EventBus eventBus; private final EurekaClient client; private final AtomicLong counter = new AtomicLong(); /** * @param client the eurekaClient * @param eventBus the eventBus to publish eureka status change events */ @Inject public EurekaUpStatusResolver(EurekaClient client, EventBus eventBus) { this.eventBus = eventBus; this.client = client; } @Subscribe public void onStatusChange(StatusChangeEvent event) { LOG.info("Eureka status changed from {} to {}", event.getPreviousStatus(), event.getStatus()); currentStatus = event.getStatus(); counter.incrementAndGet(); } @PostConstruct public void init() { try { // Must set the initial status currentStatus = client.getInstanceRemoteStatus(); LOG.info("Initial status set to {}", currentStatus); eventBus.registerSubscriber(this); } catch (InvalidSubscriberException e) { LOG.error("Error registring for discovery status change events.", e); } } @PreDestroy public void shutdown() { eventBus.unregisterSubscriber(this); } /** * @return Get the current instance status */ public InstanceInfo.InstanceStatus getStatus() { return currentStatus; } public long getChangeCount() { return counter.get(); } }
6,675
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/DiscoveryEvent.java
/** * */ package com.netflix.discovery; /** * Class to be extended by all discovery events. Abstract as it * doesn't make sense for generic events to be published directly. */ public abstract class DiscoveryEvent implements EurekaEvent { // System time when the event happened private final long timestamp; protected DiscoveryEvent() { this.timestamp = System.currentTimeMillis(); } /** * @return Return the system time in milliseconds when the event happened. */ public final long getTimestamp() { return this.timestamp; } }
6,676
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/InstanceInfoReplicator.java
package com.netflix.discovery; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.util.RateLimiter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; /** * A task for updating and replicating the local instanceinfo to the remote server. Properties of this task are: * - configured with a single update thread to guarantee sequential update to the remote server * - update tasks can be scheduled on-demand via onDemandUpdate() * - task processing is rate limited by burstSize * - a new update task is always scheduled automatically after an earlier update task. However if an on-demand task * is started, the scheduled automatic update task is discarded (and a new one will be scheduled after the new * on-demand update). * * @author dliu */ class InstanceInfoReplicator implements Runnable { private static final Logger logger = LoggerFactory.getLogger(InstanceInfoReplicator.class); private final DiscoveryClient discoveryClient; private final InstanceInfo instanceInfo; private final int replicationIntervalSeconds; private final ScheduledExecutorService scheduler; private final AtomicReference<Future> scheduledPeriodicRef; private final AtomicBoolean started; private final RateLimiter rateLimiter; private final int burstSize; private final int allowedRatePerMinute; InstanceInfoReplicator(DiscoveryClient discoveryClient, InstanceInfo instanceInfo, int replicationIntervalSeconds, int burstSize) { this.discoveryClient = discoveryClient; this.instanceInfo = instanceInfo; this.scheduler = Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder() .setNameFormat("DiscoveryClient-InstanceInfoReplicator-%d") .setDaemon(true) .build()); this.scheduledPeriodicRef = new AtomicReference<Future>(); this.started = new AtomicBoolean(false); this.rateLimiter = new RateLimiter(TimeUnit.MINUTES); this.replicationIntervalSeconds = replicationIntervalSeconds; this.burstSize = burstSize; this.allowedRatePerMinute = 60 * this.burstSize / this.replicationIntervalSeconds; logger.info("InstanceInfoReplicator onDemand update allowed rate per min is {}", allowedRatePerMinute); } public void start(int initialDelayMs) { if (started.compareAndSet(false, true)) { instanceInfo.setIsDirty(); // for initial register Future next = scheduler.schedule(this, initialDelayMs, TimeUnit.SECONDS); scheduledPeriodicRef.set(next); } } public void stop() { shutdownAndAwaitTermination(scheduler); started.set(false); } private void shutdownAndAwaitTermination(ExecutorService pool) { pool.shutdown(); try { if (!pool.awaitTermination(3, TimeUnit.SECONDS)) { pool.shutdownNow(); } } catch (InterruptedException e) { logger.warn("InstanceInfoReplicator stop interrupted"); } } public boolean onDemandUpdate() { if (rateLimiter.acquire(burstSize, allowedRatePerMinute)) { if (!scheduler.isShutdown()) { scheduler.submit(new Runnable() { @Override public void run() { logger.debug("Executing on-demand update of local InstanceInfo"); Future latestPeriodic = scheduledPeriodicRef.get(); if (latestPeriodic != null && !latestPeriodic.isDone()) { logger.debug("Canceling the latest scheduled update, it will be rescheduled at the end of on demand update"); latestPeriodic.cancel(false); } InstanceInfoReplicator.this.run(); } }); return true; } else { logger.warn("Ignoring onDemand update due to stopped scheduler"); return false; } } else { logger.warn("Ignoring onDemand update due to rate limiter"); return false; } } public void run() { try { discoveryClient.refreshInstanceInfo(); Long dirtyTimestamp = instanceInfo.isDirtyWithTime(); if (dirtyTimestamp != null) { discoveryClient.register(); instanceInfo.unsetIsDirty(dirtyTimestamp); } } catch (Throwable t) { logger.warn("There was a problem with the instance info replicator", t); } finally { Future next = scheduler.schedule(this, replicationIntervalSeconds, TimeUnit.SECONDS); scheduledPeriodicRef.set(next); } } }
6,677
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/InternalEurekaStatusModule.java
package com.netflix.discovery; import javax.inject.Inject; import javax.inject.Provider; import javax.inject.Singleton; import com.google.common.base.Supplier; import com.google.inject.AbstractModule; import com.google.inject.TypeLiteral; import com.netflix.appinfo.InstanceInfo; /** * @deprecated 2016-09-06 this class will be deleted soon. This is also an internal class. * * Specific bindings for eureka status checker. * * Note that this is an internal modules and ASSUMES that a binding for * DiscoveryClient was already set. * * Exposed bindings, * * &#64;UpStatus Supplier<Boolean> * &#64;DownStatus Supplier<Boolean> * &#64;UpStatus Observable<Boolean> * * @author elandau * */ @Deprecated @Singleton public class InternalEurekaStatusModule extends AbstractModule { @Singleton public static class UpStatusProvider implements Provider<Supplier<Boolean>> { @Inject private Provider<EurekaUpStatusResolver> upStatus; @Override public Supplier<Boolean> get() { final EurekaUpStatusResolver resolver = upStatus.get(); return new Supplier<Boolean>() { @Override public Boolean get() { return resolver.getStatus().equals(InstanceInfo.InstanceStatus.UP); } }; } } @Singleton public static class DownStatusProvider implements Provider<Supplier<Boolean>> { @Inject private Provider<EurekaUpStatusResolver> upStatus; @Override public Supplier<Boolean> get() { final EurekaUpStatusResolver resolver = upStatus.get(); return new Supplier<Boolean>() { @Override public Boolean get() { return !resolver.getStatus().equals(InstanceInfo.InstanceStatus.UP); } }; } } @Override protected void configure() { bind(new TypeLiteral<Supplier<Boolean>>() { }) .toProvider(UpStatusProvider.class); bind(new TypeLiteral<Supplier<Boolean>>() { }) .toProvider(DownStatusProvider.class); } }
6,678
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/DefaultEurekaClientConfig.java
/* * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery; import javax.annotation.Nullable; import javax.inject.Singleton; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.google.inject.ProvidedBy; import com.netflix.appinfo.EurekaAccept; import com.netflix.config.DynamicPropertyFactory; import com.netflix.config.DynamicStringProperty; import com.netflix.discovery.internal.util.Archaius1Utils; import com.netflix.discovery.providers.DefaultEurekaClientConfigProvider; import com.netflix.discovery.shared.transport.DefaultEurekaTransportConfig; import com.netflix.discovery.shared.transport.EurekaTransportConfig; import static com.netflix.discovery.PropertyBasedClientConfigConstants.*; /** * * A default implementation of eureka client configuration as required by * {@link EurekaClientConfig}. * * <p> * The information required for configuring eureka client is provided in a * configuration file.The configuration file is searched for in the classpath * with the name specified by the property <em>eureka.client.props</em> and with * the suffix <em>.properties</em>. If the property is not specified, * <em>eureka-client.properties</em> is assumed as the default.The properties * that are looked up uses the <em>namespace</em> passed on to this class. * </p> * * <p> * If the <em>eureka.environment</em> property is specified, additionally * <em>eureka-client-<eureka.environment>.properties</em> is loaded in addition * to <em>eureka-client.properties</em>. * </p> * * @author Karthik Ranganathan * */ @Singleton @ProvidedBy(DefaultEurekaClientConfigProvider.class) public class DefaultEurekaClientConfig implements EurekaClientConfig { /** * @deprecated 2016-08-29 use {@link com.netflix.discovery.CommonConstants#DEFAULT_CONFIG_NAMESPACE} */ @Deprecated public static final String DEFAULT_NAMESPACE = CommonConstants.DEFAULT_CONFIG_NAMESPACE + "."; public static final String DEFAULT_ZONE = "defaultZone"; public static final String URL_SEPARATOR = "\\s*,\\s*"; private final String namespace; private final DynamicPropertyFactory configInstance; private final EurekaTransportConfig transportConfig; public DefaultEurekaClientConfig() { this(CommonConstants.DEFAULT_CONFIG_NAMESPACE); } public DefaultEurekaClientConfig(String namespace) { this.namespace = namespace.endsWith(".") ? namespace : namespace + "."; this.configInstance = Archaius1Utils.initConfig(CommonConstants.CONFIG_FILE_NAME); this.transportConfig = new DefaultEurekaTransportConfig(namespace, configInstance); } /* * (non-Javadoc) * * @see * com.netflix.discovery.EurekaClientConfig#getRegistryFetchIntervalSeconds * () */ @Override public int getRegistryFetchIntervalSeconds() { return configInstance.getIntProperty( namespace + REGISTRY_REFRESH_INTERVAL_KEY, 30).get(); } /* * (non-Javadoc) * * @see com.netflix.discovery.EurekaClientConfig# * getInstanceInfoReplicationIntervalSeconds() */ @Override public int getInstanceInfoReplicationIntervalSeconds() { return configInstance.getIntProperty( namespace + REGISTRATION_REPLICATION_INTERVAL_KEY, 30).get(); } @Override public int getInitialInstanceInfoReplicationIntervalSeconds() { return configInstance.getIntProperty( namespace + INITIAL_REGISTRATION_REPLICATION_DELAY_KEY, 40).get(); } /* * (non-Javadoc) * * @see com.netflix.discovery.EurekaClientConfig#getDnsPollIntervalSeconds() */ @Override public int getEurekaServiceUrlPollIntervalSeconds() { return configInstance.getIntProperty( namespace + EUREKA_SERVER_URL_POLL_INTERVAL_KEY, 5 * 60 * 1000).get() / 1000; } /* * (non-Javadoc) * * @see com.netflix.discovery.EurekaClientConfig#getProxyHost() */ @Override public String getProxyHost() { return configInstance.getStringProperty( namespace + EUREKA_SERVER_PROXY_HOST_KEY, null).get(); } /* * (non-Javadoc) * * @see com.netflix.discovery.EurekaClientConfig#getProxyPort() */ @Override public String getProxyPort() { return configInstance.getStringProperty( namespace + EUREKA_SERVER_PROXY_PORT_KEY, null).get(); } @Override public String getProxyUserName() { return configInstance.getStringProperty( namespace + EUREKA_SERVER_PROXY_USERNAME_KEY, null).get(); } @Override public String getProxyPassword() { return configInstance.getStringProperty( namespace + EUREKA_SERVER_PROXY_PASSWORD_KEY, null).get(); } /* * (non-Javadoc) * * @see com.netflix.discovery.EurekaClientConfig#shouldGZipContent() */ @Override public boolean shouldGZipContent() { return configInstance.getBooleanProperty( namespace + EUREKA_SERVER_GZIP_CONTENT_KEY, true).get(); } /* * (non-Javadoc) * * @see com.netflix.discovery.EurekaClientConfig#getDSServerReadTimeout() */ @Override public int getEurekaServerReadTimeoutSeconds() { return configInstance.getIntProperty( namespace + EUREKA_SERVER_READ_TIMEOUT_KEY, 8).get(); } /* * (non-Javadoc) * * @see com.netflix.discovery.EurekaClientConfig#getDSServerConnectTimeout() */ @Override public int getEurekaServerConnectTimeoutSeconds() { return configInstance.getIntProperty( namespace + EUREKA_SERVER_CONNECT_TIMEOUT_KEY, 5).get(); } /* * (non-Javadoc) * * @see com.netflix.discovery.EurekaClientConfig#getBackupRegistryImpl() */ @Override public String getBackupRegistryImpl() { return configInstance.getStringProperty(namespace + BACKUP_REGISTRY_CLASSNAME_KEY, null).get(); } /* * (non-Javadoc) * * @see * com.netflix.discovery.EurekaClientConfig#getDSServerTotalMaxConnections() */ @Override public int getEurekaServerTotalConnections() { return configInstance.getIntProperty( namespace + EUREKA_SERVER_MAX_CONNECTIONS_KEY, 200).get(); } /* * (non-Javadoc) * * @see * com.netflix.discovery.EurekaClientConfig#getDSServerConnectionsPerHost() */ @Override public int getEurekaServerTotalConnectionsPerHost() { return configInstance.getIntProperty( namespace + EUREKA_SERVER_MAX_CONNECTIONS_PER_HOST_KEY, 50).get(); } /* * (non-Javadoc) * * @see com.netflix.discovery.EurekaClientConfig#getDSServerURLContext() */ @Override public String getEurekaServerURLContext() { return configInstance.getStringProperty( namespace + EUREKA_SERVER_URL_CONTEXT_KEY, configInstance.getStringProperty(namespace + EUREKA_SERVER_FALLBACK_URL_CONTEXT_KEY, null) .get()).get(); } /* * (non-Javadoc) * * @see com.netflix.discovery.EurekaClientConfig#getDSServerPort() */ @Override public String getEurekaServerPort() { return configInstance.getStringProperty( namespace + EUREKA_SERVER_PORT_KEY, configInstance.getStringProperty(namespace + EUREKA_SERVER_FALLBACK_PORT_KEY, null) .get()).get(); } /* * (non-Javadoc) * * @see com.netflix.discovery.EurekaClientConfig#getDSServerDomain() */ @Override public String getEurekaServerDNSName() { return configInstance.getStringProperty( namespace + EUREKA_SERVER_DNS_NAME_KEY, configInstance .getStringProperty(namespace + EUREKA_SERVER_FALLBACK_DNS_NAME_KEY, null) .get()).get(); } /* * (non-Javadoc) * * @see com.netflix.discovery.EurekaClientConfig#shouldUseDns() */ @Override public boolean shouldUseDnsForFetchingServiceUrls() { return configInstance.getBooleanProperty(namespace + SHOULD_USE_DNS_KEY, false).get(); } /* * (non-Javadoc) * * @see * com.netflix.discovery.EurekaClientConfig#getDiscoveryRegistrationEnabled() */ @Override public boolean shouldRegisterWithEureka() { return configInstance.getBooleanProperty( namespace + REGISTRATION_ENABLED_KEY, true).get(); } /* * (non-Javadoc) * * @see * com.netflix.discovery.EurekaClientConfig#shouldUnregisterOnShutdown() */ @Override public boolean shouldUnregisterOnShutdown() { return configInstance.getBooleanProperty( namespace + SHOULD_UNREGISTER_ON_SHUTDOWN_KEY, true).get(); } /* * (non-Javadoc) * * @see com.netflix.discovery.EurekaClientConfig#shouldPreferSameZoneDS() */ @Override public boolean shouldPreferSameZoneEureka() { return configInstance.getBooleanProperty(namespace + SHOULD_PREFER_SAME_ZONE_SERVER_KEY, true).get(); } @Override public boolean allowRedirects() { return configInstance.getBooleanProperty(namespace + SHOULD_ALLOW_REDIRECTS_KEY, false).get(); } /* * (non-Javadoc) * * @see com.netflix.discovery.EurekaClientConfig#shouldLogDeltaDiff() */ @Override public boolean shouldLogDeltaDiff() { return configInstance.getBooleanProperty( namespace + SHOULD_LOG_DELTA_DIFF_KEY, false).get(); } /* * (non-Javadoc) * * @see com.netflix.discovery.EurekaClientConfig#shouldDisableDelta() */ @Override public boolean shouldDisableDelta() { return configInstance.getBooleanProperty(namespace + SHOULD_DISABLE_DELTA_KEY, false).get(); } @Nullable @Override public String fetchRegistryForRemoteRegions() { return configInstance.getStringProperty(namespace + SHOULD_FETCH_REMOTE_REGION_KEY, null).get(); } /* * (non-Javadoc) * * @see com.netflix.discovery.EurekaClientConfig#getRegion() */ @Override public String getRegion() { DynamicStringProperty defaultEurekaRegion = configInstance.getStringProperty(CLIENT_REGION_FALLBACK_KEY, Values.DEFAULT_CLIENT_REGION); return configInstance.getStringProperty(namespace + CLIENT_REGION_KEY, defaultEurekaRegion.get()).get(); } /* * (non-Javadoc) * * @see com.netflix.discovery.EurekaClientConfig#getAvailabilityZones() */ @Override public String[] getAvailabilityZones(String region) { return configInstance .getStringProperty( namespace + region + "." + CONFIG_AVAILABILITY_ZONE_PREFIX, DEFAULT_ZONE).get().split(URL_SEPARATOR); } /* * (non-Javadoc) * * @see * com.netflix.discovery.EurekaClientConfig#getEurekaServerServiceUrls() */ @Override public List<String> getEurekaServerServiceUrls(String myZone) { String serviceUrls = configInstance.getStringProperty( namespace + CONFIG_EUREKA_SERVER_SERVICE_URL_PREFIX + "." + myZone, null).get(); if (serviceUrls == null || serviceUrls.isEmpty()) { serviceUrls = configInstance.getStringProperty( namespace + CONFIG_EUREKA_SERVER_SERVICE_URL_PREFIX + ".default", null).get(); } if (serviceUrls != null) { return Arrays.asList(serviceUrls.split(URL_SEPARATOR)); } return new ArrayList<String>(); } /* * (non-Javadoc) * * @see * com.netflix.discovery.EurekaClientConfig#shouldFilterOnlyUpInstances() */ @Override public boolean shouldFilterOnlyUpInstances() { return configInstance.getBooleanProperty( namespace + SHOULD_FILTER_ONLY_UP_INSTANCES_KEY, true).get(); } /* * (non-Javadoc) * * @see * com.netflix.discovery.EurekaClientConfig#getEurekaConnectionIdleTimeout() */ @Override public int getEurekaConnectionIdleTimeoutSeconds() { return configInstance.getIntProperty( namespace + EUREKA_SERVER_CONNECTION_IDLE_TIMEOUT_KEY, 45) .get(); } @Override public boolean shouldFetchRegistry() { return configInstance.getBooleanProperty( namespace + FETCH_REGISTRY_ENABLED_KEY, true).get(); } @Override public boolean shouldEnforceFetchRegistryAtInit() { return configInstance.getBooleanProperty( namespace + SHOULD_ENFORCE_FETCH_REGISTRY_AT_INIT_KEY, false).get(); } /* * (non-Javadoc) * * @see com.netflix.discovery.EurekaClientConfig#getRegistryRefreshSingleVipAddress() */ @Override public String getRegistryRefreshSingleVipAddress() { return configInstance.getStringProperty( namespace + FETCH_SINGLE_VIP_ONLY_KEY, null).get(); } /** * (non-Javadoc) * * @see com.netflix.discovery.EurekaClientConfig#getHeartbeatExecutorThreadPoolSize() */ @Override public int getHeartbeatExecutorThreadPoolSize() { return configInstance.getIntProperty( namespace + HEARTBEAT_THREADPOOL_SIZE_KEY, Values.DEFAULT_EXECUTOR_THREAD_POOL_SIZE).get(); } @Override public int getHeartbeatExecutorExponentialBackOffBound() { return configInstance.getIntProperty( namespace + HEARTBEAT_BACKOFF_BOUND_KEY, Values.DEFAULT_EXECUTOR_THREAD_POOL_BACKOFF_BOUND).get(); } /** * (non-Javadoc) * * @see com.netflix.discovery.EurekaClientConfig#getCacheRefreshExecutorThreadPoolSize() */ @Override public int getCacheRefreshExecutorThreadPoolSize() { return configInstance.getIntProperty( namespace + CACHEREFRESH_THREADPOOL_SIZE_KEY, Values.DEFAULT_EXECUTOR_THREAD_POOL_SIZE).get(); } @Override public int getCacheRefreshExecutorExponentialBackOffBound() { return configInstance.getIntProperty( namespace + CACHEREFRESH_BACKOFF_BOUND_KEY, Values.DEFAULT_EXECUTOR_THREAD_POOL_BACKOFF_BOUND).get(); } @Override public String getDollarReplacement() { return configInstance.getStringProperty( namespace + CONFIG_DOLLAR_REPLACEMENT_KEY, Values.CONFIG_DOLLAR_REPLACEMENT).get(); } @Override public String getEscapeCharReplacement() { return configInstance.getStringProperty( namespace + CONFIG_ESCAPE_CHAR_REPLACEMENT_KEY, Values.CONFIG_ESCAPE_CHAR_REPLACEMENT).get(); } @Override public boolean shouldOnDemandUpdateStatusChange() { return configInstance.getBooleanProperty( namespace + SHOULD_ONDEMAND_UPDATE_STATUS_KEY, true).get(); } @Override public boolean shouldEnforceRegistrationAtInit() { return configInstance.getBooleanProperty( namespace + SHOULD_ENFORCE_REGISTRATION_AT_INIT, false).get(); } @Override public String getEncoderName() { return configInstance.getStringProperty( namespace + CLIENT_ENCODER_NAME_KEY, null).get(); } @Override public String getDecoderName() { return configInstance.getStringProperty( namespace + CLIENT_DECODER_NAME_KEY, null).get(); } @Override public String getClientDataAccept() { return configInstance.getStringProperty( namespace + CLIENT_DATA_ACCEPT_KEY, EurekaAccept.full.name()).get(); } @Override public String getExperimental(String name) { return configInstance.getStringProperty(namespace + CONFIG_EXPERIMENTAL_PREFIX + "." + name, null).get(); } @Override public EurekaTransportConfig getTransportConfig() { return transportConfig; } }
6,679
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/StatusChangeEvent.java
package com.netflix.discovery; import com.netflix.appinfo.InstanceInfo; /** * Event containing the latest instance status information. This event * is sent to the {@link com.netflix.eventbus.spi.EventBus} by {@link EurekaClient) whenever * a status change is identified from the remote Eureka server response. */ public class StatusChangeEvent extends DiscoveryEvent { private final InstanceInfo.InstanceStatus current; private final InstanceInfo.InstanceStatus previous; public StatusChangeEvent(InstanceInfo.InstanceStatus previous, InstanceInfo.InstanceStatus current) { super(); this.current = current; this.previous = previous; } /** * Return the up current when the event was generated. * @return true if current is up or false for ALL other current values */ public boolean isUp() { return this.current.equals(InstanceInfo.InstanceStatus.UP); } /** * @return The current at the time the event is generated. */ public InstanceInfo.InstanceStatus getStatus() { return current; } /** * @return Return the client status immediately before the change */ public InstanceInfo.InstanceStatus getPreviousStatus() { return previous; } @Override public String toString() { return "StatusChangeEvent [timestamp=" + getTimestamp() + ", current=" + current + ", previous=" + previous + "]"; } }
6,680
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/DiscoveryManager.java
/* * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.EurekaInstanceConfig; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.shared.LookupService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @deprecated use EurekaModule and DI. * * <tt>Discovery Manager</tt> configures <tt>Discovery Client</tt> based on the * properties specified. * * <p> * The configuration file is searched for in the classpath with the name * specified by the property <em>eureka.client.props</em> and with the suffix * <em>.properties</em>. If the property is not specified, * <em>eureka-client.properties</em> is assumed as the default. * * @author Karthik Ranganathan * */ @Deprecated public class DiscoveryManager { private static final Logger logger = LoggerFactory.getLogger(DiscoveryManager.class); private DiscoveryClient discoveryClient; private EurekaClient clientOverride; private EurekaInstanceConfig eurekaInstanceConfig; private EurekaClientConfig eurekaClientConfig; private static final DiscoveryManager s_instance = new DiscoveryManager(); private DiscoveryManager() { } public static DiscoveryManager getInstance() { return s_instance; } public void setDiscoveryClient(DiscoveryClient discoveryClient) { this.discoveryClient = discoveryClient; } public void setClientOverride(EurekaClient eurekaClient) { this.clientOverride = eurekaClient; } public void setEurekaClientConfig(EurekaClientConfig eurekaClientConfig) { this.eurekaClientConfig = eurekaClientConfig; } public void setEurekaInstanceConfig(EurekaInstanceConfig eurekaInstanceConfig) { this.eurekaInstanceConfig = eurekaInstanceConfig; } /** * Initializes the <tt>Discovery Client</tt> with the given configuration. * * @param config * the instance info configuration that will be used for * registration with Eureka. * @param eurekaConfig the eureka client configuration of the instance. */ public void initComponent(EurekaInstanceConfig config, EurekaClientConfig eurekaConfig, AbstractDiscoveryClientOptionalArgs args) { this.eurekaInstanceConfig = config; this.eurekaClientConfig = eurekaConfig; if (ApplicationInfoManager.getInstance().getInfo() == null) { // Initialize application info ApplicationInfoManager.getInstance().initComponent(config); } InstanceInfo info = ApplicationInfoManager.getInstance().getInfo(); discoveryClient = new DiscoveryClient(info, eurekaConfig, args); } public void initComponent(EurekaInstanceConfig config, EurekaClientConfig eurekaConfig) { initComponent(config, eurekaConfig, null); } /** * Shuts down the <tt>Discovery Client</tt> which unregisters the * information about this instance from the <tt>Discovery Server</tt>. */ public void shutdownComponent() { if (discoveryClient != null) { try { discoveryClient.shutdown(); discoveryClient = null; } catch (Throwable th) { logger.error("Error in shutting down client", th); } } } public LookupService getLookupService() { return getEurekaClient(); } /** * @deprecated use {@link #getEurekaClient()} * * Get the {@link DiscoveryClient}. * @return the client that is used to talk to eureka. */ @Deprecated public DiscoveryClient getDiscoveryClient() { return discoveryClient; } /** * * Get the {@link EurekaClient} implementation. * @return the client that is used to talk to eureka. */ public EurekaClient getEurekaClient() { if (clientOverride != null) { return clientOverride; } return discoveryClient; } /** * Get the instance of {@link EurekaClientConfig} this instance was initialized with. * @return the instance of {@link EurekaClientConfig} this instance was initialized with. */ public EurekaClientConfig getEurekaClientConfig() { return eurekaClientConfig; } /** * Get the instance of {@link EurekaInstanceConfig} this instance was initialized with. * @return the instance of {@link EurekaInstanceConfig} this instance was initialized with. */ public EurekaInstanceConfig getEurekaInstanceConfig() { return eurekaInstanceConfig; } }
6,681
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/AbstractDiscoveryClientOptionalArgs.java
package com.netflix.discovery; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Optional; import java.util.Set; import javax.inject.Provider; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import com.google.inject.Inject; import com.netflix.appinfo.HealthCheckCallback; import com.netflix.appinfo.HealthCheckHandler; import com.netflix.discovery.shared.transport.TransportClientFactory; import com.netflix.discovery.shared.transport.jersey.EurekaJerseyClient; import com.netflix.discovery.shared.transport.jersey.TransportClientFactories; import com.netflix.eventbus.spi.EventBus; /** * <T> The type for client supplied filters (supports jersey1 and jersey2) */ public abstract class AbstractDiscoveryClientOptionalArgs<T> { Provider<HealthCheckCallback> healthCheckCallbackProvider; Provider<HealthCheckHandler> healthCheckHandlerProvider; PreRegistrationHandler preRegistrationHandler; Collection<T> additionalFilters; EurekaJerseyClient eurekaJerseyClient; TransportClientFactory transportClientFactory; TransportClientFactories transportClientFactories; private Set<EurekaEventListener> eventListeners; private Optional<SSLContext> sslContext = Optional.empty(); private Optional<HostnameVerifier> hostnameVerifier = Optional.empty(); @Inject(optional = true) public void setEventListeners(Set<EurekaEventListener> listeners) { if (eventListeners == null) { eventListeners = new HashSet<>(); } eventListeners.addAll(listeners); } @Inject(optional = true) public void setEventBus(final EventBus eventBus) { if (eventListeners == null) { eventListeners = new HashSet<>(); } eventListeners.add(new EurekaEventListener() { @Override public void onEvent(EurekaEvent event) { eventBus.publish(event); } }); } @Inject(optional = true) public void setHealthCheckCallbackProvider(Provider<HealthCheckCallback> healthCheckCallbackProvider) { this.healthCheckCallbackProvider = healthCheckCallbackProvider; } @Inject(optional = true) public void setHealthCheckHandlerProvider(Provider<HealthCheckHandler> healthCheckHandlerProvider) { this.healthCheckHandlerProvider = healthCheckHandlerProvider; } @Inject(optional = true) public void setPreRegistrationHandler(PreRegistrationHandler preRegistrationHandler) { this.preRegistrationHandler = preRegistrationHandler; } @Inject(optional = true) public void setAdditionalFilters(Collection<T> additionalFilters) { this.additionalFilters = additionalFilters; } @Inject(optional = true) public void setEurekaJerseyClient(EurekaJerseyClient eurekaJerseyClient) { this.eurekaJerseyClient = eurekaJerseyClient; } Set<EurekaEventListener> getEventListeners() { return eventListeners == null ? Collections.<EurekaEventListener>emptySet() : eventListeners; } public TransportClientFactories getTransportClientFactories() { return transportClientFactories; } @Inject(optional = true) public void setTransportClientFactories(TransportClientFactories transportClientFactories) { this.transportClientFactories = transportClientFactories; } public Optional<SSLContext> getSSLContext() { return sslContext; } @Inject(optional = true) public void setSSLContext(SSLContext sslContext) { this.sslContext = Optional.of(sslContext); } public Optional<HostnameVerifier> getHostnameVerifier() { return hostnameVerifier; } @Inject(optional = true) public void setHostnameVerifier(HostnameVerifier hostnameVerifier) { this.hostnameVerifier = Optional.of(hostnameVerifier); } }
6,682
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/EurekaIdentityHeaderFilter.java
package com.netflix.discovery; import com.netflix.appinfo.AbstractEurekaIdentity; import com.sun.jersey.api.client.ClientHandlerException; import com.sun.jersey.api.client.ClientRequest; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.filter.ClientFilter; public class EurekaIdentityHeaderFilter extends ClientFilter { private final AbstractEurekaIdentity authInfo; public EurekaIdentityHeaderFilter(AbstractEurekaIdentity authInfo) { this.authInfo = authInfo; } @Override public ClientResponse handle(ClientRequest cr) throws ClientHandlerException { if (authInfo != null) { cr.getHeaders().putSingle(AbstractEurekaIdentity.AUTH_NAME_HEADER_KEY, authInfo.getName()); cr.getHeaders().putSingle(AbstractEurekaIdentity.AUTH_VERSION_HEADER_KEY, authInfo.getVersion()); if (authInfo.getId() != null) { cr.getHeaders().putSingle(AbstractEurekaIdentity.AUTH_ID_HEADER_KEY, authInfo.getId()); } } return getNext().handle(cr); } }
6,683
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/EurekaClientConfig.java
/* * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery; import java.util.List; import javax.annotation.Nullable; import com.google.inject.ImplementedBy; import com.netflix.discovery.shared.transport.EurekaTransportConfig; /** * Configuration information required by the eureka clients to register an * instance with <em>Eureka</em> server. * * <p> * Most of the required information is provided by the default configuration * {@link DefaultEurekaClientConfig}. The users just need to provide the eureka * server service urls. The Eureka server service urls can be configured by 2 * mechanisms * * 1) By registering the information in the DNS. 2) By specifying it in the * configuration. * </p> * * * Once the client is registered, users can look up information from * {@link EurekaClient} based on <em>virtual hostname</em> (also called * VIPAddress), the most common way of doing it or by other means to get the * information necessary to talk to other instances registered with * <em>Eureka</em>. * * <p> * Note that all configurations are not effective at runtime unless and * otherwise specified. * </p> * * @author Karthik Ranganathan * */ @ImplementedBy(DefaultEurekaClientConfig.class) public interface EurekaClientConfig { /** * Indicates how often(in seconds) to fetch the registry information from * the eureka server. * * @return the fetch interval in seconds. */ int getRegistryFetchIntervalSeconds(); /** * Indicates how often(in seconds) to replicate instance changes to be * replicated to the eureka server. * * @return the instance replication interval in seconds. */ int getInstanceInfoReplicationIntervalSeconds(); /** * Indicates how long initially (in seconds) to replicate instance info * to the eureka server */ int getInitialInstanceInfoReplicationIntervalSeconds(); /** * Indicates how often(in seconds) to poll for changes to eureka server * information. * * <p> * Eureka servers could be added or removed and this setting controls how * soon the eureka clients should know about it. * </p> * * @return the interval to poll for eureka service url changes. */ int getEurekaServiceUrlPollIntervalSeconds(); /** * Gets the proxy host to eureka server if any. * * @return the proxy host. */ String getProxyHost(); /** * Gets the proxy port to eureka server if any. * * @return the proxy port. */ String getProxyPort(); /** * Gets the proxy user name if any. * * @return the proxy user name. */ String getProxyUserName(); /** * Gets the proxy password if any. * * @return the proxy password. */ String getProxyPassword(); /** * Indicates whether the content fetched from eureka server has to be * compressed whenever it is supported by the server. The registry * information from the eureka server is compressed for optimum network * traffic. * * @return true, if the content need to be compressed, false otherwise. * @deprecated gzip content encoding will be always enforced in the next minor Eureka release (see com.netflix.eureka.GzipEncodingEnforcingFilter). */ boolean shouldGZipContent(); /** * Indicates how long to wait (in seconds) before a read from eureka server * needs to timeout. * * @return time in seconds before the read should timeout. */ int getEurekaServerReadTimeoutSeconds(); /** * Indicates how long to wait (in seconds) before a connection to eureka * server needs to timeout. * * <p> * Note that the connections in the client are pooled by * {@link org.apache.http.client.HttpClient} and this setting affects the actual * connection creation and also the wait time to get the connection from the * pool. * </p> * * @return time in seconds before the connections should timeout. */ int getEurekaServerConnectTimeoutSeconds(); /** * Gets the name of the implementation which implements * {@link BackupRegistry} to fetch the registry information as a fall back * option for only the first time when the eureka client starts. * * <p> * This may be needed for applications which needs additional resiliency for * registry information without which it cannot operate. * </p> * * @return the class name which implements {@link BackupRegistry}. */ String getBackupRegistryImpl(); /** * Gets the total number of connections that is allowed from eureka client * to all eureka servers. * * @return total number of allowed connections from eureka client to all * eureka servers. */ int getEurekaServerTotalConnections(); /** * Gets the total number of connections that is allowed from eureka client * to a eureka server host. * * @return total number of allowed connections from eureka client to a * eureka server. */ int getEurekaServerTotalConnectionsPerHost(); /** * Gets the URL context to be used to construct the <em>service url</em> to * contact eureka server when the list of eureka servers come from the * DNS.This information is not required if the contract returns the service * urls by implementing {@link #getEurekaServerServiceUrls(String)}. * * <p> * The DNS mechanism is used when * {@link #shouldUseDnsForFetchingServiceUrls()} is set to <em>true</em> and * the eureka client expects the DNS to configured a certain way so that it * can fetch changing eureka servers dynamically. * </p> * * <p> * <em>The changes are effective at runtime.</em> * </p> * * @return the string indicating the context {@link java.net.URI} of the eureka * server. */ String getEurekaServerURLContext(); /** * Gets the port to be used to construct the <em>service url</em> to contact * eureka server when the list of eureka servers come from the DNS.This * information is not required if the contract returns the service urls by * implementing {@link #getEurekaServerServiceUrls(String)}. * * <p> * The DNS mechanism is used when * {@link #shouldUseDnsForFetchingServiceUrls()} is set to <em>true</em> and * the eureka client expects the DNS to configured a certain way so that it * can fetch changing eureka servers dynamically. * </p> * * <p> * <em>The changes are effective at runtime.</em> * </p> * * @return the string indicating the port where the eureka server is * listening. */ String getEurekaServerPort(); /** * Gets the DNS name to be queried to get the list of eureka servers.This * information is not required if the contract returns the service urls by * implementing {@link #getEurekaServerServiceUrls(String)}. * * <p> * The DNS mechanism is used when * {@link #shouldUseDnsForFetchingServiceUrls()} is set to <em>true</em> and * the eureka client expects the DNS to configured a certain way so that it * can fetch changing eureka servers dynamically. * </p> * * <p> * <em>The changes are effective at runtime.</em> * </p> * * @return the string indicating the DNS name to be queried for eureka * servers. */ String getEurekaServerDNSName(); /** * Indicates whether the eureka client should use the DNS mechanism to fetch * a list of eureka servers to talk to. When the DNS name is updated to have * additional servers, that information is used immediately after the eureka * client polls for that information as specified in * {@link #getEurekaServiceUrlPollIntervalSeconds()}. * * <p> * Alternatively, the service urls can be returned * {@link #getEurekaServerServiceUrls(String)}, but the users should implement * their own mechanism to return the updated list in case of changes. * </p> * * <p> * <em>The changes are effective at runtime.</em> * </p> * * @return true if the DNS mechanism should be used for fetching urls, false otherwise. */ boolean shouldUseDnsForFetchingServiceUrls(); /** * Indicates whether or not this instance should register its information * with eureka server for discovery by others. * * <p> * In some cases, you do not want your instances to be discovered whereas * you just want do discover other instances. * </p> * * @return true if this instance should register with eureka, false * otherwise */ boolean shouldRegisterWithEureka(); /** * Indicates whether the client should explicitly unregister itself from the remote server * on client shutdown. * * @return true if this instance should unregister with eureka on client shutdown, false otherwise */ default boolean shouldUnregisterOnShutdown() { return true; } /** * Indicates whether or not this instance should try to use the eureka * server in the same zone for latency and/or other reason. * * <p> * Ideally eureka clients are configured to talk to servers in the same zone * </p> * * <p> * <em>The changes are effective at runtime at the next registry fetch cycle as specified by * {@link #getRegistryFetchIntervalSeconds()}</em> * </p> * * @return true if the eureka client should prefer the server in the same * zone, false otherwise. */ boolean shouldPreferSameZoneEureka(); /** * Indicates whether server can redirect a client request to a backup server/cluster. * If set to false, the server will handle the request directly, If set to true, it may * send HTTP redirect to the client, with a new server location. * * @return true if HTTP redirects are allowed */ boolean allowRedirects(); /** * Indicates whether to log differences between the eureka server and the * eureka client in terms of registry information. * * <p> * Eureka client tries to retrieve only delta changes from eureka server to * minimize network traffic. After receiving the deltas, eureka client * reconciles the information from the server to verify it has not missed * out some information. Reconciliation failures could happen when the * client has had network issues communicating to server.If the * reconciliation fails, eureka client gets the full registry information. * </p> * * <p> * While getting the full registry information, the eureka client can log * the differences between the client and the server and this setting * controls that. * </p> * <p> * <em>The changes are effective at runtime at the next registry fetch cycle as specified by * {@link #getRegistryFetchIntervalSeconds()}</em> * </p> * * @return true if the eureka client should log delta differences in the * case of reconciliation failure. */ boolean shouldLogDeltaDiff(); /** * Indicates whether the eureka client should disable fetching of delta and * should rather resort to getting the full registry information. * * <p> * Note that the delta fetches can reduce the traffic tremendously, because * the rate of change with the eureka server is normally much lower than the * rate of fetches. * </p> * <p> * <em>The changes are effective at runtime at the next registry fetch cycle as specified by * {@link #getRegistryFetchIntervalSeconds()}</em> * </p> * * @return true to enable fetching delta information for registry, false to * get the full registry. */ boolean shouldDisableDelta(); /** * Comma separated list of regions for which the eureka registry information will be fetched. It is mandatory to * define the availability zones for each of these regions as returned by {@link #getAvailabilityZones(String)}. * Failing to do so, will result in failure of discovery client startup. * * @return Comma separated list of regions for which the eureka registry information will be fetched. * <code>null</code> if no remote region has to be fetched. */ @Nullable String fetchRegistryForRemoteRegions(); /** * Gets the region (used in AWS datacenters) where this instance resides. * * @return AWS region where this instance resides. */ String getRegion(); /** * Gets the list of availability zones (used in AWS data centers) for the * region in which this instance resides. * * <p> * <em>The changes are effective at runtime at the next registry fetch cycle as specified by * {@link #getRegistryFetchIntervalSeconds()}</em> * </p> * @param region the region where this instance is deployed. * * @return the list of available zones accessible by this instance. */ String[] getAvailabilityZones(String region); /** * Gets the list of fully qualified {@link java.net.URL}s to communicate with eureka * server. * * <p> * Typically the eureka server {@link java.net.URL}s carry protocol,host,port,context * and version information if any. * <code>Example: http://ec2-256-156-243-129.compute-1.amazonaws.com:7001/eureka/v2/</code> * <p> * * <p> * <em>The changes are effective at runtime at the next service url refresh cycle as specified by * {@link #getEurekaServiceUrlPollIntervalSeconds()}</em> * </p> * @param myZone the zone in which the instance is deployed. * * @return the list of eureka server service urls for eureka clients to talk * to. */ List<String> getEurekaServerServiceUrls(String myZone); /** * Indicates whether to get the <em>applications</em> after filtering the * applications for instances with only {@link com.netflix.appinfo.InstanceInfo.InstanceStatus#UP} states. * * <p> * <em>The changes are effective at runtime at the next registry fetch cycle as specified by * {@link #getRegistryFetchIntervalSeconds()}</em> * </p> * * @return true to filter, false otherwise. */ boolean shouldFilterOnlyUpInstances(); /** * Indicates how much time (in seconds) that the HTTP connections to eureka * server can stay idle before it can be closed. * * <p> * In the AWS environment, it is recommended that the values is 30 seconds * or less, since the firewall cleans up the connection information after a * few mins leaving the connection hanging in limbo * </p> * * @return time in seconds the connections to eureka can stay idle before it * can be closed. */ int getEurekaConnectionIdleTimeoutSeconds(); /** * Indicates whether this client should fetch eureka registry information from eureka server. * * @return {@code true} if registry information has to be fetched, {@code false} otherwise. */ boolean shouldFetchRegistry(); /** * If set to true, the {@link EurekaClient} initialization should throw an exception at constructor time * if the initial fetch of eureka registry information from the remote servers is unsuccessful. * * Note that if {@link #shouldFetchRegistry()} is set to false, then this config is a no-op. * * @return true or false for whether the client initialization should enforce an initial fetch. */ default boolean shouldEnforceFetchRegistryAtInit() { return false; } /** * Indicates whether the client is only interested in the registry information for a single VIP. * * @return the address of the VIP (name:port). * <code>null</code> if single VIP interest is not present. */ @Nullable String getRegistryRefreshSingleVipAddress(); /** * The thread pool size for the heartbeatExecutor to initialise with * * @return the heartbeatExecutor thread pool size */ int getHeartbeatExecutorThreadPoolSize(); /** * Heartbeat executor exponential back off related property. * It is a maximum multiplier value for retry delay, in case where a sequence of timeouts * occurred. * * @return maximum multiplier value for retry delay */ int getHeartbeatExecutorExponentialBackOffBound(); /** * The thread pool size for the cacheRefreshExecutor to initialise with * * @return the cacheRefreshExecutor thread pool size */ int getCacheRefreshExecutorThreadPoolSize(); /** * Cache refresh executor exponential back off related property. * It is a maximum multiplier value for retry delay, in case where a sequence of timeouts * occurred. * * @return maximum multiplier value for retry delay */ int getCacheRefreshExecutorExponentialBackOffBound(); /** * Get a replacement string for Dollar sign <code>$</code> during serializing/deserializing information in eureka server. * * @return Replacement string for Dollar sign <code>$</code>. */ String getDollarReplacement(); /** * Get a replacement string for underscore sign <code>_</code> during serializing/deserializing information in eureka server. * * @return Replacement string for underscore sign <code>_</code>. */ String getEscapeCharReplacement(); /** * If set to true, local status updates via * {@link com.netflix.appinfo.ApplicationInfoManager#setInstanceStatus(com.netflix.appinfo.InstanceInfo.InstanceStatus)} * will trigger on-demand (but rate limited) register/updates to remote eureka servers * * @return true or false for whether local status updates should be updated to remote servers on-demand */ boolean shouldOnDemandUpdateStatusChange(); /** * If set to true, the {@link EurekaClient} initialization should throw an exception at constructor time * if an initial registration to the remote servers is unsuccessful. * * Note that if {@link #shouldRegisterWithEureka()} is set to false, then this config is a no-op * * @return true or false for whether the client initialization should enforce an initial registration */ default boolean shouldEnforceRegistrationAtInit() { return false; } /** * This is a transient config and once the latest codecs are stable, can be removed (as there will only be one) * * @return the class name of the encoding codec to use for the client. If none set a default codec will be used */ String getEncoderName(); /** * This is a transient config and once the latest codecs are stable, can be removed (as there will only be one) * * @return the class name of the decoding codec to use for the client. If none set a default codec will be used */ String getDecoderName(); /** * @return {@link com.netflix.appinfo.EurekaAccept#name()} for client data accept */ String getClientDataAccept(); /** * To avoid configuration API pollution when trying new/experimental or features or for the migration process, * the corresponding configuration can be put into experimental configuration section. Config format is: * eureka.experimental.freeFormConfigString * * @return a property of experimental feature */ String getExperimental(String name); /** * For compatibility, return the transport layer config class * * @return an instance of {@link EurekaTransportConfig} */ EurekaTransportConfig getTransportConfig(); }
6,684
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/EurekaNamespace.java
package com.netflix.discovery; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.google.inject.BindingAnnotation; @BindingAnnotation @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface EurekaNamespace { }
6,685
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/CacheRefreshedEvent.java
package com.netflix.discovery; /** * This event is sent by {@link EurekaClient) whenever it has refreshed its local * local cache with information received from the Eureka server. * * @author brenuart */ public class CacheRefreshedEvent extends DiscoveryEvent { @Override public String toString() { return "CacheRefreshedEvent[timestamp=" + getTimestamp() + "]"; } }
6,686
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/CommonConstants.java
package com.netflix.discovery; /** * @author David Liu */ public final class CommonConstants { public static final String CONFIG_FILE_NAME = "eureka-client"; public static final String DEFAULT_CONFIG_NAMESPACE = "eureka"; public static final String INSTANCE_CONFIG_NAMESPACE_KEY = "eureka.instance.config.namespace"; public static final String CLIENT_CONFIG_NAMESPACE_KEY = "eureka.client.config.namespace"; }
6,687
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/TimedSupervisorTask.java
package com.netflix.discovery; import java.util.TimerTask; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicLong; import com.netflix.servo.monitor.Counter; import com.netflix.servo.monitor.LongGauge; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.monitor.Monitors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A supervisor task that schedules subtasks while enforce a timeout. * Wrapped subtasks must be thread safe. * * @author David Qiang Liu */ public class TimedSupervisorTask extends TimerTask { private static final Logger logger = LoggerFactory.getLogger(TimedSupervisorTask.class); private final Counter successCounter; private final Counter timeoutCounter; private final Counter rejectedCounter; private final Counter throwableCounter; private final LongGauge threadPoolLevelGauge; private final String name; private final ScheduledExecutorService scheduler; private final ThreadPoolExecutor executor; private final long timeoutMillis; private final Runnable task; private final AtomicLong delay; private final long maxDelay; public TimedSupervisorTask(String name, ScheduledExecutorService scheduler, ThreadPoolExecutor executor, int timeout, TimeUnit timeUnit, int expBackOffBound, Runnable task) { this.name = name; this.scheduler = scheduler; this.executor = executor; this.timeoutMillis = timeUnit.toMillis(timeout); this.task = task; this.delay = new AtomicLong(timeoutMillis); this.maxDelay = timeoutMillis * expBackOffBound; // Initialize the counters and register. successCounter = Monitors.newCounter("success"); timeoutCounter = Monitors.newCounter("timeouts"); rejectedCounter = Monitors.newCounter("rejectedExecutions"); throwableCounter = Monitors.newCounter("throwables"); threadPoolLevelGauge = new LongGauge(MonitorConfig.builder("threadPoolUsed").build()); Monitors.registerObject(name, this); } @Override public void run() { Future<?> future = null; try { future = executor.submit(task); threadPoolLevelGauge.set((long) executor.getActiveCount()); future.get(timeoutMillis, TimeUnit.MILLISECONDS); // block until done or timeout delay.set(timeoutMillis); threadPoolLevelGauge.set((long) executor.getActiveCount()); successCounter.increment(); } catch (TimeoutException e) { logger.warn("task supervisor timed out", e); timeoutCounter.increment(); long currentDelay = delay.get(); long newDelay = Math.min(maxDelay, currentDelay * 2); delay.compareAndSet(currentDelay, newDelay); } catch (RejectedExecutionException e) { if (executor.isShutdown() || scheduler.isShutdown()) { logger.warn("task supervisor shutting down, reject the task", e); } else { logger.warn("task supervisor rejected the task", e); } rejectedCounter.increment(); } catch (Throwable e) { if (executor.isShutdown() || scheduler.isShutdown()) { logger.warn("task supervisor shutting down, can't accept the task"); } else { logger.warn("task supervisor threw an exception", e); } throwableCounter.increment(); } finally { if (future != null) { future.cancel(true); } if (!scheduler.isShutdown()) { scheduler.schedule(this, delay.get(), TimeUnit.MILLISECONDS); } } } @Override public boolean cancel() { Monitors.unregisterObject(name, this); return super.cancel(); } }
6,688
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/PropertyBasedClientConfigConstants.java
package com.netflix.discovery; /** * constants pertaining to property based client configs * * @author David Liu */ final class PropertyBasedClientConfigConstants { static final String CLIENT_REGION_FALLBACK_KEY = "eureka.region"; // NOTE: all keys are before any prefixes are applied static final String CLIENT_REGION_KEY = "region"; static final String REGISTRATION_ENABLED_KEY = "registration.enabled"; static final String FETCH_REGISTRY_ENABLED_KEY = "shouldFetchRegistry"; static final String SHOULD_ENFORCE_FETCH_REGISTRY_AT_INIT_KEY = "shouldEnforceFetchRegistryAtInit"; static final String REGISTRY_REFRESH_INTERVAL_KEY = "client.refresh.interval"; static final String REGISTRATION_REPLICATION_INTERVAL_KEY = "appinfo.replicate.interval"; static final String INITIAL_REGISTRATION_REPLICATION_DELAY_KEY = "appinfo.initial.replicate.time"; static final String HEARTBEAT_THREADPOOL_SIZE_KEY = "client.heartbeat.threadPoolSize"; static final String HEARTBEAT_BACKOFF_BOUND_KEY = "client.heartbeat.exponentialBackOffBound"; static final String CACHEREFRESH_THREADPOOL_SIZE_KEY = "client.cacheRefresh.threadPoolSize"; static final String CACHEREFRESH_BACKOFF_BOUND_KEY = "client.cacheRefresh.exponentialBackOffBound"; static final String SHOULD_UNREGISTER_ON_SHUTDOWN_KEY = "shouldUnregisterOnShutdown"; static final String SHOULD_ONDEMAND_UPDATE_STATUS_KEY = "shouldOnDemandUpdateStatusChange"; static final String SHOULD_ENFORCE_REGISTRATION_AT_INIT = "shouldEnforceRegistrationAtInit"; static final String SHOULD_DISABLE_DELTA_KEY = "disableDelta"; static final String SHOULD_FETCH_REMOTE_REGION_KEY = "fetchRemoteRegionsRegistry"; static final String SHOULD_FILTER_ONLY_UP_INSTANCES_KEY = "shouldFilterOnlyUpInstances"; static final String FETCH_SINGLE_VIP_ONLY_KEY = "registryRefreshSingleVipAddress"; static final String CLIENT_ENCODER_NAME_KEY = "encoderName"; static final String CLIENT_DECODER_NAME_KEY = "decoderName"; static final String CLIENT_DATA_ACCEPT_KEY = "clientDataAccept"; static final String BACKUP_REGISTRY_CLASSNAME_KEY = "backupregistry"; static final String SHOULD_PREFER_SAME_ZONE_SERVER_KEY = "preferSameZone"; static final String SHOULD_ALLOW_REDIRECTS_KEY = "allowRedirects"; static final String SHOULD_USE_DNS_KEY = "shouldUseDns"; static final String EUREKA_SERVER_URL_POLL_INTERVAL_KEY = "serviceUrlPollIntervalMs"; static final String EUREKA_SERVER_URL_CONTEXT_KEY = "eurekaServer.context"; static final String EUREKA_SERVER_FALLBACK_URL_CONTEXT_KEY = "context"; static final String EUREKA_SERVER_PORT_KEY = "eurekaServer.port"; static final String EUREKA_SERVER_FALLBACK_PORT_KEY = "port"; static final String EUREKA_SERVER_DNS_NAME_KEY = "eurekaServer.domainName"; static final String EUREKA_SERVER_FALLBACK_DNS_NAME_KEY = "domainName"; static final String EUREKA_SERVER_PROXY_HOST_KEY = "eurekaServer.proxyHost"; static final String EUREKA_SERVER_PROXY_PORT_KEY = "eurekaServer.proxyPort"; static final String EUREKA_SERVER_PROXY_USERNAME_KEY = "eurekaServer.proxyUserName"; static final String EUREKA_SERVER_PROXY_PASSWORD_KEY = "eurekaServer.proxyPassword"; static final String EUREKA_SERVER_GZIP_CONTENT_KEY = "eurekaServer.gzipContent"; static final String EUREKA_SERVER_READ_TIMEOUT_KEY = "eurekaServer.readTimeout"; static final String EUREKA_SERVER_CONNECT_TIMEOUT_KEY = "eurekaServer.connectTimeout"; static final String EUREKA_SERVER_MAX_CONNECTIONS_KEY = "eurekaServer.maxTotalConnections"; static final String EUREKA_SERVER_MAX_CONNECTIONS_PER_HOST_KEY = "eurekaServer.maxConnectionsPerHost"; // yeah the case on eurekaserver is different, backwards compatibility requirements :( static final String EUREKA_SERVER_CONNECTION_IDLE_TIMEOUT_KEY = "eurekaserver.connectionIdleTimeoutInSeconds"; static final String SHOULD_LOG_DELTA_DIFF_KEY = "printDeltaFullDiff"; static final String CONFIG_DOLLAR_REPLACEMENT_KEY = "dollarReplacement"; static final String CONFIG_ESCAPE_CHAR_REPLACEMENT_KEY = "escapeCharReplacement"; // additional namespaces static final String CONFIG_EXPERIMENTAL_PREFIX = "experimental"; static final String CONFIG_AVAILABILITY_ZONE_PREFIX = "availabilityZones"; static final String CONFIG_EUREKA_SERVER_SERVICE_URL_PREFIX = "serviceUrl"; static class Values { static final String CONFIG_DOLLAR_REPLACEMENT = "_-"; static final String CONFIG_ESCAPE_CHAR_REPLACEMENT = "__"; static final String DEFAULT_CLIENT_REGION = "us-east-1"; static final int DEFAULT_EXECUTOR_THREAD_POOL_SIZE = 5; static final int DEFAULT_EXECUTOR_THREAD_POOL_BACKOFF_BOUND = 10; } }
6,689
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/EurekaClientNames.java
/* * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery; /** * @author Tomasz Bak */ public final class EurekaClientNames { /** * Eureka metric names consist of three parts [source].[component].[detailed name]: * <ul> * <li>source - fixed to eurekaClient (and eurekaServer on the server side)</li> * <li>component - Eureka component, like registry cache</li> * <li>detailed name - a detailed metric name explaining its purpose</li> * </ul> */ public static final String METRIC_PREFIX = "eurekaClient."; public static final String METRIC_REGISTRATION_PREFIX = METRIC_PREFIX + "registration."; public static final String METRIC_REGISTRY_PREFIX = METRIC_PREFIX + "registry."; public static final String METRIC_RESOLVER_PREFIX = METRIC_PREFIX + "resolver."; public static final String METRIC_TRANSPORT_PREFIX = METRIC_PREFIX + "transport."; public static final String RESOLVER = "resolver"; public static final String BOOTSTRAP = "bootstrap"; public static final String QUERY = "query"; public static final String REGISTRATION = "registration"; private EurekaClientNames() { } }
6,690
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/EurekaEventListener.java
package com.netflix.discovery; /** * Listener for receiving {@link EurekaClient} events such as {@link StatusChangeEvent}. Register * a listener by calling {@link EurekaClient#registerEventListener(EurekaEventListener)} */ public interface EurekaEventListener { /** * Notification of an event within the {@link EurekaClient}. * * {@link EurekaEventListener#onEvent} is called from the context of an internal eureka thread * and must therefore return as quickly as possible without blocking. * * @param event */ public void onEvent(EurekaEvent event); }
6,691
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/InstanceRegionChecker.java
package com.netflix.discovery; import javax.annotation.Nullable; import java.util.Map; import com.netflix.appinfo.AmazonInfo; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.InstanceInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Nitesh Kant */ public class InstanceRegionChecker { private static Logger logger = LoggerFactory.getLogger(InstanceRegionChecker.class); private final AzToRegionMapper azToRegionMapper; private final String localRegion; InstanceRegionChecker(AzToRegionMapper azToRegionMapper, String localRegion) { this.azToRegionMapper = azToRegionMapper; this.localRegion = localRegion; } @Nullable public String getInstanceRegion(InstanceInfo instanceInfo) { if (instanceInfo.getDataCenterInfo() == null || instanceInfo.getDataCenterInfo().getName() == null) { logger.warn("Cannot get region for instance id:{}, app:{} as dataCenterInfo is null. Returning local:{} by default", instanceInfo.getId(), instanceInfo.getAppName(), localRegion); return localRegion; } if (DataCenterInfo.Name.Amazon.equals(instanceInfo.getDataCenterInfo().getName())) { AmazonInfo amazonInfo = (AmazonInfo) instanceInfo.getDataCenterInfo(); Map<String, String> metadata = amazonInfo.getMetadata(); String availabilityZone = metadata.get(AmazonInfo.MetaDataKey.availabilityZone.getName()); if (null != availabilityZone) { return azToRegionMapper.getRegionForAvailabilityZone(availabilityZone); } } return null; } public boolean isLocalRegion(@Nullable String instanceRegion) { return null == instanceRegion || instanceRegion.equals(localRegion); // no region == local } public String getLocalRegion() { return localRegion; } public AzToRegionMapper getAzToRegionMapper() { return azToRegionMapper; } }
6,692
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/PreRegistrationHandler.java
package com.netflix.discovery; import com.netflix.appinfo.ApplicationInfoManager; /** * A handler that can be registered with an {@link EurekaClient} at creation time to execute * pre registration logic. The pre registration logic need to be synchronous to be guaranteed * to execute before registration. */ public interface PreRegistrationHandler { void beforeRegistration(); }
6,693
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/EurekaEvent.java
package com.netflix.discovery; /** * Marker interface for Eureka events * * @see {@link EurekaEventListener} */ public interface EurekaEvent { }
6,694
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/EurekaClient.java
package com.netflix.discovery; import java.util.List; import java.util.Set; import javax.annotation.Nullable; import com.google.inject.ImplementedBy; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.HealthCheckCallback; import com.netflix.appinfo.HealthCheckHandler; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.shared.LookupService; /** * Define a simple interface over the current DiscoveryClient implementation. * * This interface does NOT try to clean up the current client interface for eureka 1.x. Rather it tries * to provide an easier transition path from eureka 1.x to eureka 2.x. * * EurekaClient API contracts are: * - provide the ability to get InstanceInfo(s) (in various different ways) * - provide the ability to get data about the local Client (known regions, own AZ etc) * - provide the ability to register and access the healthcheck handler for the client * * @author David Liu */ @ImplementedBy(DiscoveryClient.class) public interface EurekaClient extends LookupService { // ======================== // getters for InstanceInfo // ======================== /** * @param region the region that the Applications reside in * @return an {@link com.netflix.discovery.shared.Applications} for the matching region. a Null value * is treated as the local region. */ public Applications getApplicationsForARegion(@Nullable String region); /** * Get all applications registered with a specific eureka service. * * @param serviceUrl The string representation of the service url. * @return The registry information containing all applications. */ public Applications getApplications(String serviceUrl); /** * Gets the list of instances matching the given VIP Address. * * @param vipAddress The VIP address to match the instances for. * @param secure true if it is a secure vip address, false otherwise * @return - The list of {@link InstanceInfo} objects matching the criteria */ public List<InstanceInfo> getInstancesByVipAddress(String vipAddress, boolean secure); /** * Gets the list of instances matching the given VIP Address in the passed region. * * @param vipAddress The VIP address to match the instances for. * @param secure true if it is a secure vip address, false otherwise * @param region region from which the instances are to be fetched. If <code>null</code> then local region is * assumed. * * @return - The list of {@link InstanceInfo} objects matching the criteria, empty list if not instances found. */ public List<InstanceInfo> getInstancesByVipAddress(String vipAddress, boolean secure, @Nullable String region); /** * Gets the list of instances matching the given VIP Address and the given * application name if both of them are not null. If one of them is null, * then that criterion is completely ignored for matching instances. * * @param vipAddress The VIP address to match the instances for. * @param appName The applicationName to match the instances for. * @param secure true if it is a secure vip address, false otherwise. * @return - The list of {@link InstanceInfo} objects matching the criteria. */ public List<InstanceInfo> getInstancesByVipAddressAndAppName(String vipAddress, String appName, boolean secure); // ========================== // getters for local metadata // ========================== /** * @return in String form all regions (local + remote) that can be accessed by this client */ public Set<String> getAllKnownRegions(); /** * @return the current self instance status as seen on the Eureka server. */ public InstanceInfo.InstanceStatus getInstanceRemoteStatus(); /** * @deprecated see {@link com.netflix.discovery.endpoint.EndpointUtils} for replacement * * Get the list of all eureka service urls for the eureka client to talk to. * * @param zone the zone in which the client resides * @return The list of all eureka service urls for the eureka client to talk to. */ @Deprecated public List<String> getDiscoveryServiceUrls(String zone); /** * @deprecated see {@link com.netflix.discovery.endpoint.EndpointUtils} for replacement * * Get the list of all eureka service urls from properties file for the eureka client to talk to. * * @param instanceZone The zone in which the client resides * @param preferSameZone true if we have to prefer the same zone as the client, false otherwise * @return The list of all eureka service urls for the eureka client to talk to */ @Deprecated public List<String> getServiceUrlsFromConfig(String instanceZone, boolean preferSameZone); /** * @deprecated see {@link com.netflix.discovery.endpoint.EndpointUtils} for replacement * * Get the list of all eureka service urls from DNS for the eureka client to * talk to. The client picks up the service url from its zone and then fails over to * other zones randomly. If there are multiple servers in the same zone, the client once * again picks one randomly. This way the traffic will be distributed in the case of failures. * * @param instanceZone The zone in which the client resides. * @param preferSameZone true if we have to prefer the same zone as the client, false otherwise. * @return The list of all eureka service urls for the eureka client to talk to. */ @Deprecated public List<String> getServiceUrlsFromDNS(String instanceZone, boolean preferSameZone); // =========================== // healthcheck related methods // =========================== /** * @deprecated Use {@link #registerHealthCheck(com.netflix.appinfo.HealthCheckHandler)} instead. * * Register {@link HealthCheckCallback} with the eureka client. * * Once registered, the eureka client will invoke the * {@link HealthCheckCallback} in intervals specified by * {@link EurekaClientConfig#getInstanceInfoReplicationIntervalSeconds()}. * * @param callback app specific healthcheck. */ @Deprecated public void registerHealthCheckCallback(HealthCheckCallback callback); /** * Register {@link HealthCheckHandler} with the eureka client. * * Once registered, the eureka client will first make an onDemand update of the * registering instanceInfo by calling the newly registered healthcheck handler, * and subsequently invoke the {@link HealthCheckHandler} in intervals specified * by {@link EurekaClientConfig#getInstanceInfoReplicationIntervalSeconds()}. * * @param healthCheckHandler app specific healthcheck handler. */ public void registerHealthCheck(HealthCheckHandler healthCheckHandler); /** * Register {@link EurekaEventListener} with the eureka client. * * Once registered, the eureka client will invoke {@link EurekaEventListener#onEvent} * whenever there is a change in eureka client's internal state. Use this instead of * polling the client for changes. * * {@link EurekaEventListener#onEvent} is called from the context of an internal thread * and must therefore return as quickly as possible without blocking. * * @param eventListener */ public void registerEventListener(EurekaEventListener eventListener); /** * Unregister a {@link EurekaEventListener} previous registered with {@link EurekaClient#registerEventListener} * or injected into the constructor of {@link DiscoveryClient} * * @param eventListener * @return True if removed otherwise false if the listener was never registered. */ public boolean unregisterEventListener(EurekaEventListener eventListener); /** * @return the current registered healthcheck handler */ public HealthCheckHandler getHealthCheckHandler(); // ============= // other methods // ============= /** * Shuts down Eureka Client. Also sends a deregistration request to the eureka server. */ public void shutdown(); /** * @return the configuration of this eureka client */ public EurekaClientConfig getEurekaClientConfig(); /** * @return the application info manager of this eureka client */ public ApplicationInfoManager getApplicationInfoManager(); }
6,695
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/NotImplementedRegistryImpl.java
package com.netflix.discovery; import javax.inject.Singleton; import com.netflix.discovery.shared.Applications; /** * @author Nitesh Kant */ @Singleton public class NotImplementedRegistryImpl implements BackupRegistry { @Override public Applications fetchRegistry() { return null; } @Override public Applications fetchRegistry(String[] includeRemoteRegions) { return null; } }
6,696
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/DiscoveryClient.java
/* * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery; import static com.netflix.discovery.EurekaClientNames.METRIC_REGISTRATION_PREFIX; import static com.netflix.discovery.EurekaClientNames.METRIC_REGISTRY_PREFIX; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.annotation.Nullable; import javax.annotation.PreDestroy; import javax.inject.Provider; import javax.inject.Singleton; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.ws.rs.core.Response.Status; import com.netflix.discovery.shared.resolver.EndpointRandomizer; import com.netflix.discovery.shared.resolver.ResolverUtils; import org.apache.commons.lang.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.inject.Inject; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.HealthCheckCallback; import com.netflix.appinfo.HealthCheckCallbackToHandlerBridge; import com.netflix.appinfo.HealthCheckHandler; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.ActionType; import com.netflix.appinfo.InstanceInfo.InstanceStatus; import com.netflix.discovery.endpoint.EndpointUtils; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.shared.resolver.ClosableResolver; import com.netflix.discovery.shared.resolver.aws.ApplicationsResolver; import com.netflix.discovery.shared.transport.EurekaHttpClient; import com.netflix.discovery.shared.transport.EurekaHttpClientFactory; import com.netflix.discovery.shared.transport.EurekaHttpClients; import com.netflix.discovery.shared.transport.EurekaHttpResponse; import com.netflix.discovery.shared.transport.EurekaTransportConfig; import com.netflix.discovery.shared.transport.TransportClientFactory; import com.netflix.discovery.shared.transport.jersey.EurekaJerseyClient; import com.netflix.discovery.shared.transport.jersey.Jersey1DiscoveryClientOptionalArgs; import com.netflix.discovery.shared.transport.jersey.Jersey1TransportClientFactories; import com.netflix.discovery.shared.transport.jersey.TransportClientFactories; import com.netflix.discovery.util.ThresholdLevelsMetric; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.monitor.Counter; import com.netflix.servo.monitor.Monitors; import com.netflix.servo.monitor.Stopwatch; /** * The class that is instrumental for interactions with <tt>Eureka Server</tt>. * * <p> * <tt>Eureka Client</tt> is responsible for a) <em>Registering</em> the * instance with <tt>Eureka Server</tt> b) <em>Renewal</em>of the lease with * <tt>Eureka Server</tt> c) <em>Cancellation</em> of the lease from * <tt>Eureka Server</tt> during shutdown * <p> * d) <em>Querying</em> the list of services/instances registered with * <tt>Eureka Server</tt> * <p> * * <p> * <tt>Eureka Client</tt> needs a configured list of <tt>Eureka Server</tt> * {@link java.net.URL}s to talk to.These {@link java.net.URL}s are typically amazon elastic eips * which do not change. All of the functions defined above fail-over to other * {@link java.net.URL}s specified in the list in the case of failure. * </p> * * @author Karthik Ranganathan, Greg Kim * @author Spencer Gibb * */ @Singleton public class DiscoveryClient implements EurekaClient { private static final Logger logger = LoggerFactory.getLogger(DiscoveryClient.class); // Constants public static final String HTTP_X_DISCOVERY_ALLOW_REDIRECT = "X-Discovery-AllowRedirect"; private static final String VALUE_DELIMITER = ","; private static final String COMMA_STRING = VALUE_DELIMITER; /** * @deprecated here for legacy support as the client config has moved to be an instance variable */ @Deprecated private static EurekaClientConfig staticClientConfig; // Timers private static final String PREFIX = "DiscoveryClient_"; private final Counter RECONCILE_HASH_CODES_MISMATCH = Monitors.newCounter(PREFIX + "ReconcileHashCodeMismatch"); private final com.netflix.servo.monitor.Timer FETCH_REGISTRY_TIMER = Monitors .newTimer(PREFIX + "FetchRegistry"); private final Counter REREGISTER_COUNTER = Monitors.newCounter(PREFIX + "Reregister"); // instance variables /** * A scheduler to be used for the following 3 tasks: * - updating service urls * - scheduling a TimedSuperVisorTask */ private final ScheduledExecutorService scheduler; // additional executors for supervised subtasks private final ThreadPoolExecutor heartbeatExecutor; private final ThreadPoolExecutor cacheRefreshExecutor; private TimedSupervisorTask cacheRefreshTask; private TimedSupervisorTask heartbeatTask; private final Provider<HealthCheckHandler> healthCheckHandlerProvider; private final Provider<HealthCheckCallback> healthCheckCallbackProvider; private final PreRegistrationHandler preRegistrationHandler; private final AtomicReference<Applications> localRegionApps = new AtomicReference<>(); private final Lock fetchRegistryUpdateLock = new ReentrantLock(); // monotonically increasing generation counter to ensure stale threads do not reset registry to an older version private final AtomicLong fetchRegistryGeneration; private final ApplicationInfoManager applicationInfoManager; private final InstanceInfo instanceInfo; private final AtomicReference<String> remoteRegionsToFetch; private final AtomicReference<String[]> remoteRegionsRef; private final InstanceRegionChecker instanceRegionChecker; private final EndpointUtils.ServiceUrlRandomizer urlRandomizer; private final EndpointRandomizer endpointRandomizer; private final Provider<BackupRegistry> backupRegistryProvider; private final EurekaTransport eurekaTransport; private final AtomicReference<HealthCheckHandler> healthCheckHandlerRef = new AtomicReference<>(); private volatile Map<String, Applications> remoteRegionVsApps = new ConcurrentHashMap<>(); private volatile InstanceInfo.InstanceStatus lastRemoteInstanceStatus = InstanceInfo.InstanceStatus.UNKNOWN; private final CopyOnWriteArraySet<EurekaEventListener> eventListeners = new CopyOnWriteArraySet<>(); private String appPathIdentifier; private ApplicationInfoManager.StatusChangeListener statusChangeListener; private InstanceInfoReplicator instanceInfoReplicator; private volatile int registrySize = 0; private volatile long lastSuccessfulRegistryFetchTimestamp = -1; private volatile long lastSuccessfulHeartbeatTimestamp = -1; private final ThresholdLevelsMetric heartbeatStalenessMonitor; private final ThresholdLevelsMetric registryStalenessMonitor; private final AtomicBoolean isShutdown = new AtomicBoolean(false); protected final EurekaClientConfig clientConfig; protected final EurekaTransportConfig transportConfig; private final long initTimestampMs; private final int initRegistrySize; private final Stats stats = new Stats(); private static final class EurekaTransport { private ClosableResolver bootstrapResolver; private TransportClientFactory transportClientFactory; private EurekaHttpClient registrationClient; private EurekaHttpClientFactory registrationClientFactory; private EurekaHttpClient queryClient; private EurekaHttpClientFactory queryClientFactory; void shutdown() { if (registrationClientFactory != null) { registrationClientFactory.shutdown(); } if (queryClientFactory != null) { queryClientFactory.shutdown(); } if (registrationClient != null) { registrationClient.shutdown(); } if (queryClient != null) { queryClient.shutdown(); } if (transportClientFactory != null) { transportClientFactory.shutdown(); } if (bootstrapResolver != null) { bootstrapResolver.shutdown(); } } } public static class DiscoveryClientOptionalArgs extends Jersey1DiscoveryClientOptionalArgs { } /** * Assumes applicationInfoManager is already initialized * * @deprecated use constructor that takes ApplicationInfoManager instead of InstanceInfo directly */ @Deprecated public DiscoveryClient(InstanceInfo myInfo, EurekaClientConfig config) { this(myInfo, config, null); } /** * Assumes applicationInfoManager is already initialized * * @deprecated use constructor that takes ApplicationInfoManager instead of InstanceInfo directly */ @Deprecated public DiscoveryClient(InstanceInfo myInfo, EurekaClientConfig config, DiscoveryClientOptionalArgs args) { this(ApplicationInfoManager.getInstance(), config, args); } /** * @deprecated use constructor that takes ApplicationInfoManager instead of InstanceInfo directly */ @Deprecated public DiscoveryClient(InstanceInfo myInfo, EurekaClientConfig config, AbstractDiscoveryClientOptionalArgs args) { this(ApplicationInfoManager.getInstance(), config, args); } public DiscoveryClient(ApplicationInfoManager applicationInfoManager, EurekaClientConfig config) { this(applicationInfoManager, config, null); } /** * @deprecated use the version that take {@link com.netflix.discovery.AbstractDiscoveryClientOptionalArgs} instead */ @Deprecated public DiscoveryClient(ApplicationInfoManager applicationInfoManager, final EurekaClientConfig config, DiscoveryClientOptionalArgs args) { this(applicationInfoManager, config, (AbstractDiscoveryClientOptionalArgs) args); } public DiscoveryClient(ApplicationInfoManager applicationInfoManager, final EurekaClientConfig config, AbstractDiscoveryClientOptionalArgs args) { this(applicationInfoManager, config, args, ResolverUtils::randomize); } public DiscoveryClient(ApplicationInfoManager applicationInfoManager, final EurekaClientConfig config, AbstractDiscoveryClientOptionalArgs args, EndpointRandomizer randomizer) { this(applicationInfoManager, config, args, new Provider<BackupRegistry>() { private volatile BackupRegistry backupRegistryInstance; @Override public synchronized BackupRegistry get() { if (backupRegistryInstance == null) { String backupRegistryClassName = config.getBackupRegistryImpl(); if (null != backupRegistryClassName) { try { backupRegistryInstance = (BackupRegistry) Class.forName(backupRegistryClassName).newInstance(); logger.info("Enabled backup registry of type {}", backupRegistryInstance.getClass()); } catch (InstantiationException e) { logger.error("Error instantiating BackupRegistry.", e); } catch (IllegalAccessException e) { logger.error("Error instantiating BackupRegistry.", e); } catch (ClassNotFoundException e) { logger.error("Error instantiating BackupRegistry.", e); } } if (backupRegistryInstance == null) { logger.warn("Using default backup registry implementation which does not do anything."); backupRegistryInstance = new NotImplementedRegistryImpl(); } } return backupRegistryInstance; } }, randomizer); } /** * @deprecated Use {@link #DiscoveryClient(ApplicationInfoManager, EurekaClientConfig, AbstractDiscoveryClientOptionalArgs, Provider<BackupRegistry>, EndpointRandomizer)} */ @Deprecated DiscoveryClient(ApplicationInfoManager applicationInfoManager, EurekaClientConfig config, AbstractDiscoveryClientOptionalArgs args, Provider<BackupRegistry> backupRegistryProvider) { this(applicationInfoManager, config, args, backupRegistryProvider, ResolverUtils::randomize); } @Inject DiscoveryClient(ApplicationInfoManager applicationInfoManager, EurekaClientConfig config, AbstractDiscoveryClientOptionalArgs args, Provider<BackupRegistry> backupRegistryProvider, EndpointRandomizer endpointRandomizer) { if (args != null) { this.healthCheckHandlerProvider = args.healthCheckHandlerProvider; this.healthCheckCallbackProvider = args.healthCheckCallbackProvider; this.eventListeners.addAll(args.getEventListeners()); this.preRegistrationHandler = args.preRegistrationHandler; } else { this.healthCheckCallbackProvider = null; this.healthCheckHandlerProvider = null; this.preRegistrationHandler = null; } this.applicationInfoManager = applicationInfoManager; InstanceInfo myInfo = applicationInfoManager.getInfo(); clientConfig = config; staticClientConfig = clientConfig; transportConfig = config.getTransportConfig(); instanceInfo = myInfo; if (myInfo != null) { appPathIdentifier = instanceInfo.getAppName() + "/" + instanceInfo.getId(); } else { logger.warn("Setting instanceInfo to a passed in null value"); } this.backupRegistryProvider = backupRegistryProvider; this.endpointRandomizer = endpointRandomizer; this.urlRandomizer = new EndpointUtils.InstanceInfoBasedUrlRandomizer(instanceInfo); localRegionApps.set(new Applications()); fetchRegistryGeneration = new AtomicLong(0); remoteRegionsToFetch = new AtomicReference<String>(clientConfig.fetchRegistryForRemoteRegions()); remoteRegionsRef = new AtomicReference<>(remoteRegionsToFetch.get() == null ? null : remoteRegionsToFetch.get().split(",")); if (config.shouldFetchRegistry()) { this.registryStalenessMonitor = new ThresholdLevelsMetric(this, METRIC_REGISTRY_PREFIX + "lastUpdateSec_", new long[]{15L, 30L, 60L, 120L, 240L, 480L}); } else { this.registryStalenessMonitor = ThresholdLevelsMetric.NO_OP_METRIC; } if (config.shouldRegisterWithEureka()) { this.heartbeatStalenessMonitor = new ThresholdLevelsMetric(this, METRIC_REGISTRATION_PREFIX + "lastHeartbeatSec_", new long[]{15L, 30L, 60L, 120L, 240L, 480L}); } else { this.heartbeatStalenessMonitor = ThresholdLevelsMetric.NO_OP_METRIC; } logger.info("Initializing Eureka in region {}", clientConfig.getRegion()); if (!config.shouldRegisterWithEureka() && !config.shouldFetchRegistry()) { logger.info("Client configured to neither register nor query for data."); scheduler = null; heartbeatExecutor = null; cacheRefreshExecutor = null; eurekaTransport = null; instanceRegionChecker = new InstanceRegionChecker(new PropertyBasedAzToRegionMapper(config), clientConfig.getRegion()); // This is a bit of hack to allow for existing code using DiscoveryManager.getInstance() // to work with DI'd DiscoveryClient DiscoveryManager.getInstance().setDiscoveryClient(this); DiscoveryManager.getInstance().setEurekaClientConfig(config); initTimestampMs = System.currentTimeMillis(); initRegistrySize = this.getApplications().size(); registrySize = initRegistrySize; logger.info("Discovery Client initialized at timestamp {} with initial instances count: {}", initTimestampMs, initRegistrySize); return; // no need to setup up an network tasks and we are done } try { // default size of 2 - 1 each for heartbeat and cacheRefresh scheduler = Executors.newScheduledThreadPool(2, new ThreadFactoryBuilder() .setNameFormat("DiscoveryClient-%d") .setDaemon(true) .build()); heartbeatExecutor = new ThreadPoolExecutor( 1, clientConfig.getHeartbeatExecutorThreadPoolSize(), 0, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new ThreadFactoryBuilder() .setNameFormat("DiscoveryClient-HeartbeatExecutor-%d") .setDaemon(true) .build() ); // use direct handoff cacheRefreshExecutor = new ThreadPoolExecutor( 1, clientConfig.getCacheRefreshExecutorThreadPoolSize(), 0, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new ThreadFactoryBuilder() .setNameFormat("DiscoveryClient-CacheRefreshExecutor-%d") .setDaemon(true) .build() ); // use direct handoff eurekaTransport = new EurekaTransport(); scheduleServerEndpointTask(eurekaTransport, args); AzToRegionMapper azToRegionMapper; if (clientConfig.shouldUseDnsForFetchingServiceUrls()) { azToRegionMapper = new DNSBasedAzToRegionMapper(clientConfig); } else { azToRegionMapper = new PropertyBasedAzToRegionMapper(clientConfig); } if (null != remoteRegionsToFetch.get()) { azToRegionMapper.setRegionsToFetch(remoteRegionsToFetch.get().split(",")); } instanceRegionChecker = new InstanceRegionChecker(azToRegionMapper, clientConfig.getRegion()); } catch (Throwable e) { throw new RuntimeException("Failed to initialize DiscoveryClient!", e); } if (clientConfig.shouldFetchRegistry()) { try { boolean primaryFetchRegistryResult = fetchRegistry(false); if (!primaryFetchRegistryResult) { logger.info("Initial registry fetch from primary servers failed"); } boolean backupFetchRegistryResult = true; if (!primaryFetchRegistryResult && !fetchRegistryFromBackup()) { backupFetchRegistryResult = false; logger.info("Initial registry fetch from backup servers failed"); } if (!primaryFetchRegistryResult && !backupFetchRegistryResult && clientConfig.shouldEnforceFetchRegistryAtInit()) { throw new IllegalStateException("Fetch registry error at startup. Initial fetch failed."); } } catch (Throwable th) { logger.error("Fetch registry error at startup: {}", th.getMessage()); throw new IllegalStateException(th); } } // call and execute the pre registration handler before all background tasks (inc registration) is started if (this.preRegistrationHandler != null) { this.preRegistrationHandler.beforeRegistration(); } if (clientConfig.shouldRegisterWithEureka() && clientConfig.shouldEnforceRegistrationAtInit()) { try { if (!register() ) { throw new IllegalStateException("Registration error at startup. Invalid server response."); } } catch (Throwable th) { logger.error("Registration error at startup: {}", th.getMessage()); throw new IllegalStateException(th); } } // finally, init the schedule tasks (e.g. cluster resolvers, heartbeat, instanceInfo replicator, fetch initScheduledTasks(); try { Monitors.registerObject(this); } catch (Throwable e) { logger.warn("Cannot register timers", e); } // This is a bit of hack to allow for existing code using DiscoveryManager.getInstance() // to work with DI'd DiscoveryClient DiscoveryManager.getInstance().setDiscoveryClient(this); DiscoveryManager.getInstance().setEurekaClientConfig(config); initTimestampMs = System.currentTimeMillis(); initRegistrySize = this.getApplications().size(); registrySize = initRegistrySize; logger.info("Discovery Client initialized at timestamp {} with initial instances count: {}", initTimestampMs, initRegistrySize); } private void scheduleServerEndpointTask(EurekaTransport eurekaTransport, AbstractDiscoveryClientOptionalArgs args) { Collection<?> additionalFilters = args == null ? Collections.emptyList() : args.additionalFilters; EurekaJerseyClient providedJerseyClient = args == null ? null : args.eurekaJerseyClient; TransportClientFactories argsTransportClientFactories = null; if (args != null && args.getTransportClientFactories() != null) { argsTransportClientFactories = args.getTransportClientFactories(); } // Ignore the raw types warnings since the client filter interface changed between jersey 1/2 @SuppressWarnings("rawtypes") TransportClientFactories transportClientFactories = argsTransportClientFactories == null ? new Jersey1TransportClientFactories() : argsTransportClientFactories; Optional<SSLContext> sslContext = args == null ? Optional.empty() : args.getSSLContext(); Optional<HostnameVerifier> hostnameVerifier = args == null ? Optional.empty() : args.getHostnameVerifier(); // If the transport factory was not supplied with args, assume they are using jersey 1 for passivity eurekaTransport.transportClientFactory = providedJerseyClient == null ? transportClientFactories.newTransportClientFactory(clientConfig, additionalFilters, applicationInfoManager.getInfo(), sslContext, hostnameVerifier) : transportClientFactories.newTransportClientFactory(additionalFilters, providedJerseyClient); ApplicationsResolver.ApplicationsSource applicationsSource = new ApplicationsResolver.ApplicationsSource() { @Override public Applications getApplications(int stalenessThreshold, TimeUnit timeUnit) { long thresholdInMs = TimeUnit.MILLISECONDS.convert(stalenessThreshold, timeUnit); long delay = getLastSuccessfulRegistryFetchTimePeriod(); if (delay > thresholdInMs) { logger.info("Local registry is too stale for local lookup. Threshold:{}, actual:{}", thresholdInMs, delay); return null; } else { return localRegionApps.get(); } } }; eurekaTransport.bootstrapResolver = EurekaHttpClients.newBootstrapResolver( clientConfig, transportConfig, eurekaTransport.transportClientFactory, applicationInfoManager.getInfo(), applicationsSource, endpointRandomizer ); if (clientConfig.shouldRegisterWithEureka()) { EurekaHttpClientFactory newRegistrationClientFactory = null; EurekaHttpClient newRegistrationClient = null; try { newRegistrationClientFactory = EurekaHttpClients.registrationClientFactory( eurekaTransport.bootstrapResolver, eurekaTransport.transportClientFactory, transportConfig ); newRegistrationClient = newRegistrationClientFactory.newClient(); } catch (Exception e) { logger.warn("Transport initialization failure", e); } eurekaTransport.registrationClientFactory = newRegistrationClientFactory; eurekaTransport.registrationClient = newRegistrationClient; } // new method (resolve from primary servers for read) // Configure new transport layer (candidate for injecting in the future) if (clientConfig.shouldFetchRegistry()) { EurekaHttpClientFactory newQueryClientFactory = null; EurekaHttpClient newQueryClient = null; try { newQueryClientFactory = EurekaHttpClients.queryClientFactory( eurekaTransport.bootstrapResolver, eurekaTransport.transportClientFactory, clientConfig, transportConfig, applicationInfoManager.getInfo(), applicationsSource, endpointRandomizer ); newQueryClient = newQueryClientFactory.newClient(); } catch (Exception e) { logger.warn("Transport initialization failure", e); } eurekaTransport.queryClientFactory = newQueryClientFactory; eurekaTransport.queryClient = newQueryClient; } } @Override public EurekaClientConfig getEurekaClientConfig() { return clientConfig; } @Override public ApplicationInfoManager getApplicationInfoManager() { return applicationInfoManager; } /* * (non-Javadoc) * @see com.netflix.discovery.shared.LookupService#getApplication(java.lang.String) */ @Override public Application getApplication(String appName) { return getApplications().getRegisteredApplications(appName); } /* * (non-Javadoc) * * @see com.netflix.discovery.shared.LookupService#getApplications() */ @Override public Applications getApplications() { return localRegionApps.get(); } @Override public Applications getApplicationsForARegion(@Nullable String region) { if (instanceRegionChecker.isLocalRegion(region)) { return localRegionApps.get(); } else { return remoteRegionVsApps.get(region); } } public Set<String> getAllKnownRegions() { String localRegion = instanceRegionChecker.getLocalRegion(); if (!remoteRegionVsApps.isEmpty()) { Set<String> regions = remoteRegionVsApps.keySet(); Set<String> toReturn = new HashSet<>(regions); toReturn.add(localRegion); return toReturn; } else { return Collections.singleton(localRegion); } } /* * (non-Javadoc) * @see com.netflix.discovery.shared.LookupService#getInstancesById(java.lang.String) */ @Override public List<InstanceInfo> getInstancesById(String id) { List<InstanceInfo> instancesList = new ArrayList<>(); for (Application app : this.getApplications() .getRegisteredApplications()) { InstanceInfo instanceInfo = app.getByInstanceId(id); if (instanceInfo != null) { instancesList.add(instanceInfo); } } return instancesList; } /** * Register {@link HealthCheckCallback} with the eureka client. * * Once registered, the eureka client will invoke the * {@link HealthCheckCallback} in intervals specified by * {@link EurekaClientConfig#getInstanceInfoReplicationIntervalSeconds()}. * * @param callback app specific healthcheck. * * @deprecated Use */ @Deprecated @Override public void registerHealthCheckCallback(HealthCheckCallback callback) { if (instanceInfo == null) { logger.error("Cannot register a listener for instance info since it is null!"); } if (callback != null) { healthCheckHandlerRef.set(new HealthCheckCallbackToHandlerBridge(callback)); } } @Override public void registerHealthCheck(HealthCheckHandler healthCheckHandler) { if (instanceInfo == null) { logger.error("Cannot register a healthcheck handler when instance info is null!"); } if (healthCheckHandler != null) { this.healthCheckHandlerRef.set(healthCheckHandler); // schedule an onDemand update of the instanceInfo when a new healthcheck handler is registered if (instanceInfoReplicator != null) { instanceInfoReplicator.onDemandUpdate(); } } } @Override public void registerEventListener(EurekaEventListener eventListener) { this.eventListeners.add(eventListener); } @Override public boolean unregisterEventListener(EurekaEventListener eventListener) { return this.eventListeners.remove(eventListener); } /** * Gets the list of instances matching the given VIP Address. * * @param vipAddress * - The VIP address to match the instances for. * @param secure * - true if it is a secure vip address, false otherwise * @return - The list of {@link InstanceInfo} objects matching the criteria */ @Override public List<InstanceInfo> getInstancesByVipAddress(String vipAddress, boolean secure) { return getInstancesByVipAddress(vipAddress, secure, instanceRegionChecker.getLocalRegion()); } /** * Gets the list of instances matching the given VIP Address in the passed region. * * @param vipAddress - The VIP address to match the instances for. * @param secure - true if it is a secure vip address, false otherwise * @param region - region from which the instances are to be fetched. If <code>null</code> then local region is * assumed. * * @return - The list of {@link InstanceInfo} objects matching the criteria, empty list if not instances found. */ @Override public List<InstanceInfo> getInstancesByVipAddress(String vipAddress, boolean secure, @Nullable String region) { if (vipAddress == null) { throw new IllegalArgumentException( "Supplied VIP Address cannot be null"); } Applications applications; if (instanceRegionChecker.isLocalRegion(region)) { applications = this.localRegionApps.get(); } else { applications = remoteRegionVsApps.get(region); if (null == applications) { logger.debug("No applications are defined for region {}, so returning an empty instance list for vip " + "address {}.", region, vipAddress); return Collections.emptyList(); } } if (!secure) { return applications.getInstancesByVirtualHostName(vipAddress); } else { return applications.getInstancesBySecureVirtualHostName(vipAddress); } } /** * Gets the list of instances matching the given VIP Address and the given * application name if both of them are not null. If one of them is null, * then that criterion is completely ignored for matching instances. * * @param vipAddress * - The VIP address to match the instances for. * @param appName * - The applicationName to match the instances for. * @param secure * - true if it is a secure vip address, false otherwise. * @return - The list of {@link InstanceInfo} objects matching the criteria. */ @Override public List<InstanceInfo> getInstancesByVipAddressAndAppName( String vipAddress, String appName, boolean secure) { List<InstanceInfo> result = new ArrayList<>(); if (vipAddress == null && appName == null) { throw new IllegalArgumentException( "Supplied VIP Address and application name cannot both be null"); } else if (vipAddress != null && appName == null) { return getInstancesByVipAddress(vipAddress, secure); } else if (vipAddress == null && appName != null) { Application application = getApplication(appName); if (application != null) { result = application.getInstances(); } return result; } String instanceVipAddress; for (Application app : getApplications().getRegisteredApplications()) { for (InstanceInfo instance : app.getInstances()) { if (secure) { instanceVipAddress = instance.getSecureVipAddress(); } else { instanceVipAddress = instance.getVIPAddress(); } if (instanceVipAddress == null) { continue; } String[] instanceVipAddresses = instanceVipAddress .split(COMMA_STRING); // If the VIP Address is delimited by a comma, then consider to // be a list of VIP Addresses. // Try to match at least one in the list, if it matches then // return the instance info for the same for (String vipAddressFromList : instanceVipAddresses) { if (vipAddress.equalsIgnoreCase(vipAddressFromList.trim()) && appName.equalsIgnoreCase(instance.getAppName())) { result.add(instance); break; } } } } return result; } /* * (non-Javadoc) * * @see * com.netflix.discovery.shared.LookupService#getNextServerFromEureka(java * .lang.String, boolean) */ @Override public InstanceInfo getNextServerFromEureka(String virtualHostname, boolean secure) { List<InstanceInfo> instanceInfoList = this.getInstancesByVipAddress( virtualHostname, secure); if (instanceInfoList == null || instanceInfoList.isEmpty()) { throw new RuntimeException("No matches for the virtual host name :" + virtualHostname); } Applications apps = this.localRegionApps.get(); int index = (int) (apps.getNextIndex(virtualHostname, secure).incrementAndGet() % instanceInfoList.size()); return instanceInfoList.get(index); } /** * Get all applications registered with a specific eureka service. * * @param serviceUrl * - The string representation of the service url. * @return - The registry information containing all applications. */ @Override public Applications getApplications(String serviceUrl) { try { EurekaHttpResponse<Applications> response = clientConfig.getRegistryRefreshSingleVipAddress() == null ? eurekaTransport.queryClient.getApplications() : eurekaTransport.queryClient.getVip(clientConfig.getRegistryRefreshSingleVipAddress()); if (response.getStatusCode() == Status.OK.getStatusCode()) { logger.debug(PREFIX + "{} - refresh status: {}", appPathIdentifier, response.getStatusCode()); return response.getEntity(); } logger.info(PREFIX + "{} - was unable to refresh its cache! This periodic background refresh will be retried in {} seconds. status = {}", appPathIdentifier, clientConfig.getRegistryFetchIntervalSeconds(), response.getStatusCode()); } catch (Throwable th) { logger.info(PREFIX + "{} - was unable to refresh its cache! This periodic background refresh will be retried in {} seconds. status = {} stacktrace = {}", appPathIdentifier, clientConfig.getRegistryFetchIntervalSeconds(), th.getMessage(), ExceptionUtils.getStackTrace(th)); } return null; } /** * Register with the eureka service by making the appropriate REST call. */ boolean register() throws Throwable { logger.info(PREFIX + "{}: registering service...", appPathIdentifier); EurekaHttpResponse<Void> httpResponse; try { httpResponse = eurekaTransport.registrationClient.register(instanceInfo); } catch (Exception e) { logger.warn(PREFIX + "{} - registration failed {}", appPathIdentifier, e.getMessage(), e); throw e; } if (logger.isInfoEnabled()) { logger.info(PREFIX + "{} - registration status: {}", appPathIdentifier, httpResponse.getStatusCode()); } return httpResponse.getStatusCode() == Status.NO_CONTENT.getStatusCode(); } /** * Renew with the eureka service by making the appropriate REST call */ boolean renew() { EurekaHttpResponse<InstanceInfo> httpResponse; try { httpResponse = eurekaTransport.registrationClient.sendHeartBeat(instanceInfo.getAppName(), instanceInfo.getId(), instanceInfo, null); logger.debug(PREFIX + "{} - Heartbeat status: {}", appPathIdentifier, httpResponse.getStatusCode()); if (httpResponse.getStatusCode() == Status.NOT_FOUND.getStatusCode()) { REREGISTER_COUNTER.increment(); logger.info(PREFIX + "{} - Re-registering apps/{}", appPathIdentifier, instanceInfo.getAppName()); long timestamp = instanceInfo.setIsDirtyWithTime(); boolean success = register(); if (success) { instanceInfo.unsetIsDirty(timestamp); } return success; } return httpResponse.getStatusCode() == Status.OK.getStatusCode(); } catch (Throwable e) { logger.error(PREFIX + "{} - was unable to send heartbeat!", appPathIdentifier, e); return false; } } /** * @deprecated see replacement in {@link com.netflix.discovery.endpoint.EndpointUtils} * * Get the list of all eureka service urls from properties file for the eureka client to talk to. * * @param instanceZone The zone in which the client resides * @param preferSameZone true if we have to prefer the same zone as the client, false otherwise * @return The list of all eureka service urls for the eureka client to talk to */ @Deprecated @Override public List<String> getServiceUrlsFromConfig(String instanceZone, boolean preferSameZone) { return EndpointUtils.getServiceUrlsFromConfig(clientConfig, instanceZone, preferSameZone); } /** * Shuts down Eureka Client. Also sends a deregistration request to the * eureka server. */ @PreDestroy @Override public synchronized void shutdown() { if (isShutdown.compareAndSet(false, true)) { logger.info("Shutting down DiscoveryClient ..."); if (statusChangeListener != null && applicationInfoManager != null) { applicationInfoManager.unregisterStatusChangeListener(statusChangeListener.getId()); } cancelScheduledTasks(); // If APPINFO was registered if (applicationInfoManager != null && clientConfig.shouldRegisterWithEureka() && clientConfig.shouldUnregisterOnShutdown()) { applicationInfoManager.setInstanceStatus(InstanceStatus.DOWN); unregister(); } if (eurekaTransport != null) { eurekaTransport.shutdown(); } heartbeatStalenessMonitor.shutdown(); registryStalenessMonitor.shutdown(); Monitors.unregisterObject(this); logger.info("Completed shut down of DiscoveryClient"); } } /** * unregister w/ the eureka service. */ void unregister() { // It can be null if shouldRegisterWithEureka == false if(eurekaTransport != null && eurekaTransport.registrationClient != null) { try { logger.info("Unregistering ..."); EurekaHttpResponse<Void> httpResponse = eurekaTransport.registrationClient.cancel(instanceInfo.getAppName(), instanceInfo.getId()); logger.info(PREFIX + "{} - deregister status: {}", appPathIdentifier, httpResponse.getStatusCode()); } catch (Exception e) { logger.error(PREFIX + "{} - de-registration failed{}", appPathIdentifier, e.getMessage(), e); } } } /** * Fetches the registry information. * * <p> * This method tries to get only deltas after the first fetch unless there * is an issue in reconciling eureka server and client registry information. * </p> * * @param forceFullRegistryFetch Forces a full registry fetch. * * @return true if the registry was fetched */ private boolean fetchRegistry(boolean forceFullRegistryFetch) { Stopwatch tracer = FETCH_REGISTRY_TIMER.start(); try { // If the delta is disabled or if it is the first time, get all // applications Applications applications = getApplications(); if (clientConfig.shouldDisableDelta() || (!Strings.isNullOrEmpty(clientConfig.getRegistryRefreshSingleVipAddress())) || forceFullRegistryFetch || (applications == null) || (applications.getRegisteredApplications().size() == 0) || (applications.getVersion() == -1)) //Client application does not have latest library supporting delta { logger.info("Disable delta property : {}", clientConfig.shouldDisableDelta()); logger.info("Single vip registry refresh property : {}", clientConfig.getRegistryRefreshSingleVipAddress()); logger.info("Force full registry fetch : {}", forceFullRegistryFetch); logger.info("Application is null : {}", (applications == null)); logger.info("Registered Applications size is zero : {}", (applications.getRegisteredApplications().size() == 0)); logger.info("Application version is -1: {}", (applications.getVersion() == -1)); getAndStoreFullRegistry(); } else { getAndUpdateDelta(applications); } applications.setAppsHashCode(applications.getReconcileHashCode()); logTotalInstances(); } catch (Throwable e) { logger.info(PREFIX + "{} - was unable to refresh its cache! This periodic background refresh will be retried in {} seconds. status = {} stacktrace = {}", appPathIdentifier, clientConfig.getRegistryFetchIntervalSeconds(), e.getMessage(), ExceptionUtils.getStackTrace(e)); return false; } finally { if (tracer != null) { tracer.stop(); } } // Notify about cache refresh before updating the instance remote status onCacheRefreshed(); // Update remote status based on refreshed data held in the cache updateInstanceRemoteStatus(); // registry was fetched successfully, so return true return true; } private synchronized void updateInstanceRemoteStatus() { // Determine this instance's status for this app and set to UNKNOWN if not found InstanceInfo.InstanceStatus currentRemoteInstanceStatus = null; if (instanceInfo.getAppName() != null) { Application app = getApplication(instanceInfo.getAppName()); if (app != null) { InstanceInfo remoteInstanceInfo = app.getByInstanceId(instanceInfo.getId()); if (remoteInstanceInfo != null) { currentRemoteInstanceStatus = remoteInstanceInfo.getStatus(); } } } if (currentRemoteInstanceStatus == null) { currentRemoteInstanceStatus = InstanceInfo.InstanceStatus.UNKNOWN; } // Notify if status changed if (lastRemoteInstanceStatus != currentRemoteInstanceStatus) { onRemoteStatusChanged(lastRemoteInstanceStatus, currentRemoteInstanceStatus); lastRemoteInstanceStatus = currentRemoteInstanceStatus; } } /** * @return Return he current instance status as seen on the Eureka server. */ @Override public InstanceInfo.InstanceStatus getInstanceRemoteStatus() { return lastRemoteInstanceStatus; } private String getReconcileHashCode(Applications applications) { TreeMap<String, AtomicInteger> instanceCountMap = new TreeMap<String, AtomicInteger>(); if (isFetchingRemoteRegionRegistries()) { for (Applications remoteApp : remoteRegionVsApps.values()) { remoteApp.populateInstanceCountMap(instanceCountMap); } } applications.populateInstanceCountMap(instanceCountMap); return Applications.getReconcileHashCode(instanceCountMap); } /** * Gets the full registry information from the eureka server and stores it locally. * When applying the full registry, the following flow is observed: * * if (update generation have not advanced (due to another thread)) * atomically set the registry to the new registry * fi * * @return the full registry information. * @throws Throwable * on error. */ private void getAndStoreFullRegistry() throws Throwable { long currentUpdateGeneration = fetchRegistryGeneration.get(); logger.info("Getting all instance registry info from the eureka server"); Applications apps = null; EurekaHttpResponse<Applications> httpResponse = clientConfig.getRegistryRefreshSingleVipAddress() == null ? eurekaTransport.queryClient.getApplications(remoteRegionsRef.get()) : eurekaTransport.queryClient.getVip(clientConfig.getRegistryRefreshSingleVipAddress(), remoteRegionsRef.get()); if (httpResponse.getStatusCode() == Status.OK.getStatusCode()) { apps = httpResponse.getEntity(); } logger.info("The response status is {}", httpResponse.getStatusCode()); if (apps == null) { logger.error("The application is null for some reason. Not storing this information"); } else if (fetchRegistryGeneration.compareAndSet(currentUpdateGeneration, currentUpdateGeneration + 1)) { localRegionApps.set(this.filterAndShuffle(apps)); logger.debug("Got full registry with apps hashcode {}", apps.getAppsHashCode()); } else { logger.warn("Not updating applications as another thread is updating it already"); } } /** * Get the delta registry information from the eureka server and update it locally. * When applying the delta, the following flow is observed: * * if (update generation have not advanced (due to another thread)) * atomically try to: update application with the delta and get reconcileHashCode * abort entire processing otherwise * do reconciliation if reconcileHashCode clash * fi * * @return the client response * @throws Throwable on error */ private void getAndUpdateDelta(Applications applications) throws Throwable { long currentUpdateGeneration = fetchRegistryGeneration.get(); Applications delta = null; EurekaHttpResponse<Applications> httpResponse = eurekaTransport.queryClient.getDelta(remoteRegionsRef.get()); if (httpResponse.getStatusCode() == Status.OK.getStatusCode()) { delta = httpResponse.getEntity(); } if (delta == null) { logger.warn("The server does not allow the delta revision to be applied because it is not safe. " + "Hence got the full registry."); getAndStoreFullRegistry(); } else if (fetchRegistryGeneration.compareAndSet(currentUpdateGeneration, currentUpdateGeneration + 1)) { logger.debug("Got delta update with apps hashcode {}", delta.getAppsHashCode()); String reconcileHashCode = ""; if (fetchRegistryUpdateLock.tryLock()) { try { updateDelta(delta); reconcileHashCode = getReconcileHashCode(applications); } finally { fetchRegistryUpdateLock.unlock(); } } else { logger.warn("Cannot acquire update lock, aborting getAndUpdateDelta"); } // There is a diff in number of instances for some reason if (!reconcileHashCode.equals(delta.getAppsHashCode()) || clientConfig.shouldLogDeltaDiff()) { reconcileAndLogDifference(delta, reconcileHashCode); // this makes a remoteCall } } else { logger.warn("Not updating application delta as another thread is updating it already"); logger.debug("Ignoring delta update with apps hashcode {}, as another thread is updating it already", delta.getAppsHashCode()); } } /** * Logs the total number of non-filtered instances stored locally. */ private void logTotalInstances() { if (logger.isDebugEnabled()) { int totInstances = 0; for (Application application : getApplications().getRegisteredApplications()) { totInstances += application.getInstancesAsIsFromEureka().size(); } logger.debug("The total number of all instances in the client now is {}", totInstances); } } /** * Reconcile the eureka server and client registry information and logs the differences if any. * When reconciling, the following flow is observed: * * make a remote call to the server for the full registry * calculate and log differences * if (update generation have not advanced (due to another thread)) * atomically set the registry to the new registry * fi * * @param delta * the last delta registry information received from the eureka * server. * @param reconcileHashCode * the hashcode generated by the server for reconciliation. * @return ClientResponse the HTTP response object. * @throws Throwable * on any error. */ private void reconcileAndLogDifference(Applications delta, String reconcileHashCode) throws Throwable { logger.debug("The Reconcile hashcodes do not match, client : {}, server : {}. Getting the full registry", reconcileHashCode, delta.getAppsHashCode()); RECONCILE_HASH_CODES_MISMATCH.increment(); long currentUpdateGeneration = fetchRegistryGeneration.get(); EurekaHttpResponse<Applications> httpResponse = clientConfig.getRegistryRefreshSingleVipAddress() == null ? eurekaTransport.queryClient.getApplications(remoteRegionsRef.get()) : eurekaTransport.queryClient.getVip(clientConfig.getRegistryRefreshSingleVipAddress(), remoteRegionsRef.get()); Applications serverApps = httpResponse.getEntity(); if (serverApps == null) { logger.warn("Cannot fetch full registry from the server; reconciliation failure"); return; } if (fetchRegistryGeneration.compareAndSet(currentUpdateGeneration, currentUpdateGeneration + 1)) { localRegionApps.set(this.filterAndShuffle(serverApps)); getApplications().setVersion(delta.getVersion()); logger.debug( "The Reconcile hashcodes after complete sync up, client : {}, server : {}.", getApplications().getReconcileHashCode(), delta.getAppsHashCode()); } else { logger.warn("Not setting the applications map as another thread has advanced the update generation"); } } /** * Updates the delta information fetches from the eureka server into the * local cache. * * @param delta * the delta information received from eureka server in the last * poll cycle. */ private void updateDelta(Applications delta) { int deltaCount = 0; for (Application app : delta.getRegisteredApplications()) { for (InstanceInfo instance : app.getInstances()) { Applications applications = getApplications(); String instanceRegion = instanceRegionChecker.getInstanceRegion(instance); if (!instanceRegionChecker.isLocalRegion(instanceRegion)) { Applications remoteApps = remoteRegionVsApps.get(instanceRegion); if (null == remoteApps) { remoteApps = new Applications(); remoteRegionVsApps.put(instanceRegion, remoteApps); } applications = remoteApps; } ++deltaCount; if (ActionType.ADDED.equals(instance.getActionType())) { Application existingApp = applications.getRegisteredApplications(instance.getAppName()); if (existingApp == null) { applications.addApplication(app); } logger.debug("Added instance {} to the existing apps in region {}", instance.getId(), instanceRegion); applications.getRegisteredApplications(instance.getAppName()).addInstance(instance); } else if (ActionType.MODIFIED.equals(instance.getActionType())) { Application existingApp = applications.getRegisteredApplications(instance.getAppName()); if (existingApp == null) { applications.addApplication(app); } logger.debug("Modified instance {} to the existing apps ", instance.getId()); applications.getRegisteredApplications(instance.getAppName()).addInstance(instance); } else if (ActionType.DELETED.equals(instance.getActionType())) { Application existingApp = applications.getRegisteredApplications(instance.getAppName()); if (existingApp != null) { logger.debug("Deleted instance {} to the existing apps ", instance.getId()); existingApp.removeInstance(instance); /* * We find all instance list from application(The status of instance status is not only the status is UP but also other status) * if instance list is empty, we remove the application. */ if (existingApp.getInstancesAsIsFromEureka().isEmpty()) { applications.removeApplication(existingApp); } } } } } logger.debug("The total number of instances fetched by the delta processor : {}", deltaCount); getApplications().setVersion(delta.getVersion()); getApplications().shuffleInstances(clientConfig.shouldFilterOnlyUpInstances()); for (Applications applications : remoteRegionVsApps.values()) { applications.setVersion(delta.getVersion()); applications.shuffleInstances(clientConfig.shouldFilterOnlyUpInstances()); } } /** * Initializes all scheduled tasks. */ private void initScheduledTasks() { if (clientConfig.shouldFetchRegistry()) { // registry cache refresh timer int registryFetchIntervalSeconds = clientConfig.getRegistryFetchIntervalSeconds(); int expBackOffBound = clientConfig.getCacheRefreshExecutorExponentialBackOffBound(); cacheRefreshTask = new TimedSupervisorTask( "cacheRefresh", scheduler, cacheRefreshExecutor, registryFetchIntervalSeconds, TimeUnit.SECONDS, expBackOffBound, new CacheRefreshThread() ); scheduler.schedule( cacheRefreshTask, registryFetchIntervalSeconds, TimeUnit.SECONDS); } if (clientConfig.shouldRegisterWithEureka()) { int renewalIntervalInSecs = instanceInfo.getLeaseInfo().getRenewalIntervalInSecs(); int expBackOffBound = clientConfig.getHeartbeatExecutorExponentialBackOffBound(); logger.info("Starting heartbeat executor: " + "renew interval is: {}", renewalIntervalInSecs); // Heartbeat timer heartbeatTask = new TimedSupervisorTask( "heartbeat", scheduler, heartbeatExecutor, renewalIntervalInSecs, TimeUnit.SECONDS, expBackOffBound, new HeartbeatThread() ); scheduler.schedule( heartbeatTask, renewalIntervalInSecs, TimeUnit.SECONDS); // InstanceInfo replicator instanceInfoReplicator = new InstanceInfoReplicator( this, instanceInfo, clientConfig.getInstanceInfoReplicationIntervalSeconds(), 2); // burstSize statusChangeListener = new ApplicationInfoManager.StatusChangeListener() { @Override public String getId() { return "statusChangeListener"; } @Override public void notify(StatusChangeEvent statusChangeEvent) { logger.info("Saw local status change event {}", statusChangeEvent); instanceInfoReplicator.onDemandUpdate(); } }; if (clientConfig.shouldOnDemandUpdateStatusChange()) { applicationInfoManager.registerStatusChangeListener(statusChangeListener); } instanceInfoReplicator.start(clientConfig.getInitialInstanceInfoReplicationIntervalSeconds()); } else { logger.info("Not registering with Eureka server per configuration"); } } private void cancelScheduledTasks() { if (instanceInfoReplicator != null) { instanceInfoReplicator.stop(); } if (heartbeatExecutor != null) { heartbeatExecutor.shutdownNow(); } if (cacheRefreshExecutor != null) { cacheRefreshExecutor.shutdownNow(); } if (scheduler != null) { scheduler.shutdownNow(); } if (cacheRefreshTask != null) { cacheRefreshTask.cancel(); } if (heartbeatTask != null) { heartbeatTask.cancel(); } } /** * @deprecated see replacement in {@link com.netflix.discovery.endpoint.EndpointUtils} * * Get the list of all eureka service urls from DNS for the eureka client to * talk to. The client picks up the service url from its zone and then fails over to * other zones randomly. If there are multiple servers in the same zone, the client once * again picks one randomly. This way the traffic will be distributed in the case of failures. * * @param instanceZone The zone in which the client resides. * @param preferSameZone true if we have to prefer the same zone as the client, false otherwise. * @return The list of all eureka service urls for the eureka client to talk to. */ @Deprecated @Override public List<String> getServiceUrlsFromDNS(String instanceZone, boolean preferSameZone) { return EndpointUtils.getServiceUrlsFromDNS(clientConfig, instanceZone, preferSameZone, urlRandomizer); } /** * @deprecated see replacement in {@link com.netflix.discovery.endpoint.EndpointUtils} */ @Deprecated @Override public List<String> getDiscoveryServiceUrls(String zone) { return EndpointUtils.getDiscoveryServiceUrls(clientConfig, zone, urlRandomizer); } /** * @deprecated see replacement in {@link com.netflix.discovery.endpoint.EndpointUtils} * * Get the list of EC2 URLs given the zone name. * * @param dnsName The dns name of the zone-specific CNAME * @param type CNAME or EIP that needs to be retrieved * @return The list of EC2 URLs associated with the dns name */ @Deprecated public static Set<String> getEC2DiscoveryUrlsFromZone(String dnsName, EndpointUtils.DiscoveryUrlType type) { return EndpointUtils.getEC2DiscoveryUrlsFromZone(dnsName, type); } /** * Refresh the current local instanceInfo. Note that after a valid refresh where changes are observed, the * isDirty flag on the instanceInfo is set to true */ void refreshInstanceInfo() { applicationInfoManager.refreshDataCenterInfoIfRequired(); applicationInfoManager.refreshLeaseInfoIfRequired(); InstanceStatus status; try { status = getHealthCheckHandler().getStatus(instanceInfo.getStatus()); } catch (Exception e) { logger.warn("Exception from healthcheckHandler.getStatus, setting status to DOWN", e); status = InstanceStatus.DOWN; } if (null != status) { applicationInfoManager.setInstanceStatus(status); } } /** * The heartbeat task that renews the lease in the given intervals. */ private class HeartbeatThread implements Runnable { public void run() { if (renew()) { lastSuccessfulHeartbeatTimestamp = System.currentTimeMillis(); } } } @VisibleForTesting InstanceInfoReplicator getInstanceInfoReplicator() { return instanceInfoReplicator; } @VisibleForTesting InstanceInfo getInstanceInfo() { return instanceInfo; } @Override public HealthCheckHandler getHealthCheckHandler() { HealthCheckHandler healthCheckHandler = this.healthCheckHandlerRef.get(); if (healthCheckHandler == null) { if (null != healthCheckHandlerProvider) { healthCheckHandler = healthCheckHandlerProvider.get(); } else if (null != healthCheckCallbackProvider) { healthCheckHandler = new HealthCheckCallbackToHandlerBridge(healthCheckCallbackProvider.get()); } if (null == healthCheckHandler) { healthCheckHandler = new HealthCheckCallbackToHandlerBridge(null); } this.healthCheckHandlerRef.compareAndSet(null, healthCheckHandler); } return this.healthCheckHandlerRef.get(); } /** * The task that fetches the registry information at specified intervals. * */ class CacheRefreshThread implements Runnable { public void run() { refreshRegistry(); } } @VisibleForTesting void refreshRegistry() { try { boolean isFetchingRemoteRegionRegistries = isFetchingRemoteRegionRegistries(); boolean remoteRegionsModified = false; // This makes sure that a dynamic change to remote regions to fetch is honored. String latestRemoteRegions = clientConfig.fetchRegistryForRemoteRegions(); if (null != latestRemoteRegions) { String currentRemoteRegions = remoteRegionsToFetch.get(); if (!latestRemoteRegions.equals(currentRemoteRegions)) { // Both remoteRegionsToFetch and AzToRegionMapper.regionsToFetch need to be in sync synchronized (instanceRegionChecker.getAzToRegionMapper()) { if (remoteRegionsToFetch.compareAndSet(currentRemoteRegions, latestRemoteRegions)) { String[] remoteRegions = latestRemoteRegions.split(","); remoteRegionsRef.set(remoteRegions); instanceRegionChecker.getAzToRegionMapper().setRegionsToFetch(remoteRegions); remoteRegionsModified = true; } else { logger.info("Remote regions to fetch modified concurrently," + " ignoring change from {} to {}", currentRemoteRegions, latestRemoteRegions); } } } else { // Just refresh mapping to reflect any DNS/Property change instanceRegionChecker.getAzToRegionMapper().refreshMapping(); } } boolean success = fetchRegistry(remoteRegionsModified); if (success) { registrySize = localRegionApps.get().size(); lastSuccessfulRegistryFetchTimestamp = System.currentTimeMillis(); } if (logger.isDebugEnabled()) { StringBuilder allAppsHashCodes = new StringBuilder(); allAppsHashCodes.append("Local region apps hashcode: "); allAppsHashCodes.append(localRegionApps.get().getAppsHashCode()); allAppsHashCodes.append(", is fetching remote regions? "); allAppsHashCodes.append(isFetchingRemoteRegionRegistries); for (Map.Entry<String, Applications> entry : remoteRegionVsApps.entrySet()) { allAppsHashCodes.append(", Remote region: "); allAppsHashCodes.append(entry.getKey()); allAppsHashCodes.append(" , apps hashcode: "); allAppsHashCodes.append(entry.getValue().getAppsHashCode()); } logger.debug("Completed cache refresh task for discovery. All Apps hash code is {} ", allAppsHashCodes); } } catch (Throwable e) { logger.error("Cannot fetch registry from server", e); } } /** * Fetch the registry information from back up registry if all eureka server * urls are unreachable. * * @return true if the registry was fetched */ private boolean fetchRegistryFromBackup() { try { @SuppressWarnings("deprecation") BackupRegistry backupRegistryInstance = newBackupRegistryInstance(); if (null == backupRegistryInstance) { // backward compatibility with the old protected method, in case it is being used. backupRegistryInstance = backupRegistryProvider.get(); } if (null != backupRegistryInstance) { Applications apps = null; if (isFetchingRemoteRegionRegistries()) { String remoteRegionsStr = remoteRegionsToFetch.get(); if (null != remoteRegionsStr) { apps = backupRegistryInstance.fetchRegistry(remoteRegionsStr.split(",")); } } else { apps = backupRegistryInstance.fetchRegistry(); } if (apps != null) { final Applications applications = this.filterAndShuffle(apps); applications.setAppsHashCode(applications.getReconcileHashCode()); localRegionApps.set(applications); logTotalInstances(); logger.info("Fetched registry successfully from the backup"); return true; } } else { logger.warn("No backup registry instance defined & unable to find any discovery servers."); } } catch (Throwable e) { logger.warn("Cannot fetch applications from apps although backup registry was specified", e); } return false; } /** * @deprecated Use injection to provide {@link BackupRegistry} implementation. */ @Deprecated @Nullable protected BackupRegistry newBackupRegistryInstance() throws ClassNotFoundException, IllegalAccessException, InstantiationException { return null; } /** * Gets the <em>applications</em> after filtering the applications for * instances with only UP states and shuffling them. * * <p> * The filtering depends on the option specified by the configuration * {@link EurekaClientConfig#shouldFilterOnlyUpInstances()}. Shuffling helps * in randomizing the applications list there by avoiding the same instances * receiving traffic during start ups. * </p> * * @param apps * The applications that needs to be filtered and shuffled. * @return The applications after the filter and the shuffle. */ private Applications filterAndShuffle(Applications apps) { if (apps != null) { if (isFetchingRemoteRegionRegistries()) { Map<String, Applications> remoteRegionVsApps = new ConcurrentHashMap<String, Applications>(); apps.shuffleAndIndexInstances(remoteRegionVsApps, clientConfig, instanceRegionChecker); for (Applications applications : remoteRegionVsApps.values()) { applications.shuffleInstances(clientConfig.shouldFilterOnlyUpInstances()); } this.remoteRegionVsApps = remoteRegionVsApps; } else { apps.shuffleInstances(clientConfig.shouldFilterOnlyUpInstances()); } } return apps; } private boolean isFetchingRemoteRegionRegistries() { return null != remoteRegionsToFetch.get(); } /** * Invoked when the remote status of this client has changed. * Subclasses may override this method to implement custom behavior if needed. * * @param oldStatus the previous remote {@link InstanceStatus} * @param newStatus the new remote {@link InstanceStatus} */ protected void onRemoteStatusChanged(InstanceInfo.InstanceStatus oldStatus, InstanceInfo.InstanceStatus newStatus) { fireEvent(new StatusChangeEvent(oldStatus, newStatus)); } /** * Invoked every time the local registry cache is refreshed (whether changes have * been detected or not). * * Subclasses may override this method to implement custom behavior if needed. */ protected void onCacheRefreshed() { fireEvent(new CacheRefreshedEvent()); } /** * Send the given event on the EventBus if one is available * * @param event the event to send on the eventBus */ protected void fireEvent(final EurekaEvent event) { for (EurekaEventListener listener : eventListeners) { try { listener.onEvent(event); } catch (Exception e) { logger.info("Event {} throw an exception for listener {}", event, listener, e.getMessage()); } } } /** * @deprecated see {@link com.netflix.appinfo.InstanceInfo#getZone(String[], com.netflix.appinfo.InstanceInfo)} * * Get the zone that a particular instance is in. * * @param myInfo * - The InstanceInfo object of the instance. * @return - The zone in which the particular instance belongs to. */ @Deprecated public static String getZone(InstanceInfo myInfo) { String[] availZones = staticClientConfig.getAvailabilityZones(staticClientConfig.getRegion()); return InstanceInfo.getZone(availZones, myInfo); } /** * @deprecated see replacement in {@link com.netflix.discovery.endpoint.EndpointUtils} * * Get the region that this particular instance is in. * * @return - The region in which the particular instance belongs to. */ @Deprecated public static String getRegion() { String region = staticClientConfig.getRegion(); if (region == null) { region = "default"; } region = region.trim().toLowerCase(); return region; } /** * @deprecated use {@link #getServiceUrlsFromConfig(String, boolean)} instead. */ @Deprecated public static List<String> getEurekaServiceUrlsFromConfig(String instanceZone, boolean preferSameZone) { return EndpointUtils.getServiceUrlsFromConfig(staticClientConfig, instanceZone, preferSameZone); } public long getLastSuccessfulHeartbeatTimePeriod() { return lastSuccessfulHeartbeatTimestamp < 0 ? lastSuccessfulHeartbeatTimestamp : System.currentTimeMillis() - lastSuccessfulHeartbeatTimestamp; } public long getLastSuccessfulRegistryFetchTimePeriod() { return lastSuccessfulRegistryFetchTimestamp < 0 ? lastSuccessfulRegistryFetchTimestamp : System.currentTimeMillis() - lastSuccessfulRegistryFetchTimestamp; } @com.netflix.servo.annotations.Monitor(name = METRIC_REGISTRATION_PREFIX + "lastSuccessfulHeartbeatTimePeriod", description = "How much time has passed from last successful heartbeat", type = DataSourceType.GAUGE) private long getLastSuccessfulHeartbeatTimePeriodInternal() { final long delay = (!clientConfig.shouldRegisterWithEureka() || isShutdown.get()) ? 0 : getLastSuccessfulHeartbeatTimePeriod(); heartbeatStalenessMonitor.update(computeStalenessMonitorDelay(delay)); return delay; } // for metrics only @com.netflix.servo.annotations.Monitor(name = METRIC_REGISTRY_PREFIX + "lastSuccessfulRegistryFetchTimePeriod", description = "How much time has passed from last successful local registry update", type = DataSourceType.GAUGE) private long getLastSuccessfulRegistryFetchTimePeriodInternal() { final long delay = (!clientConfig.shouldFetchRegistry() || isShutdown.get()) ? 0 : getLastSuccessfulRegistryFetchTimePeriod(); registryStalenessMonitor.update(computeStalenessMonitorDelay(delay)); return delay; } @com.netflix.servo.annotations.Monitor(name = METRIC_REGISTRY_PREFIX + "localRegistrySize", description = "Count of instances in the local registry", type = DataSourceType.GAUGE) public int localRegistrySize() { return registrySize; } private long computeStalenessMonitorDelay(long delay) { if (delay < 0) { return System.currentTimeMillis() - initTimestampMs; } else { return delay; } } /** * Gets stats for the DiscoveryClient. * * @return The DiscoveryClientStats instance. */ public Stats getStats() { return stats; } /** * Stats is used to track useful attributes of the DiscoveryClient. It includes helpers that can aid * debugging and log analysis. */ public class Stats { private Stats() {} public int initLocalRegistrySize() { return initRegistrySize; } public long initTimestampMs() { return initTimestampMs; } public int localRegistrySize() { return registrySize; } public long lastSuccessfulRegistryFetchTimestampMs() { return lastSuccessfulRegistryFetchTimestamp; } public long lastSuccessfulHeartbeatTimestampMs() { return lastSuccessfulHeartbeatTimestamp; } /** * Used to determine if the Discovery client's first attempt to fetch from the service registry succeeded with * non-empty results. * * @return true if succeeded, failed otherwise */ public boolean initSucceeded() { return initLocalRegistrySize() > 0 && initTimestampMs() > 0; } } }
6,697
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/PropertyBasedAzToRegionMapper.java
package com.netflix.discovery; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * @author Nitesh Kant */ public class PropertyBasedAzToRegionMapper extends AbstractAzToRegionMapper { public PropertyBasedAzToRegionMapper(EurekaClientConfig clientConfig) { super(clientConfig); } @Override protected Set<String> getZonesForARegion(String region) { return new HashSet<String>(Arrays.asList(clientConfig.getAvailabilityZones(region))); } }
6,698
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/BackupRegistry.java
/* * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery; import com.google.inject.ImplementedBy; import com.netflix.discovery.shared.Applications; /** * A simple contract for <em>eureka</em> clients to fallback for getting * registry information in case eureka clients are unable to retrieve this * information from any of the <em>eureka</em> servers. * * <p> * This is normally not required, but for applications that cannot exist without * the registry information it can provide some additional reslience. * </p> * * @author Karthik Ranganathan * */ @ImplementedBy(NotImplementedRegistryImpl.class) public interface BackupRegistry { Applications fetchRegistry(); Applications fetchRegistry(String[] includeRemoteRegions); }
6,699