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/src/main/java/com/netflix/discovery/shared
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/resolver/AsyncResolver.java
package com.netflix.discovery.shared.resolver; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.netflix.discovery.TimedSupervisorTask; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.annotations.Monitor; import com.netflix.servo.monitor.Monitors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.Future; 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.AtomicReference; import static com.netflix.discovery.EurekaClientNames.METRIC_RESOLVER_PREFIX; /** * An async resolver that keeps a cached version of the endpoint list value for gets, and updates this cache * periodically in a different thread. * * @author David Liu */ public class AsyncResolver<T extends EurekaEndpoint> implements ClosableResolver<T> { private static final Logger logger = LoggerFactory.getLogger(AsyncResolver.class); // Note that warm up is best effort. If the resolver is accessed by multiple threads pre warmup, // only the first thread will block for the warmup (up to the configurable timeout). private final AtomicBoolean warmedUp = new AtomicBoolean(false); private final AtomicBoolean scheduled = new AtomicBoolean(false); private final String name; // a name for metric purposes private final ClusterResolver<T> delegate; private final ScheduledExecutorService executorService; private final ThreadPoolExecutor threadPoolExecutor; private final TimedSupervisorTask backgroundTask; private final AtomicReference<List<T>> resultsRef; private final int refreshIntervalMs; private final int warmUpTimeoutMs; // Metric timestamp, tracking last time when data were effectively changed. private volatile long lastLoadTimestamp = -1; /** * Create an async resolver with an empty initial value. When this resolver is called for the first time, * an initial warm up will be executed before scheduling the periodic update task. */ public AsyncResolver(String name, ClusterResolver<T> delegate, int executorThreadPoolSize, int refreshIntervalMs, int warmUpTimeoutMs) { this( name, delegate, Collections.<T>emptyList(), executorThreadPoolSize, refreshIntervalMs, warmUpTimeoutMs ); } /** * Create an async resolver with a preset initial value. WHen this resolver is called for the first time, * there will be no warm up and the initial value will be returned. The periodic update task will not be * scheduled until after the first time getClusterEndpoints call. */ public AsyncResolver(String name, ClusterResolver<T> delegate, List<T> initialValues, int executorThreadPoolSize, int refreshIntervalMs) { this( name, delegate, initialValues, executorThreadPoolSize, refreshIntervalMs, 0 ); warmedUp.set(true); } /** * @param delegate the delegate resolver to async resolve from * @param initialValue the initial value to use * @param executorThreadPoolSize the max number of threads for the threadpool * @param refreshIntervalMs the async refresh interval * @param warmUpTimeoutMs the time to wait for the initial warm up */ AsyncResolver(String name, ClusterResolver<T> delegate, List<T> initialValue, int executorThreadPoolSize, int refreshIntervalMs, int warmUpTimeoutMs) { this.name = name; this.delegate = delegate; this.refreshIntervalMs = refreshIntervalMs; this.warmUpTimeoutMs = warmUpTimeoutMs; this.executorService = Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder() .setNameFormat("AsyncResolver-" + name + "-%d") .setDaemon(true) .build()); this.threadPoolExecutor = new ThreadPoolExecutor( 1, executorThreadPoolSize, 0, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), // use direct handoff new ThreadFactoryBuilder() .setNameFormat("AsyncResolver-" + name + "-executor-%d") .setDaemon(true) .build() ); this.backgroundTask = new TimedSupervisorTask( this.getClass().getSimpleName(), executorService, threadPoolExecutor, refreshIntervalMs, TimeUnit.MILLISECONDS, 5, updateTask ); this.resultsRef = new AtomicReference<>(initialValue); Monitors.registerObject(name, this); } @Override public void shutdown() { if(Monitors.isObjectRegistered(name, this)) { Monitors.unregisterObject(name, this); } executorService.shutdownNow(); threadPoolExecutor.shutdownNow(); backgroundTask.cancel(); } @Override public String getRegion() { return delegate.getRegion(); } @Override public List<T> getClusterEndpoints() { long delay = refreshIntervalMs; if (warmedUp.compareAndSet(false, true)) { if (!doWarmUp()) { delay = 0; } } if (scheduled.compareAndSet(false, true)) { scheduleTask(delay); } return resultsRef.get(); } /* visible for testing */ boolean doWarmUp() { Future future = null; try { future = threadPoolExecutor.submit(updateTask); future.get(warmUpTimeoutMs, TimeUnit.MILLISECONDS); // block until done or timeout return true; } catch (Exception e) { logger.warn("Best effort warm up failed", e); } finally { if (future != null) { future.cancel(true); } } return false; } /* visible for testing */ void scheduleTask(long delay) { executorService.schedule( backgroundTask, delay, TimeUnit.MILLISECONDS); } @Monitor(name = METRIC_RESOLVER_PREFIX + "lastLoadTimestamp", description = "How much time has passed from last successful async load", type = DataSourceType.GAUGE) public long getLastLoadTimestamp() { return lastLoadTimestamp < 0 ? 0 : System.currentTimeMillis() - lastLoadTimestamp; } @Monitor(name = METRIC_RESOLVER_PREFIX + "endpointsSize", description = "How many records are the in the endpoints ref", type = DataSourceType.GAUGE) public long getEndpointsSize() { return resultsRef.get().size(); // return directly from the ref and not the method so as to not trigger warming } private final Runnable updateTask = new Runnable() { @Override public void run() { try { List<T> newList = delegate.getClusterEndpoints(); if (newList != null) { resultsRef.getAndSet(newList); lastLoadTimestamp = System.currentTimeMillis(); } else { logger.warn("Delegate returned null list of cluster endpoints"); } logger.debug("Resolved to {}", newList); } catch (Exception e) { logger.warn("Failed to retrieve cluster endpoints from the delegate", e); } } }; }
6,800
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/resolver/LegacyClusterResolver.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.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.endpoint.EndpointUtils; import com.netflix.discovery.shared.resolver.aws.AwsEndpoint; import com.netflix.discovery.shared.resolver.aws.DnsTxtRecordClusterResolver; import com.netflix.discovery.shared.resolver.aws.ZoneAffinityClusterResolver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @deprecated as of 2016-02-11. Will be deleted in an upcoming release. * See {@link com.netflix.discovery.shared.resolver.aws.ConfigClusterResolver} for replacement. * * Server resolver that mimics the behavior of the original implementation. Either DNS or server * list resolvers are instantiated, and they can be swapped in runtime because of the dynamic configuration * change. * <h3>Failures</h3> * If there is configuration change (from DNS to server list or reverse), and the new resolver cannot be instantiated, * it will be retried with exponential back-off (see {@link ReloadingClusterResolver}). * * @author Tomasz Bak */ @Deprecated public class LegacyClusterResolver implements ClusterResolver<AwsEndpoint> { private static final Logger logger = LoggerFactory.getLogger(LegacyClusterResolver.class); private final ClusterResolver<AwsEndpoint> delegate; public LegacyClusterResolver(EurekaClientConfig clientConfig, String myZone, EndpointRandomizer randomizer) { this.delegate = new ReloadingClusterResolver<>( new LegacyClusterResolverFactory(clientConfig, myZone, randomizer), clientConfig.getEurekaServiceUrlPollIntervalSeconds() * 1000 ); } @Override public String getRegion() { return delegate.getRegion(); } @Override public List<AwsEndpoint> getClusterEndpoints() { return delegate.getClusterEndpoints(); } static class LegacyClusterResolverFactory implements ClusterResolverFactory<AwsEndpoint> { private final EurekaClientConfig clientConfig; private final String myRegion; private final String myZone; private final EndpointRandomizer randomizer; LegacyClusterResolverFactory(EurekaClientConfig clientConfig, String myZone, EndpointRandomizer randomizer) { this.clientConfig = clientConfig; this.myRegion = clientConfig.getRegion(); this.myZone = myZone; this.randomizer = randomizer; } @Override public ClusterResolver<AwsEndpoint> createClusterResolver() { ClusterResolver<AwsEndpoint> newResolver; if (clientConfig.shouldUseDnsForFetchingServiceUrls()) { String discoveryDnsName = "txt." + myRegion + '.' + clientConfig.getEurekaServerDNSName(); newResolver = new DnsTxtRecordClusterResolver( myRegion, discoveryDnsName, true, Integer.parseInt(clientConfig.getEurekaServerPort()), false, clientConfig.getEurekaServerURLContext() ); newResolver = new ZoneAffinityClusterResolver(newResolver, myZone, clientConfig.shouldPreferSameZoneEureka(), randomizer); } else { // FIXME Not randomized in the EndpointUtils.getServiceUrlsFromConfig, and no zone info to do this here newResolver = new StaticClusterResolver<>(myRegion, createEurekaEndpointsFromConfig()); } return newResolver; } private List<AwsEndpoint> createEurekaEndpointsFromConfig() { List<String> serviceUrls = EndpointUtils.getServiceUrlsFromConfig(clientConfig, myZone, clientConfig.shouldPreferSameZoneEureka()); List<AwsEndpoint> endpoints = new ArrayList<>(serviceUrls.size()); for (String serviceUrl : serviceUrls) { try { URI serviceURI = new URI(serviceUrl); endpoints.add(new AwsEndpoint( serviceURI.getHost(), serviceURI.getPort(), "https".equalsIgnoreCase(serviceURI.getSchemeSpecificPart()), serviceURI.getPath(), myRegion, myZone )); } catch (URISyntaxException ignore) { logger.warn("Invalid eureka server URI: {}; removing from the server pool", serviceUrl); } } return endpoints; } } }
6,801
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/resolver/ClusterResolverFactory.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; /** * @author Tomasz Bak */ public interface ClusterResolverFactory<T extends EurekaEndpoint> { ClusterResolver<T> createClusterResolver(); }
6,802
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/resolver/EndpointRandomizer.java
package com.netflix.discovery.shared.resolver; import java.util.List; public interface EndpointRandomizer { <T extends EurekaEndpoint> List<T> randomize(List<T> list); }
6,803
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/resolver/ClosableResolver.java
package com.netflix.discovery.shared.resolver; /** * @author David Liu */ public interface ClosableResolver<T extends EurekaEndpoint> extends ClusterResolver<T> { void shutdown(); }
6,804
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/resolver/ClusterResolverException.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; /** * @author Tomasz Bak */ public class ClusterResolverException extends RuntimeException { private static final long serialVersionUID = -3027237921418208925L; public ClusterResolverException(String message) { super(message); } public ClusterResolverException(String message, Throwable cause) { super(message, cause); } }
6,805
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/resolver
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/resolver/aws/ApplicationsResolver.java
package com.netflix.discovery.shared.resolver.aws; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.shared.resolver.ClusterResolver; import com.netflix.discovery.shared.resolver.ResolverUtils; import com.netflix.discovery.shared.transport.EurekaTransportConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; /** * @author David Liu */ public class ApplicationsResolver implements ClusterResolver<AwsEndpoint> { private static final Logger logger = LoggerFactory.getLogger(ApplicationsResolver.class); private final EurekaClientConfig clientConfig; private final EurekaTransportConfig transportConfig; private final ApplicationsSource applicationsSource; private final String vipAddress; @Deprecated public ApplicationsResolver(EurekaClientConfig clientConfig, EurekaTransportConfig transportConfig, ApplicationsSource applicationsSource) { this(clientConfig, transportConfig, applicationsSource, transportConfig.getReadClusterVip()); } public ApplicationsResolver(EurekaClientConfig clientConfig, EurekaTransportConfig transportConfig, ApplicationsSource applicationsSource, String vipAddress) { this.clientConfig = clientConfig; this.transportConfig = transportConfig; this.applicationsSource = applicationsSource; this.vipAddress = vipAddress; } @Override public String getRegion() { return null; } @Override public List<AwsEndpoint> getClusterEndpoints() { List<AwsEndpoint> result = new ArrayList<>(); Applications applications = applicationsSource.getApplications( transportConfig.getApplicationsResolverDataStalenessThresholdSeconds(), TimeUnit.SECONDS); if (applications != null && vipAddress != null) { List<InstanceInfo> validInstanceInfos = applications.getInstancesByVirtualHostName(vipAddress); for (InstanceInfo instanceInfo : validInstanceInfos) { if (instanceInfo.getStatus() == InstanceInfo.InstanceStatus.UP) { AwsEndpoint endpoint = ResolverUtils.instanceInfoToEndpoint(clientConfig, transportConfig, instanceInfo); if (endpoint != null) { result.add(endpoint); } } } } logger.debug("Retrieved endpoint list {}", result); return result; } public interface ApplicationsSource { /** * @return the known set of Applications, or null if the data is beyond the stalenss threshold */ Applications getApplications(int stalenessThreshold, TimeUnit timeUnit); } }
6,806
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/resolver
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/resolver/aws/ConfigClusterResolver.java
package com.netflix.discovery.shared.resolver.aws; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.endpoint.EndpointUtils; import com.netflix.discovery.shared.resolver.ClusterResolver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * A resolver that on-demand resolves from configuration what the endpoints should be. * * @author David Liu */ public class ConfigClusterResolver implements ClusterResolver<AwsEndpoint> { private static final Logger logger = LoggerFactory.getLogger(ConfigClusterResolver.class); private final EurekaClientConfig clientConfig; private final InstanceInfo myInstanceInfo; public ConfigClusterResolver(EurekaClientConfig clientConfig, InstanceInfo myInstanceInfo) { this.clientConfig = clientConfig; this.myInstanceInfo = myInstanceInfo; } @Override public String getRegion() { return clientConfig.getRegion(); } @Override public List<AwsEndpoint> getClusterEndpoints() { if (clientConfig.shouldUseDnsForFetchingServiceUrls()) { if (logger.isInfoEnabled()) { logger.info("Resolving eureka endpoints via DNS: {}", getDNSName()); } return getClusterEndpointsFromDns(); } else { logger.info("Resolving eureka endpoints via configuration"); return getClusterEndpointsFromConfig(); } } private List<AwsEndpoint> getClusterEndpointsFromDns() { String discoveryDnsName = getDNSName(); int port = Integer.parseInt(clientConfig.getEurekaServerPort()); // cheap enough so just re-use DnsTxtRecordClusterResolver dnsResolver = new DnsTxtRecordClusterResolver( getRegion(), discoveryDnsName, true, port, false, clientConfig.getEurekaServerURLContext() ); List<AwsEndpoint> endpoints = dnsResolver.getClusterEndpoints(); if (endpoints.isEmpty()) { logger.error("Cannot resolve to any endpoints for the given dnsName: {}", discoveryDnsName); } return endpoints; } private List<AwsEndpoint> getClusterEndpointsFromConfig() { String[] availZones = clientConfig.getAvailabilityZones(clientConfig.getRegion()); String myZone = InstanceInfo.getZone(availZones, myInstanceInfo); Map<String, List<String>> serviceUrls = EndpointUtils .getServiceUrlsMapFromConfig(clientConfig, myZone, clientConfig.shouldPreferSameZoneEureka()); List<AwsEndpoint> endpoints = new ArrayList<>(); for (String zone : serviceUrls.keySet()) { for (String url : serviceUrls.get(zone)) { try { endpoints.add(new AwsEndpoint(url, getRegion(), zone)); } catch (Exception ignore) { logger.warn("Invalid eureka server URI: {}; removing from the server pool", url); } } } logger.debug("Config resolved to {}", endpoints); if (endpoints.isEmpty()) { logger.error("Cannot resolve to any endpoints from provided configuration: {}", serviceUrls); } return endpoints; } private String getDNSName() { return "txt." + getRegion() + '.' + clientConfig.getEurekaServerDNSName(); } }
6,807
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/resolver
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/resolver/aws/AwsEndpoint.java
package com.netflix.discovery.shared.resolver.aws; import com.netflix.discovery.shared.resolver.DefaultEndpoint; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @author David Liu */ public class AwsEndpoint extends DefaultEndpoint { protected final String zone; protected final String region; public AwsEndpoint(String serviceURI, String region, String zone) { super(serviceURI); this.region = region; this.zone = zone; } public AwsEndpoint(String hostName, int port, boolean isSecure, String relativeUri, String region, String zone) { super(hostName, port, isSecure, relativeUri); this.region=region; this.zone=zone; } public String getRegion(){ return region; } public String getZone(){ return zone; } public static List<AwsEndpoint> createForServerList( List<String> hostNames, int port, boolean isSecure, String relativeUri, String region,String zone) { if (hostNames.isEmpty()) { return Collections.emptyList(); } List<AwsEndpoint> awsEndpoints = new ArrayList<>(hostNames.size()); for (String hostName : hostNames) { awsEndpoints.add(new AwsEndpoint(hostName, port, isSecure, relativeUri, region, zone)); } return awsEndpoints; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof AwsEndpoint)) return false; if (!super.equals(o)) return false; AwsEndpoint that = (AwsEndpoint) o; if (region != null ? !region.equals(that.region) : that.region != null) return false; if (zone != null ? !zone.equals(that.zone) : that.zone != null) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (zone != null ? zone.hashCode() : 0); result = 31 * result + (region != null ? region.hashCode() : 0); return result; } @Override public String toString(){ return"AwsEndpoint{ serviceUrl='"+serviceUrl+'\'' +", region='"+region+'\'' +", zone='"+zone+'\''+'}'; } }
6,808
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/resolver
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/resolver/aws/ZoneAffinityClusterResolver.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.Collections; import java.util.List; import com.netflix.discovery.shared.resolver.ClusterResolver; import com.netflix.discovery.shared.resolver.EndpointRandomizer; import com.netflix.discovery.shared.resolver.ResolverUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * It is a cluster resolver that reorders the server list, such that the first server on the list * is in the same zone as the client. The server is chosen randomly from the available pool of server in * that zone. The remaining servers are appended in a random order, local zone first, followed by servers from other zones. * * @author Tomasz Bak */ public class ZoneAffinityClusterResolver implements ClusterResolver<AwsEndpoint> { private static final Logger logger = LoggerFactory.getLogger(ZoneAffinityClusterResolver.class); private final ClusterResolver<AwsEndpoint> delegate; private final String myZone; private final boolean zoneAffinity; private final EndpointRandomizer randomizer; /** * A zoneAffinity defines zone affinity (true) or anti-affinity rules (false). */ public ZoneAffinityClusterResolver( ClusterResolver<AwsEndpoint> delegate, String myZone, boolean zoneAffinity, EndpointRandomizer randomizer ) { this.delegate = delegate; this.myZone = myZone; this.zoneAffinity = zoneAffinity; this.randomizer = randomizer; } @Override public String getRegion() { return delegate.getRegion(); } @Override public List<AwsEndpoint> getClusterEndpoints() { List<AwsEndpoint>[] parts = ResolverUtils.splitByZone(delegate.getClusterEndpoints(), myZone); List<AwsEndpoint> myZoneEndpoints = parts[0]; List<AwsEndpoint> remainingEndpoints = parts[1]; List<AwsEndpoint> randomizedList = randomizeAndMerge(myZoneEndpoints, remainingEndpoints); if (!zoneAffinity) { Collections.reverse(randomizedList); } logger.debug("Local zone={}; resolved to: {}", myZone, randomizedList); return randomizedList; } private List<AwsEndpoint> randomizeAndMerge(List<AwsEndpoint> myZoneEndpoints, List<AwsEndpoint> remainingEndpoints) { if (myZoneEndpoints.isEmpty()) { return randomizer.randomize(remainingEndpoints); } if (remainingEndpoints.isEmpty()) { return randomizer.randomize(myZoneEndpoints); } List<AwsEndpoint> mergedList = randomizer.randomize(myZoneEndpoints); mergedList.addAll(randomizer.randomize(remainingEndpoints)); return mergedList; } }
6,809
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/resolver
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/resolver/aws/DnsTxtRecordClusterResolver.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 javax.naming.NamingException; import java.util.ArrayList; import java.util.List; import java.util.Set; import com.netflix.discovery.endpoint.DnsResolver; import com.netflix.discovery.shared.resolver.ClusterResolver; import com.netflix.discovery.shared.resolver.ClusterResolverException; import com.netflix.discovery.shared.resolver.ResolverUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A cluster resolver implementation that assumes that Eureka cluster configuration is provided in two level, * cascading DNS TXT records. The first level shall point to zone level DNS entries, while at the zone level * server pools shall be provided (either CNAMEs or A records). * If no TXT record is found at the provided address, the resolver will add 'txt.' suffix to the address, and try * to resolve that address. * * * <h3>Example</h3> * Lets assume we have a service with root domain myservice.net, and a deployment in AWS us-east-1 on all three zones. * The root discovery domain would be:<br/> * <table border='1'> * <thead> * <th>DNS record</th> * <th>TXT record content</th> * </thead> * <tbody> * <tr><td>txt.myservice.net</td> * <td> * txt.us-east-1a.myservice.net * txt.us-east-1b.myservice.net * txt.us-east-1c.myservice.net * </td> * </tr> * <tr><td>txt.us-east-1a.myservice.net</td> * <td> * ec2-1-2-3-4.compute-1.amazonaws.com * ec2-1-2-3-5.compute-1.amazonaws.com * </td> * </tr> * <tr><td>txt.us-east-1b.myservice.net</td> * <td> * ec2-1-2-3-6.compute-1.amazonaws.com * ec2-1-2-3-7.compute-1.amazonaws.com * </td> * </tr> * <tr><td>txt.us-east-1c.myservice.net</td> * <td> * ec2-1-2-3-8.compute-1.amazonaws.com * ec2-1-2-3-9.compute-1.amazonaws.com * </td> * </tr> * </tbody> * </table> * * @author Tomasz Bak */ public class DnsTxtRecordClusterResolver implements ClusterResolver<AwsEndpoint> { private static final Logger logger = LoggerFactory.getLogger(DnsTxtRecordClusterResolver.class); private final String region; private final String rootClusterDNS; private final boolean extractZoneFromDNS; private final int port; private final boolean isSecure; private final String relativeUri; /** * @param rootClusterDNS top level domain name, in the two level hierarchy (see {@link DnsTxtRecordClusterResolver} documentation). * @param extractZoneFromDNS if set to true, zone information will be extract from zone DNS name. It assumed that the zone * name is the name part immediately followint 'txt.' suffix. * @param port Eureka sever port number * @param relativeUri service relative URI that will be appended to server address */ public DnsTxtRecordClusterResolver(String region, String rootClusterDNS, boolean extractZoneFromDNS, int port, boolean isSecure, String relativeUri) { this.region = region; this.rootClusterDNS = rootClusterDNS; this.extractZoneFromDNS = extractZoneFromDNS; this.port = port; this.isSecure = isSecure; this.relativeUri = relativeUri; } @Override public String getRegion() { return region; } @Override public List<AwsEndpoint> getClusterEndpoints() { List<AwsEndpoint> eurekaEndpoints = resolve(region, rootClusterDNS, extractZoneFromDNS, port, isSecure, relativeUri); logger.debug("Resolved {} to {}", rootClusterDNS, eurekaEndpoints); return eurekaEndpoints; } private static List<AwsEndpoint> resolve(String region, String rootClusterDNS, boolean extractZone, int port, boolean isSecure, String relativeUri) { try { Set<String> zoneDomainNames = resolve(rootClusterDNS); if (zoneDomainNames.isEmpty()) { throw new ClusterResolverException("Cannot resolve Eureka cluster addresses; there are no data in TXT record for DN " + rootClusterDNS); } List<AwsEndpoint> endpoints = new ArrayList<>(); for (String zoneDomain : zoneDomainNames) { String zone = extractZone ? ResolverUtils.extractZoneFromHostName(zoneDomain) : null; Set<String> zoneAddresses = resolve(zoneDomain); for (String address : zoneAddresses) { endpoints.add(new AwsEndpoint(address, port, isSecure, relativeUri, region, zone)); } } return endpoints; } catch (NamingException e) { throw new ClusterResolverException("Cannot resolve Eureka cluster addresses for root: " + rootClusterDNS, e); } } private static Set<String> resolve(String rootClusterDNS) throws NamingException { Set<String> result; try { result = DnsResolver.getCNamesFromTxtRecord(rootClusterDNS); if (!rootClusterDNS.startsWith("txt.")) { result = DnsResolver.getCNamesFromTxtRecord("txt." + rootClusterDNS); } } catch (NamingException e) { if (!rootClusterDNS.startsWith("txt.")) { result = DnsResolver.getCNamesFromTxtRecord("txt." + rootClusterDNS); } else { throw e; } } return result; } }
6,810
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/resolver
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/resolver/aws/EurekaHttpResolver.java
package com.netflix.discovery.shared.resolver.aws; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.EurekaClientNames; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.shared.resolver.ClusterResolver; import com.netflix.discovery.shared.resolver.EurekaEndpoint; import com.netflix.discovery.shared.resolver.ResolverUtils; 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.shared.transport.TransportClientFactory; import com.netflix.discovery.shared.transport.decorator.RetryableEurekaHttpClient; import com.netflix.discovery.shared.transport.decorator.ServerStatusEvaluators; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @author David Liu */ public class EurekaHttpResolver implements ClusterResolver<AwsEndpoint> { private static final Logger logger = LoggerFactory.getLogger(EurekaHttpResolver.class); private final EurekaClientConfig clientConfig; private final EurekaTransportConfig transportConfig; private final String vipAddress; private final EurekaHttpClientFactory clientFactory; public EurekaHttpResolver(EurekaClientConfig clientConfig, EurekaTransportConfig transportConfig, ClusterResolver<EurekaEndpoint> bootstrapResolver, TransportClientFactory transportClientFactory, String vipAddress) { this( clientConfig, transportConfig, RetryableEurekaHttpClient.createFactory( EurekaClientNames.RESOLVER, transportConfig, bootstrapResolver, transportClientFactory, ServerStatusEvaluators.httpSuccessEvaluator() ), vipAddress ); } /* visible for testing */ EurekaHttpResolver(EurekaClientConfig clientConfig, EurekaTransportConfig transportConfig, EurekaHttpClientFactory clientFactory, String vipAddress) { this.clientConfig = clientConfig; this.transportConfig = transportConfig; this.clientFactory = clientFactory; this.vipAddress = vipAddress; } @Override public String getRegion() { return clientConfig.getRegion(); } @Override public List<AwsEndpoint> getClusterEndpoints() { List<AwsEndpoint> result = new ArrayList<>(); EurekaHttpClient client = null; try { client = clientFactory.newClient(); EurekaHttpResponse<Applications> response = client.getVip(vipAddress); if (validResponse(response)) { Applications applications = response.getEntity(); if (applications != null) { applications.shuffleInstances(true); // filter out non-UP instances List<InstanceInfo> validInstanceInfos = applications.getInstancesByVirtualHostName(vipAddress); for (InstanceInfo instanceInfo : validInstanceInfos) { AwsEndpoint endpoint = ResolverUtils.instanceInfoToEndpoint(clientConfig, transportConfig, instanceInfo); if (endpoint != null) { result.add(endpoint); } } logger.debug("Retrieved endpoint list {}", result); return result; } } } catch (Exception e) { logger.error("Error contacting server for endpoints with vipAddress:{}", vipAddress, e); } finally { if (client != null) { client.shutdown(); } } logger.info("Returning empty endpoint list"); return Collections.emptyList(); } private <T> boolean validResponse(EurekaHttpResponse<T> response) { if (response == null) { return false; } int responseCode = response.getStatusCode(); return responseCode >= 200 && responseCode < 300; } }
6,811
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/endpoint/DnsResolver.java
package com.netflix.discovery.endpoint; import javax.annotation.Nullable; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import java.util.ArrayList; import java.util.Collections; import java.util.Hashtable; import java.util.List; import java.util.Set; import java.util.TreeSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Tomasz Bak */ public final class DnsResolver { private static final Logger logger = LoggerFactory.getLogger(DnsResolver.class); private static final String DNS_PROVIDER_URL = "dns:"; private static final String DNS_NAMING_FACTORY = "com.sun.jndi.dns.DnsContextFactory"; private static final String JAVA_NAMING_FACTORY_INITIAL = "java.naming.factory.initial"; private static final String JAVA_NAMING_PROVIDER_URL = "java.naming.provider.url"; private static final String A_RECORD_TYPE = "A"; private static final String CNAME_RECORD_TYPE = "CNAME"; private static final String TXT_RECORD_TYPE = "TXT"; private DnsResolver() { } /** * Load up the DNS JNDI context provider. */ public static DirContext getDirContext() { Hashtable<String, String> env = new Hashtable<String, String>(); env.put(JAVA_NAMING_FACTORY_INITIAL, DNS_NAMING_FACTORY); env.put(JAVA_NAMING_PROVIDER_URL, DNS_PROVIDER_URL); try { return new InitialDirContext(env); } catch (Throwable e) { throw new RuntimeException("Cannot get dir context for some reason", e); } } /** * Resolve host name to the bottom A-Record or the latest available CNAME * * @return resolved host name */ public static String resolve(String originalHost) { String currentHost = originalHost; if (isLocalOrIp(currentHost)) { return originalHost; } try { String targetHost = null; do { Attributes attrs = getDirContext().getAttributes(currentHost, new String[]{A_RECORD_TYPE, CNAME_RECORD_TYPE}); Attribute attr = attrs.get(A_RECORD_TYPE); if (attr != null) { targetHost = attr.get().toString(); } attr = attrs.get(CNAME_RECORD_TYPE); if (attr != null) { currentHost = attr.get().toString(); } else { targetHost = currentHost; } } while (targetHost == null); return targetHost; } catch (NamingException e) { logger.warn("Cannot resolve eureka server address {}; returning original value {}", currentHost, originalHost, e); return originalHost; } } /** * Look into A-record at a specific DNS address. * * @return resolved IP addresses or null if no A-record was present */ @Nullable public static List<String> resolveARecord(String rootDomainName) { if (isLocalOrIp(rootDomainName)) { return null; } try { Attributes attrs = getDirContext().getAttributes(rootDomainName, new String[]{A_RECORD_TYPE, CNAME_RECORD_TYPE}); Attribute aRecord = attrs.get(A_RECORD_TYPE); Attribute cRecord = attrs.get(CNAME_RECORD_TYPE); if (aRecord != null && cRecord == null) { List<String> result = new ArrayList<>(); NamingEnumeration<String> entries = (NamingEnumeration<String>) aRecord.getAll(); while (entries.hasMore()) { result.add(entries.next()); } return result; } } catch (Exception e) { logger.warn("Cannot load A-record for eureka server address {}", rootDomainName, e); return null; } return null; } private static boolean isLocalOrIp(String currentHost) { if ("localhost".equals(currentHost)) { return true; } if ("127.0.0.1".equals(currentHost)) { return true; } return false; } /** * Looks up the DNS name provided in the JNDI context. */ public static Set<String> getCNamesFromTxtRecord(String discoveryDnsName) throws NamingException { Attributes attrs = getDirContext().getAttributes(discoveryDnsName, new String[]{TXT_RECORD_TYPE}); Attribute attr = attrs.get(TXT_RECORD_TYPE); String txtRecord = null; if (attr != null) { txtRecord = attr.get().toString(); /** * compatible splited txt record of "host1 host2 host3" but not "host1" "host2" "host3". * some dns service provider support txt value only format "host1 host2 host3" */ if (txtRecord.startsWith("\"") && txtRecord.endsWith("\"")) { txtRecord = txtRecord.substring(1, txtRecord.length() - 1); } } Set<String> cnamesSet = new TreeSet<>(); if (txtRecord == null || txtRecord.trim().isEmpty()) { return cnamesSet; } String[] cnames = txtRecord.split(" "); Collections.addAll(cnamesSet, cnames); return cnamesSet; } }
6,812
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/endpoint/EndpointUtils.java
package com.netflix.discovery.endpoint; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.EurekaClientConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; /** * This class contains some of the utility functions previously found in DiscoveryClient, but should be elsewhere. * It *does not yet* clean up the moved code. */ public class EndpointUtils { private static final Logger logger = LoggerFactory.getLogger(EndpointUtils.class); public static final String DEFAULT_REGION = "default"; public static final String DEFAULT_ZONE = "default"; public enum DiscoveryUrlType { CNAME, A } public static interface ServiceUrlRandomizer { void randomize(List<String> urlList); } public static class InstanceInfoBasedUrlRandomizer implements ServiceUrlRandomizer { private final InstanceInfo instanceInfo; public InstanceInfoBasedUrlRandomizer(InstanceInfo instanceInfo) { this.instanceInfo = instanceInfo; } @Override public void randomize(List<String> urlList) { int listSize = 0; if (urlList != null) { listSize = urlList.size(); } if ((instanceInfo == null) || (listSize == 0)) { return; } // Find the hashcode of the instance hostname and use it to find an entry // and then arrange the rest of the entries after this entry. int instanceHashcode = instanceInfo.getHostName().hashCode(); if (instanceHashcode < 0) { instanceHashcode = instanceHashcode * -1; } int backupInstance = instanceHashcode % listSize; for (int i = 0; i < backupInstance; i++) { String zone = urlList.remove(0); urlList.add(zone); } } } /** * Get the list of all eureka service urls for the eureka client to talk to. * * @param clientConfig the clientConfig to use * @param zone the zone in which the client resides * @param randomizer a randomizer to randomized returned urls, if loading from dns * * @return The list of all eureka service urls for the eureka client to talk to. */ public static List<String> getDiscoveryServiceUrls(EurekaClientConfig clientConfig, String zone, ServiceUrlRandomizer randomizer) { boolean shouldUseDns = clientConfig.shouldUseDnsForFetchingServiceUrls(); if (shouldUseDns) { return getServiceUrlsFromDNS(clientConfig, zone, clientConfig.shouldPreferSameZoneEureka(), randomizer); } return getServiceUrlsFromConfig(clientConfig, zone, clientConfig.shouldPreferSameZoneEureka()); } /** * 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 clientConfig the clientConfig to use * @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. * @param randomizer a randomizer to randomized returned urls * * @return The list of all eureka service urls for the eureka client to talk to. */ public static List<String> getServiceUrlsFromDNS(EurekaClientConfig clientConfig, String instanceZone, boolean preferSameZone, ServiceUrlRandomizer randomizer) { String region = getRegion(clientConfig); // Get zone-specific DNS names for the given region so that we can get a // list of available zones Map<String, List<String>> zoneDnsNamesMap = getZoneBasedDiscoveryUrlsFromRegion(clientConfig, region); Set<String> availableZones = zoneDnsNamesMap.keySet(); List<String> zones = new ArrayList<>(availableZones); if (zones.isEmpty()) { throw new RuntimeException("No available zones configured for the instanceZone " + instanceZone); } int zoneIndex = 0; boolean zoneFound = false; for (String zone : zones) { logger.debug("Checking if the instance zone {} is the same as the zone from DNS {}", instanceZone, zone); if (preferSameZone) { if (instanceZone.equalsIgnoreCase(zone)) { zoneFound = true; } } else { if (!instanceZone.equalsIgnoreCase(zone)) { zoneFound = true; } } if (zoneFound) { logger.debug("The zone index from the list {} that matches the instance zone {} is {}", zones, instanceZone, zoneIndex); break; } zoneIndex++; } if (zoneIndex >= zones.size()) { if (logger.isWarnEnabled()) { logger.warn("No match for the zone {} in the list of available zones {}", instanceZone, zones.toArray()); } } else { // Rearrange the zones with the instance zone first for (int i = 0; i < zoneIndex; i++) { String zone = zones.remove(0); zones.add(zone); } } // Now get the eureka urls for all the zones in the order and return it List<String> serviceUrls = new ArrayList<>(); for (String zone : zones) { for (String zoneCname : zoneDnsNamesMap.get(zone)) { List<String> ec2Urls = new ArrayList<>(getEC2DiscoveryUrlsFromZone(zoneCname, DiscoveryUrlType.CNAME)); // Rearrange the list to distribute the load in case of multiple servers if (ec2Urls.size() > 1) { randomizer.randomize(ec2Urls); } for (String ec2Url : ec2Urls) { StringBuilder sb = new StringBuilder() .append("http://") .append(ec2Url) .append(":") .append(clientConfig.getEurekaServerPort()); if (clientConfig.getEurekaServerURLContext() != null) { if (!clientConfig.getEurekaServerURLContext().startsWith("/")) { sb.append("/"); } sb.append(clientConfig.getEurekaServerURLContext()); if (!clientConfig.getEurekaServerURLContext().endsWith("/")) { sb.append("/"); } } else { sb.append("/"); } String serviceUrl = sb.toString(); logger.debug("The EC2 url is {}", serviceUrl); serviceUrls.add(serviceUrl); } } } // Rearrange the fail over server list to distribute the load String primaryServiceUrl = serviceUrls.remove(0); randomizer.randomize(serviceUrls); serviceUrls.add(0, primaryServiceUrl); if (logger.isDebugEnabled()) { logger.debug("This client will talk to the following serviceUrls in order : {} ", (Object) serviceUrls.toArray()); } return serviceUrls; } /** * Get the list of all eureka service urls from properties file for the eureka client to talk to. * * @param clientConfig the clientConfig to use * @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 */ public static List<String> getServiceUrlsFromConfig(EurekaClientConfig clientConfig, String instanceZone, boolean preferSameZone) { List<String> orderedUrls = new ArrayList<>(); String region = getRegion(clientConfig); String[] availZones = clientConfig.getAvailabilityZones(clientConfig.getRegion()); if (availZones == null || availZones.length == 0) { availZones = new String[1]; availZones[0] = DEFAULT_ZONE; } logger.debug("The availability zone for the given region {} are {}", region, availZones); int myZoneOffset = getZoneOffset(instanceZone, preferSameZone, availZones); List<String> serviceUrls = clientConfig.getEurekaServerServiceUrls(availZones[myZoneOffset]); if (serviceUrls != null) { orderedUrls.addAll(serviceUrls); } int currentOffset = myZoneOffset == (availZones.length - 1) ? 0 : (myZoneOffset + 1); while (currentOffset != myZoneOffset) { serviceUrls = clientConfig.getEurekaServerServiceUrls(availZones[currentOffset]); if (serviceUrls != null) { orderedUrls.addAll(serviceUrls); } if (currentOffset == (availZones.length - 1)) { currentOffset = 0; } else { currentOffset++; } } if (orderedUrls.size() < 1) { throw new IllegalArgumentException("DiscoveryClient: invalid serviceUrl specified!"); } return orderedUrls; } /** * Get the list of all eureka service urls from properties file for the eureka client to talk to. * * @param clientConfig the clientConfig to use * @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 an (ordered) map of zone -> list of urls mappings, with the preferred zone first in iteration order */ public static Map<String, List<String>> getServiceUrlsMapFromConfig(EurekaClientConfig clientConfig, String instanceZone, boolean preferSameZone) { Map<String, List<String>> orderedUrls = new LinkedHashMap<>(); String region = getRegion(clientConfig); String[] availZones = clientConfig.getAvailabilityZones(clientConfig.getRegion()); if (availZones == null || availZones.length == 0) { availZones = new String[1]; availZones[0] = DEFAULT_ZONE; } logger.debug("The availability zone for the given region {} are {}", region, availZones); int myZoneOffset = getZoneOffset(instanceZone, preferSameZone, availZones); String zone = availZones[myZoneOffset]; List<String> serviceUrls = clientConfig.getEurekaServerServiceUrls(zone); if (serviceUrls != null) { orderedUrls.put(zone, serviceUrls); } int currentOffset = myZoneOffset == (availZones.length - 1) ? 0 : (myZoneOffset + 1); while (currentOffset != myZoneOffset) { zone = availZones[currentOffset]; serviceUrls = clientConfig.getEurekaServerServiceUrls(zone); if (serviceUrls != null) { orderedUrls.put(zone, serviceUrls); } if (currentOffset == (availZones.length - 1)) { currentOffset = 0; } else { currentOffset++; } } if (orderedUrls.size() < 1) { throw new IllegalArgumentException("DiscoveryClient: invalid serviceUrl specified!"); } return orderedUrls; } /** * 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 */ public static Set<String> getEC2DiscoveryUrlsFromZone(String dnsName, DiscoveryUrlType type) { Set<String> eipsForZone = null; try { dnsName = "txt." + dnsName; logger.debug("The zone url to be looked up is {} :", dnsName); Set<String> ec2UrlsForZone = DnsResolver.getCNamesFromTxtRecord(dnsName); for (String ec2Url : ec2UrlsForZone) { logger.debug("The eureka url for the dns name {} is {}", dnsName, ec2Url); } if (DiscoveryUrlType.CNAME.equals(type)) { return ec2UrlsForZone; } eipsForZone = new TreeSet<String>(); for (String cname : ec2UrlsForZone) { String[] tokens = cname.split("\\."); String ec2HostName = tokens[0]; String[] ips = ec2HostName.split("-"); StringBuilder eipBuffer = new StringBuilder(); for (int ipCtr = 1; ipCtr < 5; ipCtr++) { eipBuffer.append(ips[ipCtr]); if (ipCtr < 4) { eipBuffer.append("."); } } eipsForZone.add(eipBuffer.toString()); } logger.debug("The EIPS for {} is {} :", dnsName, eipsForZone); } catch (Throwable e) { throw new RuntimeException("Cannot get cnames bound to the region:" + dnsName, e); } return eipsForZone; } /** * Get the zone based CNAMES that are bound to a region. * * @param region * - The region for which the zone names need to be retrieved * @return - The list of CNAMES from which the zone-related information can * be retrieved */ public static Map<String, List<String>> getZoneBasedDiscoveryUrlsFromRegion(EurekaClientConfig clientConfig, String region) { String discoveryDnsName = null; try { discoveryDnsName = "txt." + region + "." + clientConfig.getEurekaServerDNSName(); logger.debug("The region url to be looked up is {} :", discoveryDnsName); Set<String> zoneCnamesForRegion = new TreeSet<>(DnsResolver.getCNamesFromTxtRecord(discoveryDnsName)); Map<String, List<String>> zoneCnameMapForRegion = new TreeMap<String, List<String>>(); for (String zoneCname : zoneCnamesForRegion) { String zone = null; if (isEC2Url(zoneCname)) { throw new RuntimeException( "Cannot find the right DNS entry for " + discoveryDnsName + ". " + "Expected mapping of the format <aws_zone>.<domain_name>"); } else { String[] cnameTokens = zoneCname.split("\\."); zone = cnameTokens[0]; logger.debug("The zoneName mapped to region {} is {}", region, zone); } List<String> zoneCnamesSet = zoneCnameMapForRegion.get(zone); if (zoneCnamesSet == null) { zoneCnamesSet = new ArrayList<String>(); zoneCnameMapForRegion.put(zone, zoneCnamesSet); } zoneCnamesSet.add(zoneCname); } return zoneCnameMapForRegion; } catch (Throwable e) { throw new RuntimeException("Cannot get cnames bound to the region:" + discoveryDnsName, e); } } /** * Get the region that this particular instance is in. * * @return - The region in which the particular instance belongs to. */ public static String getRegion(EurekaClientConfig clientConfig) { String region = clientConfig.getRegion(); if (region == null) { region = DEFAULT_REGION; } region = region.trim().toLowerCase(); return region; } // FIXME this is no valid for vpc private static boolean isEC2Url(String zoneCname) { return zoneCname.startsWith("ec2"); } /** * Gets the zone to pick up for this instance. */ private static int getZoneOffset(String myZone, boolean preferSameZone, String[] availZones) { for (int i = 0; i < availZones.length; i++) { if (myZone != null && (availZones[i].equalsIgnoreCase(myZone.trim()) == preferSameZone)) { return i; } } logger.warn("DISCOVERY: Could not pick a zone based on preferred zone settings. My zone - {}," + " preferSameZone - {}. Defaulting to {}", myZone, preferSameZone, availZones[0]); return 0; } }
6,813
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/RefreshableInstanceConfig.java
package com.netflix.appinfo; public interface RefreshableInstanceConfig { /** * resolve the default address * * @param refresh * @return */ String resolveDefaultAddress(boolean refresh); }
6,814
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/AmazonInfoConfig.java
package com.netflix.appinfo; /** * Config related to loading of amazon metadata from the EC2 metadata url. * * @author David Liu */ public interface AmazonInfoConfig { /** * @return the config namespace */ String getNamespace(); /** * @return whether errors reading from the ec2 metadata url should be logged */ boolean shouldLogAmazonMetadataErrors(); /** * @return the read timeout when connecting to the metadata url */ int getReadTimeout(); /** * @return the connect timeout when connecting to the metadata url */ int getConnectTimeout(); /** * @return the number of retries when unable to read a value from the metadata url */ int getNumRetries(); /** * When creating an AmazonInfo via {@link com.netflix.appinfo.AmazonInfo.Builder#autoBuild(String)}, * a fail fast mechanism exist based on the below configuration. * If enabled (default to true), the {@link com.netflix.appinfo.AmazonInfo.Builder#autoBuild(String)} * method will exit early after failing to load the value for the first metadata key (instanceId), * after the expected number of retries as defined by {@link #getNumRetries()}. * * @return whether autoloading should fail fast if loading has failed for the first field (after all retries) */ boolean shouldFailFastOnFirstLoad(); /** * When AmazonInfo is specified, setting this to false allows progress on building the AmazonInfo even if * the instanceId of the environment is not able to be validated. * * @return whether to progress with AmazonInfo construction if the instanceId cannot be validated. */ boolean shouldValidateInstanceId(); }
6,815
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/AbstractEurekaIdentity.java
package com.netflix.appinfo; import javax.annotation.Nullable; public abstract class AbstractEurekaIdentity { public static final String PREFIX = "DiscoveryIdentity-"; public static final String AUTH_NAME_HEADER_KEY = PREFIX + "Name"; public static final String AUTH_VERSION_HEADER_KEY = PREFIX + "Version"; public static final String AUTH_ID_HEADER_KEY = PREFIX + "Id"; public abstract String getName(); public abstract String getVersion(); @Nullable public abstract String getId(); }
6,816
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/PropertiesInstanceConfig.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.appinfo; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import com.netflix.config.ConfigurationManager; import com.netflix.config.DynamicPropertyFactory; import com.netflix.discovery.CommonConstants; import com.netflix.discovery.internal.util.Archaius1Utils; import org.apache.commons.configuration.Configuration; import static com.netflix.appinfo.PropertyBasedInstanceConfigConstants.*; /** * A properties based {@link InstanceInfo} configuration. * * <p> * The information required for registration with eureka server 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 * */ public abstract class PropertiesInstanceConfig extends AbstractInstanceConfig implements EurekaInstanceConfig { protected final String namespace; protected final DynamicPropertyFactory configInstance; private String appGrpNameFromEnv; public PropertiesInstanceConfig() { this(CommonConstants.DEFAULT_CONFIG_NAMESPACE); } public PropertiesInstanceConfig(String namespace) { this(namespace, new DataCenterInfo() { @Override public Name getName() { return Name.MyOwn; } }); } public PropertiesInstanceConfig(String namespace, DataCenterInfo info) { super(info); this.namespace = namespace.endsWith(".") ? namespace : namespace + "."; appGrpNameFromEnv = ConfigurationManager.getConfigInstance() .getString(FALLBACK_APP_GROUP_KEY, Values.UNKNOWN_APPLICATION); this.configInstance = Archaius1Utils.initConfig(CommonConstants.CONFIG_FILE_NAME); } /* * (non-Javadoc) * * @see com.netflix.appinfo.AbstractInstanceConfig#isInstanceEnabledOnit() */ @Override public boolean isInstanceEnabledOnit() { return configInstance.getBooleanProperty(namespace + TRAFFIC_ENABLED_ON_INIT_KEY, super.isInstanceEnabledOnit()).get(); } /* * (non-Javadoc) * * @see com.netflix.appinfo.AbstractInstanceConfig#getNonSecurePort() */ @Override public int getNonSecurePort() { return configInstance.getIntProperty(namespace + PORT_KEY, super.getNonSecurePort()).get(); } /* * (non-Javadoc) * * @see com.netflix.appinfo.AbstractInstanceConfig#getSecurePort() */ @Override public int getSecurePort() { return configInstance.getIntProperty(namespace + SECURE_PORT_KEY, super.getSecurePort()).get(); } /* * (non-Javadoc) * * @see com.netflix.appinfo.AbstractInstanceConfig#isNonSecurePortEnabled() */ @Override public boolean isNonSecurePortEnabled() { return configInstance.getBooleanProperty(namespace + PORT_ENABLED_KEY, super.isNonSecurePortEnabled()).get(); } /* * (non-Javadoc) * * @see com.netflix.appinfo.AbstractInstanceConfig#getSecurePortEnabled() */ @Override public boolean getSecurePortEnabled() { return configInstance.getBooleanProperty(namespace + SECURE_PORT_ENABLED_KEY, super.getSecurePortEnabled()).get(); } /* * (non-Javadoc) * * @see * com.netflix.appinfo.AbstractInstanceConfig#getLeaseRenewalIntervalInSeconds * () */ @Override public int getLeaseRenewalIntervalInSeconds() { return configInstance.getIntProperty(namespace + LEASE_RENEWAL_INTERVAL_KEY, super.getLeaseRenewalIntervalInSeconds()).get(); } /* * (non-Javadoc) * * @see com.netflix.appinfo.AbstractInstanceConfig# * getLeaseExpirationDurationInSeconds() */ @Override public int getLeaseExpirationDurationInSeconds() { return configInstance.getIntProperty(namespace + LEASE_EXPIRATION_DURATION_KEY, super.getLeaseExpirationDurationInSeconds()).get(); } /* * (non-Javadoc) * * @see com.netflix.appinfo.AbstractInstanceConfig#getVirtualHostName() */ @Override public String getVirtualHostName() { if (this.isNonSecurePortEnabled()) { return configInstance.getStringProperty(namespace + VIRTUAL_HOSTNAME_KEY, super.getVirtualHostName()).get(); } else { return null; } } /* * (non-Javadoc) * * @see * com.netflix.appinfo.AbstractInstanceConfig#getSecureVirtualHostName() */ @Override public String getSecureVirtualHostName() { if (this.getSecurePortEnabled()) { return configInstance.getStringProperty(namespace + SECURE_VIRTUAL_HOSTNAME_KEY, super.getSecureVirtualHostName()).get(); } else { return null; } } /* * (non-Javadoc) * * @see com.netflix.appinfo.AbstractInstanceConfig#getASGName() */ @Override public String getASGName() { return configInstance.getStringProperty(namespace + ASG_NAME_KEY, super.getASGName()).get(); } /** * Gets the metadata map associated with the instance. The properties that * will be looked up for this will be <code>namespace + ".metadata"</code>. * * <p> * For instance, if the given namespace is <code>eureka.appinfo</code>, the * metadata keys are searched under the namespace * <code>eureka.appinfo.metadata</code>. * </p> */ @Override public Map<String, String> getMetadataMap() { String metadataNamespace = namespace + INSTANCE_METADATA_PREFIX + "."; Map<String, String> metadataMap = new LinkedHashMap<>(); Configuration config = (Configuration) configInstance.getBackingConfigurationSource(); String subsetPrefix = metadataNamespace.charAt(metadataNamespace.length() - 1) == '.' ? metadataNamespace.substring(0, metadataNamespace.length() - 1) : metadataNamespace; for (Iterator<String> iter = config.subset(subsetPrefix).getKeys(); iter.hasNext(); ) { String key = iter.next(); String value = config.getString(subsetPrefix + "." + key); metadataMap.put(key, value); } return metadataMap; } @Override public String getInstanceId() { String result = configInstance.getStringProperty(namespace + INSTANCE_ID_KEY, null).get(); return result == null ? null : result.trim(); } @Override public String getAppname() { return configInstance.getStringProperty(namespace + APP_NAME_KEY, Values.UNKNOWN_APPLICATION).get().trim(); } @Override public String getAppGroupName() { return configInstance.getStringProperty(namespace + APP_GROUP_KEY, appGrpNameFromEnv).get().trim(); } public String getIpAddress() { return super.getIpAddress(); } @Override public String getStatusPageUrlPath() { return configInstance.getStringProperty(namespace + STATUS_PAGE_URL_PATH_KEY, Values.DEFAULT_STATUSPAGE_URLPATH).get(); } @Override public String getStatusPageUrl() { return configInstance.getStringProperty(namespace + STATUS_PAGE_URL_KEY, null) .get(); } @Override public String getHomePageUrlPath() { return configInstance.getStringProperty(namespace + HOME_PAGE_URL_PATH_KEY, Values.DEFAULT_HOMEPAGE_URLPATH).get(); } @Override public String getHomePageUrl() { return configInstance.getStringProperty(namespace + HOME_PAGE_URL_KEY, null) .get(); } @Override public String getHealthCheckUrlPath() { return configInstance.getStringProperty(namespace + HEALTHCHECK_URL_PATH_KEY, Values.DEFAULT_HEALTHCHECK_URLPATH).get(); } @Override public String getHealthCheckUrl() { return configInstance.getStringProperty(namespace + HEALTHCHECK_URL_KEY, null) .get(); } @Override public String getSecureHealthCheckUrl() { return configInstance.getStringProperty(namespace + SECURE_HEALTHCHECK_URL_KEY, null).get(); } @Override public String[] getDefaultAddressResolutionOrder() { String result = configInstance.getStringProperty(namespace + DEFAULT_ADDRESS_RESOLUTION_ORDER_KEY, null).get(); return result == null ? new String[0] : result.split(","); } /** * Indicates if the public ipv4 address of the instance should be advertised. * @return true if the public ipv4 address of the instance should be advertised, false otherwise . */ public boolean shouldBroadcastPublicIpv4Addr() { return configInstance.getBooleanProperty(namespace + BROADCAST_PUBLIC_IPV4_ADDR_KEY, super.shouldBroadcastPublicIpv4Addr()).get(); } @Override public String getNamespace() { return this.namespace; } }
6,817
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/HealthCheckHandler.java
package com.netflix.appinfo; /** * This provides a more granular healthcheck contract than the existing {@link HealthCheckCallback} * * @author Nitesh Kant */ public interface HealthCheckHandler { InstanceInfo.InstanceStatus getStatus(InstanceInfo.InstanceStatus currentStatus); }
6,818
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/AbstractInstanceConfig.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.appinfo; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Map; import com.netflix.discovery.CommonConstants; import com.netflix.discovery.shared.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * An abstract instance info configuration with some defaults to get the users * started quickly.The users have to override only a few methods to register * their instance with eureka server. * * @author Karthik Ranganathan * */ public abstract class AbstractInstanceConfig implements EurekaInstanceConfig { private static final Logger logger = LoggerFactory.getLogger(AbstractInstanceConfig.class); /** * @deprecated 2016-08-29 use {@link CommonConstants#DEFAULT_CONFIG_NAMESPACE} */ @Deprecated public static final String DEFAULT_NAMESPACE = CommonConstants.DEFAULT_CONFIG_NAMESPACE; private static final int LEASE_EXPIRATION_DURATION_SECONDS = 90; private static final int LEASE_RENEWAL_INTERVAL_SECONDS = 30; private static final boolean SECURE_PORT_ENABLED = false; private static final boolean NON_SECURE_PORT_ENABLED = true; private static final int NON_SECURE_PORT = 80; private static final int SECURE_PORT = 443; private static final boolean INSTANCE_ENABLED_ON_INIT = false; private static final Pair<String, String> hostInfo = getHostInfo(); private DataCenterInfo info = new DataCenterInfo() { @Override public Name getName() { return Name.MyOwn; } }; protected AbstractInstanceConfig() { } protected AbstractInstanceConfig(DataCenterInfo info) { this.info = info; } /* * (non-Javadoc) * * @see com.netflix.appinfo.InstanceConfig#isInstanceEnabledOnit() */ @Override public boolean isInstanceEnabledOnit() { return INSTANCE_ENABLED_ON_INIT; } /* * (non-Javadoc) * * @see com.netflix.appinfo.InstanceConfig#getNonSecurePort() */ @Override public int getNonSecurePort() { return NON_SECURE_PORT; } /* * (non-Javadoc) * * @see com.netflix.appinfo.InstanceConfig#getSecurePort() */ @Override public int getSecurePort() { return SECURE_PORT; } /* * (non-Javadoc) * * @see com.netflix.appinfo.InstanceConfig#isNonSecurePortEnabled() */ @Override public boolean isNonSecurePortEnabled() { return NON_SECURE_PORT_ENABLED; } /* * (non-Javadoc) * * @see com.netflix.appinfo.InstanceConfig#getSecurePortEnabled() */ @Override public boolean getSecurePortEnabled() { // TODO Auto-generated method stub return SECURE_PORT_ENABLED; } /* * (non-Javadoc) * * @see * com.netflix.appinfo.InstanceConfig#getLeaseRenewalIntervalInSeconds() */ @Override public int getLeaseRenewalIntervalInSeconds() { return LEASE_RENEWAL_INTERVAL_SECONDS; } /* * (non-Javadoc) * * @see * com.netflix.appinfo.InstanceConfig#getLeaseExpirationDurationInSeconds() */ @Override public int getLeaseExpirationDurationInSeconds() { return LEASE_EXPIRATION_DURATION_SECONDS; } /* * (non-Javadoc) * * @see com.netflix.appinfo.InstanceConfig#getVirtualHostName() */ @Override public String getVirtualHostName() { return (getHostName(false) + ":" + getNonSecurePort()); } /* * (non-Javadoc) * * @see com.netflix.appinfo.InstanceConfig#getSecureVirtualHostName() */ @Override public String getSecureVirtualHostName() { return (getHostName(false) + ":" + getSecurePort()); } /* * (non-Javadoc) * * @see com.netflix.appinfo.InstanceConfig#getASGName() */ @Override public String getASGName() { // TODO Auto-generated method stub return null; } /* * (non-Javadoc) * * @see com.netflix.appinfo.InstanceConfig#getHostName() */ @Override public String getHostName(boolean refresh) { return hostInfo.second(); } /* * (non-Javadoc) * * @see com.netflix.appinfo.InstanceConfig#getMetadataMap() */ @Override public Map<String, String> getMetadataMap() { // TODO Auto-generated method stub return null; } /* * (non-Javadoc) * * @see com.netflix.appinfo.InstanceConfig#getDataCenterInfo() */ @Override public DataCenterInfo getDataCenterInfo() { // TODO Auto-generated method stub return info; } /* * (non-Javadoc) * * @see com.netflix.appinfo.InstanceConfig#getIpAddress() */ @Override public String getIpAddress() { return hostInfo.first(); } public boolean shouldBroadcastPublicIpv4Addr () { return false; } private static Pair<String, String> getHostInfo() { Pair<String, String> pair; try { InetAddress localHost = InetAddress.getLocalHost(); pair = new Pair<String, String>(localHost.getHostAddress(), localHost.getHostName()); } catch (UnknownHostException e) { logger.error("Cannot get host info", e); pair = new Pair<String, String>("", ""); } return pair; } }
6,819
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/PropertyBasedInstanceConfigConstants.java
package com.netflix.appinfo; /** * constants pertaining to property based instance configs * * @author David Liu */ final class PropertyBasedInstanceConfigConstants { // NOTE: all keys are before any prefixes are applied static final String INSTANCE_ID_KEY = "instanceId"; static final String APP_NAME_KEY = "name"; static final String APP_GROUP_KEY = "appGroup"; static final String FALLBACK_APP_GROUP_KEY = "NETFLIX_APP_GROUP"; static final String ASG_NAME_KEY = "asgName"; static final String PORT_KEY = "port"; static final String SECURE_PORT_KEY = "securePort"; static final String PORT_ENABLED_KEY = PORT_KEY + ".enabled"; static final String SECURE_PORT_ENABLED_KEY = SECURE_PORT_KEY + ".enabled"; static final String VIRTUAL_HOSTNAME_KEY = "vipAddress"; static final String SECURE_VIRTUAL_HOSTNAME_KEY = "secureVipAddress"; static final String STATUS_PAGE_URL_PATH_KEY = "statusPageUrlPath"; static final String STATUS_PAGE_URL_KEY = "statusPageUrl"; static final String HOME_PAGE_URL_PATH_KEY = "homePageUrlPath"; static final String HOME_PAGE_URL_KEY = "homePageUrl"; static final String HEALTHCHECK_URL_PATH_KEY = "healthCheckUrlPath"; static final String HEALTHCHECK_URL_KEY = "healthCheckUrl"; static final String SECURE_HEALTHCHECK_URL_KEY = "secureHealthCheckUrl"; static final String LEASE_RENEWAL_INTERVAL_KEY = "lease.renewalInterval"; static final String LEASE_EXPIRATION_DURATION_KEY = "lease.duration"; static final String INSTANCE_METADATA_PREFIX = "metadata"; static final String DEFAULT_ADDRESS_RESOLUTION_ORDER_KEY = "defaultAddressResolutionOrder"; static final String BROADCAST_PUBLIC_IPV4_ADDR_KEY = "broadcastPublicIpv4"; static final String TRAFFIC_ENABLED_ON_INIT_KEY = "traffic.enabled"; static class Values { static final String UNKNOWN_APPLICATION = "unknown"; static final String DEFAULT_STATUSPAGE_URLPATH = "/Status"; static final String DEFAULT_HOMEPAGE_URLPATH = "/"; static final String DEFAULT_HEALTHCHECK_URLPATH = "/healthcheck"; } }
6,820
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/HealthCheckResource.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.appinfo; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A basic <em>healthcheck</em> jersey resource. * * This can be used a {@link HealthCheckCallback} resource if required. * @author Karthik Ranganathan, Greg Kim * */ @Path("/healthcheck") public class HealthCheckResource { private static final Logger s_logger = LoggerFactory .getLogger(HealthCheckResource.class); @GET public Response doHealthCheck() { try { InstanceInfo myInfo = ApplicationInfoManager.getInstance() .getInfo(); switch (myInfo.getStatus()) { case UP: // Return status 200 return Response.status(Status.OK).build(); case STARTING: // Return status 204 return Response.status(Status.NO_CONTENT).build(); case OUT_OF_SERVICE: // Return 503 return Response.status(Status.SERVICE_UNAVAILABLE).build(); default: // Return status 500 return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } } catch (Throwable th) { s_logger.error("Error doing healthceck", th); // Return status 500 return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } } }
6,821
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/ApplicationInfoManager.java
/* * Copyright 2012 Netflix, Inc. *f * 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.appinfo; import javax.inject.Inject; import javax.inject.Singleton; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import com.netflix.appinfo.InstanceInfo.InstanceStatus; import com.netflix.appinfo.providers.EurekaConfigBasedInstanceInfoProvider; import com.netflix.discovery.StatusChangeEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The class that initializes information required for registration with * <tt>Eureka Server</tt> and to be discovered by other components. * * <p> * The information required for registration is provided by the user by passing * the configuration defined by the contract in {@link EurekaInstanceConfig} * }.AWS clients can either use or extend {@link CloudInstanceConfig * }. Other non-AWS clients can use or extend either * {@link MyDataCenterInstanceConfig} or very basic * {@link AbstractInstanceConfig}. * </p> * * * @author Karthik Ranganathan, Greg Kim * */ @Singleton public class ApplicationInfoManager { private static final Logger logger = LoggerFactory.getLogger(ApplicationInfoManager.class); private static final InstanceStatusMapper NO_OP_MAPPER = new InstanceStatusMapper() { @Override public InstanceStatus map(InstanceStatus prev) { return prev; } }; private static ApplicationInfoManager instance = new ApplicationInfoManager(null, null, null); protected final Map<String, StatusChangeListener> listeners; private final InstanceStatusMapper instanceStatusMapper; private InstanceInfo instanceInfo; private EurekaInstanceConfig config; public static class OptionalArgs { private InstanceStatusMapper instanceStatusMapper; @com.google.inject.Inject(optional = true) public void setInstanceStatusMapper(InstanceStatusMapper instanceStatusMapper) { this.instanceStatusMapper = instanceStatusMapper; } InstanceStatusMapper getInstanceStatusMapper() { return instanceStatusMapper == null ? NO_OP_MAPPER : instanceStatusMapper; } } /** * public for DI use. This class should be in singleton scope so do not create explicitly. * Either use DI or create this explicitly using one of the other public constructors. */ @Inject public ApplicationInfoManager(EurekaInstanceConfig config, InstanceInfo instanceInfo, OptionalArgs optionalArgs) { this.config = config; this.instanceInfo = instanceInfo; this.listeners = new ConcurrentHashMap<String, StatusChangeListener>(); if (optionalArgs != null) { this.instanceStatusMapper = optionalArgs.getInstanceStatusMapper(); } else { this.instanceStatusMapper = NO_OP_MAPPER; } // Hack to allow for getInstance() to use the DI'd ApplicationInfoManager instance = this; } public ApplicationInfoManager(EurekaInstanceConfig config, /* nullable */ OptionalArgs optionalArgs) { this(config, new EurekaConfigBasedInstanceInfoProvider(config).get(), optionalArgs); } public ApplicationInfoManager(EurekaInstanceConfig config, InstanceInfo instanceInfo) { this(config, instanceInfo, null); } /** * @deprecated 2016-09-19 prefer {@link #ApplicationInfoManager(EurekaInstanceConfig, com.netflix.appinfo.ApplicationInfoManager.OptionalArgs)} */ @Deprecated public ApplicationInfoManager(EurekaInstanceConfig config) { this(config, (OptionalArgs) null); } /** * @deprecated please use DI instead */ @Deprecated public static ApplicationInfoManager getInstance() { return instance; } public void initComponent(EurekaInstanceConfig config) { try { this.config = config; this.instanceInfo = new EurekaConfigBasedInstanceInfoProvider(config).get(); } catch (Throwable e) { throw new RuntimeException("Failed to initialize ApplicationInfoManager", e); } } /** * Gets the information about this instance that is registered with eureka. * * @return information about this instance that is registered with eureka. */ public InstanceInfo getInfo() { return instanceInfo; } public EurekaInstanceConfig getEurekaInstanceConfig() { return config; } /** * Register user-specific instance meta data. Application can send any other * additional meta data that need to be accessed for other reasons.The data * will be periodically sent to the eureka server. * * Please Note that metadata added via this method is not guaranteed to be submitted * to the eureka servers upon initial registration, and may be submitted as an update * at a subsequent time. If you want guaranteed metadata for initial registration, * please use the mechanism described in {@link EurekaInstanceConfig#getMetadataMap()} * * @param appMetadata application specific meta data. */ public void registerAppMetadata(Map<String, String> appMetadata) { instanceInfo.registerRuntimeMetadata(appMetadata); } /** * Set the status of this instance. Application can use this to indicate * whether it is ready to receive traffic. Setting the status here also notifies all registered listeners * of a status change event. * * @param status Status of the instance */ public synchronized void setInstanceStatus(InstanceStatus status) { InstanceStatus next = instanceStatusMapper.map(status); if (next == null) { return; } InstanceStatus prev = instanceInfo.setStatus(next); if (prev != null) { for (StatusChangeListener listener : listeners.values()) { try { listener.notify(new StatusChangeEvent(prev, next)); } catch (Exception e) { logger.warn("failed to notify listener: {}", listener.getId(), e); } } } } public void registerStatusChangeListener(StatusChangeListener listener) { listeners.put(listener.getId(), listener); } public void unregisterStatusChangeListener(String listenerId) { listeners.remove(listenerId); } /** * Refetches the hostname to check if it has changed. If it has, the entire * <code>DataCenterInfo</code> is refetched and passed on to the eureka * server on next heartbeat. * * see {@link InstanceInfo#getHostName()} for explanation on why the hostname is used as the default address */ public void refreshDataCenterInfoIfRequired() { String existingAddress = instanceInfo.getHostName(); String existingSpotInstanceAction = null; if (instanceInfo.getDataCenterInfo() instanceof AmazonInfo) { existingSpotInstanceAction = ((AmazonInfo) instanceInfo.getDataCenterInfo()).get(AmazonInfo.MetaDataKey.spotInstanceAction); } String newAddress; if (config instanceof RefreshableInstanceConfig) { // Refresh data center info, and return up to date address newAddress = ((RefreshableInstanceConfig) config).resolveDefaultAddress(true); } else { newAddress = config.getHostName(true); } String newIp = config.getIpAddress(); if (newAddress != null && !newAddress.equals(existingAddress)) { logger.warn("The address changed from : {} => {}", existingAddress, newAddress); updateInstanceInfo(newAddress, newIp); } if (config.getDataCenterInfo() instanceof AmazonInfo) { String newSpotInstanceAction = ((AmazonInfo) config.getDataCenterInfo()).get(AmazonInfo.MetaDataKey.spotInstanceAction); if (newSpotInstanceAction != null && !newSpotInstanceAction.equals(existingSpotInstanceAction)) { logger.info(String.format("The spot instance termination action changed from: %s => %s", existingSpotInstanceAction, newSpotInstanceAction)); updateInstanceInfo(null , null ); } } } private void updateInstanceInfo(String newAddress, String newIp) { // :( in the legacy code here the builder is acting as a mutator. // This is hard to fix as this same instanceInfo instance is referenced elsewhere. // We will most likely re-write the client at sometime so not fixing for now. InstanceInfo.Builder builder = new InstanceInfo.Builder(instanceInfo); if (newAddress != null) { builder.setHostName(newAddress); } if (newIp != null) { builder.setIPAddr(newIp); } builder.setDataCenterInfo(config.getDataCenterInfo()); instanceInfo.setIsDirty(); } public void refreshLeaseInfoIfRequired() { LeaseInfo leaseInfo = instanceInfo.getLeaseInfo(); if (leaseInfo == null) { return; } int currentLeaseDuration = config.getLeaseExpirationDurationInSeconds(); int currentLeaseRenewal = config.getLeaseRenewalIntervalInSeconds(); if (leaseInfo.getDurationInSecs() != currentLeaseDuration || leaseInfo.getRenewalIntervalInSecs() != currentLeaseRenewal) { LeaseInfo newLeaseInfo = LeaseInfo.Builder.newBuilder() .setRenewalIntervalInSecs(currentLeaseRenewal) .setDurationInSecs(currentLeaseDuration) .build(); instanceInfo.setLeaseInfo(newLeaseInfo); instanceInfo.setIsDirty(); } } public static interface StatusChangeListener { String getId(); void notify(StatusChangeEvent statusChangeEvent); } public static interface InstanceStatusMapper { /** * given a starting {@link com.netflix.appinfo.InstanceInfo.InstanceStatus}, apply a mapping to return * the follow up status, if applicable. * * @return the mapped instance status, or null if the mapping is not applicable. */ InstanceStatus map(InstanceStatus prev); } }
6,822
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/MyDataCenterInstanceConfig.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.appinfo; import com.google.inject.ProvidedBy; import com.netflix.appinfo.providers.MyDataCenterInstanceConfigProvider; import javax.inject.Singleton; /** * An {@link InstanceInfo} configuration for the non-AWS datacenter. * * @author Karthik Ranganathan * */ @Singleton @ProvidedBy(MyDataCenterInstanceConfigProvider.class) public class MyDataCenterInstanceConfig extends PropertiesInstanceConfig implements EurekaInstanceConfig { public MyDataCenterInstanceConfig() { } public MyDataCenterInstanceConfig(String namespace) { super(namespace); } public MyDataCenterInstanceConfig(String namespace, DataCenterInfo dataCenterInfo) { super(namespace, dataCenterInfo); } }
6,823
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/Archaius1AmazonInfoConfig.java
package com.netflix.appinfo; import com.netflix.config.DynamicPropertyFactory; import com.netflix.discovery.CommonConstants; import com.netflix.discovery.internal.util.Archaius1Utils; import static com.netflix.appinfo.PropertyBasedAmazonInfoConfigConstants.*; /** * @author David Liu */ public class Archaius1AmazonInfoConfig implements AmazonInfoConfig { private final DynamicPropertyFactory configInstance; private final String namespace; public Archaius1AmazonInfoConfig(String namespace) { this.namespace = namespace.endsWith(".") ? namespace : namespace + "."; this.configInstance = Archaius1Utils.initConfig(CommonConstants.CONFIG_FILE_NAME); } @Override public String getNamespace() { return namespace; } @Override public boolean shouldLogAmazonMetadataErrors() { return configInstance.getBooleanProperty(namespace + LOG_METADATA_ERROR_KEY, false).get(); } @Override public int getReadTimeout() { return configInstance.getIntProperty(namespace + READ_TIMEOUT_KEY, Values.DEFAULT_READ_TIMEOUT).get(); } @Override public int getConnectTimeout() { return configInstance.getIntProperty(namespace + CONNECT_TIMEOUT_KEY, Values.DEFAULT_CONNECT_TIMEOUT).get(); } @Override public int getNumRetries() { return configInstance.getIntProperty(namespace + NUM_RETRIES_KEY, Values.DEFAULT_NUM_RETRIES).get(); } @Override public boolean shouldFailFastOnFirstLoad() { return configInstance.getBooleanProperty(namespace + FAIL_FAST_ON_FIRST_LOAD_KEY, true).get(); } @Override public boolean shouldValidateInstanceId() { return configInstance.getBooleanProperty(namespace + SHOULD_VALIDATE_INSTANCE_ID_KEY, true).get(); } }
6,824
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/InstanceInfo.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.appinfo; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonRootName; import com.google.inject.ProvidedBy; import com.netflix.appinfo.providers.Archaius1VipAddressResolver; import com.netflix.appinfo.providers.EurekaConfigBasedInstanceInfoProvider; import com.netflix.appinfo.providers.VipAddressResolver; import com.netflix.discovery.converters.Auto; import com.netflix.discovery.converters.EurekaJacksonCodec.InstanceInfoSerializer; import com.netflix.discovery.provider.Serializer; import com.netflix.discovery.util.StringCache; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamOmitField; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The class that holds information required for registration with * <tt>Eureka Server</tt> and to be discovered by other components. * <p> * <code>@Auto</code> annotated fields are serialized as is; Other fields are * serialized as specified by the <code>@Serializer</code>. * </p> * * @author Karthik Ranganathan, Greg Kim */ @ProvidedBy(EurekaConfigBasedInstanceInfoProvider.class) @Serializer("com.netflix.discovery.converters.EntityBodyConverter") @XStreamAlias("instance") @JsonRootName("instance") public class InstanceInfo { private static final String VERSION_UNKNOWN = "unknown"; /** * {@link InstanceInfo} JSON and XML format for port information does not follow the usual conventions, which * makes its mapping complicated. This class represents the wire format for port information. */ public static class PortWrapper { private final boolean enabled; private final int port; @JsonCreator public PortWrapper(@JsonProperty("@enabled") boolean enabled, @JsonProperty("$") int port) { this.enabled = enabled; this.port = port; } public boolean isEnabled() { return enabled; } public int getPort() { return port; } } private static final Logger logger = LoggerFactory.getLogger(InstanceInfo.class); public static final int DEFAULT_PORT = 7001; public static final int DEFAULT_SECURE_PORT = 7002; public static final int DEFAULT_COUNTRY_ID = 1; // US // The (fixed) instanceId for this instanceInfo. This should be unique within the scope of the appName. private volatile String instanceId; private volatile String appName; @Auto private volatile String appGroupName; private volatile String ipAddr; private static final String SID_DEFAULT = "na"; @Deprecated private volatile String sid = SID_DEFAULT; private volatile int port = DEFAULT_PORT; private volatile int securePort = DEFAULT_SECURE_PORT; @Auto private volatile String homePageUrl; @Auto private volatile String statusPageUrl; @Auto private volatile String healthCheckUrl; @Auto private volatile String secureHealthCheckUrl; @Auto private volatile String vipAddress; @Auto private volatile String secureVipAddress; @XStreamOmitField private String statusPageRelativeUrl; @XStreamOmitField private String statusPageExplicitUrl; @XStreamOmitField private String healthCheckRelativeUrl; @XStreamOmitField private String healthCheckSecureExplicitUrl; @XStreamOmitField private String vipAddressUnresolved; @XStreamOmitField private String secureVipAddressUnresolved; @XStreamOmitField private String healthCheckExplicitUrl; @Deprecated private volatile int countryId = DEFAULT_COUNTRY_ID; // Defaults to US private volatile boolean isSecurePortEnabled = false; private volatile boolean isUnsecurePortEnabled = true; private volatile DataCenterInfo dataCenterInfo; private volatile String hostName; private volatile InstanceStatus status = InstanceStatus.UP; private volatile InstanceStatus overriddenStatus = InstanceStatus.UNKNOWN; @XStreamOmitField private volatile boolean isInstanceInfoDirty = false; private volatile LeaseInfo leaseInfo; @Auto private volatile Boolean isCoordinatingDiscoveryServer = Boolean.FALSE; @XStreamAlias("metadata") private volatile Map<String, String> metadata; @Auto private volatile Long lastUpdatedTimestamp; @Auto private volatile Long lastDirtyTimestamp; @Auto private volatile ActionType actionType; @Auto private volatile String asgName; private String version = VERSION_UNKNOWN; private InstanceInfo() { this.metadata = new ConcurrentHashMap<String, String>(); this.lastUpdatedTimestamp = System.currentTimeMillis(); this.lastDirtyTimestamp = lastUpdatedTimestamp; } @JsonCreator public InstanceInfo( @JsonProperty("instanceId") String instanceId, @JsonProperty("app") String appName, @JsonProperty("appGroupName") String appGroupName, @JsonProperty("ipAddr") String ipAddr, @JsonProperty("sid") String sid, @JsonProperty("port") PortWrapper port, @JsonProperty("securePort") PortWrapper securePort, @JsonProperty("homePageUrl") String homePageUrl, @JsonProperty("statusPageUrl") String statusPageUrl, @JsonProperty("healthCheckUrl") String healthCheckUrl, @JsonProperty("secureHealthCheckUrl") String secureHealthCheckUrl, @JsonProperty("vipAddress") String vipAddress, @JsonProperty("secureVipAddress") String secureVipAddress, @JsonProperty("countryId") int countryId, @JsonProperty("dataCenterInfo") DataCenterInfo dataCenterInfo, @JsonProperty("hostName") String hostName, @JsonProperty("status") InstanceStatus status, @JsonProperty("overriddenstatus") InstanceStatus overriddenStatus, @JsonProperty("overriddenStatus") InstanceStatus overriddenStatusAlt, @JsonProperty("leaseInfo") LeaseInfo leaseInfo, @JsonProperty("isCoordinatingDiscoveryServer") Boolean isCoordinatingDiscoveryServer, @JsonProperty("metadata") HashMap<String, String> metadata, @JsonProperty("lastUpdatedTimestamp") Long lastUpdatedTimestamp, @JsonProperty("lastDirtyTimestamp") Long lastDirtyTimestamp, @JsonProperty("actionType") ActionType actionType, @JsonProperty("asgName") String asgName) { this.instanceId = instanceId; this.sid = sid; this.appName = StringCache.intern(appName); this.appGroupName = StringCache.intern(appGroupName); this.ipAddr = ipAddr; this.port = port == null ? 0 : port.getPort(); this.isUnsecurePortEnabled = port != null && port.isEnabled(); this.securePort = securePort == null ? 0 : securePort.getPort(); this.isSecurePortEnabled = securePort != null && securePort.isEnabled(); this.homePageUrl = homePageUrl; this.statusPageUrl = statusPageUrl; this.healthCheckUrl = healthCheckUrl; this.secureHealthCheckUrl = secureHealthCheckUrl; this.vipAddress = StringCache.intern(vipAddress); this.secureVipAddress = StringCache.intern(secureVipAddress); this.countryId = countryId; this.dataCenterInfo = dataCenterInfo; this.hostName = hostName; this.status = status; this.overriddenStatus = overriddenStatus == null ? overriddenStatusAlt : overriddenStatus; this.leaseInfo = leaseInfo; this.isCoordinatingDiscoveryServer = isCoordinatingDiscoveryServer; this.lastUpdatedTimestamp = lastUpdatedTimestamp; this.lastDirtyTimestamp = lastDirtyTimestamp; this.actionType = actionType; this.asgName = StringCache.intern(asgName); // --------------------------------------------------------------- // for compatibility if (metadata == null) { this.metadata = Collections.emptyMap(); } else if (metadata.size() == 1) { this.metadata = removeMetadataMapLegacyValues(metadata); } else { this.metadata = metadata; } if (sid == null) { this.sid = SID_DEFAULT; } } @Override public String toString(){ return "InstanceInfo [instanceId = " + this.instanceId + ", appName = " + this.appName + ", hostName = " + this.hostName + ", status = " + this.status + ", ipAddr = " + this.ipAddr + ", port = " + this.port + ", securePort = " + this.securePort + ", dataCenterInfo = " + this.dataCenterInfo; } private Map<String, String> removeMetadataMapLegacyValues(Map<String, String> metadata) { if (InstanceInfoSerializer.METADATA_COMPATIBILITY_VALUE.equals(metadata.get(InstanceInfoSerializer.METADATA_COMPATIBILITY_KEY))) { // TODO this else if can be removed once the server no longer uses legacy json metadata.remove(InstanceInfoSerializer.METADATA_COMPATIBILITY_KEY); } else if (InstanceInfoSerializer.METADATA_COMPATIBILITY_VALUE.equals(metadata.get("class"))) { // TODO this else if can be removed once the server no longer uses legacy xml metadata.remove("class"); } return metadata; } /** * shallow copy constructor. * * @param ii The object to copy */ public InstanceInfo(InstanceInfo ii) { this.instanceId = ii.instanceId; this.appName = ii.appName; this.appGroupName = ii.appGroupName; this.ipAddr = ii.ipAddr; this.sid = ii.sid; this.port = ii.port; this.securePort = ii.securePort; this.homePageUrl = ii.homePageUrl; this.statusPageUrl = ii.statusPageUrl; this.healthCheckUrl = ii.healthCheckUrl; this.secureHealthCheckUrl = ii.secureHealthCheckUrl; this.vipAddress = ii.vipAddress; this.secureVipAddress = ii.secureVipAddress; this.statusPageRelativeUrl = ii.statusPageRelativeUrl; this.statusPageExplicitUrl = ii.statusPageExplicitUrl; this.healthCheckRelativeUrl = ii.healthCheckRelativeUrl; this.healthCheckSecureExplicitUrl = ii.healthCheckSecureExplicitUrl; this.vipAddressUnresolved = ii.vipAddressUnresolved; this.secureVipAddressUnresolved = ii.secureVipAddressUnresolved; this.healthCheckExplicitUrl = ii.healthCheckExplicitUrl; this.countryId = ii.countryId; this.isSecurePortEnabled = ii.isSecurePortEnabled; this.isUnsecurePortEnabled = ii.isUnsecurePortEnabled; this.dataCenterInfo = ii.dataCenterInfo; this.hostName = ii.hostName; this.status = ii.status; this.overriddenStatus = ii.overriddenStatus; this.isInstanceInfoDirty = ii.isInstanceInfoDirty; this.leaseInfo = ii.leaseInfo; this.isCoordinatingDiscoveryServer = ii.isCoordinatingDiscoveryServer; this.metadata = ii.metadata; this.lastUpdatedTimestamp = ii.lastUpdatedTimestamp; this.lastDirtyTimestamp = ii.lastDirtyTimestamp; this.actionType = ii.actionType; this.asgName = ii.asgName; this.version = ii.version; } public enum InstanceStatus { UP, // Ready to receive traffic DOWN, // Do not send traffic- healthcheck callback failed STARTING, // Just about starting- initializations to be done - do not // send traffic OUT_OF_SERVICE, // Intentionally shutdown for traffic UNKNOWN; public static InstanceStatus toEnum(String s) { if (s != null) { try { return InstanceStatus.valueOf(s.toUpperCase()); } catch (IllegalArgumentException e) { // ignore and fall through to unknown logger.debug("illegal argument supplied to InstanceStatus.valueOf: {}, defaulting to {}", s, UNKNOWN); } } return UNKNOWN; } } @Override public int hashCode() { String id = getId(); return (id == null) ? 31 : (id.hashCode() + 31); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } InstanceInfo other = (InstanceInfo) obj; String id = getId(); if (id == null) { if (other.getId() != null) { return false; } } else if (!id.equals(other.getId())) { return false; } return true; } public enum PortType { SECURE, UNSECURE } public static final class Builder { private static final String COLON = ":"; private static final String HTTPS_PROTOCOL = "https://"; private static final String HTTP_PROTOCOL = "http://"; private final Function<String,String> intern; private static final class LazyHolder { private static final VipAddressResolver DEFAULT_VIP_ADDRESS_RESOLVER = new Archaius1VipAddressResolver(); } @XStreamOmitField private InstanceInfo result; @XStreamOmitField private final VipAddressResolver vipAddressResolver; private String namespace; private Builder(InstanceInfo result, VipAddressResolver vipAddressResolver, Function<String,String> intern) { this.vipAddressResolver = vipAddressResolver; this.result = result; this.intern = intern != null ? intern : StringCache::intern; } public Builder(InstanceInfo instanceInfo) { this(instanceInfo, LazyHolder.DEFAULT_VIP_ADDRESS_RESOLVER, null); } public static Builder newBuilder() { return new Builder(new InstanceInfo(), LazyHolder.DEFAULT_VIP_ADDRESS_RESOLVER, null); } public static Builder newBuilder(Function<String,String> intern) { return new Builder(new InstanceInfo(), LazyHolder.DEFAULT_VIP_ADDRESS_RESOLVER, intern); } public static Builder newBuilder(VipAddressResolver vipAddressResolver) { return new Builder(new InstanceInfo(), vipAddressResolver, null); } public Builder setInstanceId(String instanceId) { result.instanceId = instanceId; return this; } /** * Set the application name of the instance.This is mostly used in * querying of instances. * * @param appName the application name. * @return the instance info builder. */ public Builder setAppName(String appName) { result.appName = intern.apply(appName.toUpperCase(Locale.ROOT)); return this; } public Builder setAppNameForDeser(String appName) { result.appName = appName; return this; } public Builder setAppGroupName(String appGroupName) { if (appGroupName != null) { result.appGroupName = intern.apply(appGroupName.toUpperCase(Locale.ROOT)); } else { result.appGroupName = null; } return this; } public Builder setAppGroupNameForDeser(String appGroupName) { result.appGroupName = appGroupName; return this; } /** * Sets the fully qualified hostname of this running instance.This is * mostly used in constructing the {@link java.net.URL} for communicating with * the instance. * * @param hostName the host name of the instance. * @return the {@link InstanceInfo} builder. */ public Builder setHostName(String hostName) { if (hostName == null || hostName.isEmpty()) { logger.warn("Passed in hostname is blank, not setting it"); return this; } String existingHostName = result.hostName; result.hostName = hostName; if ((existingHostName != null) && !(hostName.equals(existingHostName))) { refreshStatusPageUrl().refreshHealthCheckUrl() .refreshVIPAddress().refreshSecureVIPAddress(); } return this; } /** * Sets the status of the instances.If the status is UP, that is when * the instance is ready to service requests. * * @param status the {@link InstanceStatus} of the instance. * @return the {@link InstanceInfo} builder. */ public Builder setStatus(InstanceStatus status) { result.status = status; return this; } /** * Sets the status overridden by some other external process.This is * mostly used in putting an instance out of service to block traffic to * it. * * @param status the overridden {@link InstanceStatus} of the instance. * @return @return the {@link InstanceInfo} builder. */ public Builder setOverriddenStatus(InstanceStatus status) { result.overriddenStatus = status; return this; } /** * Sets the ip address of this running instance. * * @param ip the ip address of the instance. * @return the {@link InstanceInfo} builder. */ public Builder setIPAddr(String ip) { result.ipAddr = ip; return this; } /** * Sets the identity of this application instance. * * @param sid the sid of the instance. * @return the {@link InstanceInfo} builder. */ @Deprecated public Builder setSID(String sid) { result.sid = sid; return this; } /** * Sets the port number that is used to service requests. * * @param port the port number that is used to service requests. * @return the {@link InstanceInfo} builder. */ public Builder setPort(int port) { result.port = port; return this; } /** * Sets the secure port that is used to service requests. * * @param port the secure port that is used to service requests. * @return the {@link InstanceInfo} builder. */ public Builder setSecurePort(int port) { result.securePort = port; return this; } /** * Enabled or disable secure/non-secure ports . * * @param type Secure or Non-Secure. * @param isEnabled true if enabled. * @return the instance builder. */ public Builder enablePort(PortType type, boolean isEnabled) { if (type == PortType.SECURE) { result.isSecurePortEnabled = isEnabled; } else { result.isUnsecurePortEnabled = isEnabled; } return this; } @Deprecated public Builder setCountryId(int id) { result.countryId = id; return this; } /** * Sets the absolute home page {@link java.net.URL} for this instance. The users * can provide the <code>homePageUrlPath</code> if the home page resides * in the same instance talking to discovery, else in the cases where * the instance is a proxy for some other server, it can provide the * full {@link java.net.URL}. If the full {@link java.net.URL} is provided it takes * precedence. * <p> * <p> * The full {@link java.net.URL} should follow the format * http://${netflix.appinfo.hostname}:7001/ where the value * ${netflix.appinfo.hostname} is replaced at runtime. * </p> * * @param relativeUrl the relative url path of the home page. * @param explicitUrl - The full {@link java.net.URL} for the home page * @return the instance builder. */ public Builder setHomePageUrl(String relativeUrl, String explicitUrl) { String hostNameInterpolationExpression = "${" + namespace + "hostname}"; if (explicitUrl != null) { result.homePageUrl = explicitUrl.replace( hostNameInterpolationExpression, result.hostName); } else if (relativeUrl != null) { result.homePageUrl = HTTP_PROTOCOL + result.hostName + COLON + result.port + relativeUrl; } return this; } /** * {@link #setHomePageUrl(String, String)} has complex logic that should not be invoked when * we deserialize {@link InstanceInfo} object, or home page URL is formatted already by the client. */ public Builder setHomePageUrlForDeser(String homePageUrl) { result.homePageUrl = homePageUrl; return this; } /** * Sets the absolute status page {@link java.net.URL} for this instance. The * users can provide the <code>statusPageUrlPath</code> if the status * page resides in the same instance talking to discovery, else in the * cases where the instance is a proxy for some other server, it can * provide the full {@link java.net.URL}. If the full {@link java.net.URL} is provided it * takes precedence. * <p> * <p> * The full {@link java.net.URL} should follow the format * http://${netflix.appinfo.hostname}:7001/Status where the value * ${netflix.appinfo.hostname} is replaced at runtime. * </p> * * @param relativeUrl - The {@link java.net.URL} path for status page for this instance * @param explicitUrl - The full {@link java.net.URL} for the status page * @return - Builder instance */ public Builder setStatusPageUrl(String relativeUrl, String explicitUrl) { String hostNameInterpolationExpression = "${" + namespace + "hostname}"; result.statusPageRelativeUrl = relativeUrl; result.statusPageExplicitUrl = explicitUrl; if (explicitUrl != null) { result.statusPageUrl = explicitUrl.replace( hostNameInterpolationExpression, result.hostName); } else if (relativeUrl != null) { result.statusPageUrl = HTTP_PROTOCOL + result.hostName + COLON + result.port + relativeUrl; } return this; } /** * {@link #setStatusPageUrl(String, String)} has complex logic that should not be invoked when * we deserialize {@link InstanceInfo} object, or status page URL is formatted already by the client. */ public Builder setStatusPageUrlForDeser(String statusPageUrl) { result.statusPageUrl = statusPageUrl; return this; } /** * Sets the absolute health check {@link java.net.URL} for this instance for both * secure and non-secure communication The users can provide the * <code>healthCheckUrlPath</code> if the healthcheck page resides in * the same instance talking to discovery, else in the cases where the * instance is a proxy for some other server, it can provide the full * {@link java.net.URL}. If the full {@link java.net.URL} is provided it takes precedence. * <p> * <p> * The full {@link java.net.URL} should follow the format * http://${netflix.appinfo.hostname}:7001/healthcheck where the value * ${netflix.appinfo.hostname} is replaced at runtime. * </p> * * @param relativeUrl - The {@link java.net.URL} path for healthcheck page for this * instance. * @param explicitUrl - The full {@link java.net.URL} for the healthcheck page. * @param secureExplicitUrl the full secure explicit url of the healthcheck page. * @return the instance builder */ public Builder setHealthCheckUrls(String relativeUrl, String explicitUrl, String secureExplicitUrl) { String hostNameInterpolationExpression = "${" + namespace + "hostname}"; result.healthCheckRelativeUrl = relativeUrl; result.healthCheckExplicitUrl = explicitUrl; result.healthCheckSecureExplicitUrl = secureExplicitUrl; if (explicitUrl != null) { result.healthCheckUrl = explicitUrl.replace( hostNameInterpolationExpression, result.hostName); } else if (result.isUnsecurePortEnabled && relativeUrl != null) { result.healthCheckUrl = HTTP_PROTOCOL + result.hostName + COLON + result.port + relativeUrl; } if (secureExplicitUrl != null) { result.secureHealthCheckUrl = secureExplicitUrl.replace( hostNameInterpolationExpression, result.hostName); } else if (result.isSecurePortEnabled && relativeUrl != null) { result.secureHealthCheckUrl = HTTPS_PROTOCOL + result.hostName + COLON + result.securePort + relativeUrl; } return this; } /** * {@link #setHealthCheckUrls(String, String, String)} has complex logic that should not be invoked when * we deserialize {@link InstanceInfo} object, or health check URLs are formatted already by the client. */ public Builder setHealthCheckUrlsForDeser(String healthCheckUrl, String secureHealthCheckUrl) { if (healthCheckUrl != null) { result.healthCheckUrl = healthCheckUrl; } if (secureHealthCheckUrl != null) { result.secureHealthCheckUrl = secureHealthCheckUrl; } return this; } /** * Sets the Virtual Internet Protocol address for this instance. The * address should follow the format <code><hostname:port></code> This * address needs to be resolved into a real address for communicating * with this instance. * * @param vipAddress - The Virtual Internet Protocol address of this instance. * @return the instance builder. */ public Builder setVIPAddress(final String vipAddress) { result.vipAddressUnresolved = intern.apply(vipAddress); result.vipAddress = intern.apply( vipAddressResolver.resolveDeploymentContextBasedVipAddresses(vipAddress)); return this; } /** * Setter used during deserialization process, that does not do macro expansion on the provided value. */ public Builder setVIPAddressDeser(String vipAddress) { result.vipAddress = intern.apply(vipAddress); return this; } /** * Sets the Secure Virtual Internet Protocol address for this instance. * The address should follow the format <hostname:port> This address * needs to be resolved into a real address for communicating with this * instance. * * @param secureVIPAddress the secure VIP address of the instance. * @return - Builder instance */ public Builder setSecureVIPAddress(final String secureVIPAddress) { result.secureVipAddressUnresolved = intern.apply(secureVIPAddress); result.secureVipAddress = intern.apply( vipAddressResolver.resolveDeploymentContextBasedVipAddresses(secureVIPAddress)); return this; } /** * Setter used during deserialization process, that does not do macro expansion on the provided value. */ public Builder setSecureVIPAddressDeser(String secureVIPAddress) { result.secureVipAddress = intern.apply(secureVIPAddress); return this; } /** * Sets the datacenter information. * * @param datacenter the datacenter information for where this instance is * running. * @return the {@link InstanceInfo} builder. */ public Builder setDataCenterInfo(DataCenterInfo datacenter) { result.dataCenterInfo = datacenter; return this; } /** * Set the instance lease information. * * @param info the lease information for this instance. */ public Builder setLeaseInfo(LeaseInfo info) { result.leaseInfo = info; return this; } /** * Add arbitrary metadata to running instance. * * @param key The key of the metadata. * @param val The value of the metadata. * @return the {@link InstanceInfo} builder. */ public Builder add(String key, String val) { result.metadata.put(key, val); return this; } /** * Replace the existing metadata map with a new one. * * @param mt the new metadata name. * @return instance info builder. */ public Builder setMetadata(Map<String, String> mt) { result.metadata = mt; return this; } /** * Returns the encapsulated instance info even it it is not built fully. * * @return the existing information about the instance. */ public InstanceInfo getRawInstance() { return result; } /** * Build the {@link InstanceInfo} object. * * @return the {@link InstanceInfo} that was built based on the * information supplied. */ public InstanceInfo build() { if (!isInitialized()) { throw new IllegalStateException("name is required!"); } return result; } public boolean isInitialized() { return (result.appName != null); } /** * Sets the AWS ASG name for this instance. * * @param asgName the asg name for this instance. * @return the instance info builder. */ public Builder setASGName(String asgName) { result.asgName = intern.apply(asgName); return this; } private Builder refreshStatusPageUrl() { setStatusPageUrl(result.statusPageRelativeUrl, result.statusPageExplicitUrl); return this; } private Builder refreshHealthCheckUrl() { setHealthCheckUrls(result.healthCheckRelativeUrl, result.healthCheckExplicitUrl, result.healthCheckSecureExplicitUrl); return this; } private Builder refreshSecureVIPAddress() { setSecureVIPAddress(result.secureVipAddressUnresolved); return this; } private Builder refreshVIPAddress() { setVIPAddress(result.vipAddressUnresolved); return this; } public Builder setIsCoordinatingDiscoveryServer(boolean isCoordinatingDiscoveryServer) { result.isCoordinatingDiscoveryServer = isCoordinatingDiscoveryServer; return this; } public Builder setLastUpdatedTimestamp(long lastUpdatedTimestamp) { result.lastUpdatedTimestamp = lastUpdatedTimestamp; return this; } public Builder setLastDirtyTimestamp(long lastDirtyTimestamp) { result.lastDirtyTimestamp = lastDirtyTimestamp; return this; } public Builder setActionType(ActionType actionType) { result.actionType = actionType; return this; } public Builder setNamespace(String namespace) { this.namespace = namespace.endsWith(".") ? namespace : namespace + "."; return this; } } /** * @return the raw instanceId. For compatibility, prefer to use {@link #getId()} */ public String getInstanceId() { return instanceId; } /** * Return the name of the application registering with discovery. * * @return the string denoting the application name. */ @JsonProperty("app") public String getAppName() { return appName; } public String getAppGroupName() { return appGroupName; } /** * Return the default network address to connect to this instance. Typically this would be the fully * qualified public hostname. * * However the user can configure the {@link EurekaInstanceConfig} to change the default value used * to populate this field using the {@link EurekaInstanceConfig#getDefaultAddressResolutionOrder()} property. * * If a use case need more specific hostnames or ips, please use data from {@link #getDataCenterInfo()}. * * For legacy reasons, it is difficult to introduce a new address-type field that is agnostic to hostname/ip. * * @return the default address (by default the public hostname) */ public String getHostName() { return hostName; } @Deprecated public void setSID(String sid) { this.sid = sid; setIsDirty(); } @JsonProperty("sid") @Deprecated public String getSID() { return sid; } /** * Returns the unique id of the instance. * (Note) now that id is set at creation time within the instanceProvider, why do the other checks? * This is still necessary for backwards compatibility when upgrading in a deployment with multiple * client versions (some with the change, some without). * * @return the unique id. */ @JsonIgnore public String getId() { if (instanceId != null && !instanceId.isEmpty()) { return instanceId; } else if (dataCenterInfo instanceof UniqueIdentifier) { String uniqueId = ((UniqueIdentifier) dataCenterInfo).getId(); if (uniqueId != null && !uniqueId.isEmpty()) { return uniqueId; } } return hostName; } /** * Returns the ip address of the instance. * * @return - the ip address, in AWS scenario it is a private IP. */ @JsonProperty("ipAddr") public String getIPAddr() { return ipAddr; } /** * Returns the port number that is used for servicing requests. * * @return - the non-secure port number. */ @JsonIgnore public int getPort() { return port; } /** * Returns the status of the instance. * * @return the status indicating whether the instance can handle requests. */ public InstanceStatus getStatus() { return status; } /** * Returns the overridden status if any of the instance. * * @return the status indicating whether an external process has changed the * status. */ public InstanceStatus getOverriddenStatus() { return overriddenStatus; } /** * Returns data center information identifying if it is AWS or not. * * @return the data center information. */ public DataCenterInfo getDataCenterInfo() { return dataCenterInfo; } /** * Returns the lease information regarding when it expires. * * @return the lease information of this instance. */ public LeaseInfo getLeaseInfo() { return leaseInfo; } /** * Sets the lease information regarding when it expires. * * @param info the lease information of this instance. */ public void setLeaseInfo(LeaseInfo info) { leaseInfo = info; } /** * Returns all application specific metadata set on the instance. * * @return application specific metadata. */ public Map<String, String> getMetadata() { return metadata; } @Deprecated public int getCountryId() { return countryId; } /** * Returns the secure port that is used for servicing requests. * * @return the secure port. */ @JsonIgnore public int getSecurePort() { return securePort; } /** * Checks whether a port is enabled for traffic or not. * * @param type indicates whether it is secure or non-secure port. * @return true if the port is enabled, false otherwise. */ @JsonIgnore public boolean isPortEnabled(PortType type) { if (type == PortType.SECURE) { return isSecurePortEnabled; } else { return isUnsecurePortEnabled; } } /** * Returns the time elapsed since epoch since the instance status has been * last updated. * * @return the time elapsed since epoch since the instance has been last * updated. */ public long getLastUpdatedTimestamp() { return lastUpdatedTimestamp; } /** * Set the update time for this instance when the status was update. */ public void setLastUpdatedTimestamp() { this.lastUpdatedTimestamp = System.currentTimeMillis(); } /** * Gets the home page {@link java.net.URL} set for this instance. * * @return home page {@link java.net.URL} */ public String getHomePageUrl() { return homePageUrl; } /** * Gets the status page {@link java.net.URL} set for this instance. * * @return status page {@link java.net.URL} */ public String getStatusPageUrl() { return statusPageUrl; } /** * Gets the absolute URLs for the health check page for both secure and * non-secure protocols. If the port is not enabled then the URL is * excluded. * * @return A Set containing the string representation of health check urls * for secure and non secure protocols */ @JsonIgnore public Set<String> getHealthCheckUrls() { Set<String> healthCheckUrlSet = new LinkedHashSet<>(); if (this.isUnsecurePortEnabled && healthCheckUrl != null && !healthCheckUrl.isEmpty()) { healthCheckUrlSet.add(healthCheckUrl); } if (this.isSecurePortEnabled && secureHealthCheckUrl != null && !secureHealthCheckUrl.isEmpty()) { healthCheckUrlSet.add(secureHealthCheckUrl); } return healthCheckUrlSet; } public String getHealthCheckUrl() { return healthCheckUrl; } public String getSecureHealthCheckUrl() { return secureHealthCheckUrl; } /** * Gets the Virtual Internet Protocol address for this instance. Defaults to * hostname if not specified. * * @return - The Virtual Internet Protocol address */ @JsonProperty("vipAddress") public String getVIPAddress() { return vipAddress; } /** * Get the Secure Virtual Internet Protocol address for this instance. * Defaults to hostname if not specified. * * @return - The Secure Virtual Internet Protocol address. */ public String getSecureVipAddress() { return secureVipAddress; } /** * Gets the last time stamp when this instance was touched. * * @return last timestamp when this instance was touched. */ public Long getLastDirtyTimestamp() { return lastDirtyTimestamp; } /** * Set the time indicating that the instance was touched. * * @param lastDirtyTimestamp time when the instance was touched. */ public void setLastDirtyTimestamp(Long lastDirtyTimestamp) { this.lastDirtyTimestamp = lastDirtyTimestamp; } /** * Set the status for this instance. * * @param status status for this instance. * @return the prev status if a different status from the current was set, null otherwise */ public synchronized InstanceStatus setStatus(InstanceStatus status) { if (this.status != status) { InstanceStatus prev = this.status; this.status = status; setIsDirty(); return prev; } return null; } /** * Set the status for this instance without updating the dirty timestamp. * * @param status status for this instance. */ public synchronized void setStatusWithoutDirty(InstanceStatus status) { if (this.status != status) { this.status = status; } } /** * Sets the overridden status for this instance.Normally set by an external * process to disable instance from taking traffic. * * @param status overridden status for this instance. */ public synchronized void setOverriddenStatus(InstanceStatus status) { if (this.overriddenStatus != status) { this.overriddenStatus = status; } } /** * Returns whether any state changed so that {@link com.netflix.discovery.EurekaClient} can * check whether to retransmit info or not on the next heartbeat. * * @return true if the {@link InstanceInfo} is dirty, false otherwise. */ @JsonIgnore public boolean isDirty() { return isInstanceInfoDirty; } /** * @return the lastDirtyTimestamp if is dirty, null otherwise. */ public synchronized Long isDirtyWithTime() { if (isInstanceInfoDirty) { return lastDirtyTimestamp; } else { return null; } } /** * @param isDirty true if dirty, false otherwise. * @deprecated use {@link #setIsDirty()} and {@link #unsetIsDirty(long)} to set and unset * <p> * Sets the dirty flag so that the instance information can be carried to * the discovery server on the next heartbeat. */ @Deprecated public synchronized void setIsDirty(boolean isDirty) { if (isDirty) { setIsDirty(); } else { isInstanceInfoDirty = false; // else don't update lastDirtyTimestamp as we are setting isDirty to false } } /** * Sets the dirty flag so that the instance information can be carried to * the discovery server on the next heartbeat. */ public synchronized void setIsDirty() { isInstanceInfoDirty = true; lastDirtyTimestamp = System.currentTimeMillis(); } /** * Set the dirty flag, and also return the timestamp of the isDirty event * * @return the timestamp when the isDirty flag is set */ public synchronized long setIsDirtyWithTime() { setIsDirty(); return lastDirtyTimestamp; } /** * Unset the dirty flag iff the unsetDirtyTimestamp matches the lastDirtyTimestamp. No-op if * lastDirtyTimestamp > unsetDirtyTimestamp * * @param unsetDirtyTimestamp the expected lastDirtyTimestamp to unset. */ public synchronized void unsetIsDirty(long unsetDirtyTimestamp) { if (lastDirtyTimestamp <= unsetDirtyTimestamp) { isInstanceInfoDirty = false; } else { } } /** * Sets a flag if this instance is the same as the discovery server that is * return the instances. This flag is used by the discovery clients to * identity the discovery server which is coordinating/returning the * information. */ public void setIsCoordinatingDiscoveryServer() { String instanceId = getId(); if ((instanceId != null) && (instanceId.equals(ApplicationInfoManager.getInstance() .getInfo().getId()))) { isCoordinatingDiscoveryServer = Boolean.TRUE; } else { isCoordinatingDiscoveryServer = Boolean.FALSE; } } /** * Finds if this instance is the coordinating discovery server. * * @return - true, if this instance is the coordinating discovery server, * false otherwise. */ @JsonProperty("isCoordinatingDiscoveryServer") public Boolean isCoordinatingDiscoveryServer() { return isCoordinatingDiscoveryServer; } /** * Returns the type of action done on the instance in the server.Primarily * used for updating deltas in the {@link com.netflix.discovery.EurekaClient} * instance. * * @return action type done on the instance. */ public ActionType getActionType() { return actionType; } /** * Set the action type performed on this instance in the server. * * @param actionType action type done on the instance. */ public void setActionType(ActionType actionType) { this.actionType = actionType; } /** * Get AWS autoscaling group name if any. * * @return autoscaling group name of this instance. */ @JsonProperty("asgName") public String getASGName() { return this.asgName; } /** * Returns the specification version of this application. * * @return the string indicating the version of the application. */ @Deprecated @JsonIgnore public String getVersion() { return version; } public enum ActionType { ADDED, // Added in the discovery server MODIFIED, // Changed in the discovery server DELETED // Deleted from the discovery server } /** * Register application specific metadata to be sent to the discovery * server. * * @param runtimeMetadata * Map containing key/value pairs. */ synchronized void registerRuntimeMetadata( Map<String, String> runtimeMetadata) { metadata.putAll(runtimeMetadata); setIsDirty(); } /** * Get the zone that a particular instance is in. * Note that for AWS deployments, myInfo should contain AWS dataCenterInfo which should contain * the AWS zone of the instance, and availZones is ignored. * * @param availZones the list of available zones for non-AWS deployments * @param myInfo * - The InstanceInfo object of the instance. * @return - The zone in which the particular instance belongs to. */ public static String getZone(String[] availZones, InstanceInfo myInfo) { String instanceZone = ((availZones == null || availZones.length == 0) ? "default" : availZones[0]); if (myInfo != null && myInfo.getDataCenterInfo().getName() == DataCenterInfo.Name.Amazon) { String awsInstanceZone = ((AmazonInfo) myInfo.getDataCenterInfo()) .get(AmazonInfo.MetaDataKey.availabilityZone); if (awsInstanceZone != null) { instanceZone = awsInstanceZone; } } return instanceZone; } }
6,825
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/UniqueIdentifier.java
package com.netflix.appinfo; /** * Generally indicates the unique identifier of a {@link com.netflix.appinfo.DataCenterInfo}, if applicable. * * @author rthomas@atlassian.com */ public interface UniqueIdentifier { String getId(); }
6,826
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/PropertyBasedAmazonInfoConfigConstants.java
package com.netflix.appinfo; /** * @author David Liu */ final class PropertyBasedAmazonInfoConfigConstants { static final String LOG_METADATA_ERROR_KEY = "logAmazonMetadataErrors"; static final String READ_TIMEOUT_KEY = "mt.read_timeout"; static final String CONNECT_TIMEOUT_KEY = "mt.connect_timeout"; static final String NUM_RETRIES_KEY = "mt.num_retries"; static final String FAIL_FAST_ON_FIRST_LOAD_KEY = "mt.fail_fast_on_first_load"; static final String SHOULD_VALIDATE_INSTANCE_ID_KEY = "validateInstanceId"; static class Values { static final int DEFAULT_READ_TIMEOUT = 5000; static final int DEFAULT_CONNECT_TIMEOUT = 2000; static final int DEFAULT_NUM_RETRIES = 3; } }
6,827
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/EurekaAccept.java
package com.netflix.appinfo; import java.util.HashMap; import java.util.Map; import com.netflix.discovery.converters.wrappers.CodecWrappers; import com.netflix.discovery.converters.wrappers.CodecWrappers.JacksonJson; import com.netflix.discovery.converters.wrappers.CodecWrappers.JacksonJsonMini; import com.netflix.discovery.converters.wrappers.CodecWrappers.JacksonXml; import com.netflix.discovery.converters.wrappers.CodecWrappers.JacksonXmlMini; import com.netflix.discovery.converters.wrappers.CodecWrappers.LegacyJacksonJson; import com.netflix.discovery.converters.wrappers.CodecWrappers.XStreamJson; import com.netflix.discovery.converters.wrappers.CodecWrappers.XStreamXml; import com.netflix.discovery.converters.wrappers.DecoderWrapper; /** * @author David Liu */ public enum EurekaAccept { full, compact; public static final String HTTP_X_EUREKA_ACCEPT = "X-Eureka-Accept"; private static final Map<String, EurekaAccept> decoderNameToAcceptMap = new HashMap<>(); static { decoderNameToAcceptMap.put(CodecWrappers.getCodecName(LegacyJacksonJson.class), full); decoderNameToAcceptMap.put(CodecWrappers.getCodecName(JacksonJson.class), full); decoderNameToAcceptMap.put(CodecWrappers.getCodecName(XStreamJson.class), full); decoderNameToAcceptMap.put(CodecWrappers.getCodecName(XStreamXml.class), full); decoderNameToAcceptMap.put(CodecWrappers.getCodecName(JacksonXml.class), full); decoderNameToAcceptMap.put(CodecWrappers.getCodecName(JacksonJsonMini.class), compact); decoderNameToAcceptMap.put(CodecWrappers.getCodecName(JacksonXmlMini.class), compact); } public static EurekaAccept getClientAccept(DecoderWrapper decoderWrapper) { return decoderNameToAcceptMap.get(decoderWrapper.codecName()); } public static EurekaAccept fromString(String name) { if (name == null || name.isEmpty()) { return full; } try { return EurekaAccept.valueOf(name.toLowerCase()); } catch (Exception e) { return full; } } }
6,828
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/LeaseInfo.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.appinfo; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonRootName; import com.thoughtworks.xstream.annotations.XStreamOmitField; /** * Represents the <em>lease</em> information with <em>Eureka</em>. * * <p> * <em>Eureka</em> decides to remove the instance out of its view depending on * the duration that is set in * {@link EurekaInstanceConfig#getLeaseExpirationDurationInSeconds()} which is * held in this lease. The lease also tracks the last time it was renewed. * </p> * * @author Karthik Ranganathan, Greg Kim * */ @JsonRootName("leaseInfo") public class LeaseInfo { public static final int DEFAULT_LEASE_RENEWAL_INTERVAL = 30; public static final int DEFAULT_LEASE_DURATION = 90; // Client settings private int renewalIntervalInSecs = DEFAULT_LEASE_RENEWAL_INTERVAL; private int durationInSecs = DEFAULT_LEASE_DURATION; // Server populated private long registrationTimestamp; private long lastRenewalTimestamp; private long evictionTimestamp; private long serviceUpTimestamp; public static final class Builder { @XStreamOmitField private LeaseInfo result; private Builder() { result = new LeaseInfo(); } public static Builder newBuilder() { return new Builder(); } /** * Sets the registration timestamp. * * @param ts * time when the lease was first registered. * @return the {@link LeaseInfo} builder. */ public Builder setRegistrationTimestamp(long ts) { result.registrationTimestamp = ts; return this; } /** * Sets the last renewal timestamp of lease. * * @param ts * time when the lease was last renewed. * @return the {@link LeaseInfo} builder. */ public Builder setRenewalTimestamp(long ts) { result.lastRenewalTimestamp = ts; return this; } /** * Sets the de-registration timestamp. * * @param ts * time when the lease was removed. * @return the {@link LeaseInfo} builder. */ public Builder setEvictionTimestamp(long ts) { result.evictionTimestamp = ts; return this; } /** * Sets the service UP timestamp. * * @param ts * time when the leased service marked as UP. * @return the {@link LeaseInfo} builder. */ public Builder setServiceUpTimestamp(long ts) { result.serviceUpTimestamp = ts; return this; } /** * Sets the client specified setting for eviction (e.g. how long to wait * without renewal event). * * @param d * time in seconds after which the lease would expire without * renewa. * @return the {@link LeaseInfo} builder. */ public Builder setDurationInSecs(int d) { if (d <= 0) { result.durationInSecs = DEFAULT_LEASE_DURATION; } else { result.durationInSecs = d; } return this; } /** * Sets the client specified setting for renew interval. * * @param i * the time interval with which the renewals will be renewed. * @return the {@link LeaseInfo} builder. */ public Builder setRenewalIntervalInSecs(int i) { if (i <= 0) { result.renewalIntervalInSecs = DEFAULT_LEASE_RENEWAL_INTERVAL; } else { result.renewalIntervalInSecs = i; } return this; } /** * Build the {@link InstanceInfo}. * * @return the {@link LeaseInfo} information built based on the supplied * information. */ public LeaseInfo build() { return result; } } private LeaseInfo() { } /** * TODO: note about renewalTimestamp legacy: * The previous change to use Jackson ser/deser changed the field name for lastRenewalTimestamp to renewalTimestamp * for serialization, which causes an incompatibility with the jacksonNG codec when the server returns data with * field renewalTimestamp and jacksonNG expects lastRenewalTimestamp. Remove this legacy field from client code * in a few releases (once servers are updated to a release that generates json with the correct * lastRenewalTimestamp). */ @JsonCreator public LeaseInfo(@JsonProperty("renewalIntervalInSecs") int renewalIntervalInSecs, @JsonProperty("durationInSecs") int durationInSecs, @JsonProperty("registrationTimestamp") long registrationTimestamp, @JsonProperty("lastRenewalTimestamp") Long lastRenewalTimestamp, @JsonProperty("renewalTimestamp") long lastRenewalTimestampLegacy, // for legacy @JsonProperty("evictionTimestamp") long evictionTimestamp, @JsonProperty("serviceUpTimestamp") long serviceUpTimestamp) { this.renewalIntervalInSecs = renewalIntervalInSecs; this.durationInSecs = durationInSecs; this.registrationTimestamp = registrationTimestamp; this.evictionTimestamp = evictionTimestamp; this.serviceUpTimestamp = serviceUpTimestamp; if (lastRenewalTimestamp == null) { this.lastRenewalTimestamp = lastRenewalTimestampLegacy; } else { this.lastRenewalTimestamp = lastRenewalTimestamp; } } /** * Returns the registration timestamp. * * @return time in milliseconds since epoch. */ public long getRegistrationTimestamp() { return registrationTimestamp; } /** * Returns the last renewal timestamp of lease. * * @return time in milliseconds since epoch. */ @JsonProperty("lastRenewalTimestamp") public long getRenewalTimestamp() { return lastRenewalTimestamp; } /** * Returns the de-registration timestamp. * * @return time in milliseconds since epoch. */ public long getEvictionTimestamp() { return evictionTimestamp; } /** * Returns the service UP timestamp. * * @return time in milliseconds since epoch. */ public long getServiceUpTimestamp() { return serviceUpTimestamp; } /** * Returns client specified setting for renew interval. * * @return time in milliseconds since epoch. */ public int getRenewalIntervalInSecs() { return renewalIntervalInSecs; } /** * Returns client specified setting for eviction (e.g. how long to wait w/o * renewal event) * * @return time in milliseconds since epoch. */ public int getDurationInSecs() { return durationInSecs; } }
6,829
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/EurekaInstanceConfig.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.appinfo; import java.util.Map; import com.google.inject.ImplementedBy; /** * Configuration information required by the instance to register with Eureka * server. Once registered, users can look up information from * {@link com.netflix.discovery.EurekaClient} based on virtual hostname (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> * As requirements of registration, an id and an appname must be supplied. The id should be * unique within the scope of the appname. * </P> * * <p> * Note that all configurations are not effective at runtime unless and * otherwise specified. * </p> * * @author Karthik Ranganathan * */ @ImplementedBy(CloudInstanceConfig.class) public interface EurekaInstanceConfig { /** * Get the unique Id (within the scope of the appName) of this instance to be registered with eureka. * * @return the (appname scoped) unique id for this instance */ String getInstanceId(); /** * Get the name of the application to be registered with eureka. * * @return string denoting the name. */ String getAppname(); /** * Get the name of the application group to be registered with eureka. * * @return string denoting the name. */ String getAppGroupName(); /** * Indicates whether the instance should be enabled for taking traffic as * soon as it is registered with eureka. Sometimes the application might * need to do some pre-processing before it is ready to take traffic. * * :( public API typos are the worst. I think this was meant to be "OnInit". * * @return true to immediately start taking traffic, false otherwise. */ boolean isInstanceEnabledOnit(); /** * Get the <code>non-secure</code> port on which the instance should receive * traffic. * * @return the non-secure port on which the instance should receive traffic. */ int getNonSecurePort(); /** * Get the <code>Secure port</code> on which the instance should receive * traffic. * * @return the secure port on which the instance should receive traffic. */ int getSecurePort(); /** * Indicates whether the <code>non-secure</code> port should be enabled for * traffic or not. * * @return true if the <code>non-secure</code> port is enabled, false * otherwise. */ boolean isNonSecurePortEnabled(); /** * Indicates whether the <code>secure</code> port should be enabled for * traffic or not. * * @return true if the <code>secure</code> port is enabled, false otherwise. */ boolean getSecurePortEnabled(); /** * Indicates how often (in seconds) the eureka client needs to send * heartbeats to eureka server to indicate that it is still alive. If the * heartbeats are not received for the period specified in * {@link #getLeaseExpirationDurationInSeconds()}, eureka server will remove * the instance from its view, there by disallowing traffic to this * instance. * * <p> * Note that the instance could still not take traffic if it implements * {@link HealthCheckCallback} and then decides to make itself unavailable. * </p> * * @return time in seconds */ int getLeaseRenewalIntervalInSeconds(); /** * Indicates the time in seconds that the eureka server waits since it * received the last heartbeat before it can remove this instance from its * view and there by disallowing traffic to this instance. * * <p> * Setting this value too long could mean that the traffic could be routed * to the instance even though the instance is not alive. Setting this value * too small could mean, the instance may be taken out of traffic because of * temporary network glitches.This value to be set to atleast higher than * the value specified in {@link #getLeaseRenewalIntervalInSeconds()} * . * </p> * * @return value indicating time in seconds. */ int getLeaseExpirationDurationInSeconds(); /** * Gets the virtual host name defined for this instance. * * <p> * This is typically the way other instance would find this instance by * using the virtual host name.Think of this as similar to the fully * qualified domain name, that the users of your services will need to find * this instance. * </p> * * @return the string indicating the virtual host name which the clients use * to call this service. */ String getVirtualHostName(); /** * Gets the secure virtual host name defined for this instance. * * <p> * This is typically the way other instance would find this instance by * using the secure virtual host name.Think of this as similar to the fully * qualified domain name, that the users of your services will need to find * this instance. * </p> * * @return the string indicating the secure virtual host name which the * clients use to call this service. */ String getSecureVirtualHostName(); /** * Gets the <code>AWS autoscaling group name</code> associated with this * instance. This information is specifically used in an AWS environment to * automatically put an instance out of service after the instance is * launched and it has been disabled for traffic.. * * @return the autoscaling group name associated with this instance. */ String getASGName(); /** * Gets the hostname associated with this instance. This is the exact name * that would be used by other instances to make calls. * * @param refresh * true if the information needs to be refetched, false * otherwise. * @return hostname of this instance which is identifiable by other * instances for making remote calls. */ String getHostName(boolean refresh); /** * Gets the metadata name/value pairs associated with this instance. This * information is sent to eureka server and can be used by other instances. * * @return Map containing application-specific metadata. */ Map<String, String> getMetadataMap(); /** * Returns the data center this instance is deployed. This information is * used to get some AWS specific instance information if the instance is * deployed in AWS. * * @return information that indicates which data center this instance is * deployed in. */ DataCenterInfo getDataCenterInfo(); /** * Get the IPAdress of the instance. This information is for academic * purposes only as the communication from other instances primarily happen * using the information supplied in {@link #getHostName(boolean)}. * * @return the ip address of this instance. */ String getIpAddress(); /** * Gets the relative status page {@link java.net.URL} <em>Path</em> for this * instance. The status page URL is then constructed out of the * {@link #getHostName(boolean)} and the type of communication - secure or * unsecure as specified in {@link #getSecurePort()} and * {@link #getNonSecurePort()}. * * <p> * It is normally used for informational purposes for other services to find * about the status of this instance. Users can provide a simple * <code>HTML</code> indicating what is the current status of the instance. * </p> * * @return - relative <code>URL</code> that specifies the status page. */ String getStatusPageUrlPath(); /** * Gets the absolute status page {@link java.net.URL} for this instance. The users * can provide the {@link #getStatusPageUrlPath()} if the status page * resides in the same instance talking to eureka, else in the cases where * the instance is a proxy for some other server, users can provide the full * {@link java.net.URL}. If the full {@link java.net.URL} is provided it takes precedence. * * <p> * * It is normally used for informational purposes for other services to * find about the status of this instance. Users can provide a simple * <code>HTML</code> indicating what is the current status of the instance. * . The full {@link java.net.URL} should follow the format * http://${eureka.hostname}:7001/ where the value ${eureka.hostname} is * replaced at runtime. * </p> * * @return absolute status page URL of this instance. */ String getStatusPageUrl(); /** * Gets the relative home page {@link java.net.URL} <em>Path</em> for this instance. * The home page URL is then constructed out of the * {@link #getHostName(boolean)} and the type of communication - secure or * unsecure as specified in {@link #getSecurePort()} and * {@link #getNonSecurePort()}. * * <p> * It is normally used for informational purposes for other services to use * it as a landing page. * </p> * * @return relative <code>URL</code> that specifies the home page. */ String getHomePageUrlPath(); /** * Gets the absolute home page {@link java.net.URL} for this instance. The users can * provide the {@link #getHomePageUrlPath()} if the home page resides in the * same instance talking to eureka, else in the cases where the instance is * a proxy for some other server, users can provide the full {@link java.net.URL}. If * the full {@link java.net.URL} is provided it takes precedence. * * <p> * It is normally used for informational purposes for other services to use * it as a landing page. The full {@link java.net.URL} should follow the format * http://${eureka.hostname}:7001/ where the value ${eureka.hostname} is * replaced at runtime. * </p> * * @return absolute home page URL of this instance. */ String getHomePageUrl(); /** * Gets the relative health check {@link java.net.URL} <em>Path</em> for this * instance. The health check page URL is then constructed out of the * {@link #getHostName(boolean)} and the type of communication - secure or * unsecure as specified in {@link #getSecurePort()} and * {@link #getNonSecurePort()}. * * <p> * It is normally used for making educated decisions based on the health of * the instance - for example, it can be used to determine whether to * proceed deployments to an entire farm or stop the deployments without * causing further damage. * </p> * * @return - relative <code>URL</code> that specifies the health check page. */ String getHealthCheckUrlPath(); /** * Gets the absolute health check page {@link java.net.URL} for this instance. The * users can provide the {@link #getHealthCheckUrlPath()} if the health * check page resides in the same instance talking to eureka, else in the * cases where the instance is a proxy for some other server, users can * provide the full {@link java.net.URL}. If the full {@link java.net.URL} is provided it * takes precedence. * * <p> * It is normally used for making educated decisions based on the health of * the instance - for example, it can be used to determine whether to * proceed deployments to an entire farm or stop the deployments without * causing further damage. The full {@link java.net.URL} should follow the format * http://${eureka.hostname}:7001/ where the value ${eureka.hostname} is * replaced at runtime. * </p> * * @return absolute health check page URL of this instance. */ String getHealthCheckUrl(); /** * Gets the absolute secure health check page {@link java.net.URL} for this instance. * The users can provide the {@link #getSecureHealthCheckUrl()} if the * health check page resides in the same instance talking to eureka, else in * the cases where the instance is a proxy for some other server, users can * provide the full {@link java.net.URL}. If the full {@link java.net.URL} is provided it * takes precedence. * * <p> * It is normally used for making educated decisions based on the health of * the instance - for example, it can be used to determine whether to * proceed deployments to an entire farm or stop the deployments without * causing further damage. The full {@link java.net.URL} should follow the format * http://${eureka.hostname}:7001/ where the value ${eureka.hostname} is * replaced at runtime. * </p> * * @return absolute health check page URL of this instance. */ String getSecureHealthCheckUrl(); /** * An instance's network addresses should be fully expressed in it's {@link DataCenterInfo}. * For example for instances in AWS, this will include the publicHostname, publicIp, * privateHostname and privateIp, when available. The {@link com.netflix.appinfo.InstanceInfo} * will further express a "default address", which is a field that can be configured by the * registering instance to advertise it's default address. This configuration allowed * for the expression of an ordered list of fields that can be used to resolve the default * address. The exact field values will depend on the implementation details of the corresponding * implementing DataCenterInfo types. * * @return an ordered list of fields that should be used to preferentially * resolve this instance's default address, empty String[] for default. */ String[] getDefaultAddressResolutionOrder(); /** * Get the namespace used to find properties. * @return the namespace used to find properties. */ String getNamespace(); }
6,830
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/HealthCheckCallback.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.appinfo; /** * Applications can implement this interface and register a callback with the * {@link com.netflix.discovery.EurekaClient#registerHealthCheckCallback(HealthCheckCallback)}. * * <p> * Your callback will be invoked every * {@link EurekaInstanceConfig#getLeaseRenewalIntervalInSeconds()} if the * instance is in {@link InstanceInfo.InstanceStatus#STARTING} status, we will * delay the callback until the status changes.Returning a false to the * checkHealth() method will mark the instance * {@link InstanceInfo.InstanceStatus#DOWN} with eureka. * </p> * * <p> * Eureka server normally just relies on <em>heartbeats</em> to identify the * <em>status</em> of an instance. Application could decide to implement their * own <em>healthpage</em> check here or use the built-in jersey resource * {@link HealthCheckResource}. * </p> * * @deprecated Use {@link com.netflix.appinfo.HealthCheckHandler} instead. * @author Karthik Ranganathan, Greg Kim */ @Deprecated public interface HealthCheckCallback { /** * If false, the instance will be marked * {@link InstanceInfo.InstanceStatus#DOWN} with eureka. If the instance was * already marked {@link InstanceInfo.InstanceStatus#DOWN} , returning true * here will mark the instance back to * {@link InstanceInfo.InstanceStatus#UP}. * * @return true if the call back returns healthy, false otherwise. */ boolean isHealthy(); }
6,831
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/RefreshableAmazonInfoProvider.java
package com.netflix.appinfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Provider; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * A holder class for AmazonInfo that exposes some APIs to allow for refreshes. */ public class RefreshableAmazonInfoProvider implements Provider<AmazonInfo> { /** * A fallback provider for a default set of IP and hostname if equivalent data are not available * from the EC2 metadata url. */ public static interface FallbackAddressProvider { String getFallbackIp(); String getFallbackHostname(); } private static final Logger logger = LoggerFactory.getLogger(RefreshableAmazonInfoProvider.class); /* Visible for testing */ volatile AmazonInfo info; private final AmazonInfoConfig amazonInfoConfig; public RefreshableAmazonInfoProvider(AmazonInfoConfig amazonInfoConfig, FallbackAddressProvider fallbackAddressProvider) { this(init(amazonInfoConfig, fallbackAddressProvider), amazonInfoConfig); } /* visible for testing */ RefreshableAmazonInfoProvider(AmazonInfo initialInfo, AmazonInfoConfig amazonInfoConfig) { this.amazonInfoConfig = amazonInfoConfig; this.info = initialInfo; } private static AmazonInfo init(AmazonInfoConfig amazonInfoConfig, FallbackAddressProvider fallbackAddressProvider) { AmazonInfo info; try { info = AmazonInfo.Builder .newBuilder() .withAmazonInfoConfig(amazonInfoConfig) .autoBuild(amazonInfoConfig.getNamespace()); logger.info("Datacenter is: {}", DataCenterInfo.Name.Amazon); } catch (Throwable e) { logger.error("Cannot initialize amazon info :", e); throw new RuntimeException(e); } // Instance id being null means we could not get the amazon metadata if (info.get(AmazonInfo.MetaDataKey.instanceId) == null) { if (amazonInfoConfig.shouldValidateInstanceId()) { throw new RuntimeException( "Your datacenter is defined as cloud but we are not able to get the amazon metadata to " + "register. \nSet the property " + amazonInfoConfig.getNamespace() + "validateInstanceId to false to ignore the metadata call"); } else { // The property to not validate instance ids may be set for // development and in that scenario, populate instance id // and public hostname with the hostname of the machine Map<String, String> metadataMap = new HashMap<>(); metadataMap.put(AmazonInfo.MetaDataKey.instanceId.getName(), fallbackAddressProvider.getFallbackIp()); metadataMap.put(AmazonInfo.MetaDataKey.publicHostname.getName(), fallbackAddressProvider.getFallbackHostname()); info.setMetadata(metadataMap); } } else if ((info.get(AmazonInfo.MetaDataKey.publicHostname) == null) && (info.get(AmazonInfo.MetaDataKey.localIpv4) != null)) { // :( legacy code and logic // This might be a case of VPC where the instance id is not null, but // public hostname might be null info.getMetadata().put(AmazonInfo.MetaDataKey.publicHostname.getName(), (info.get(AmazonInfo.MetaDataKey.localIpv4))); } return info; } /** * Refresh the locally held version of {@link com.netflix.appinfo.AmazonInfo} */ public synchronized void refresh() { try { AmazonInfo newInfo = getNewAmazonInfo(); if (shouldUpdate(newInfo, info)) { // the datacenter info has changed, re-sync it logger.info("The AmazonInfo changed from : {} => {}", info, newInfo); this.info = newInfo; } } catch (Throwable t) { logger.error("Cannot refresh the Amazon Info ", t); } } /* visible for testing */ AmazonInfo getNewAmazonInfo() { return AmazonInfo.Builder .newBuilder() .withAmazonInfoConfig(amazonInfoConfig) .autoBuild(amazonInfoConfig.getNamespace()); } /** * @return the locally held version of {@link com.netflix.appinfo.AmazonInfo} */ @Override public AmazonInfo get() { return info; } /** * Rules of updating AmazonInfo: * - instanceId must exist * - localIp/privateIp must exist * - publicHostname does not necessarily need to exist (e.g. in vpc) */ /* visible for testing */ static boolean shouldUpdate(AmazonInfo newInfo, AmazonInfo oldInfo) { if (newInfo.getMetadata().isEmpty()) { logger.warn("Newly resolved AmazonInfo is empty, skipping an update cycle"); } else if (!newInfo.equals(oldInfo)) { if (isBlank(newInfo.get(AmazonInfo.MetaDataKey.instanceId))) { logger.warn("instanceId is blank, skipping an update cycle"); return false; } else if (isBlank(newInfo.get(AmazonInfo.MetaDataKey.localIpv4))) { logger.warn("localIpv4 is blank, skipping an update cycle"); return false; } else { Set<String> newKeys = new HashSet<>(newInfo.getMetadata().keySet()); Set<String> oldKeys = new HashSet<>(oldInfo.getMetadata().keySet()); Set<String> union = new HashSet<>(newKeys); union.retainAll(oldKeys); newKeys.removeAll(union); oldKeys.removeAll(union); for (String key : newKeys) { logger.info("Adding new metadata {}={}", key, newInfo.getMetadata().get(key)); } for (String key : oldKeys) { logger.info("Removing old metadata {}={}", key, oldInfo.getMetadata().get(key)); } } return true; } return false; } private static boolean isBlank(String str) { return str == null || str.isEmpty(); } }
6,832
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/CloudInstanceConfig.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.appinfo; import com.google.inject.ProvidedBy; import com.netflix.appinfo.AmazonInfo.MetaDataKey; import com.netflix.appinfo.providers.CloudInstanceConfigProvider; import com.netflix.discovery.CommonConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Singleton; /** * An {@link InstanceInfo} configuration for AWS cloud deployments. * * <p> * The information required for registration with eureka by a combination of * user-supplied values as well as querying AWS instance metadata.An utility * class {@link AmazonInfo} helps in retrieving AWS specific values. Some of * that information including <em>availability zone</em> is used for determining * which eureka server to communicate to. * </p> * * @author Karthik Ranganathan * */ @Singleton @ProvidedBy(CloudInstanceConfigProvider.class) public class CloudInstanceConfig extends PropertiesInstanceConfig implements RefreshableInstanceConfig { private static final Logger logger = LoggerFactory.getLogger(CloudInstanceConfig.class); private static final String[] DEFAULT_AWS_ADDRESS_RESOLUTION_ORDER = new String[] { MetaDataKey.publicHostname.name(), MetaDataKey.localIpv4.name() }; private final RefreshableAmazonInfoProvider amazonInfoHolder; public CloudInstanceConfig() { this(CommonConstants.DEFAULT_CONFIG_NAMESPACE); } public CloudInstanceConfig(String namespace) { this(namespace, new Archaius1AmazonInfoConfig(namespace), null, true); } /* visible for testing */ CloudInstanceConfig(AmazonInfo info) { this(CommonConstants.DEFAULT_CONFIG_NAMESPACE, new Archaius1AmazonInfoConfig(CommonConstants.DEFAULT_CONFIG_NAMESPACE), info, false); } /* visible for testing */ CloudInstanceConfig(String namespace, RefreshableAmazonInfoProvider refreshableAmazonInfoProvider) { super(namespace); this.amazonInfoHolder = refreshableAmazonInfoProvider; } /* visible for testing */ CloudInstanceConfig(String namespace, AmazonInfoConfig amazonInfoConfig, AmazonInfo initialInfo, boolean eagerInit) { super(namespace); if (eagerInit) { RefreshableAmazonInfoProvider.FallbackAddressProvider fallbackAddressProvider = new RefreshableAmazonInfoProvider.FallbackAddressProvider() { @Override public String getFallbackIp() { return CloudInstanceConfig.super.getIpAddress(); } @Override public String getFallbackHostname() { return CloudInstanceConfig.super.getHostName(false); } }; this.amazonInfoHolder = new RefreshableAmazonInfoProvider(amazonInfoConfig, fallbackAddressProvider); } else { this.amazonInfoHolder = new RefreshableAmazonInfoProvider(initialInfo, amazonInfoConfig); } } /** * @deprecated use {@link #resolveDefaultAddress(boolean)} */ @Deprecated public String resolveDefaultAddress() { return this.resolveDefaultAddress(true); } @Override public String resolveDefaultAddress(boolean refresh) { // In this method invocation data center info will be refreshed. String result = getHostName(refresh); for (String name : getDefaultAddressResolutionOrder()) { try { AmazonInfo.MetaDataKey key = AmazonInfo.MetaDataKey.valueOf(name); String address = amazonInfoHolder.get().get(key); if (address != null && !address.isEmpty()) { result = address; break; } } catch (Exception e) { logger.error("failed to resolve default address for key {}, skipping", name, e); } } return result; } @Override public String getHostName(boolean refresh) { if (refresh) { amazonInfoHolder.refresh(); } return amazonInfoHolder.get().get(MetaDataKey.publicHostname); } @Override public String getIpAddress() { return this.shouldBroadcastPublicIpv4Addr() ? getPublicIpv4Addr() : getPrivateIpv4Addr(); } private String getPrivateIpv4Addr() { String privateIpv4Addr = amazonInfoHolder.get().get(MetaDataKey.localIpv4); return privateIpv4Addr == null ? super.getIpAddress() : privateIpv4Addr; } private String getPublicIpv4Addr() { String publicIpv4Addr = amazonInfoHolder.get().get(MetaDataKey.publicIpv4); if (publicIpv4Addr == null) { // publicIpv4s is named as a plural to not conflict with the existing publicIpv4 key. In AmazonInfo.java, // we filter out for the first found IPv4 address in any of the network interface IMDS keys. If it exists, // the value for MetaDataKey.publicIpv4s will always be a string with at most 1 public IPv4 address. publicIpv4Addr = amazonInfoHolder.get().get(MetaDataKey.publicIpv4s); } return publicIpv4Addr == null ? super.getIpAddress() : publicIpv4Addr; } @Override public DataCenterInfo getDataCenterInfo() { return amazonInfoHolder.get(); } @Override public String[] getDefaultAddressResolutionOrder() { String[] order = super.getDefaultAddressResolutionOrder(); return (order.length == 0) ? DEFAULT_AWS_ADDRESS_RESOLUTION_ORDER : order; } /** * @deprecated 2016-09-07 * * Refresh instance info - currently only used when in AWS cloud * as a public ip can change whenever an EIP is associated or dissociated. */ @Deprecated public synchronized void refreshAmazonInfo() { amazonInfoHolder.refresh(); } /** * @deprecated 2016-09-07 */ @Deprecated /* visible for testing */ static boolean shouldUpdate(AmazonInfo newInfo, AmazonInfo oldInfo) { return RefreshableAmazonInfoProvider.shouldUpdate(newInfo, oldInfo); } }
6,833
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/DataCenterInfo.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.appinfo; import com.fasterxml.jackson.annotation.JsonRootName; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeInfo.As; import com.fasterxml.jackson.databind.annotation.JsonTypeIdResolver; import com.netflix.discovery.converters.jackson.DataCenterTypeInfoResolver; /** * A simple interface for indicating which <em>datacenter</em> a particular instance belongs. * * @author Karthik Ranganathan * */ @JsonRootName("dataCenterInfo") @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = As.PROPERTY, property = "@class") @JsonTypeIdResolver(DataCenterTypeInfoResolver.class) public interface DataCenterInfo { enum Name {Netflix, Amazon, MyOwn} Name getName(); }
6,834
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/HealthCheckCallbackToHandlerBridge.java
package com.netflix.appinfo; /** * @author Nitesh Kant */ @SuppressWarnings("deprecation") public class HealthCheckCallbackToHandlerBridge implements HealthCheckHandler { private final HealthCheckCallback callback; public HealthCheckCallbackToHandlerBridge() { callback = null; } public HealthCheckCallbackToHandlerBridge(HealthCheckCallback callback) { this.callback = callback; } @Override public InstanceInfo.InstanceStatus getStatus(InstanceInfo.InstanceStatus currentStatus) { if (null == callback || InstanceInfo.InstanceStatus.STARTING == currentStatus || InstanceInfo.InstanceStatus.OUT_OF_SERVICE == currentStatus) { // Do not go to healthcheck handler if the status is starting or OOS. return currentStatus; } return callback.isHealthy() ? InstanceInfo.InstanceStatus.UP : InstanceInfo.InstanceStatus.DOWN; } }
6,835
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/MyDataCenterInfo.java
package com.netflix.appinfo; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; /** * @author Tomasz Bak */ public class MyDataCenterInfo implements DataCenterInfo { private final Name name; @JsonCreator public MyDataCenterInfo(@JsonProperty("name") Name name) { this.name = name; } @Override public Name getName() { return name; } }
6,836
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/EurekaClientIdentity.java
package com.netflix.appinfo; /** * This class holds metadata information related to eureka client auth with the eureka server */ public class EurekaClientIdentity extends AbstractEurekaIdentity { public static final String DEFAULT_CLIENT_NAME = "DefaultClient"; private final String clientVersion = "1.4"; private final String id; private final String clientName; public EurekaClientIdentity(String id) { this(id, DEFAULT_CLIENT_NAME); } public EurekaClientIdentity(String id, String clientName) { this.id = id; this.clientName = clientName; } @Override public String getName() { return clientName; } @Override public String getVersion() { return clientVersion; } @Override public String getId() { return id; } }
6,837
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/AmazonInfo.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.appinfo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.netflix.discovery.converters.jackson.builder.StringInterningAmazonInfoBuilder; import com.netflix.discovery.internal.util.AmazonInfoUtils; import com.thoughtworks.xstream.annotations.XStreamOmitField; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * An AWS specific {@link DataCenterInfo} implementation. * * <p> * Gets AWS specific information for registration with eureka by making a HTTP * call to an AWS service as recommended by AWS. * </p> * * @author Karthik Ranganathan, Greg Kim * */ @JsonDeserialize(using = StringInterningAmazonInfoBuilder.class) public class AmazonInfo implements DataCenterInfo, UniqueIdentifier { private static final String AWS_API_VERSION = "latest"; private static final String AWS_METADATA_URL = "http://169.254.169.254/" + AWS_API_VERSION + "/meta-data/"; public enum MetaDataKey { instanceId("instance-id"), // always have this first as we use it as a fail fast mechanism amiId("ami-id"), instanceType("instance-type"), localIpv4("local-ipv4"), localHostname("local-hostname"), availabilityZone("availability-zone", "placement/"), publicHostname("public-hostname"), publicIpv4("public-ipv4"), // macs declared above public-ipv4s so will be found before publicIpv4s (where it is needed) macs("macs", "network/interfaces/") { @Override public String read(InputStream inputStream) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); String toReturn; try { toReturn = br.lines().collect(Collectors.joining("\n")); } finally { br.close(); } return toReturn; } }, // Because we stop reading the body returned by IMDS after the first newline, // publicIPv4s will only contain the first IPv4 address returned in the body of the // URL for a given MAC, despite IMDS being able to return multiple addresses under // that key (separated by \n). The first IPv4 address is always the one attached to // the interface and is the only address that should be registered for this instance. publicIpv4s("public-ipv4s", "network/interfaces/macs/") { @Override public URL getURL(String prepend, String mac) throws MalformedURLException { return new URL(AWS_METADATA_URL + this.path + mac + "/" + this.name); } }, ipv6("ipv6"), spotTerminationTime("termination-time", "spot/"), spotInstanceAction("instance-action", "spot/"), mac("mac"), // mac is declared above vpcId so will be found before vpcId (where it is needed) vpcId("vpc-id", "network/interfaces/macs/") { @Override public URL getURL(String prepend, String mac) throws MalformedURLException { return new URL(AWS_METADATA_URL + this.path + mac + "/" + this.name); } }, accountId("accountId") { private Pattern pattern = Pattern.compile("\"accountId\"\\s?:\\s?\\\"([A-Za-z0-9]*)\\\""); @Override public URL getURL(String prepend, String append) throws MalformedURLException { return new URL("http://169.254.169.254/" + AWS_API_VERSION + "/dynamic/instance-identity/document"); } // no need to use a json deserializer, do a custom regex parse @Override public String read(InputStream inputStream) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); try { String toReturn = null; String inputLine; while ((inputLine = br.readLine()) != null) { Matcher matcher = pattern.matcher(inputLine); if (toReturn == null && matcher.find()) { toReturn = matcher.group(1); // don't break here as we want to read the full buffer for a clean connection close } } return toReturn; } finally { br.close(); } } }; protected String name; protected String path; MetaDataKey(String name) { this(name, ""); } MetaDataKey(String name, String path) { this.name = name; this.path = path; } public String getName() { return name; } // override to apply prepend and append public URL getURL(String prepend, String append) throws MalformedURLException { return new URL(AWS_METADATA_URL + path + name); } public String read(InputStream inputStream) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); String toReturn; try { String line = br.readLine(); toReturn = line; while (line != null) { // need to read all the buffer for a clean connection close line = br.readLine(); } return toReturn; } finally { br.close(); } } public String toString() { return getName(); } } public static final class Builder { private static final Logger logger = LoggerFactory.getLogger(Builder.class); private static final int SLEEP_TIME_MS = 100; @XStreamOmitField private AmazonInfo result; @XStreamOmitField private AmazonInfoConfig config; private Builder() { result = new AmazonInfo(); } public static Builder newBuilder() { return new Builder(); } public Builder addMetadata(MetaDataKey key, String value) { result.metadata.put(key.getName(), value); return this; } public Builder withAmazonInfoConfig(AmazonInfoConfig config) { this.config = config; return this; } /** * Build the {@link InstanceInfo} information. * * @return AWS specific instance information. */ public AmazonInfo build() { return result; } /** * Build the {@link AmazonInfo} automatically via HTTP calls to instance * metadata API. * * @param namespace the namespace to look for configuration properties. * @return the instance information specific to AWS. */ public AmazonInfo autoBuild(String namespace) { if (config == null) { config = new Archaius1AmazonInfoConfig(namespace); } for (MetaDataKey key : MetaDataKey.values()) { int numOfRetries = config.getNumRetries(); while (numOfRetries-- > 0) { try { if (key == MetaDataKey.publicIpv4s) { // macs should be read before publicIpv4s due to declaration order String[] macs = result.metadata.get(MetaDataKey.macs.getName()).split("\n"); for (String mac : macs) { URL url = key.getURL(null, mac); String publicIpv4s = AmazonInfoUtils.readEc2MetadataUrl(key, url, config.getConnectTimeout(), config.getReadTimeout()); if (publicIpv4s != null) { result.metadata.put(key.getName(), publicIpv4s); break; } } break; } String mac = null; if (key == MetaDataKey.vpcId) { mac = result.metadata.get(MetaDataKey.mac.getName()); // mac should be read before vpcId due to declaration order } URL url = key.getURL(null, mac); String value = AmazonInfoUtils.readEc2MetadataUrl(key, url, config.getConnectTimeout(), config.getReadTimeout()); if (value != null) { result.metadata.put(key.getName(), value); } break; } catch (Throwable e) { if (config.shouldLogAmazonMetadataErrors()) { logger.warn("Cannot get the value for the metadata key: {} Reason :", key, e); } if (numOfRetries >= 0) { try { Thread.sleep(SLEEP_TIME_MS); } catch (InterruptedException e1) { } continue; } } } if (key == MetaDataKey.instanceId && config.shouldFailFastOnFirstLoad() && !result.metadata.containsKey(MetaDataKey.instanceId.getName())) { logger.warn("Skipping the rest of AmazonInfo init as we were not able to load instanceId after " + "the configured number of retries: {}, per fail fast configuration: {}", config.getNumRetries(), config.shouldFailFastOnFirstLoad()); break; // break out of loop and return whatever we have thus far } } return result; } } private Map<String, String> metadata; public AmazonInfo() { this.metadata = new HashMap<String, String>(); } /** * Constructor provided for deserialization framework. It is expected that {@link AmazonInfo} will be built * programmatically using {@link AmazonInfo.Builder}. * * @param name this value is ignored, as it is always set to "Amazon" */ @JsonCreator public AmazonInfo( @JsonProperty("name") String name, @JsonProperty("metadata") HashMap<String, String> metadata) { this.metadata = metadata; } public AmazonInfo( @JsonProperty("name") String name, @JsonProperty("metadata") Map<String, String> metadata) { this.metadata = metadata; } @Override public Name getName() { return Name.Amazon; } /** * Get the metadata information specific to AWS. * * @return the map of AWS metadata as specified by {@link MetaDataKey}. */ @JsonProperty("metadata") public Map<String, String> getMetadata() { return metadata; } /** * Set AWS metadata. * * @param metadataMap * the map containing AWS metadata. */ public void setMetadata(Map<String, String> metadataMap) { this.metadata = metadataMap; } /** * Gets the AWS metadata specified in {@link MetaDataKey}. * * @param key * the metadata key. * @return String returning the value. */ public String get(MetaDataKey key) { return metadata.get(key.getName()); } @Override @JsonIgnore public String getId() { return get(MetaDataKey.instanceId); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof AmazonInfo)) return false; AmazonInfo that = (AmazonInfo) o; if (metadata != null ? !metadata.equals(that.metadata) : that.metadata != null) return false; return true; } @Override public int hashCode() { return metadata != null ? metadata.hashCode() : 0; } @Override public String toString() { return "AmazonInfo{" + "metadata=" + metadata + '}'; } }
6,838
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/providers/VipAddressResolver.java
package com.netflix.appinfo.providers; /** * This only really exist for legacy support */ public interface VipAddressResolver { /** * Convert <code>VIPAddress</code> by substituting environment variables if necessary. * * @param vipAddressMacro the macro for which the interpolation needs to be made. * @return a string representing the final <code>VIPAddress</code> after substitution. */ String resolveDeploymentContextBasedVipAddresses(String vipAddressMacro); }
6,839
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/providers/Archaius1VipAddressResolver.java
package com.netflix.appinfo.providers; import com.netflix.config.DynamicPropertyFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Archaius1VipAddressResolver implements VipAddressResolver { private static final Logger logger = LoggerFactory.getLogger(Archaius1VipAddressResolver.class); private static final Pattern VIP_ATTRIBUTES_PATTERN = Pattern.compile("\\$\\{(.*?)\\}"); @Override public String resolveDeploymentContextBasedVipAddresses(String vipAddressMacro) { if (vipAddressMacro == null) { return null; } String result = vipAddressMacro; Matcher matcher = VIP_ATTRIBUTES_PATTERN.matcher(result); while (matcher.find()) { String key = matcher.group(1); String value = DynamicPropertyFactory.getInstance().getStringProperty(key, "").get(); logger.debug("att:{}", matcher.group()); logger.debug(", att key:{}", key); logger.debug(", att value:{}", value); logger.debug(""); result = result.replaceAll("\\$\\{" + key + "\\}", value); matcher = VIP_ATTRIBUTES_PATTERN.matcher(result); } return result; } }
6,840
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/providers/EurekaConfigBasedInstanceInfoProvider.java
package com.netflix.appinfo.providers; import javax.inject.Singleton; import javax.inject.Provider; import java.util.Map; import com.google.inject.Inject; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.EurekaInstanceConfig; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.InstanceStatus; import com.netflix.appinfo.InstanceInfo.PortType; import com.netflix.appinfo.LeaseInfo; import com.netflix.appinfo.RefreshableInstanceConfig; import com.netflix.appinfo.UniqueIdentifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * InstanceInfo provider that constructs the InstanceInfo this this instance using * EurekaInstanceConfig. * * This provider is @Singleton scope as it provides the InstanceInfo for both DiscoveryClient * and ApplicationInfoManager, and need to provide the same InstanceInfo to both. * * @author elandau * */ @Singleton public class EurekaConfigBasedInstanceInfoProvider implements Provider<InstanceInfo> { private static final Logger LOG = LoggerFactory.getLogger(EurekaConfigBasedInstanceInfoProvider.class); private final EurekaInstanceConfig config; private InstanceInfo instanceInfo; @Inject(optional = true) private VipAddressResolver vipAddressResolver = null; @Inject public EurekaConfigBasedInstanceInfoProvider(EurekaInstanceConfig config) { this.config = config; } @Override public synchronized InstanceInfo get() { if (instanceInfo == null) { // Build the lease information to be passed to the server based on config LeaseInfo.Builder leaseInfoBuilder = LeaseInfo.Builder.newBuilder() .setRenewalIntervalInSecs(config.getLeaseRenewalIntervalInSeconds()) .setDurationInSecs(config.getLeaseExpirationDurationInSeconds()); if (vipAddressResolver == null) { vipAddressResolver = new Archaius1VipAddressResolver(); } // Builder the instance information to be registered with eureka server InstanceInfo.Builder builder = InstanceInfo.Builder.newBuilder(vipAddressResolver); // set the appropriate id for the InstanceInfo, falling back to datacenter Id if applicable, else hostname String instanceId = config.getInstanceId(); if (instanceId == null || instanceId.isEmpty()) { DataCenterInfo dataCenterInfo = config.getDataCenterInfo(); if (dataCenterInfo instanceof UniqueIdentifier) { instanceId = ((UniqueIdentifier) dataCenterInfo).getId(); } else { instanceId = config.getHostName(false); } } String defaultAddress; if (config instanceof RefreshableInstanceConfig) { // Refresh AWS data center info, and return up to date address defaultAddress = ((RefreshableInstanceConfig) config).resolveDefaultAddress(false); } else { defaultAddress = config.getHostName(false); } // fail safe if (defaultAddress == null || defaultAddress.isEmpty()) { defaultAddress = config.getIpAddress(); } builder.setNamespace(config.getNamespace()) .setInstanceId(instanceId) .setAppName(config.getAppname()) .setAppGroupName(config.getAppGroupName()) .setDataCenterInfo(config.getDataCenterInfo()) .setIPAddr(config.getIpAddress()) .setHostName(defaultAddress) .setPort(config.getNonSecurePort()) .enablePort(PortType.UNSECURE, config.isNonSecurePortEnabled()) .setSecurePort(config.getSecurePort()) .enablePort(PortType.SECURE, config.getSecurePortEnabled()) .setVIPAddress(config.getVirtualHostName()) .setSecureVIPAddress(config.getSecureVirtualHostName()) .setHomePageUrl(config.getHomePageUrlPath(), config.getHomePageUrl()) .setStatusPageUrl(config.getStatusPageUrlPath(), config.getStatusPageUrl()) .setASGName(config.getASGName()) .setHealthCheckUrls(config.getHealthCheckUrlPath(), config.getHealthCheckUrl(), config.getSecureHealthCheckUrl()); // Start off with the STARTING state to avoid traffic if (!config.isInstanceEnabledOnit()) { InstanceStatus initialStatus = InstanceStatus.STARTING; LOG.info("Setting initial instance status as: {}", initialStatus); builder.setStatus(initialStatus); } else { LOG.info("Setting initial instance status as: {}. This may be too early for the instance to advertise " + "itself as available. You would instead want to control this via a healthcheck handler.", InstanceStatus.UP); } // Add any user-specific metadata information for (Map.Entry<String, String> mapEntry : config.getMetadataMap().entrySet()) { String key = mapEntry.getKey(); String value = mapEntry.getValue(); // only add the metadata if the value is present if (value != null && !value.isEmpty()) { builder.add(key, value); } } instanceInfo = builder.build(); instanceInfo.setLeaseInfo(leaseInfoBuilder.build()); } return instanceInfo; } }
6,841
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/providers/CloudInstanceConfigProvider.java
package com.netflix.appinfo.providers; import javax.inject.Provider; import com.google.inject.Inject; import com.netflix.appinfo.CloudInstanceConfig; import com.netflix.discovery.DiscoveryManager; import com.netflix.discovery.EurekaNamespace; /** * This provider is necessary because the namespace is optional. * @author elandau */ public class CloudInstanceConfigProvider implements Provider<CloudInstanceConfig> { @Inject(optional = true) @EurekaNamespace private String namespace; private CloudInstanceConfig config; @Override public synchronized CloudInstanceConfig get() { if (config == null) { if (namespace == null) { config = new CloudInstanceConfig(); } else { config = new CloudInstanceConfig(namespace); } // TODO: Remove this when DiscoveryManager is finally no longer used DiscoveryManager.getInstance().setEurekaInstanceConfig(config); } return config; } }
6,842
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo
Create_ds/eureka/eureka-client/src/main/java/com/netflix/appinfo/providers/MyDataCenterInstanceConfigProvider.java
package com.netflix.appinfo.providers; import javax.inject.Provider; import com.google.inject.Inject; import com.netflix.appinfo.EurekaInstanceConfig; import com.netflix.appinfo.MyDataCenterInstanceConfig; import com.netflix.discovery.DiscoveryManager; import com.netflix.discovery.EurekaNamespace; public class MyDataCenterInstanceConfigProvider implements Provider<EurekaInstanceConfig> { @Inject(optional = true) @EurekaNamespace private String namespace; private MyDataCenterInstanceConfig config; @Override public synchronized MyDataCenterInstanceConfig get() { if (config == null) { if (namespace == null) { config = new MyDataCenterInstanceConfig(); } else { config = new MyDataCenterInstanceConfig(namespace); } // TODO: Remove this when DiscoveryManager is finally no longer used DiscoveryManager.getInstance().setEurekaInstanceConfig(config); } return config; } }
6,843
0
Create_ds/eureka/eureka-client-archaius2/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client-archaius2/src/test/java/com/netflix/discovery/guice/NonEc2EurekaClientModuleTest.java
package com.netflix.discovery.guice; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.EurekaArchaius2InstanceConfig; import com.netflix.appinfo.EurekaInstanceConfig; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.providers.Archaius2VipAddressResolver; import com.netflix.appinfo.providers.VipAddressResolver; import com.netflix.archaius.config.MapConfig; import com.netflix.archaius.guice.ArchaiusModule; import com.netflix.discovery.DiscoveryClient; import com.netflix.discovery.DiscoveryManager; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.EurekaClientConfig; 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 NonEc2EurekaClientModuleTest { private LifecycleInjector injector; @Before public void setUp() throws Exception { injector = InjectorBuilder .fromModules( new ArchaiusModule() { @Override protected void configureArchaius() { bindApplicationConfigurationOverride().toInstance( MapConfig.builder() .put("eureka.region", "default") .put("eureka.shouldFetchRegistry", "false") .put("eureka.registration.enabled", "false") .put("eureka.serviceUrl.default", "http://localhost:8080/eureka/v2") .put("eureka.shouldInitAsEc2", "false") .put("eureka.instanceDeploymentEnvironment", "non-ec2") .build() ); } }, new EurekaClientModule() ) .createInjector(); } @After public void tearDown() { if (injector != null) { injector.shutdown(); } } @SuppressWarnings("deprecation") @Test public void testDI() { InstanceInfo instanceInfo = injector.getInstance(InstanceInfo.class); Assert.assertEquals(ApplicationInfoManager.getInstance().getInfo(), instanceInfo); VipAddressResolver vipAddressResolver = injector.getInstance(VipAddressResolver.class); Assert.assertTrue(vipAddressResolver instanceof Archaius2VipAddressResolver); 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); Assert.assertTrue(eurekaInstanceConfig instanceof EurekaArchaius2InstanceConfig); ApplicationInfoManager applicationInfoManager = injector.getInstance(ApplicationInfoManager.class); InstanceInfo myInfo = applicationInfoManager.getInfo(); Assert.assertEquals(DataCenterInfo.Name.MyOwn, myInfo.getDataCenterInfo().getName()); } }
6,844
0
Create_ds/eureka/eureka-client-archaius2/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client-archaius2/src/test/java/com/netflix/discovery/guice/EurekaClientModuleConfigurationTest.java
package com.netflix.discovery.guice; import com.google.inject.AbstractModule; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.EurekaInstanceConfig; import com.netflix.appinfo.providers.EurekaInstanceConfigFactory; import com.netflix.archaius.guice.ArchaiusModule; import com.netflix.governator.InjectorBuilder; import com.netflix.governator.LifecycleInjector; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; /** * @author David Liu */ public class EurekaClientModuleConfigurationTest { @Test public void testBindEurekaInstanceConfigFactory() { final EurekaInstanceConfigFactory mockFactory = Mockito.mock(EurekaInstanceConfigFactory.class); final EurekaInstanceConfig mockConfig = Mockito.mock(EurekaInstanceConfig.class); final ApplicationInfoManager mockInfoManager = Mockito.mock(ApplicationInfoManager.class); Mockito.when(mockFactory.get()).thenReturn(mockConfig); LifecycleInjector injector = InjectorBuilder .fromModules( new ArchaiusModule(), new EurekaClientModule() { @Override protected void configureEureka() { bindEurekaInstanceConfigFactory().toInstance(mockFactory); } } ) .overrideWith( new AbstractModule() { @Override protected void configure() { // this is usually bound as an eager singleton that can trigger other parts to // initialize, so do an override to a mock here to prevent that. bind(ApplicationInfoManager.class).toInstance(mockInfoManager); } }) .createInjector(); EurekaInstanceConfig config = injector.getInstance(EurekaInstanceConfig.class); Assert.assertEquals(mockConfig, config); } }
6,845
0
Create_ds/eureka/eureka-client-archaius2/src/test/java/com/netflix/discovery
Create_ds/eureka/eureka-client-archaius2/src/test/java/com/netflix/discovery/guice/Ec2EurekaClientModuleTest.java
package com.netflix.discovery.guice; import com.netflix.appinfo.AmazonInfo; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.Ec2EurekaArchaius2InstanceConfig; import com.netflix.appinfo.EurekaInstanceConfig; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.providers.Archaius2VipAddressResolver; import com.netflix.appinfo.providers.VipAddressResolver; import com.netflix.archaius.config.MapConfig; import com.netflix.archaius.guice.ArchaiusModule; import com.netflix.discovery.DiscoveryClient; import com.netflix.discovery.DiscoveryManager; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.EurekaClientConfig; 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 Ec2EurekaClientModuleTest { private LifecycleInjector injector; @Before public void setUp() throws Exception { injector = InjectorBuilder .fromModules( new ArchaiusModule() { @Override protected void configureArchaius() { bindApplicationConfigurationOverride().toInstance( MapConfig.builder() .put("eureka.region", "default") .put("eureka.shouldFetchRegistry", "false") .put("eureka.registration.enabled", "false") .put("eureka.serviceUrl.default", "http://localhost:8080/eureka/v2") .put("eureka.vipAddress", "some-thing") .put("eureka.validateInstanceId", "false") .put("eureka.mt.num_retries", 0) .put("eureka.mt.connect_timeout", 1000) .put("eureka.shouldInitAsEc2", true) // this override is required to force EC2 env as out tests may not // be executed in EC2 .put("eureka.instanceDeploymentEnvironment", "ec2") .build() ); } }, new EurekaClientModule() ) .createInjector(); } @After public void tearDown() { if (injector != null) { injector.shutdown(); } } @SuppressWarnings("deprecation") @Test public void testDI() { InstanceInfo instanceInfo = injector.getInstance(InstanceInfo.class); Assert.assertEquals(ApplicationInfoManager.getInstance().getInfo(), instanceInfo); VipAddressResolver vipAddressResolver = injector.getInstance(VipAddressResolver.class); Assert.assertTrue(vipAddressResolver instanceof Archaius2VipAddressResolver); 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); Assert.assertTrue(eurekaInstanceConfig instanceof Ec2EurekaArchaius2InstanceConfig); ApplicationInfoManager applicationInfoManager = injector.getInstance(ApplicationInfoManager.class); InstanceInfo myInfo = applicationInfoManager.getInfo(); Assert.assertTrue(myInfo.getDataCenterInfo() instanceof AmazonInfo); Assert.assertEquals(DataCenterInfo.Name.Amazon, myInfo.getDataCenterInfo().getName()); } }
6,846
0
Create_ds/eureka/eureka-client-archaius2/src/test/java/com/netflix/discovery/internal
Create_ds/eureka/eureka-client-archaius2/src/test/java/com/netflix/discovery/internal/util/InternalPrefixedConfigTest.java
package com.netflix.discovery.internal.util; import com.netflix.archaius.api.Config; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; /** * @author David Liu */ public class InternalPrefixedConfigTest { @Test public void testPrefixes() { Config configInstance = Mockito.mock(Config.class); InternalPrefixedConfig config = new InternalPrefixedConfig(configInstance); Assert.assertEquals("", config.getNamespace()); config = new InternalPrefixedConfig(configInstance, "foo"); Assert.assertEquals("foo.", config.getNamespace()); config = new InternalPrefixedConfig(configInstance, "foo", "bar"); Assert.assertEquals("foo.bar.", config.getNamespace()); } }
6,847
0
Create_ds/eureka/eureka-client-archaius2/src/test/java/com/netflix
Create_ds/eureka/eureka-client-archaius2/src/test/java/com/netflix/appinfo/Ec2EurekaArchaius2InstanceConfigTest.java
package com.netflix.appinfo; import com.netflix.archaius.config.MapConfig; import com.netflix.discovery.util.InstanceInfoGenerator; import org.junit.Before; import org.junit.Test; import java.util.Collections; 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; /** * @author David Liu */ public class Ec2EurekaArchaius2InstanceConfigTest { private Ec2EurekaArchaius2InstanceConfig 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)); } private Ec2EurekaArchaius2InstanceConfig createConfig(AmazonInfo info) { return new Ec2EurekaArchaius2InstanceConfig(MapConfig.from(Collections.<String, String>emptyMap()), info) { @Override public String[] getDefaultAddressResolutionOrder() { return new String[] { publicHostname.name(), localIpv4.name(), ipv6.name() }; } @Override public String getHostName(boolean refresh) { return dummyDefault; } }; } }
6,848
0
Create_ds/eureka/eureka-client-archaius2/src/main/java/com/netflix
Create_ds/eureka/eureka-client-archaius2/src/main/java/com/netflix/discovery/EurekaArchaius2ClientConfig.java
package com.netflix.discovery; import java.util.Arrays; import java.util.Collections; import java.util.List; import com.google.inject.Inject; import com.netflix.appinfo.EurekaAccept; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.annotations.ConfigurationSource; import com.netflix.discovery.internal.util.InternalPrefixedConfig; import com.netflix.discovery.shared.transport.EurekaTransportConfig; import javax.inject.Singleton; import static com.netflix.discovery.PropertyBasedClientConfigConstants.*; @Singleton @ConfigurationSource(CommonConstants.CONFIG_FILE_NAME) public class EurekaArchaius2ClientConfig implements EurekaClientConfig { public static final String DEFAULT_ZONE = "defaultZone"; private static final String DEFAULT_NAMESPACE = "eureka"; private final Config configInstance; private final InternalPrefixedConfig prefixedConfig; private final EurekaTransportConfig transportConfig; @Inject public EurekaArchaius2ClientConfig(Config configInstance, EurekaTransportConfig transportConfig) { this(configInstance, transportConfig, DEFAULT_NAMESPACE); } public EurekaArchaius2ClientConfig(Config configInstance, EurekaTransportConfig transportConfig, String namespace) { this.transportConfig = transportConfig; this.configInstance = configInstance; this.prefixedConfig = new InternalPrefixedConfig(configInstance, namespace); } public int getRegistryFetchIntervalSeconds() { return prefixedConfig.getInteger(REGISTRY_REFRESH_INTERVAL_KEY, 30); } public int getInstanceInfoReplicationIntervalSeconds() { return prefixedConfig.getInteger(REGISTRATION_REPLICATION_INTERVAL_KEY, 30); } public int getInitialInstanceInfoReplicationIntervalSeconds() { return prefixedConfig.getInteger(INITIAL_REGISTRATION_REPLICATION_DELAY_KEY, 40); } public int getEurekaServiceUrlPollIntervalSeconds() { return prefixedConfig.getInteger(EUREKA_SERVER_URL_POLL_INTERVAL_KEY, 300); } public String getProxyHost() { return prefixedConfig.getString(EUREKA_SERVER_PROXY_HOST_KEY, null); } public String getProxyPort() { return prefixedConfig.getString(EUREKA_SERVER_PROXY_PORT_KEY, null); } public String getProxyUserName() { return prefixedConfig.getString(EUREKA_SERVER_PROXY_USERNAME_KEY, null); } public String getProxyPassword() { return prefixedConfig.getString(EUREKA_SERVER_PROXY_PASSWORD_KEY, null); } public boolean shouldGZipContent() { return prefixedConfig.getBoolean(EUREKA_SERVER_GZIP_CONTENT_KEY, true); } public int getEurekaServerReadTimeoutSeconds() { return prefixedConfig.getInteger(EUREKA_SERVER_READ_TIMEOUT_KEY, 8); } public int getEurekaServerConnectTimeoutSeconds() { return prefixedConfig.getInteger(EUREKA_SERVER_CONNECT_TIMEOUT_KEY, 5); } public String getBackupRegistryImpl() { return prefixedConfig.getString(BACKUP_REGISTRY_CLASSNAME_KEY, null); } public int getEurekaServerTotalConnections() { return prefixedConfig.getInteger(EUREKA_SERVER_MAX_CONNECTIONS_KEY, 200); } public int getEurekaServerTotalConnectionsPerHost() { return prefixedConfig.getInteger(EUREKA_SERVER_MAX_CONNECTIONS_PER_HOST_KEY, 50); } public String getEurekaServerURLContext() { return prefixedConfig.getString(EUREKA_SERVER_URL_CONTEXT_KEY, null); } public String getEurekaServerPort() { return prefixedConfig.getString( EUREKA_SERVER_PORT_KEY, prefixedConfig.getString(EUREKA_SERVER_FALLBACK_PORT_KEY, null) ); } public String getEurekaServerDNSName() { return prefixedConfig.getString( EUREKA_SERVER_DNS_NAME_KEY, prefixedConfig.getString(EUREKA_SERVER_FALLBACK_DNS_NAME_KEY, null) ); } public boolean shouldUseDnsForFetchingServiceUrls() { return prefixedConfig.getBoolean(SHOULD_USE_DNS_KEY, false); } public boolean shouldRegisterWithEureka() { return prefixedConfig.getBoolean(REGISTRATION_ENABLED_KEY, true); } public boolean shouldUnregisterOnShutdown() { return prefixedConfig.getBoolean(SHOULD_UNREGISTER_ON_SHUTDOWN_KEY, true); } public boolean shouldPreferSameZoneEureka() { return prefixedConfig.getBoolean(SHOULD_PREFER_SAME_ZONE_SERVER_KEY, true); } public boolean allowRedirects() { return prefixedConfig.getBoolean(SHOULD_ALLOW_REDIRECTS_KEY, false); } public boolean shouldLogDeltaDiff() { return prefixedConfig.getBoolean(SHOULD_LOG_DELTA_DIFF_KEY, false); } public boolean shouldDisableDelta() { return prefixedConfig.getBoolean(SHOULD_DISABLE_DELTA_KEY, false); } public String fetchRegistryForRemoteRegions() { return prefixedConfig.getString(SHOULD_FETCH_REMOTE_REGION_KEY, null); } public String getRegion() { return prefixedConfig.getString( CLIENT_REGION_KEY, prefixedConfig.getString(CLIENT_REGION_FALLBACK_KEY, Values.DEFAULT_CLIENT_REGION) ); } public String[] getAvailabilityZones(String region) { return prefixedConfig.getString(String.format("%s." + CONFIG_AVAILABILITY_ZONE_PREFIX, region), DEFAULT_ZONE).split(","); } public List<String> getEurekaServerServiceUrls(String myZone) { String serviceUrls = prefixedConfig.getString(CONFIG_EUREKA_SERVER_SERVICE_URL_PREFIX + "." + myZone, null); if (serviceUrls == null || serviceUrls.isEmpty()) { serviceUrls = prefixedConfig.getString(CONFIG_EUREKA_SERVER_SERVICE_URL_PREFIX + ".default", null); } return serviceUrls != null ? Arrays.asList(serviceUrls.split(",")) : Collections.<String>emptyList(); } public boolean shouldFilterOnlyUpInstances() { return prefixedConfig.getBoolean(SHOULD_FILTER_ONLY_UP_INSTANCES_KEY, true); } public int getEurekaConnectionIdleTimeoutSeconds() { return prefixedConfig.getInteger(EUREKA_SERVER_CONNECTION_IDLE_TIMEOUT_KEY, 30); } public boolean shouldFetchRegistry() { return prefixedConfig.getBoolean(FETCH_REGISTRY_ENABLED_KEY, true); } public boolean shouldEnforceFetchRegistryAtInit() { return prefixedConfig.getBoolean(SHOULD_ENFORCE_FETCH_REGISTRY_AT_INIT_KEY, false); } public String getRegistryRefreshSingleVipAddress() { return prefixedConfig.getString(FETCH_SINGLE_VIP_ONLY_KEY, null); } public int getHeartbeatExecutorThreadPoolSize() { return prefixedConfig.getInteger(HEARTBEAT_THREADPOOL_SIZE_KEY, Values.DEFAULT_EXECUTOR_THREAD_POOL_SIZE); } public int getHeartbeatExecutorExponentialBackOffBound() { return prefixedConfig.getInteger(HEARTBEAT_BACKOFF_BOUND_KEY, Values.DEFAULT_EXECUTOR_THREAD_POOL_BACKOFF_BOUND); } public int getCacheRefreshExecutorThreadPoolSize() { return prefixedConfig.getInteger(CACHEREFRESH_THREADPOOL_SIZE_KEY, Values.DEFAULT_EXECUTOR_THREAD_POOL_SIZE); } public int getCacheRefreshExecutorExponentialBackOffBound() { return prefixedConfig.getInteger(CACHEREFRESH_BACKOFF_BOUND_KEY, Values.DEFAULT_EXECUTOR_THREAD_POOL_BACKOFF_BOUND); } public String getDollarReplacement() { return prefixedConfig.getString(CONFIG_DOLLAR_REPLACEMENT_KEY, Values.CONFIG_DOLLAR_REPLACEMENT); } public String getEscapeCharReplacement() { return prefixedConfig.getString(CONFIG_ESCAPE_CHAR_REPLACEMENT_KEY, Values.CONFIG_ESCAPE_CHAR_REPLACEMENT); } public boolean shouldOnDemandUpdateStatusChange() { return prefixedConfig.getBoolean(SHOULD_ONDEMAND_UPDATE_STATUS_KEY, true); } public boolean shouldEnforceRegistrationAtInit() { return prefixedConfig.getBoolean(SHOULD_ENFORCE_REGISTRATION_AT_INIT, false); } @Override public String getEncoderName() { return prefixedConfig.getString(CLIENT_ENCODER_NAME_KEY, null); } @Override public String getDecoderName() { return prefixedConfig.getString(CLIENT_DECODER_NAME_KEY, null); } @Override public String getClientDataAccept() { return prefixedConfig.getString(CLIENT_DATA_ACCEPT_KEY, EurekaAccept.full.name()); } @Override public String getExperimental(String name) { return prefixedConfig.getString(CONFIG_EXPERIMENTAL_PREFIX + "." + name, null); } @Override public EurekaTransportConfig getTransportConfig() { return transportConfig; } }
6,849
0
Create_ds/eureka/eureka-client-archaius2/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client-archaius2/src/main/java/com/netflix/discovery/guice/InternalEurekaClientModule.java
package com.netflix.discovery.guice; import com.google.inject.AbstractModule; import com.google.inject.Inject; import com.google.inject.Provides; 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.Archaius2VipAddressResolver; import com.netflix.appinfo.providers.CompositeInstanceConfigFactory; import com.netflix.appinfo.providers.EurekaConfigBasedInstanceInfoProvider; import com.netflix.appinfo.providers.EurekaInstanceConfigFactory; import com.netflix.appinfo.providers.VipAddressResolver; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.annotations.ConfigurationSource; import com.netflix.discovery.AbstractDiscoveryClientOptionalArgs; import com.netflix.discovery.CommonConstants; import com.netflix.discovery.DiscoveryClient; import com.netflix.discovery.EurekaArchaius2ClientConfig; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.shared.resolver.EndpointRandomizer; import com.netflix.discovery.shared.resolver.ResolverUtils; import com.netflix.discovery.shared.transport.EurekaArchaius2TransportConfig; import com.netflix.discovery.shared.transport.EurekaTransportConfig; import com.netflix.discovery.shared.transport.jersey.Jersey1DiscoveryClientOptionalArgs; import javax.inject.Named; import javax.inject.Singleton; final class InternalEurekaClientModule extends AbstractModule { @Singleton static class ModuleConfig { @Inject Config config; @Inject(optional = true) @Named(CommonConstants.INSTANCE_CONFIG_NAMESPACE_KEY) String instanceConfigNamespace; @Inject(optional = true) @Named(CommonConstants.CLIENT_CONFIG_NAMESPACE_KEY) String clientConfigNamespace; @Inject(optional = true) EurekaInstanceConfigFactory instanceConfigFactory; String getInstanceConfigNamespace() { return instanceConfigNamespace == null ? "eureka" : instanceConfigNamespace; } String getClientConfigNamespace() { return clientConfigNamespace == null ? "eureka" : clientConfigNamespace; } EurekaInstanceConfigFactory getInstanceConfigProvider() { return instanceConfigFactory == null ? new CompositeInstanceConfigFactory(config, getInstanceConfigNamespace()) : instanceConfigFactory; } } @Override protected void configure() { // require binding for Config from archaius2 requireBinding(Config.class); bind(ApplicationInfoManager.class).asEagerSingleton(); bind(VipAddressResolver.class).to(Archaius2VipAddressResolver.class); bind(InstanceInfo.class).toProvider(EurekaConfigBasedInstanceInfoProvider.class); bind(EurekaClient.class).to(DiscoveryClient.class); bind(EndpointRandomizer.class).toInstance(ResolverUtils::randomize); // Default to the jersey1 discovery client optional args bind(AbstractDiscoveryClientOptionalArgs.class).to(Jersey1DiscoveryClientOptionalArgs.class).in(Scopes.SINGLETON); } @Provides @Singleton public EurekaTransportConfig getEurekaTransportConfig(Config config, ModuleConfig moduleConfig, EurekaConfigLoader configLoader) { return new EurekaArchaius2TransportConfig(config, moduleConfig.getClientConfigNamespace()); } @Provides @Singleton public EurekaClientConfig getEurekaClientConfig(Config config, EurekaTransportConfig transportConfig, ModuleConfig moduleConfig, EurekaConfigLoader configLoader) { return new EurekaArchaius2ClientConfig(config, transportConfig, moduleConfig.getClientConfigNamespace()); } @Provides @Singleton public EurekaInstanceConfig getEurekaInstanceConfigProvider(ModuleConfig moduleConfig, EurekaConfigLoader configLoader) { return moduleConfig.getInstanceConfigProvider().get(); } @Override public boolean equals(Object obj) { return obj != null && getClass().equals(obj.getClass()); } @Override public int hashCode() { return getClass().hashCode(); } // need this internal class to ensure config file loading happens @ConfigurationSource(CommonConstants.CONFIG_FILE_NAME) private static class EurekaConfigLoader { } }
6,850
0
Create_ds/eureka/eureka-client-archaius2/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client-archaius2/src/main/java/com/netflix/discovery/guice/EurekaClientModule.java
package com.netflix.discovery.guice; import com.google.inject.AbstractModule; import com.google.inject.binder.LinkedBindingBuilder; import com.google.inject.name.Names; import com.netflix.appinfo.providers.EurekaInstanceConfigFactory; import com.netflix.discovery.CommonConstants; /** * How to use: * - install this module to access all eureka client functionality. * * Custom config namespace may be registered as follows: * <code> * InjectorBuilder.fromModules(new EurekaClientModule() { * protected void configureEureka() { * bindEurekaInstanceConfigNamespace().toInstance("namespaceForMyInstanceConfig"); * bindEurekaClientConfigNamespace().toInstance("namespaceForMyClientAndTransportConfig"); * } * }).createInjector() * </code> * * This module support the binding of a custom {@link EurekaInstanceConfigFactory} to supply your own * way of providing a config for the creation of an {@link com.netflix.appinfo.InstanceInfo} used for * eureka registration. * * Custom {@link EurekaInstanceConfigFactory} may be registered as follows: * <code> * InjectorBuilder.fromModules(new EurekaClientModule() { * protected void configureEureka() { * bindEurekaInstanceConfigFactory().to(MyEurekaInstanceConfigFactory.class); * } * }).createInjector() * </code> * * Note that this module is NOT compatible with the archaius1 based {@link com.netflix.discovery.guice.EurekaModule} * * @author David Liu */ public class EurekaClientModule extends AbstractModule { protected LinkedBindingBuilder<String> bindEurekaInstanceConfigNamespace() { return bind(String.class).annotatedWith(Names.named(CommonConstants.INSTANCE_CONFIG_NAMESPACE_KEY)); } protected LinkedBindingBuilder<String> bindEurekaClientConfigNamespace() { return bind(String.class).annotatedWith(Names.named(CommonConstants.CLIENT_CONFIG_NAMESPACE_KEY)); } protected LinkedBindingBuilder<EurekaInstanceConfigFactory> bindEurekaInstanceConfigFactory() { return bind(EurekaInstanceConfigFactory.class); } @Override protected void configure() { install(new InternalEurekaClientModule()); configureEureka(); } protected void configureEureka() { } }
6,851
0
Create_ds/eureka/eureka-client-archaius2/src/main/java/com/netflix/discovery/internal
Create_ds/eureka/eureka-client-archaius2/src/main/java/com/netflix/discovery/internal/util/InternalPrefixedConfig.java
package com.netflix.discovery.internal.util; import com.netflix.archaius.api.Config; import java.util.Iterator; /** * An internal only module to help with config loading with prefixes, due to the fact Archaius2 config's * getPrefixedView() has odd behaviour when config substitution gets involved. * * @author David Liu */ public final class InternalPrefixedConfig { private final Config config; private final String namespace; public InternalPrefixedConfig(Config config, String... namespaces) { this.config = config; String tempNamespace = ""; for (String namespace : namespaces) { if (namespace != null && !namespace.isEmpty()) { tempNamespace += namespace.endsWith(".") ? namespace : namespace + "."; } } this.namespace = tempNamespace; } public String getNamespace() { return namespace; } public String getString(String key, String defaultValue) { return config.getString(namespace + key, defaultValue); } public Integer getInteger(String key, Integer defaultValue) { return config.getInteger(namespace + key, defaultValue); } public Long getLong(String key, Long defaultValue) { return config.getLong(namespace + key, defaultValue); } public Double getDouble(String key, Double defaultValue) { return config.getDouble(namespace + key, defaultValue); } public Boolean getBoolean(String key, Boolean defaultValue) { return config.getBoolean(namespace + key, defaultValue); } public Iterator<String> getKeys() { final String prefixRegex = "^" + namespace; final Iterator<String> internalIterator = config.getKeys(namespace); return new Iterator<String>() { @Override public boolean hasNext() { return internalIterator.hasNext(); } @Override public String next() { String value = internalIterator.next(); return value.replaceFirst(prefixRegex, ""); } }; } }
6,852
0
Create_ds/eureka/eureka-client-archaius2/src/main/java/com/netflix/discovery/shared
Create_ds/eureka/eureka-client-archaius2/src/main/java/com/netflix/discovery/shared/transport/EurekaArchaius2TransportConfig.java
package com.netflix.discovery.shared.transport; import com.google.inject.Inject; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.annotations.ConfigurationSource; import com.netflix.discovery.CommonConstants; import com.netflix.discovery.internal.util.InternalPrefixedConfig; import javax.inject.Singleton; import static com.netflix.discovery.shared.transport.PropertyBasedTransportConfigConstants.*; /** * @author David Liu */ @Singleton @ConfigurationSource(CommonConstants.CONFIG_FILE_NAME) public class EurekaArchaius2TransportConfig implements EurekaTransportConfig { private final Config configInstance; private final InternalPrefixedConfig prefixedConfig; @Inject public EurekaArchaius2TransportConfig(Config configInstance) { this(configInstance, CommonConstants.DEFAULT_CONFIG_NAMESPACE, TRANSPORT_CONFIG_SUB_NAMESPACE); } public EurekaArchaius2TransportConfig(Config configInstance, String parentNamespace) { this(configInstance, parentNamespace, TRANSPORT_CONFIG_SUB_NAMESPACE); } public EurekaArchaius2TransportConfig(Config configInstance, String parentNamespace, String subNamespace) { this.configInstance = configInstance; this.prefixedConfig = new InternalPrefixedConfig(configInstance, parentNamespace, subNamespace); } @Override public int getSessionedClientReconnectIntervalSeconds() { return prefixedConfig.getInteger(SESSION_RECONNECT_INTERVAL_KEY, Values.SESSION_RECONNECT_INTERVAL); } @Override public double getRetryableClientQuarantineRefreshPercentage() { return prefixedConfig.getDouble(QUARANTINE_REFRESH_PERCENTAGE_KEY, Values.QUARANTINE_REFRESH_PERCENTAGE); } @Override public int getApplicationsResolverDataStalenessThresholdSeconds() { return prefixedConfig.getInteger(DATA_STALENESS_THRESHOLD_KEY, Values.DATA_STALENESS_TRHESHOLD); } @Override public boolean applicationsResolverUseIp() { return prefixedConfig.getBoolean(APPLICATION_RESOLVER_USE_IP_KEY, false); } @Override public int getAsyncResolverRefreshIntervalMs() { return prefixedConfig.getInteger(ASYNC_RESOLVER_REFRESH_INTERVAL_KEY, Values.ASYNC_RESOLVER_REFRESH_INTERVAL); } @Override public int getAsyncResolverWarmUpTimeoutMs() { return prefixedConfig.getInteger(ASYNC_RESOLVER_WARMUP_TIMEOUT_KEY, Values.ASYNC_RESOLVER_WARMUP_TIMEOUT); } @Override public int getAsyncExecutorThreadPoolSize() { return prefixedConfig.getInteger(ASYNC_EXECUTOR_THREADPOOL_SIZE_KEY, Values.ASYNC_EXECUTOR_THREADPOOL_SIZE); } @Override public String getWriteClusterVip() { return prefixedConfig.getString(WRITE_CLUSTER_VIP_KEY, null); } @Override public String getReadClusterVip() { return prefixedConfig.getString(READ_CLUSTER_VIP_KEY, null); } @Override public String getBootstrapResolverStrategy() { return prefixedConfig.getString(BOOTSTRAP_RESOLVER_STRATEGY_KEY, null); } @Override public boolean useBootstrapResolverForQuery() { return prefixedConfig.getBoolean(USE_BOOTSTRAP_RESOLVER_FOR_QUERY, true); } }
6,853
0
Create_ds/eureka/eureka-client-archaius2/src/main/java/com/netflix
Create_ds/eureka/eureka-client-archaius2/src/main/java/com/netflix/appinfo/Archaius2AmazonInfoConfig.java
package com.netflix.appinfo; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.annotations.ConfigurationSource; import com.netflix.discovery.CommonConstants; import com.netflix.discovery.internal.util.InternalPrefixedConfig; import javax.inject.Inject; import javax.inject.Singleton; import static com.netflix.appinfo.PropertyBasedAmazonInfoConfigConstants.*; /** * @author David Liu */ @Singleton @ConfigurationSource(CommonConstants.CONFIG_FILE_NAME) public class Archaius2AmazonInfoConfig implements AmazonInfoConfig { private final Config configInstance; private final InternalPrefixedConfig prefixedConfig; private final String namespace; @Inject public Archaius2AmazonInfoConfig(Config configInstance) { this(configInstance, CommonConstants.DEFAULT_CONFIG_NAMESPACE); } public Archaius2AmazonInfoConfig(Config configInstance, String namespace) { this.namespace = namespace; this.configInstance = configInstance; this.prefixedConfig = new InternalPrefixedConfig(configInstance, namespace); } @Override public String getNamespace() { return namespace; } @Override public boolean shouldLogAmazonMetadataErrors() { return prefixedConfig.getBoolean(LOG_METADATA_ERROR_KEY, false); } @Override public int getReadTimeout() { return prefixedConfig.getInteger(READ_TIMEOUT_KEY, Values.DEFAULT_READ_TIMEOUT); } @Override public int getConnectTimeout() { return prefixedConfig.getInteger(CONNECT_TIMEOUT_KEY, Values.DEFAULT_CONNECT_TIMEOUT); } @Override public int getNumRetries() { return prefixedConfig.getInteger(NUM_RETRIES_KEY, Values.DEFAULT_NUM_RETRIES); } @Override public boolean shouldFailFastOnFirstLoad() { return prefixedConfig.getBoolean(FAIL_FAST_ON_FIRST_LOAD_KEY, true); } @Override public boolean shouldValidateInstanceId() { return prefixedConfig.getBoolean(SHOULD_VALIDATE_INSTANCE_ID_KEY, true); } }
6,854
0
Create_ds/eureka/eureka-client-archaius2/src/main/java/com/netflix
Create_ds/eureka/eureka-client-archaius2/src/main/java/com/netflix/appinfo/Ec2EurekaArchaius2InstanceConfig.java
package com.netflix.appinfo; import javax.inject.Inject; import javax.inject.Provider; import javax.inject.Singleton; import com.netflix.discovery.CommonConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.appinfo.AmazonInfo.MetaDataKey; import com.netflix.archaius.api.Config; /** * When running in EC2 add the following override binding. * * bind(EurekaInstanceConfig.class).to(KaryonEc2EurekaInstanceConfig.class); * * * @author elandau * */ @Singleton public class Ec2EurekaArchaius2InstanceConfig extends EurekaArchaius2InstanceConfig implements RefreshableInstanceConfig { private static final Logger LOG = LoggerFactory.getLogger(Ec2EurekaArchaius2InstanceConfig.class); private static final String[] DEFAULT_AWS_ADDRESS_RESOLUTION_ORDER = new String[] { MetaDataKey.publicHostname.name(), MetaDataKey.localIpv4.name() }; private final AmazonInfoConfig amazonInfoConfig; private final Provider<AmazonInfo> amazonInfoHolder; @Inject public Ec2EurekaArchaius2InstanceConfig(Config configInstance, AmazonInfoConfig amazonInfoConfig) { this(configInstance, amazonInfoConfig, CommonConstants.DEFAULT_CONFIG_NAMESPACE); } /* visible for testing */ Ec2EurekaArchaius2InstanceConfig(Config configInstance, AmazonInfo info) { this(configInstance, new Archaius2AmazonInfoConfig(configInstance), CommonConstants.DEFAULT_CONFIG_NAMESPACE, info, false); } public Ec2EurekaArchaius2InstanceConfig(Config configInstance, Provider<AmazonInfo> amazonInfoProvider) { super(configInstance, CommonConstants.DEFAULT_CONFIG_NAMESPACE); this.amazonInfoConfig = null; this.amazonInfoHolder = amazonInfoProvider; } public Ec2EurekaArchaius2InstanceConfig(Config configInstance, Provider<AmazonInfo> amazonInfoProvider, String namespace) { super(configInstance, namespace); this.amazonInfoConfig = null; this.amazonInfoHolder = amazonInfoProvider; } public Ec2EurekaArchaius2InstanceConfig(Config configInstance, AmazonInfoConfig amazonInfoConfig, String namespace) { this(configInstance, amazonInfoConfig, namespace, null, true); } /* visible for testing */ Ec2EurekaArchaius2InstanceConfig(Config configInstance, AmazonInfoConfig amazonInfoConfig, String namespace, AmazonInfo initialInfo, boolean eagerInit) { super(configInstance, namespace); this.amazonInfoConfig = amazonInfoConfig; if (eagerInit) { RefreshableAmazonInfoProvider.FallbackAddressProvider fallbackAddressProvider = new RefreshableAmazonInfoProvider.FallbackAddressProvider() { @Override public String getFallbackIp() { return Ec2EurekaArchaius2InstanceConfig.super.getIpAddress(); } @Override public String getFallbackHostname() { return Ec2EurekaArchaius2InstanceConfig.super.getHostName(false); } }; this.amazonInfoHolder = new RefreshableAmazonInfoProvider(amazonInfoConfig, fallbackAddressProvider); } else { this.amazonInfoHolder = new RefreshableAmazonInfoProvider(initialInfo, amazonInfoConfig); } } @Override public String getHostName(boolean refresh) { if (refresh && this.amazonInfoHolder instanceof RefreshableAmazonInfoProvider) { ((RefreshableAmazonInfoProvider)amazonInfoHolder).refresh(); } return amazonInfoHolder.get().get(MetaDataKey.publicHostname); } @Override public DataCenterInfo getDataCenterInfo() { return amazonInfoHolder.get(); } @Override public String[] getDefaultAddressResolutionOrder() { String[] order = super.getDefaultAddressResolutionOrder(); return (order.length == 0) ? DEFAULT_AWS_ADDRESS_RESOLUTION_ORDER : order; } /** * @deprecated 2016-09-07 * * Refresh instance info - currently only used when in AWS cloud * as a public ip can change whenever an EIP is associated or dissociated. */ @Deprecated public synchronized void refreshAmazonInfo() { if (this.amazonInfoHolder instanceof RefreshableAmazonInfoProvider) { ((RefreshableAmazonInfoProvider)amazonInfoHolder).refresh(); } } @Override public String resolveDefaultAddress(boolean refresh) { // In this method invocation data center info will be refreshed. String result = getHostName(refresh); for (String name : getDefaultAddressResolutionOrder()) { try { AmazonInfo.MetaDataKey key = AmazonInfo.MetaDataKey.valueOf(name); String address = amazonInfoHolder.get().get(key); if (address != null && !address.isEmpty()) { result = address; break; } } catch (Exception e) { LOG.error("failed to resolve default address for key {}, skipping", name, e); } } return result; } }
6,855
0
Create_ds/eureka/eureka-client-archaius2/src/main/java/com/netflix
Create_ds/eureka/eureka-client-archaius2/src/main/java/com/netflix/appinfo/EurekaArchaius2InstanceConfig.java
package com.netflix.appinfo; import java.util.HashMap; import java.util.Map; import javax.inject.Inject; import javax.inject.Singleton; import com.google.common.collect.Sets; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.annotations.ConfigurationSource; import com.netflix.discovery.CommonConstants; import com.netflix.discovery.internal.util.InternalPrefixedConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.netflix.appinfo.PropertyBasedInstanceConfigConstants.*; @Singleton @ConfigurationSource(CommonConstants.CONFIG_FILE_NAME) public class EurekaArchaius2InstanceConfig extends AbstractInstanceConfig { private static final Logger logger = LoggerFactory.getLogger(EurekaArchaius2InstanceConfig.class); protected String namespace; private final Config configInstance; private final InternalPrefixedConfig prefixedConfig; private final DataCenterInfo dcInfo; private final String defaultAppGroup; @Inject public EurekaArchaius2InstanceConfig(Config configInstance) { this(configInstance, CommonConstants.DEFAULT_CONFIG_NAMESPACE); } public EurekaArchaius2InstanceConfig(Config configInstance, String namespace) { this(configInstance, namespace, new DataCenterInfo() { @Override public Name getName() { return Name.MyOwn; } }); } public EurekaArchaius2InstanceConfig(Config configInstance, String namespace, DataCenterInfo dcInfo) { this.defaultAppGroup = configInstance.getString(FALLBACK_APP_GROUP_KEY, Values.UNKNOWN_APPLICATION); this.namespace = namespace; this.configInstance = configInstance; this.prefixedConfig = new InternalPrefixedConfig(configInstance, namespace); this.dcInfo = dcInfo; } @Override public String getInstanceId() { String result = prefixedConfig.getString(INSTANCE_ID_KEY, null); return result == null ? null : result.trim(); } @Override public String getAppname() { return prefixedConfig.getString(APP_NAME_KEY, Values.UNKNOWN_APPLICATION).trim(); } @Override public String getAppGroupName() { return prefixedConfig.getString(APP_GROUP_KEY, defaultAppGroup).trim(); } @Override public boolean isInstanceEnabledOnit() { return prefixedConfig.getBoolean(TRAFFIC_ENABLED_ON_INIT_KEY, super.isInstanceEnabledOnit()); } @Override public int getNonSecurePort() { return prefixedConfig.getInteger(PORT_KEY, super.getNonSecurePort()); } @Override public int getSecurePort() { return prefixedConfig.getInteger(SECURE_PORT_KEY, super.getSecurePort()); } @Override public boolean isNonSecurePortEnabled() { return prefixedConfig.getBoolean(PORT_ENABLED_KEY, super.isNonSecurePortEnabled()); } @Override public boolean getSecurePortEnabled() { return prefixedConfig.getBoolean(SECURE_PORT_ENABLED_KEY, super.getSecurePortEnabled()); } @Override public int getLeaseRenewalIntervalInSeconds() { return prefixedConfig.getInteger(LEASE_RENEWAL_INTERVAL_KEY, super.getLeaseRenewalIntervalInSeconds()); } @Override public int getLeaseExpirationDurationInSeconds() { return prefixedConfig.getInteger(LEASE_EXPIRATION_DURATION_KEY, super.getLeaseExpirationDurationInSeconds()); } @Override public String getVirtualHostName() { return this.isNonSecurePortEnabled() ? prefixedConfig.getString(VIRTUAL_HOSTNAME_KEY, super.getVirtualHostName()) : null; } @Override public String getSecureVirtualHostName() { return this.getSecurePortEnabled() ? prefixedConfig.getString(SECURE_VIRTUAL_HOSTNAME_KEY, super.getSecureVirtualHostName()) : null; } @Override public String getASGName() { return prefixedConfig.getString(ASG_NAME_KEY, super.getASGName()); } @Override public Map<String, String> getMetadataMap() { Map<String, String> meta = new HashMap<>(); InternalPrefixedConfig metadataConfig = new InternalPrefixedConfig(configInstance, namespace, INSTANCE_METADATA_PREFIX); for (String key : Sets.newHashSet(metadataConfig.getKeys())) { String value = metadataConfig.getString(key, null); // only add the metadata if the value is present if (value != null && !value.isEmpty()) { meta.put(key, value); } else { logger.warn("Not adding metadata with key \"{}\" as it has null or empty value", key); } } return meta; } @Override public DataCenterInfo getDataCenterInfo() { return dcInfo; } @Override public String getStatusPageUrlPath() { return prefixedConfig.getString(STATUS_PAGE_URL_PATH_KEY, Values.DEFAULT_STATUSPAGE_URLPATH); } @Override public String getStatusPageUrl() { return prefixedConfig.getString(STATUS_PAGE_URL_KEY, null); } @Override public String getHomePageUrlPath() { return prefixedConfig.getString(HOME_PAGE_URL_PATH_KEY, Values.DEFAULT_HOMEPAGE_URLPATH); } @Override public String getHomePageUrl() { return prefixedConfig.getString(HOME_PAGE_URL_KEY, null); } @Override public String getHealthCheckUrlPath() { return prefixedConfig.getString(HEALTHCHECK_URL_PATH_KEY, Values.DEFAULT_HEALTHCHECK_URLPATH); } @Override public String getHealthCheckUrl() { return prefixedConfig.getString(HEALTHCHECK_URL_KEY, null); } @Override public String getSecureHealthCheckUrl() { return prefixedConfig.getString(SECURE_HEALTHCHECK_URL_KEY, null); } @Override public String[] getDefaultAddressResolutionOrder() { String result = prefixedConfig.getString(DEFAULT_ADDRESS_RESOLUTION_ORDER_KEY, null); return result == null ? new String[0] : result.split(","); } @Override public String getNamespace() { return namespace; } }
6,856
0
Create_ds/eureka/eureka-client-archaius2/src/main/java/com/netflix/appinfo
Create_ds/eureka/eureka-client-archaius2/src/main/java/com/netflix/appinfo/providers/CustomAmazonInfoProviderInstanceConfigFactory.java
package com.netflix.appinfo.providers; import com.netflix.appinfo.AmazonInfo; import com.netflix.appinfo.Ec2EurekaArchaius2InstanceConfig; import com.netflix.appinfo.EurekaInstanceConfig; import com.netflix.archaius.api.Config; import com.netflix.discovery.CommonConstants; import com.netflix.discovery.DiscoveryManager; import com.google.inject.Inject; import javax.inject.Named; import javax.inject.Provider; import javax.inject.Singleton; @Singleton public class CustomAmazonInfoProviderInstanceConfigFactory implements EurekaInstanceConfigFactory { private final Config configInstance; private final Provider<AmazonInfo> amazonInfoProvider; private EurekaInstanceConfig eurekaInstanceConfig; @Inject(optional = true) @Named(CommonConstants.INSTANCE_CONFIG_NAMESPACE_KEY) String instanceConfigNamespace; String getInstanceConfigNamespace() { return instanceConfigNamespace == null ? "eureka" : instanceConfigNamespace; } @Inject public CustomAmazonInfoProviderInstanceConfigFactory(Config configInstance, AmazonInfoProviderFactory amazonInfoProviderFactory) { this.configInstance = configInstance; this.amazonInfoProvider = amazonInfoProviderFactory.get(); } @Override public EurekaInstanceConfig get() { if (eurekaInstanceConfig == null) { eurekaInstanceConfig = new Ec2EurekaArchaius2InstanceConfig(configInstance, amazonInfoProvider, getInstanceConfigNamespace()); // Copied from CompositeInstanceConfigFactory.get DiscoveryManager.getInstance().setEurekaInstanceConfig(eurekaInstanceConfig); } return eurekaInstanceConfig; } }
6,857
0
Create_ds/eureka/eureka-client-archaius2/src/main/java/com/netflix/appinfo
Create_ds/eureka/eureka-client-archaius2/src/main/java/com/netflix/appinfo/providers/Archaius2VipAddressResolver.java
package com.netflix.appinfo.providers; import com.netflix.archaius.api.Config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.inject.Singleton; import java.util.regex.Matcher; import java.util.regex.Pattern; @Singleton public class Archaius2VipAddressResolver implements VipAddressResolver { private static final Logger logger = LoggerFactory.getLogger(Archaius2VipAddressResolver.class); private static final Pattern VIP_ATTRIBUTES_PATTERN = Pattern.compile("\\$\\{(.*?)\\}"); private final Config config; @Inject public Archaius2VipAddressResolver(Config config) { this.config = config; } @Override public String resolveDeploymentContextBasedVipAddresses(String vipAddressMacro) { if (vipAddressMacro == null) { return null; } String result = vipAddressMacro; Matcher matcher = VIP_ATTRIBUTES_PATTERN.matcher(result); while (matcher.find()) { String key = matcher.group(1); String value = config.getString(key, ""); logger.debug("att:{}", matcher.group()); logger.debug(", att key:{}", key); logger.debug(", att value:{}", value); logger.debug(""); result = result.replaceAll("\\$\\{" + key + "\\}", value); matcher = VIP_ATTRIBUTES_PATTERN.matcher(result); } return result; } }
6,858
0
Create_ds/eureka/eureka-client-archaius2/src/main/java/com/netflix/appinfo
Create_ds/eureka/eureka-client-archaius2/src/main/java/com/netflix/appinfo/providers/CompositeInstanceConfigFactory.java
package com.netflix.appinfo.providers; import com.netflix.appinfo.AmazonInfo; import com.netflix.appinfo.AmazonInfoConfig; import com.netflix.appinfo.Archaius2AmazonInfoConfig; import com.netflix.appinfo.Ec2EurekaArchaius2InstanceConfig; import com.netflix.appinfo.EurekaArchaius2InstanceConfig; import com.netflix.appinfo.EurekaInstanceConfig; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.annotations.ConfigurationSource; import com.netflix.discovery.CommonConstants; import com.netflix.discovery.DiscoveryManager; import com.netflix.discovery.internal.util.AmazonInfoUtils; import com.netflix.discovery.internal.util.InternalPrefixedConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.inject.Singleton; import java.net.SocketTimeoutException; import java.net.URL; /** * A factory for {@link com.netflix.appinfo.EurekaInstanceConfig} that can provide either * {@link com.netflix.appinfo.Ec2EurekaArchaius2InstanceConfig} or * {@link com.netflix.appinfo.EurekaArchaius2InstanceConfig} based on some selection strategy. * * If no config based override is applied, this Factory will automatically detect whether the * current deployment environment is EC2 or not, and create the appropriate Config instances. * * Setting the property <b>eureka.instanceDeploymentEnvironment=ec2</b> will force the instantiation * of {@link com.netflix.appinfo.Ec2EurekaArchaius2InstanceConfig}, regardless of what the * automatic environment detection says. * * Setting the property <b>eureka.instanceDeploymentEnvironment={a non-null, non-ec2 string}</b> * will force the instantiation of {@link com.netflix.appinfo.EurekaArchaius2InstanceConfig}, * regardless of what the automatic environment detection says. * * Why define the {@link com.netflix.appinfo.providers.EurekaInstanceConfigFactory} instead * of using {@link javax.inject.Provider} instead? Provider does not work due to the fact that * Guice treats Providers specially. * * @author David Liu */ @Singleton @ConfigurationSource(CommonConstants.CONFIG_FILE_NAME) public class CompositeInstanceConfigFactory implements EurekaInstanceConfigFactory { private static final Logger logger = LoggerFactory.getLogger(CompositeInstanceConfigFactory.class); private static final String DEPLOYMENT_ENVIRONMENT_OVERRIDE_KEY = "instanceDeploymentEnvironment"; private final String namespace; private final Config configInstance; private final InternalPrefixedConfig prefixedConfig; private EurekaInstanceConfig eurekaInstanceConfig; @Inject public CompositeInstanceConfigFactory(Config configInstance, String namespace) { this.configInstance = configInstance; this.namespace = namespace; this.prefixedConfig = new InternalPrefixedConfig(configInstance, namespace); } @Override public synchronized EurekaInstanceConfig get() { if (eurekaInstanceConfig == null) { // create the amazonInfoConfig before we can determine if we are in EC2, as we want to use the amazonInfoConfig for // that determination. This is just the config however so is cheap to do and does not have side effects. AmazonInfoConfig amazonInfoConfig = new Archaius2AmazonInfoConfig(configInstance, namespace); if (isInEc2(amazonInfoConfig)) { eurekaInstanceConfig = new Ec2EurekaArchaius2InstanceConfig(configInstance, amazonInfoConfig, namespace); logger.info("Creating EC2 specific instance config"); } else { eurekaInstanceConfig = new EurekaArchaius2InstanceConfig(configInstance, namespace); logger.info("Creating generic instance config"); } // TODO: Remove this when DiscoveryManager is finally no longer used DiscoveryManager.getInstance().setEurekaInstanceConfig(eurekaInstanceConfig); } return eurekaInstanceConfig; } private boolean isInEc2(AmazonInfoConfig amazonInfoConfig) { String deploymentEnvironmentOverride = getDeploymentEnvironmentOverride(); if (deploymentEnvironmentOverride == null) { return autoDetectEc2(amazonInfoConfig); } else if ("ec2".equalsIgnoreCase(deploymentEnvironmentOverride)) { logger.info("Assuming EC2 deployment environment due to config override"); return true; } else { return false; } } // best effort try to determine if we are in ec2 by trying to read the instanceId from metadata url private boolean autoDetectEc2(AmazonInfoConfig amazonInfoConfig) { try { URL url = AmazonInfo.MetaDataKey.instanceId.getURL(null, null); String id = AmazonInfoUtils.readEc2MetadataUrl( AmazonInfo.MetaDataKey.instanceId, url, amazonInfoConfig.getConnectTimeout(), amazonInfoConfig.getReadTimeout() ); if (id != null) { logger.info("Auto detected EC2 deployment environment, instanceId = {}", id); return true; } else { logger.info("Auto detected non-EC2 deployment environment, instanceId from metadata url is null"); return false; } } catch (SocketTimeoutException e) { logger.info("Auto detected non-EC2 deployment environment, connection to ec2 instance metadata url failed."); } catch (Exception e) { logger.warn("Failed to auto-detect whether we are in EC2 due to unexpected exception", e); } return false; } private String getDeploymentEnvironmentOverride() { return prefixedConfig.getString(DEPLOYMENT_ENVIRONMENT_OVERRIDE_KEY, null); } }
6,859
0
Create_ds/eureka/eureka-client-archaius2/src/main/java/com/netflix/appinfo
Create_ds/eureka/eureka-client-archaius2/src/main/java/com/netflix/appinfo/providers/AmazonInfoProviderFactory.java
package com.netflix.appinfo.providers; import com.netflix.appinfo.AmazonInfo; import javax.inject.Provider; public interface AmazonInfoProviderFactory { Provider<AmazonInfo> get(); }
6,860
0
Create_ds/eureka/eureka-client-archaius2/src/main/java/com/netflix/appinfo
Create_ds/eureka/eureka-client-archaius2/src/main/java/com/netflix/appinfo/providers/EurekaInstanceConfigFactory.java
package com.netflix.appinfo.providers; import com.netflix.appinfo.EurekaInstanceConfig; /** * An equivalent {@link javax.inject.Provider} interface for {@link com.netflix.appinfo.EurekaInstanceConfig}. * * Why define this {@link com.netflix.appinfo.providers.EurekaInstanceConfigFactory} instead * of using {@link javax.inject.Provider} instead? Provider does not work due to the fact that * Guice treats Providers specially. * * @author David Liu */ public interface EurekaInstanceConfigFactory { EurekaInstanceConfig get(); }
6,861
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/RemoteRegionSoftDependencyTest.java
package com.netflix.eureka; import com.netflix.eureka.mock.MockRemoteEurekaServer; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import static org.mockito.Mockito.doReturn; /** * @author Nitesh Kant */ public class RemoteRegionSoftDependencyTest extends AbstractTester { @Override @Before public void setUp() throws Exception { super.setUp(); doReturn(10).when(serverConfig).getWaitTimeInMsWhenSyncEmpty(); doReturn(1).when(serverConfig).getRegistrySyncRetries(); doReturn(1l).when(serverConfig).getRegistrySyncRetryWaitMs(); registry.syncUp(); } @Test public void testSoftDepRemoteDown() throws Exception { Assert.assertTrue("Registry access disallowed when remote region is down.", registry.shouldAllowAccess(false)); Assert.assertFalse("Registry access allowed when remote region is down.", registry.shouldAllowAccess(true)); } @Override protected MockRemoteEurekaServer newMockRemoteServer() { MockRemoteEurekaServer server = super.newMockRemoteServer(); server.simulateNotReady(true); return server; } }
6,862
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/RateLimitingFilterTest.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.eureka; import javax.servlet.FilterChain; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.netflix.appinfo.AbstractEurekaIdentity; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.EurekaClientIdentity; import com.netflix.appinfo.MyDataCenterInstanceConfig; import com.netflix.config.ConfigurationManager; import com.netflix.eureka.util.EurekaMonitors; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * @author Tomasz Bak */ @RunWith(MockitoJUnitRunner.class) public class RateLimitingFilterTest { private static final String FULL_FETCH = "base/apps"; private static final String DELTA_FETCH = "base/apps/delta"; private static final String APP_FETCH = "base/apps/myAppId"; private static final String CUSTOM_CLIENT = "CustomClient"; private static final String PYTHON_CLIENT = "PythonClient"; @Mock private HttpServletRequest request; @Mock private HttpServletResponse response; @Mock private FilterChain filterChain; private RateLimitingFilter filter; @Before public void setUp() throws Exception { RateLimitingFilter.reset(); ConfigurationManager.getConfigInstance().setProperty("eureka.rateLimiter.privilegedClients", PYTHON_CLIENT); ConfigurationManager.getConfigInstance().setProperty("eureka.rateLimiter.enabled", true); ConfigurationManager.getConfigInstance().setProperty("eureka.rateLimiter.burstSize", 2); ConfigurationManager.getConfigInstance().setProperty("eureka.rateLimiter.registryFetchAverageRate", 1); ConfigurationManager.getConfigInstance().setProperty("eureka.rateLimiter.fullFetchAverageRate", 1); ConfigurationManager.getConfigInstance().setProperty("eureka.rateLimiter.throttleStandardClients", false); ApplicationInfoManager applicationInfoManager = new ApplicationInfoManager(new MyDataCenterInstanceConfig()); DefaultEurekaServerConfig config = new DefaultEurekaServerConfig(); EurekaServerContext mockServer = mock(EurekaServerContext.class); when(mockServer.getServerConfig()).thenReturn(config); filter = new RateLimitingFilter(mockServer); } @Test public void testPrivilegedClientAlwaysServed() throws Exception { whenRequest(FULL_FETCH, PYTHON_CLIENT); filter.doFilter(request, response, filterChain); whenRequest(DELTA_FETCH, EurekaClientIdentity.DEFAULT_CLIENT_NAME); filter.doFilter(request, response, filterChain); whenRequest(APP_FETCH, EurekaServerIdentity.DEFAULT_SERVER_NAME); filter.doFilter(request, response, filterChain); verify(filterChain, times(3)).doFilter(request, response); verify(response, never()).setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } @Test public void testStandardClientsThrottlingEnforceable() throws Exception { ConfigurationManager.getConfigInstance().setProperty("eureka.rateLimiter.throttleStandardClients", true); // Custom clients will go up to the window limit whenRequest(FULL_FETCH, EurekaClientIdentity.DEFAULT_CLIENT_NAME); filter.doFilter(request, response, filterChain); filter.doFilter(request, response, filterChain); verify(filterChain, times(2)).doFilter(request, response); // Now we hit the limit long rateLimiterCounter = EurekaMonitors.RATE_LIMITED.getCount(); filter.doFilter(request, response, filterChain); assertEquals("Expected rate limiter counter increase", rateLimiterCounter + 1, EurekaMonitors.RATE_LIMITED.getCount()); verify(response, times(1)).setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } @Test public void testCustomClientShedding() throws Exception { // Custom clients will go up to the window limit whenRequest(FULL_FETCH, CUSTOM_CLIENT); filter.doFilter(request, response, filterChain); filter.doFilter(request, response, filterChain); verify(filterChain, times(2)).doFilter(request, response); // Now we hit the limit long rateLimiterCounter = EurekaMonitors.RATE_LIMITED.getCount(); filter.doFilter(request, response, filterChain); assertEquals("Expected rate limiter counter increase", rateLimiterCounter + 1, EurekaMonitors.RATE_LIMITED.getCount()); verify(response, times(1)).setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } @Test public void testCustomClientThrottlingCandidatesCounter() throws Exception { ConfigurationManager.getConfigInstance().setProperty("eureka.rateLimiter.enabled", false); // Custom clients will go up to the window limit whenRequest(FULL_FETCH, CUSTOM_CLIENT); filter.doFilter(request, response, filterChain); filter.doFilter(request, response, filterChain); verify(filterChain, times(2)).doFilter(request, response); // Now we hit the limit long rateLimiterCounter = EurekaMonitors.RATE_LIMITED_CANDIDATES.getCount(); filter.doFilter(request, response, filterChain); assertEquals("Expected rate limiter counter increase", rateLimiterCounter + 1, EurekaMonitors.RATE_LIMITED_CANDIDATES.getCount()); // We just test the counter verify(response, times(0)).setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } private void whenRequest(String path, String client) { when(request.getMethod()).thenReturn("GET"); when(request.getRequestURI()).thenReturn(path); when(request.getHeader(AbstractEurekaIdentity.AUTH_NAME_HEADER_KEY)).thenReturn(client); } }
6,863
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/GzipEncodingEnforcingFilterTest.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.eureka; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Enumeration; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; /** * @author Kebe Liu */ @RunWith(MockitoJUnitRunner.class) public class GzipEncodingEnforcingFilterTest { private static final String ACCEPT_ENCODING_HEADER = "Accept-Encoding"; @Mock private HttpServletRequest request; private HttpServletRequest filteredRequest; @Mock private HttpServletResponse response; @Mock private FilterChain filterChain; private GzipEncodingEnforcingFilter filter; @Before public void setUp() throws Exception { filter = new GzipEncodingEnforcingFilter(); filterChain = new FilterChain() { @Override public void doFilter(ServletRequest req, ServletResponse response) throws IOException, ServletException { filteredRequest = (HttpServletRequest) req; } }; } @Test public void testAlreadyGzip() throws Exception { gzipRequest(); filter.doFilter(request, response, filterChain); Enumeration values = filteredRequest.getHeaders(ACCEPT_ENCODING_HEADER); assertEquals("Expected Accept-Encoding null", null, values); } @Test public void testForceGzip() throws Exception { noneGzipRequest(); filter.doFilter(request, response, filterChain); String res = ""; Enumeration values = filteredRequest.getHeaders(ACCEPT_ENCODING_HEADER); while (values.hasMoreElements()) { res = res + values.nextElement() + "\n"; } assertEquals("Expected Accept-Encoding gzip", "gzip\n", res); } @Test public void testForceGzipOtherHeader() throws Exception { noneGzipRequest(); when(request.getHeaders("Test")).thenReturn(new Enumeration() { private int c = 0; @Override public boolean hasMoreElements() { return c == 0; } @Override public Object nextElement() { c++; return "ok"; } }); filter.doFilter(request, response, filterChain); String res = ""; Enumeration values = filteredRequest.getHeaders("Test"); while (values.hasMoreElements()) { res = res + values.nextElement() + "\n"; } assertEquals("Expected Test ok", "ok\n", res); } private void gzipRequest() { when(request.getMethod()).thenReturn("GET"); when(request.getHeader(ACCEPT_ENCODING_HEADER)).thenReturn("gzip"); } private void noneGzipRequest() { when(request.getMethod()).thenReturn("GET"); when(request.getHeader(ACCEPT_ENCODING_HEADER)).thenReturn(null); } }
6,864
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/DefaultEurekaServerConfigTest.java
package com.netflix.eureka; import java.util.Map; import java.util.Set; import com.netflix.config.ConfigurationManager; import org.junit.Assert; import org.junit.Test; /** * @author Nitesh Kant */ public class DefaultEurekaServerConfigTest { @Test public void testRemoteRegionUrlsWithName2Regions() throws Exception { String region1 = "myregion1"; String region1url = "http://local:888/eee"; String region2 = "myregion2"; String region2url = "http://local:888/eee"; ConfigurationManager.getConfigInstance().setProperty("eureka.remoteRegionUrlsWithName", region1 + ';' + region1url + ',' + region2 + ';' + region2url); DefaultEurekaServerConfig config = new DefaultEurekaServerConfig(); Map<String, String> remoteRegionUrlsWithName = config.getRemoteRegionUrlsWithName(); Assert.assertEquals("Unexpected remote region url count.", 2, remoteRegionUrlsWithName.size()); Assert.assertTrue("Remote region 1 not found.", remoteRegionUrlsWithName.containsKey(region1)); Assert.assertTrue("Remote region 2 not found.", remoteRegionUrlsWithName.containsKey(region2)); Assert.assertEquals("Unexpected remote region 1 url.", region1url, remoteRegionUrlsWithName.get(region1)); Assert.assertEquals("Unexpected remote region 2 url.", region2url, remoteRegionUrlsWithName.get(region2)); } @Test public void testRemoteRegionUrlsWithName1Region() throws Exception { String region1 = "myregion1"; String region1url = "http://local:888/eee"; ConfigurationManager.getConfigInstance().setProperty("eureka.remoteRegionUrlsWithName", region1 + ';' + region1url); DefaultEurekaServerConfig config = new DefaultEurekaServerConfig(); Map<String, String> remoteRegionUrlsWithName = config.getRemoteRegionUrlsWithName(); Assert.assertEquals("Unexpected remote region url count.", 1, remoteRegionUrlsWithName.size()); Assert.assertTrue("Remote region 1 not found.", remoteRegionUrlsWithName.containsKey(region1)); Assert.assertEquals("Unexpected remote region 1 url.", region1url, remoteRegionUrlsWithName.get(region1)); } @Test public void testGetGlobalAppWhiteList() throws Exception { String whitelistApp = "myapp"; ConfigurationManager.getConfigInstance().setProperty("eureka.remoteRegion.global.appWhiteList", whitelistApp); DefaultEurekaServerConfig config = new DefaultEurekaServerConfig(); Set<String> globalList = config.getRemoteRegionAppWhitelist(null); Assert.assertNotNull("Global whitelist is null.", globalList); Assert.assertEquals("Global whitelist not as expected.", 1, globalList.size()); Assert.assertEquals("Global whitelist not as expected.", whitelistApp, globalList.iterator().next()); } @Test public void testGetRegionAppWhiteList() throws Exception { String globalWhiteListApp = "myapp"; String regionWhiteListApp = "myapp"; ConfigurationManager.getConfigInstance().setProperty("eureka.remoteRegion.global.appWhiteList", globalWhiteListApp); ConfigurationManager.getConfigInstance().setProperty("eureka.remoteRegion.region1.appWhiteList", regionWhiteListApp); DefaultEurekaServerConfig config = new DefaultEurekaServerConfig(); Set<String> regionList = config.getRemoteRegionAppWhitelist(null); Assert.assertNotNull("Region whitelist is null.", regionList); Assert.assertEquals("Region whitelist not as expected.", 1, regionList.size()); Assert.assertEquals("Region whitelist not as expected.", regionWhiteListApp, regionList.iterator().next()); } }
6,865
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/AbstractTester.java
package com.netflix.eureka; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import com.google.common.collect.Lists; import com.netflix.appinfo.AmazonInfo; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.LeaseInfo; import com.netflix.appinfo.MyDataCenterInstanceConfig; import com.netflix.config.ConfigurationManager; import com.netflix.discovery.DefaultEurekaClientConfig; import com.netflix.discovery.DiscoveryClient; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Pair; import com.netflix.eureka.cluster.PeerEurekaNodes; import com.netflix.eureka.mock.MockRemoteEurekaServer; import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl; import com.netflix.eureka.resources.DefaultServerCodecs; import com.netflix.eureka.resources.ServerCodecs; import com.netflix.eureka.test.async.executor.SingleEvent; import org.junit.After; import org.junit.Before; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsNull.notNullValue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; /** * @author Nitesh Kant */ public class AbstractTester { public static final String REMOTE_REGION_NAME = "us-east-1"; public static final String REMOTE_REGION_APP_NAME = "MYAPP"; 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 = "MYLOCAPP"; 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_ZONE = "us-east-1c"; protected final List<Pair<String, String>> registeredApps = new ArrayList<>(); protected final Map<String, Application> remoteRegionApps = new HashMap<>(); protected final Map<String, Application> remoteRegionAppsDelta = new HashMap<>(); protected MockRemoteEurekaServer mockRemoteEurekaServer; protected EurekaServerConfig serverConfig; protected EurekaServerContext serverContext; protected EurekaClient client; protected PeerAwareInstanceRegistryImpl registry; @Before public void setUp() throws Exception { ConfigurationManager.getConfigInstance().clearProperty("eureka.remoteRegion.global.appWhiteList"); ConfigurationManager.getConfigInstance().setProperty("eureka.responseCacheAutoExpirationInSeconds", "10"); ConfigurationManager.getConfigInstance().clearProperty("eureka.remoteRegion." + REMOTE_REGION_NAME + ".appWhiteList"); ConfigurationManager.getConfigInstance().setProperty("eureka.deltaRetentionTimerIntervalInMs", "600000"); ConfigurationManager.getConfigInstance().setProperty("eureka.remoteRegion.registryFetchIntervalInSeconds", "5"); ConfigurationManager.getConfigInstance().setProperty("eureka.renewalThresholdUpdateIntervalMs", "5000"); ConfigurationManager.getConfigInstance().setProperty("eureka.evictionIntervalTimerInMs", "10000"); populateRemoteRegistryAtStartup(); mockRemoteEurekaServer = newMockRemoteServer(); mockRemoteEurekaServer.start(); ConfigurationManager.getConfigInstance().setProperty("eureka.remoteRegionUrlsWithName", REMOTE_REGION_NAME + ";http://localhost:" + mockRemoteEurekaServer.getPort() + MockRemoteEurekaServer.EUREKA_API_BASE_PATH); serverConfig = spy(new DefaultEurekaServerConfig()); InstanceInfo.Builder builder = InstanceInfo.Builder.newBuilder(); builder.setIPAddr("10.10.101.00"); builder.setHostName("Hosttt"); builder.setAppName("EurekaTestApp-" + UUID.randomUUID()); builder.setLeaseInfo(LeaseInfo.Builder.newBuilder().build()); builder.setDataCenterInfo(getDataCenterInfo()); ConfigurationManager.getConfigInstance().setProperty("eureka.serviceUrl.default", "http://localhost:" + mockRemoteEurekaServer.getPort() + MockRemoteEurekaServer.EUREKA_API_BASE_PATH); DefaultEurekaClientConfig clientConfig = new DefaultEurekaClientConfig(); // setup config in advance, used in initialize converter ApplicationInfoManager applicationInfoManager = new ApplicationInfoManager(new MyDataCenterInstanceConfig(), builder.build()); client = new DiscoveryClient(applicationInfoManager, clientConfig); ServerCodecs serverCodecs = new DefaultServerCodecs(serverConfig); registry = makePeerAwareInstanceRegistry(serverConfig, clientConfig, serverCodecs, client); serverContext = new DefaultEurekaServerContext( serverConfig, serverCodecs, registry, mock(PeerEurekaNodes.class), applicationInfoManager ); serverContext.initialize(); registry.openForTraffic(applicationInfoManager, 1); } protected DataCenterInfo getDataCenterInfo() { return new DataCenterInfo() { @Override public Name getName() { return Name.MyOwn; } }; } protected PeerAwareInstanceRegistryImpl makePeerAwareInstanceRegistry(EurekaServerConfig serverConfig, EurekaClientConfig clientConfig, ServerCodecs serverCodecs, EurekaClient eurekaClient) { return new TestPeerAwareInstanceRegistry(serverConfig, clientConfig, serverCodecs, eurekaClient); } protected MockRemoteEurekaServer newMockRemoteServer() { return new MockRemoteEurekaServer(0 /* use ephemeral */, remoteRegionApps, remoteRegionAppsDelta); } @After public void tearDown() throws Exception { for (Pair<String, String> registeredApp : registeredApps) { System.out.println("Canceling application: " + registeredApp.first() + " from local registry."); registry.cancel(registeredApp.first(), registeredApp.second(), false); } serverContext.shutdown(); mockRemoteEurekaServer.stop(); remoteRegionApps.clear(); remoteRegionAppsDelta.clear(); ConfigurationManager.getConfigInstance().clearProperty("eureka.remoteRegionUrls"); ConfigurationManager.getConfigInstance().clearProperty("eureka.deltaRetentionTimerIntervalInMs"); } private static Application createRemoteApps() { Application myapp = new Application(REMOTE_REGION_APP_NAME); InstanceInfo instanceInfo = createRemoteInstance(REMOTE_REGION_INSTANCE_1_HOSTNAME); //instanceInfo.setActionType(InstanceInfo.ActionType.MODIFIED); myapp.addInstance(instanceInfo); return myapp; } private static Application createRemoteAppsDelta() { Application myapp = new Application(REMOTE_REGION_APP_NAME); InstanceInfo instanceInfo = createRemoteInstance(REMOTE_REGION_INSTANCE_1_HOSTNAME); myapp.addInstance(instanceInfo); return myapp; } protected static InstanceInfo createRemoteInstance(String instanceHostName) { InstanceInfo.Builder instanceBuilder = InstanceInfo.Builder.newBuilder(); instanceBuilder.setAppName(REMOTE_REGION_APP_NAME); instanceBuilder.setHostName(instanceHostName); instanceBuilder.setIPAddr("10.10.101.1"); instanceBuilder.setDataCenterInfo(getAmazonInfo(REMOTE_ZONE, instanceHostName)); instanceBuilder.setLeaseInfo(LeaseInfo.Builder.newBuilder().build()); return instanceBuilder.build(); } protected static InstanceInfo createLocalInstance(String hostname) { return createLocalInstanceWithStatus(hostname, InstanceInfo.InstanceStatus.UP); } protected static InstanceInfo createLocalStartingInstance(String hostname) { return createLocalInstanceWithStatus(hostname, InstanceInfo.InstanceStatus.STARTING); } protected static InstanceInfo createLocalOutOfServiceInstance(String hostname) { return createLocalInstanceWithStatus(hostname, InstanceInfo.InstanceStatus.OUT_OF_SERVICE); } protected static InstanceInfo createLocalInstanceWithIdAndStatus(String hostname, String id, InstanceInfo.InstanceStatus status) { InstanceInfo.Builder instanceBuilder = InstanceInfo.Builder.newBuilder(); instanceBuilder.setInstanceId(id); instanceBuilder.setAppName(LOCAL_REGION_APP_NAME); instanceBuilder.setHostName(hostname); instanceBuilder.setIPAddr("10.10.101.1"); instanceBuilder.setDataCenterInfo(getAmazonInfo(null, hostname)); instanceBuilder.setLeaseInfo(LeaseInfo.Builder.newBuilder().build()); instanceBuilder.setStatus(status); return instanceBuilder.build(); } private static InstanceInfo createLocalInstanceWithStatus(String hostname, InstanceInfo.InstanceStatus status) { InstanceInfo.Builder instanceBuilder = InstanceInfo.Builder.newBuilder(); instanceBuilder.setInstanceId("foo"); instanceBuilder.setAppName(LOCAL_REGION_APP_NAME); instanceBuilder.setHostName(hostname); instanceBuilder.setIPAddr("10.10.101.1"); instanceBuilder.setDataCenterInfo(getAmazonInfo(null, hostname)); instanceBuilder.setLeaseInfo(LeaseInfo.Builder.newBuilder().build()); instanceBuilder.setStatus(status); return instanceBuilder.build(); } private 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(); } private void populateRemoteRegistryAtStartup() { Application myapp = createRemoteApps(); Application myappDelta = createRemoteAppsDelta(); remoteRegionApps.put(REMOTE_REGION_APP_NAME, myapp); remoteRegionAppsDelta.put(REMOTE_REGION_APP_NAME, myappDelta); } private static class TestPeerAwareInstanceRegistry extends PeerAwareInstanceRegistryImpl { public TestPeerAwareInstanceRegistry(EurekaServerConfig serverConfig, EurekaClientConfig clientConfig, ServerCodecs serverCodecs, EurekaClient eurekaClient) { super(serverConfig, clientConfig, serverCodecs, eurekaClient); } @Override public InstanceInfo getNextServerFromEureka(String virtualHostname, boolean secure) { return null; } } protected void verifyLocalInstanceStatus(String id, InstanceInfo.InstanceStatus status) { InstanceInfo instanceInfo = registry.getApplication(LOCAL_REGION_APP_NAME).getByInstanceId(id); assertThat("InstanceInfo with id " + id + " not found", instanceInfo, is(notNullValue())); assertThat("Invalid InstanceInfo state", instanceInfo.getStatus(), is(equalTo(status))); } protected void registerInstanceLocally(InstanceInfo remoteInstance) { registry.register(remoteInstance, 10000000, false); registeredApps.add(new Pair<String, String>(LOCAL_REGION_APP_NAME, remoteInstance.getId())); } protected void registerInstanceLocallyWithLeaseDurationInSecs(InstanceInfo remoteInstance, int leaseDurationInSecs) { registry.register(remoteInstance, leaseDurationInSecs, false); registeredApps.add(new Pair<String, String>(LOCAL_REGION_APP_NAME, remoteInstance.getId())); } /** * Send renewal request to Eureka server to renew lease for 45 instances. * * @return action. */ protected SingleEvent.Action renewPartOfTheWholeInstancesAction() { return new SingleEvent.Action() { @Override public void execute() { for (int j = 0; j < 45; j++) { registry.renew(LOCAL_REGION_APP_NAME, LOCAL_REGION_INSTANCE_1_HOSTNAME + j, false); } } }; } /** * Build one single event. * * @param intervalTimeInSecs the interval time from previous event. * @param action action to take. * @return single event. */ protected SingleEvent buildEvent(int intervalTimeInSecs, SingleEvent.Action action) { return SingleEvent.Builder.newBuilder() .withIntervalTimeInMs(intervalTimeInSecs * 1000) .withAction(action).build(); } /** * Build multiple {@link SingleEvent}. * * @param intervalTimeInSecs the interval time between those events. * @param eventCount total event count. * @param action action to take for every event. * @return list consisting of multiple single events. */ protected List<SingleEvent> buildEvents(int intervalTimeInSecs, int eventCount, SingleEvent.Action action) { List<SingleEvent> result = Lists.newArrayListWithCapacity(eventCount); for (int i = 0; i < eventCount; i++) { result.add(SingleEvent.Builder.newBuilder() .withIntervalTimeInMs(intervalTimeInSecs * 1000) .withAction(action).build()); } return result; } }
6,866
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/cluster/PeerEurekaNodeTest.java
package com.netflix.eureka.cluster; import java.util.List; import java.util.concurrent.TimeUnit; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.InstanceStatus; import com.netflix.discovery.shared.transport.ClusterSampleData; import com.netflix.eureka.EurekaServerConfig; import com.netflix.eureka.registry.PeerAwareInstanceRegistry; import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl.Action; import com.netflix.eureka.cluster.TestableHttpReplicationClient.HandledRequest; import com.netflix.eureka.cluster.TestableHttpReplicationClient.RequestType; import com.netflix.eureka.cluster.protocol.ReplicationInstance; import com.netflix.eureka.cluster.protocol.ReplicationList; import com.netflix.eureka.resources.ASGResource.ASGStatus; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; /** * @author Tomasz Bak */ public class PeerEurekaNodeTest { private static final int BATCH_SIZE = 10; private static final long MAX_BATCHING_DELAY_MS = 10; private final PeerAwareInstanceRegistry registry = mock(PeerAwareInstanceRegistry.class); private final TestableHttpReplicationClient httpReplicationClient = new TestableHttpReplicationClient(); private final InstanceInfo instanceInfo = ClusterSampleData.newInstanceInfo(1); private PeerEurekaNode peerEurekaNode; @Before public void setUp() throws Exception { httpReplicationClient.withNetworkStatusCode(200); httpReplicationClient.withBatchReply(200); } @After public void tearDown() throws Exception { if (peerEurekaNode != null) { peerEurekaNode.shutDown(); } } @Test public void testRegistrationBatchReplication() throws Exception { createPeerEurekaNode().register(instanceInfo); ReplicationInstance replicationInstance = expectSingleBatchRequest(); assertThat(replicationInstance.getAction(), is(equalTo(Action.Register))); } @Test public void testCancelBatchReplication() throws Exception { createPeerEurekaNode().cancel(instanceInfo.getAppName(), instanceInfo.getId()); ReplicationInstance replicationInstance = expectSingleBatchRequest(); assertThat(replicationInstance.getAction(), is(equalTo(Action.Cancel))); } @Test public void testHeartbeatBatchReplication() throws Throwable { createPeerEurekaNode().heartbeat(instanceInfo.getAppName(), instanceInfo.getId(), instanceInfo, null, false); ReplicationInstance replicationInstance = expectSingleBatchRequest(); assertThat(replicationInstance.getAction(), is(equalTo(Action.Heartbeat))); } @Test public void testHeartbeatReplicationFailure() throws Throwable { httpReplicationClient.withNetworkStatusCode(200, 200); httpReplicationClient.withBatchReply(404); // Not found, to trigger registration createPeerEurekaNode().heartbeat(instanceInfo.getAppName(), instanceInfo.getId(), instanceInfo, null, false); // Heartbeat replied with an error ReplicationInstance replicationInstance = expectSingleBatchRequest(); assertThat(replicationInstance.getAction(), is(equalTo(Action.Heartbeat))); // Second, registration task is scheduled replicationInstance = expectSingleBatchRequest(); assertThat(replicationInstance.getAction(), is(equalTo(Action.Register))); } @Test public void testHeartbeatWithInstanceInfoFromPeer() throws Throwable { InstanceInfo instanceInfoFromPeer = ClusterSampleData.newInstanceInfo(2); httpReplicationClient.withNetworkStatusCode(200); httpReplicationClient.withBatchReply(400); httpReplicationClient.withInstanceInfo(instanceInfoFromPeer); // InstanceInfo in response from peer will trigger local registry call createPeerEurekaNode().heartbeat(instanceInfo.getAppName(), instanceInfo.getId(), instanceInfo, null, false); expectRequestType(RequestType.Batch); // Check that registry has instanceInfo from peer verify(registry, timeout(1000).times(1)).register(instanceInfoFromPeer, true); } @Test public void testAsgStatusUpdate() throws Throwable { createPeerEurekaNode().statusUpdate(instanceInfo.getASGName(), ASGStatus.DISABLED); Object newAsgStatus = expectRequestType(RequestType.AsgStatusUpdate); assertThat(newAsgStatus, is(equalTo((Object) ASGStatus.DISABLED))); } @Test public void testStatusUpdateBatchReplication() throws Throwable { createPeerEurekaNode().statusUpdate(instanceInfo.getAppName(), instanceInfo.getId(), InstanceStatus.DOWN, instanceInfo); ReplicationInstance replicationInstance = expectSingleBatchRequest(); assertThat(replicationInstance.getAction(), is(equalTo(Action.StatusUpdate))); } @Test public void testDeleteStatusOverrideBatchReplication() throws Throwable { createPeerEurekaNode().deleteStatusOverride(instanceInfo.getAppName(), instanceInfo.getId(), instanceInfo); ReplicationInstance replicationInstance = expectSingleBatchRequest(); assertThat(replicationInstance.getAction(), is(equalTo(Action.DeleteStatusOverride))); } private PeerEurekaNode createPeerEurekaNode() { EurekaServerConfig config = ClusterSampleData.newEurekaServerConfig(); peerEurekaNode = new PeerEurekaNode( registry, "test", "http://test.host.com", httpReplicationClient, config, BATCH_SIZE, MAX_BATCHING_DELAY_MS, ClusterSampleData.RETRY_SLEEP_TIME_MS, ClusterSampleData.SERVER_UNAVAILABLE_SLEEP_TIME_MS ); return peerEurekaNode; } private Object expectRequestType(RequestType requestType) throws InterruptedException { HandledRequest handledRequest = httpReplicationClient.nextHandledRequest(60, TimeUnit.SECONDS); assertThat(handledRequest, is(notNullValue())); assertThat(handledRequest.getRequestType(), is(equalTo(requestType))); return handledRequest.getData(); } private ReplicationInstance expectSingleBatchRequest() throws InterruptedException { HandledRequest handledRequest = httpReplicationClient.nextHandledRequest(30, TimeUnit.SECONDS); assertThat(handledRequest, is(notNullValue())); assertThat(handledRequest.getRequestType(), is(equalTo(RequestType.Batch))); Object data = handledRequest.getData(); assertThat(data, is(instanceOf(ReplicationList.class))); List<ReplicationInstance> replications = ((ReplicationList) data).getReplicationList(); assertThat(replications.size(), is(equalTo(1))); return replications.get(0); } }
6,867
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/cluster/ReplicationTaskProcessorTest.java
package com.netflix.eureka.cluster; import java.util.Collections; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.util.InstanceInfoGenerator; import com.netflix.eureka.cluster.TestableInstanceReplicationTask.ProcessingState; import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl.Action; import com.netflix.eureka.util.batcher.TaskProcessor.ProcessingResult; import org.junit.Before; import org.junit.Test; import static com.netflix.eureka.cluster.TestableInstanceReplicationTask.aReplicationTask; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; /** * @author Tomasz Bak */ public class ReplicationTaskProcessorTest { private final TestableHttpReplicationClient replicationClient = new TestableHttpReplicationClient(); private ReplicationTaskProcessor replicationTaskProcessor; @Before public void setUp() throws Exception { replicationTaskProcessor = new ReplicationTaskProcessor("peerId#test", replicationClient); } @Test public void testNonBatchableTaskExecution() throws Exception { TestableInstanceReplicationTask task = aReplicationTask().withAction(Action.Heartbeat).withReplyStatusCode(200).build(); ProcessingResult status = replicationTaskProcessor.process(task); assertThat(status, is(ProcessingResult.Success)); } @Test public void testNonBatchableTaskCongestionFailureHandling() throws Exception { TestableInstanceReplicationTask task = aReplicationTask().withAction(Action.Heartbeat).withReplyStatusCode(503).build(); ProcessingResult status = replicationTaskProcessor.process(task); assertThat(status, is(ProcessingResult.Congestion)); assertThat(task.getProcessingState(), is(ProcessingState.Pending)); } @Test public void testNonBatchableTaskNetworkFailureHandling() throws Exception { TestableInstanceReplicationTask task = aReplicationTask().withAction(Action.Heartbeat).withNetworkFailures(1).build(); ProcessingResult status = replicationTaskProcessor.process(task); assertThat(status, is(ProcessingResult.TransientError)); assertThat(task.getProcessingState(), is(ProcessingState.Pending)); } @Test public void testNonBatchableTaskPermanentFailureHandling() throws Exception { TestableInstanceReplicationTask task = aReplicationTask().withAction(Action.Heartbeat).withReplyStatusCode(406).build(); ProcessingResult status = replicationTaskProcessor.process(task); assertThat(status, is(ProcessingResult.PermanentError)); assertThat(task.getProcessingState(), is(ProcessingState.Failed)); } @Test public void testBatchableTaskListExecution() throws Exception { TestableInstanceReplicationTask task = aReplicationTask().build(); replicationClient.withBatchReply(200); replicationClient.withNetworkStatusCode(200); ProcessingResult status = replicationTaskProcessor.process(Collections.<ReplicationTask>singletonList(task)); assertThat(status, is(ProcessingResult.Success)); assertThat(task.getProcessingState(), is(ProcessingState.Finished)); } @Test public void testBatchableTaskCongestionFailureHandling() throws Exception { TestableInstanceReplicationTask task = aReplicationTask().build(); replicationClient.withNetworkStatusCode(503); ProcessingResult status = replicationTaskProcessor.process(Collections.<ReplicationTask>singletonList(task)); assertThat(status, is(ProcessingResult.Congestion)); assertThat(task.getProcessingState(), is(ProcessingState.Pending)); } @Test public void testBatchableTaskNetworkReadTimeOutHandling() throws Exception { TestableInstanceReplicationTask task = aReplicationTask().build(); replicationClient.withReadtimeOut(1); ProcessingResult status = replicationTaskProcessor.process(Collections.<ReplicationTask>singletonList(task)); assertThat(status, is(ProcessingResult.Congestion)); assertThat(task.getProcessingState(), is(ProcessingState.Pending)); } @Test public void testBatchableTaskNetworkFailureHandling() throws Exception { TestableInstanceReplicationTask task = aReplicationTask().build(); replicationClient.withNetworkError(1); ProcessingResult status = replicationTaskProcessor.process(Collections.<ReplicationTask>singletonList(task)); assertThat(status, is(ProcessingResult.TransientError)); assertThat(task.getProcessingState(), is(ProcessingState.Pending)); } @Test public void testBatchableTaskPermanentFailureHandling() throws Exception { TestableInstanceReplicationTask task = aReplicationTask().build(); InstanceInfo instanceInfoFromPeer = InstanceInfoGenerator.takeOne(); replicationClient.withNetworkStatusCode(200); replicationClient.withBatchReply(400); replicationClient.withInstanceInfo(instanceInfoFromPeer); ProcessingResult status = replicationTaskProcessor.process(Collections.<ReplicationTask>singletonList(task)); assertThat(status, is(ProcessingResult.Success)); assertThat(task.getProcessingState(), is(ProcessingState.Failed)); } }
6,868
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/cluster/JerseyReplicationClientTest.java
package com.netflix.eureka.cluster; 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.resources.ASGResource.ASGStatus; import com.netflix.eureka.resources.DefaultServerCodecs; import com.netflix.eureka.resources.ServerCodecs; import com.netflix.eureka.transport.JerseyReplicationClient; 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 JerseyReplicationClientTest { @Rule public MockServerRule serverMockRule = new MockServerRule(this); private MockServerClient serverMockClient; private JerseyReplicationClient 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 = JerseyReplicationClient.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,869
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/cluster/TestableHttpReplicationClient.java
package com.netflix.eureka.cluster; import javax.ws.rs.core.MediaType; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; 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.EurekaHttpResponse; 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.resources.ASGResource.ASGStatus; import static com.netflix.discovery.shared.transport.EurekaHttpResponse.anEurekaHttpResponse; /** * This stub implementation is primarily useful for batch updates, and complex failure scenarios. * Using mock would results in too convoluted code. * * @author Tomasz Bak */ public class TestableHttpReplicationClient implements HttpReplicationClient { private int[] networkStatusCodes; private InstanceInfo instanceInfoFromPeer; private int networkFailuresRepeatCount; private int readtimeOutRepeatCount; private int batchStatusCode; private final AtomicInteger callCounter = new AtomicInteger(); private final AtomicInteger networkFailureCounter = new AtomicInteger(); private final AtomicInteger readTimeOutCounter = new AtomicInteger(); private long processingDelayMs; private final BlockingQueue<HandledRequest> handledRequests = new LinkedBlockingQueue<>(); public void withNetworkStatusCode(int... networkStatusCodes) { this.networkStatusCodes = networkStatusCodes; } public void withInstanceInfo(InstanceInfo instanceInfoFromPeer) { this.instanceInfoFromPeer = instanceInfoFromPeer; } public void withBatchReply(int batchStatusCode) { this.batchStatusCode = batchStatusCode; } public void withNetworkError(int networkFailuresRepeatCount) { this.networkFailuresRepeatCount = networkFailuresRepeatCount; } public void withReadtimeOut(int readtimeOutRepeatCount) { this.readtimeOutRepeatCount = readtimeOutRepeatCount; } public void withProcessingDelay(long processingDelay, TimeUnit timeUnit) { this.processingDelayMs = timeUnit.toMillis(processingDelay); } public HandledRequest nextHandledRequest(long timeout, TimeUnit timeUnit) throws InterruptedException { return handledRequests.poll(timeout, timeUnit); } @Override public EurekaHttpResponse<Void> register(InstanceInfo info) { handledRequests.add(new HandledRequest(RequestType.Register, info)); return EurekaHttpResponse.status(networkStatusCodes[callCounter.getAndIncrement()]); } @Override public EurekaHttpResponse<Void> cancel(String appName, String id) { handledRequests.add(new HandledRequest(RequestType.Cancel, id)); return EurekaHttpResponse.status(networkStatusCodes[callCounter.getAndIncrement()]); } @Override public EurekaHttpResponse<InstanceInfo> sendHeartBeat(String appName, String id, InstanceInfo info, InstanceStatus overriddenStatus) { handledRequests.add(new HandledRequest(RequestType.Heartbeat, instanceInfoFromPeer)); int statusCode = networkStatusCodes[callCounter.getAndIncrement()]; return anEurekaHttpResponse(statusCode, instanceInfoFromPeer).type(MediaType.APPLICATION_JSON_TYPE).build(); } @Override public EurekaHttpResponse<Void> statusUpdate(String asgName, ASGStatus newStatus) { handledRequests.add(new HandledRequest(RequestType.AsgStatusUpdate, newStatus)); return EurekaHttpResponse.status(networkStatusCodes[callCounter.getAndIncrement()]); } @Override public EurekaHttpResponse<Void> statusUpdate(String appName, String id, InstanceStatus newStatus, InstanceInfo info) { handledRequests.add(new HandledRequest(RequestType.StatusUpdate, newStatus)); return EurekaHttpResponse.status(networkStatusCodes[callCounter.getAndIncrement()]); } @Override public EurekaHttpResponse<Void> deleteStatusOverride(String appName, String id, InstanceInfo info) { handledRequests.add(new HandledRequest(RequestType.DeleteStatusOverride, null)); return EurekaHttpResponse.status(networkStatusCodes[callCounter.getAndIncrement()]); } @Override public EurekaHttpResponse<Applications> getApplications(String... regions) { throw new IllegalStateException("method not supported"); } @Override public EurekaHttpResponse<Applications> getDelta(String... regions) { throw new IllegalStateException("method not supported"); } @Override public EurekaHttpResponse<Applications> getVip(String vipAddress, String... regions) { throw new IllegalStateException("method not supported"); } @Override public EurekaHttpResponse<Applications> getSecureVip(String secureVipAddress, String... regions) { throw new IllegalStateException("method not supported"); } @Override public EurekaHttpResponse<Application> getApplication(String appName) { throw new IllegalStateException("method not supported"); } @Override public EurekaHttpResponse<InstanceInfo> getInstance(String id) { throw new IllegalStateException("method not supported"); } @Override public EurekaHttpResponse<InstanceInfo> getInstance(String appName, String id) { throw new IllegalStateException("method not supported"); } @Override public EurekaHttpResponse<ReplicationListResponse> submitBatchUpdates(ReplicationList replicationList) { if (readTimeOutCounter.get() < readtimeOutRepeatCount) { readTimeOutCounter.incrementAndGet(); throw new RuntimeException(new SocketTimeoutException("Read timed out")); } if (networkFailureCounter.get() < networkFailuresRepeatCount) { networkFailureCounter.incrementAndGet(); throw new RuntimeException(new IOException("simulated network failure")); } if (processingDelayMs > 0) { try { Thread.sleep(processingDelayMs); } catch (InterruptedException e) { throw new RuntimeException(e); } } List<ReplicationInstanceResponse> responseList = new ArrayList<>(); responseList.add(new ReplicationInstanceResponse(batchStatusCode, instanceInfoFromPeer)); ReplicationListResponse replicationListResponse = new ReplicationListResponse(responseList); handledRequests.add(new HandledRequest(RequestType.Batch, replicationList)); int statusCode = networkStatusCodes[callCounter.getAndIncrement()]; return anEurekaHttpResponse(statusCode, replicationListResponse).type(MediaType.APPLICATION_JSON_TYPE).build(); } @Override public void shutdown() { } public enum RequestType {Heartbeat, Register, Cancel, StatusUpdate, DeleteStatusOverride, AsgStatusUpdate, Batch} public static class HandledRequest { private final RequestType requestType; private final Object data; public HandledRequest(RequestType requestType, Object data) { this.requestType = requestType; this.data = data; } public RequestType getRequestType() { return requestType; } public Object getData() { return data; } } }
6,870
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/cluster/PeerEurekaNodesTest.java
package com.netflix.eureka.cluster; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.discovery.DefaultEurekaClientConfig; import com.netflix.discovery.shared.transport.ClusterSampleData; import com.netflix.eureka.EurekaServerConfig; import com.netflix.eureka.registry.PeerAwareInstanceRegistry; import com.netflix.eureka.resources.DefaultServerCodecs; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; 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 Tomasz Bak */ public class PeerEurekaNodesTest { private static final String PEER_EUREKA_URL_A = "http://a.eureka.test"; private static final String PEER_EUREKA_URL_B = "http://b.eureka.test"; private static final String PEER_EUREKA_URL_C = "http://c.eureka.test"; private final PeerAwareInstanceRegistry registry = mock(PeerAwareInstanceRegistry.class); private final TestablePeerEurekaNodes peerEurekaNodes = new TestablePeerEurekaNodes(registry, ClusterSampleData.newEurekaServerConfig()); @Test public void testInitialStartupShutdown() throws Exception { peerEurekaNodes.withPeerUrls(PEER_EUREKA_URL_A); // Start peerEurekaNodes.start(); PeerEurekaNode peerNode = getPeerNode(PEER_EUREKA_URL_A); assertThat(peerNode, is(notNullValue())); // Shutdown peerEurekaNodes.shutdown(); verify(peerNode, times(1)).shutDown(); } @Test public void testReloadWithNoPeerChange() throws Exception { // Start peerEurekaNodes.withPeerUrls(PEER_EUREKA_URL_A); peerEurekaNodes.start(); PeerEurekaNode peerNode = getPeerNode(PEER_EUREKA_URL_A); assertThat(peerEurekaNodes.awaitNextReload(60, TimeUnit.SECONDS), is(true)); assertThat(getPeerNode(PEER_EUREKA_URL_A), is(equalTo(peerNode))); } @Test public void testReloadWithPeerUpdates() throws Exception { // Start peerEurekaNodes.withPeerUrls(PEER_EUREKA_URL_A); peerEurekaNodes.start(); PeerEurekaNode peerNodeA = getPeerNode(PEER_EUREKA_URL_A); // Add one more peer peerEurekaNodes.withPeerUrls(PEER_EUREKA_URL_A, PEER_EUREKA_URL_B); assertThat(peerEurekaNodes.awaitNextReload(60, TimeUnit.SECONDS), is(true)); assertThat(getPeerNode(PEER_EUREKA_URL_A), is(notNullValue())); assertThat(getPeerNode(PEER_EUREKA_URL_B), is(notNullValue())); // Remove first peer, and add yet another one peerEurekaNodes.withPeerUrls(PEER_EUREKA_URL_B, PEER_EUREKA_URL_C); assertThat(peerEurekaNodes.awaitNextReload(60, TimeUnit.SECONDS), is(true)); assertThat(getPeerNode(PEER_EUREKA_URL_A), is(nullValue())); assertThat(getPeerNode(PEER_EUREKA_URL_B), is(notNullValue())); assertThat(getPeerNode(PEER_EUREKA_URL_C), is(notNullValue())); verify(peerNodeA, times(1)).shutDown(); } private PeerEurekaNode getPeerNode(String peerEurekaUrl) { for (PeerEurekaNode node : peerEurekaNodes.getPeerEurekaNodes()) { if (node.getServiceUrl().equals(peerEurekaUrl)) { return node; } } return null; } static class TestablePeerEurekaNodes extends PeerEurekaNodes { private AtomicReference<List<String>> peerUrlsRef = new AtomicReference<>(Collections.<String>emptyList()); private final ConcurrentHashMap<String, PeerEurekaNode> peerEurekaNodeByUrl = new ConcurrentHashMap<>(); private final AtomicInteger reloadCounter = new AtomicInteger(); TestablePeerEurekaNodes(PeerAwareInstanceRegistry registry, EurekaServerConfig serverConfig) { super(registry, serverConfig, new DefaultEurekaClientConfig(), new DefaultServerCodecs(serverConfig), mock(ApplicationInfoManager.class) ); } void withPeerUrls(String... peerUrls) { this.peerUrlsRef.set(Arrays.asList(peerUrls)); } boolean awaitNextReload(long timeout, TimeUnit timeUnit) throws InterruptedException { int lastReloadCounter = reloadCounter.get(); long endTime = System.currentTimeMillis() + timeUnit.toMillis(timeout); while (endTime > System.currentTimeMillis() && lastReloadCounter == reloadCounter.get()) { Thread.sleep(10); } return lastReloadCounter != reloadCounter.get(); } @Override protected void updatePeerEurekaNodes(List<String> newPeerUrls) { super.updatePeerEurekaNodes(newPeerUrls); reloadCounter.incrementAndGet(); } @Override protected List<String> resolvePeerUrls() { return peerUrlsRef.get(); } @Override protected PeerEurekaNode createPeerEurekaNode(String peerEurekaNodeUrl) { if (peerEurekaNodeByUrl.containsKey(peerEurekaNodeUrl)) { throw new IllegalStateException("PeerEurekaNode for URL " + peerEurekaNodeUrl + " is already created"); } PeerEurekaNode peerEurekaNode = mock(PeerEurekaNode.class); when(peerEurekaNode.getServiceUrl()).thenReturn(peerEurekaNodeUrl); return peerEurekaNode; } } }
6,871
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/cluster/TestableInstanceReplicationTask.java
package com.netflix.eureka.cluster; import java.io.IOException; import java.util.concurrent.atomic.AtomicReference; import com.netflix.discovery.shared.transport.EurekaHttpResponse; import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl.Action; /** * @author Tomasz Bak */ class TestableInstanceReplicationTask extends InstanceReplicationTask { public static final String APP_NAME = "testableReplicationTaskApp"; public enum ProcessingState {Pending, Finished, Failed} private final int replyStatusCode; private final int networkFailuresRepeatCount; private final AtomicReference<ProcessingState> processingState = new AtomicReference<>(ProcessingState.Pending); private volatile int triggeredNetworkFailures; TestableInstanceReplicationTask(String peerNodeName, String appName, String id, Action action, int replyStatusCode, int networkFailuresRepeatCount) { super(peerNodeName, action, appName, id); this.replyStatusCode = replyStatusCode; this.networkFailuresRepeatCount = networkFailuresRepeatCount; } @Override public EurekaHttpResponse<Void> execute() throws Throwable { if (triggeredNetworkFailures < networkFailuresRepeatCount) { triggeredNetworkFailures++; throw new IOException("simulated network failure"); } return EurekaHttpResponse.status(replyStatusCode); } @Override public void handleSuccess() { processingState.compareAndSet(ProcessingState.Pending, ProcessingState.Finished); } @Override public void handleFailure(int statusCode, Object responseEntity) throws Throwable { processingState.compareAndSet(ProcessingState.Pending, ProcessingState.Failed); } public ProcessingState getProcessingState() { return processingState.get(); } public static TestableReplicationTaskBuilder aReplicationTask() { return new TestableReplicationTaskBuilder(); } static class TestableReplicationTaskBuilder { private int autoId; private int replyStatusCode = 200; private Action action = Action.Heartbeat; private int networkFailuresRepeatCount; public TestableReplicationTaskBuilder withReplyStatusCode(int replyStatusCode) { this.replyStatusCode = replyStatusCode; return this; } public TestableReplicationTaskBuilder withAction(Action action) { this.action = action; return this; } public TestableReplicationTaskBuilder withNetworkFailures(int networkFailuresRepeatCount) { this.networkFailuresRepeatCount = networkFailuresRepeatCount; return this; } public TestableInstanceReplicationTask build() { return new TestableInstanceReplicationTask( "peerNodeName#test", APP_NAME, "id#" + autoId++, action, replyStatusCode, networkFailuresRepeatCount ); } } }
6,872
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/cluster
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/cluster/protocol/JacksonEncodingTest.java
package com.netflix.eureka.cluster.protocol; import com.netflix.discovery.converters.EurekaJacksonCodec; import com.netflix.discovery.shared.transport.ClusterSampleData; 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 JacksonEncodingTest { private final EurekaJacksonCodec jacksonCodec = new EurekaJacksonCodec(); @Test public void testReplicationInstanceEncoding() throws Exception { ReplicationInstance replicationInstance = ClusterSampleData.newReplicationInstance(); // Encode / decode String jsonText = jacksonCodec.writeToString(replicationInstance); ReplicationInstance decodedValue = jacksonCodec.readValue(ReplicationInstance.class, jsonText); assertThat(decodedValue, is(equalTo(replicationInstance))); } @Test public void testReplicationInstanceResponseEncoding() throws Exception { ReplicationInstanceResponse replicationInstanceResponse = ClusterSampleData.newReplicationInstanceResponse(true); // Encode / decode String jsonText = jacksonCodec.writeToString(replicationInstanceResponse); ReplicationInstanceResponse decodedValue = jacksonCodec.readValue(ReplicationInstanceResponse.class, jsonText); assertThat(decodedValue, is(equalTo(replicationInstanceResponse))); } @Test public void testReplicationListEncoding() throws Exception { ReplicationList replicationList = new ReplicationList(); replicationList.addReplicationInstance(ClusterSampleData.newReplicationInstance()); // Encode / decode String jsonText = jacksonCodec.writeToString(replicationList); ReplicationList decodedValue = jacksonCodec.readValue(ReplicationList.class, jsonText); assertThat(decodedValue, is(equalTo(replicationList))); } @Test public void testReplicationListResponseEncoding() throws Exception { ReplicationListResponse replicationListResponse = new ReplicationListResponse(); replicationListResponse.addResponse(ClusterSampleData.newReplicationInstanceResponse(false)); // Encode / decode String jsonText = jacksonCodec.writeToString(replicationListResponse); ReplicationListResponse decodedValue = jacksonCodec.readValue(ReplicationListResponse.class, jsonText); assertThat(decodedValue, is(equalTo(replicationListResponse))); } }
6,873
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/test/async
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/test/async/executor/AsyncResult.java
package com.netflix.eureka.test.async.executor; import java.util.concurrent.Future; /** * Async result which extends {@link Future}. * * @param <T> The result type. */ public interface AsyncResult<T> extends Future<T> { /** * Handle result normally. * * @param result result. */ void handleResult(T result); /** * Handle error. * * @param error error during execution. */ void handleError(Throwable error); /** * Get result which will be blocked until the result is available or an error occurs. */ T getResult() throws AsyncExecutorException; /** * Get error if possible. * * @return error. */ Throwable getError(); }
6,874
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/test/async
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/test/async/executor/Backoff.java
package com.netflix.eureka.test.async.executor; /** * Backoff for pausing for a duration */ public class Backoff { /** * Pause time in milliseconds */ private final int pauseTimeInMs; /** * Prepare to pause for one duration. * * @param pauseTimeInMs pause time in milliseconds */ public Backoff(int pauseTimeInMs) { this.pauseTimeInMs = pauseTimeInMs; } /** * Backoff for one duration. */ public void backoff() throws InterruptedException { Thread.sleep(pauseTimeInMs); } }
6,875
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/test/async
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/test/async/executor/AsyncExecutorException.java
package com.netflix.eureka.test.async.executor; /** * Async executor exception for {@link ConcreteAsyncResult}. */ public class AsyncExecutorException extends RuntimeException { public AsyncExecutorException() { } public AsyncExecutorException(String message) { super(message); } public AsyncExecutorException(String message, Throwable cause) { super(message, cause); } public AsyncExecutorException(Throwable cause) { super(cause); } public AsyncExecutorException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
6,876
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/test/async
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/test/async/executor/AsyncSequentialExecutor.java
package com.netflix.eureka.test.async.executor; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicInteger; import com.amazonaws.util.CollectionUtils; import com.google.common.base.Optional; /** * Run a sequential events in asynchronous way. */ public class AsyncSequentialExecutor { /** * Index for thread naming */ private static final AtomicInteger INDEX = new AtomicInteger(0); /** * Result status, if events are executed successfully in sequential manner, then return this by default */ public enum ResultStatus { DONE } /** * Run a sequential events in asynchronous way. An result holder will be returned to the caller. * If calling is successful, then will return {@link ResultStatus#DONE}, or else exception will * be thrown and {@link AsyncResult} will be filled with the error. * * @param events sequential events. * @return result holder. */ public AsyncResult<ResultStatus> run(SequentialEvents events) { return run(new Callable<ResultStatus>() { @Override public ResultStatus call() throws Exception { if (events == null || CollectionUtils.isNullOrEmpty(events.getEventList())) { throw new IllegalArgumentException("SequentialEvents does not contain any event to run"); } for (SingleEvent singleEvent : events.getEventList()) { new Backoff(singleEvent.getIntervalTimeInMs()).backoff(); singleEvent.getAction().execute(); } return ResultStatus.DONE; } }); } /** * Run task in a thread. * * @param task task to run. */ protected <T> AsyncResult<T> run(Callable<T> task) { final AsyncResult<T> result = new ConcreteAsyncResult<>(); new Thread(new Runnable() { @Override public void run() { T value = null; Optional<Exception> e = Optional.absent(); try { value = task.call(); result.handleResult(value); } catch (Exception e1) { e = Optional.of(e1); result.handleError(e1); } } }, "AsyncSequentialExecutor-" + INDEX.incrementAndGet()).start(); return result; } }
6,877
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/test/async
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/test/async/executor/ConcreteAsyncResult.java
package com.netflix.eureka.test.async.executor; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * Async result which is usually hold be caller to retrieve result or error. */ public class ConcreteAsyncResult<T> implements AsyncResult<T> { private final CountDownLatch latch = new CountDownLatch(1); private T result = null; private Throwable error = null; public ConcreteAsyncResult() { } /** * Sets the result and unblocks all threads waiting on {@link #get()} or {@link #get(long, TimeUnit)}. * * @param result the result to set. */ @Override public void handleResult(T result) { this.result = result; latch.countDown(); } /** * Sets an error thrown during execution, and unblocks all threads waiting on {@link #get()} or * {@link #get(long, TimeUnit)}. * * @param error the RPC error to set. */ public void handleError(Throwable error) { this.error = error; latch.countDown(); } /** * Gets the value of the result in blocking way. Using {@link #get()} or {@link #get(long, TimeUnit)} is * usually preferred because these methods block until the result is available or an error occurs. * * @return the value of the response, or null if no result was returned or the RPC has not yet completed. */ public T getResult() throws AsyncExecutorException { return get(); } /** * Gets the error that was thrown during execution. Does not block. Either {@link #get()} or * {@link #get(long, TimeUnit)} should be called first because these methods block until execution has completed. * * @return the error that was thrown, or null if no error has occurred or if the execution has not yet completed. */ public Throwable getError() { return error; } public boolean cancel(boolean mayInterruptIfRunning) { latch.countDown(); return false; } public boolean isCancelled() { return false; } public T get() throws AsyncExecutorException { try { latch.await(); } catch (InterruptedException e) { throw new AsyncExecutorException("Interrupted", error); } if (error != null) { if (error instanceof AsyncExecutorException) { throw (AsyncExecutorException) error; } else { throw new AsyncExecutorException("Execution exception", error); } } return result; } public T get(long timeout, TimeUnit unit) throws AsyncExecutorException { try { if (latch.await(timeout, unit)) { if (error != null) { if (error instanceof AsyncExecutorException) { throw (AsyncExecutorException) error; } else { throw new RuntimeException("call future get exception", error); } } return result; } else { throw new AsyncExecutorException("async get time out"); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new AsyncExecutorException("call future is interuptted", e); } } /** * Waits for the CallFuture to complete without returning the result. * * @throws InterruptedException if interrupted. */ public void await() throws InterruptedException { latch.await(); } /** * Waits for the CallFuture to complete without returning the result. * * @param timeout the maximum time to wait. * @param unit the time unit of the timeout argument. * @throws InterruptedException if interrupted. * @throws TimeoutException if the wait timed out. */ public void await(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { if (!latch.await(timeout, unit)) { throw new TimeoutException(); } } public boolean isDone() { return latch.getCount() <= 0; } }
6,878
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/test/async
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/test/async/executor/SingleEvent.java
package com.netflix.eureka.test.async.executor; import com.google.common.base.Preconditions; /** * Single event which represents the action that will be executed in a time line. */ public class SingleEvent { /** * Interval time between the previous event. */ private int intervalTimeInMs; /** * Action to take. */ private Action action; /** * Constructor. */ public SingleEvent(int intervalTimeInMs, Action action) { this.intervalTimeInMs = intervalTimeInMs; this.action = action; } public int getIntervalTimeInMs() { return intervalTimeInMs; } public Action getAction() { return action; } /** * SingleEvent builder. */ public static final class Builder { /** * Interval time between the previous event. */ private int intervalTimeInMs; /** * Action to take. */ private Action action; private Builder() { } public static Builder newBuilder() { return new Builder(); } public Builder withIntervalTimeInMs(int intervalTimeInMs) { this.intervalTimeInMs = intervalTimeInMs; return this; } public Builder withAction(Action action) { this.action = action; return this; } public SingleEvent build() { Preconditions.checkNotNull(intervalTimeInMs, "IntervalTimeInMs is not set for SingleEvent"); Preconditions.checkNotNull(action, "Action is not set for SingleEvent"); return new SingleEvent(intervalTimeInMs, action); } } @Override public String toString() { return "SingleEvent{" + "intervalTimeInMs=" + intervalTimeInMs + ", action=" + action + '}'; } /** * Action to perform. */ public interface Action { void execute(); } }
6,879
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/test/async
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/test/async/executor/SequentialEvents.java
package com.netflix.eureka.test.async.executor; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.google.common.base.Preconditions; /** * SequentialEvents represents multiple events which should be executed in a * sequential manner. */ public class SequentialEvents { /** * Multiple single events. */ private List<SingleEvent> eventList; /** * Default constructor. * * @param eventList event list. */ private SequentialEvents(List<SingleEvent> eventList) { this.eventList = eventList; } /** * Instance creator. * * @return SequentialEvents. */ public static SequentialEvents newInstance() { return new SequentialEvents(new ArrayList<>()); } /** * Instance creator with expected event list size. * * @param expectedEventListSize expected event list size. * @return SequentialEvents. */ public static SequentialEvents newInstance(int expectedEventListSize) { return new SequentialEvents(new ArrayList<>(expectedEventListSize)); } /** * Build sequential events from multiple single events. * * @param event a bunch of single events. * @return SequentialEvents. */ public static SequentialEvents of(SingleEvent... events) { return new SequentialEvents(Arrays.asList(events)); } /** * Build sequential events from multiple single events. * * @param eventList a bunch of single events. * @return SequentialEvents. */ public static SequentialEvents of(List<SingleEvent> eventList) { return new SequentialEvents(eventList); } /** * Add one more single event to sequential events. * * @param event one event. * @return SequentialEvents. */ public SequentialEvents with(SingleEvent event) { Preconditions.checkNotNull(eventList, "eventList should not be null"); this.eventList.add(event); return this; } /** * Get event lists. * * @return event lists. */ public List<SingleEvent> getEventList() { return eventList; } @Override public String toString() { return "SequentialEvents{" + "eventList=" + eventList + '}'; } }
6,880
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/util/StatusUtilTest.java
package com.netflix.eureka.util; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.junit.Test; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.transport.EurekaTransportConfig; import com.netflix.eureka.EurekaServerConfig; import com.netflix.eureka.EurekaServerContext; import com.netflix.eureka.cluster.PeerEurekaNode; import com.netflix.eureka.cluster.PeerEurekaNodes; import com.netflix.eureka.registry.PeerAwareInstanceRegistry; public class StatusUtilTest { @Test public void testGetStatusInfoHealthy() { StatusUtil statusUtil = getStatusUtil(3, 3, 2); assertTrue(statusUtil.getStatusInfo().isHealthy()); } @Test public void testGetStatusInfoUnhealthy() { StatusUtil statusUtil = getStatusUtil(5, 3, 4); assertFalse(statusUtil.getStatusInfo().isHealthy()); } @Test public void testGetStatusInfoUnsetHealth() { StatusUtil statusUtil = getStatusUtil(5, 3, -1); StatusInfo statusInfo = statusUtil.getStatusInfo(); try { statusInfo.isHealthy(); } catch (NullPointerException e) { // Expected that the healthy flag is not set when the minimum value is -1 return; } fail("Excpected NPE to be thrown when healthy threshold is not set"); } /** * @param replicas the number of replicas to mock * @param instances the number of instances to mock * @param minimum the minimum number of peers * @return the status utility with the mocked replicas/instances */ private StatusUtil getStatusUtil(int replicas, int instances, int minimum) { EurekaServerContext mockEurekaServerContext = mock(EurekaServerContext.class); List<InstanceInfo> mockInstanceInfos = getMockInstanceInfos(instances); Application mockApplication = mock(Application.class); when(mockApplication.getInstances()).thenReturn(mockInstanceInfos); ApplicationInfoManager mockAppInfoManager = mock(ApplicationInfoManager.class); when(mockAppInfoManager.getInfo()).thenReturn(mockInstanceInfos.get(0)); when(mockEurekaServerContext.getApplicationInfoManager()).thenReturn(mockAppInfoManager); PeerAwareInstanceRegistry mockRegistry = mock(PeerAwareInstanceRegistry.class); when(mockRegistry.getApplication("stuff", false)).thenReturn(mockApplication); when(mockEurekaServerContext.getRegistry()).thenReturn(mockRegistry); List<PeerEurekaNode> mockNodes = getMockNodes(replicas); EurekaTransportConfig mockTransportConfig = mock(EurekaTransportConfig.class); when(mockTransportConfig.applicationsResolverUseIp()).thenReturn(false); EurekaClientConfig mockClientConfig = mock(EurekaClientConfig.class); when(mockClientConfig.getTransportConfig()).thenReturn(mockTransportConfig); EurekaServerConfig mockServerConfig = mock(EurekaServerConfig.class); when(mockServerConfig.getHealthStatusMinNumberOfAvailablePeers()).thenReturn(minimum); PeerEurekaNodes peerEurekaNodes = new PeerEurekaNodes(mockRegistry, mockServerConfig, mockClientConfig, null, mockAppInfoManager); PeerEurekaNodes spyPeerEurekaNodes = spy(peerEurekaNodes); when(spyPeerEurekaNodes.getPeerEurekaNodes()).thenReturn(mockNodes); when(mockEurekaServerContext.getPeerEurekaNodes()).thenReturn(spyPeerEurekaNodes); return new StatusUtil(mockEurekaServerContext); } List<InstanceInfo> getMockInstanceInfos(int size) { List<InstanceInfo> instances = new ArrayList<>(); for (int i = 0; i < size; i++) { InstanceInfo mockInstance = mock(InstanceInfo.class); when(mockInstance.getHostName()).thenReturn(String.valueOf(i)); when(mockInstance.getIPAddr()).thenReturn(String.valueOf(i)); when(mockInstance.getAppName()).thenReturn("stuff"); instances.add(mockInstance); } return instances; } List<PeerEurekaNode> getMockNodes(int size) { List<PeerEurekaNode> nodes = new ArrayList<>(); for (int i = 0; i < size; i++) { PeerEurekaNode mockNode = mock(PeerEurekaNode.class); when(mockNode.getServiceUrl()).thenReturn(String.format("http://%d:8080/v2", i)); nodes.add(mockNode); } return nodes; } }
6,881
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/util/AwsAsgUtilTest.java
package com.netflix.eureka.util; import com.netflix.appinfo.AmazonInfo; 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.DefaultEurekaClientConfig; import com.netflix.discovery.DiscoveryClient; import com.netflix.eureka.DefaultEurekaServerConfig; import com.netflix.eureka.EurekaServerConfig; import com.netflix.eureka.registry.PeerAwareInstanceRegistry; import com.netflix.eureka.aws.AwsAsgUtil; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.UUID; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; /** * @author David Liu */ public class AwsAsgUtilTest { private ApplicationInfoManager applicationInfoManager; private PeerAwareInstanceRegistry registry; private DiscoveryClient client; private AwsAsgUtil awsAsgUtil; private InstanceInfo instanceInfo; @Before public void setUp() throws Exception { ConfigurationManager.getConfigInstance().setProperty("eureka.awsAccessId", "fakeId"); ConfigurationManager.getConfigInstance().setProperty("eureka.awsSecretKey", "fakeKey"); AmazonInfo dataCenterInfo = mock(AmazonInfo.class); EurekaServerConfig serverConfig = new DefaultEurekaServerConfig(); InstanceInfo.Builder builder = InstanceInfo.Builder.newBuilder(); builder.setIPAddr("10.10.101.00"); builder.setHostName("fakeHost"); builder.setAppName("fake-" + UUID.randomUUID()); builder.setLeaseInfo(LeaseInfo.Builder.newBuilder().build()); builder.setDataCenterInfo(dataCenterInfo); instanceInfo = builder.build(); applicationInfoManager = new ApplicationInfoManager(new MyDataCenterInstanceConfig(), instanceInfo); DefaultEurekaClientConfig clientConfig = new DefaultEurekaClientConfig(); // setup config in advance, used in initialize converter client = mock(DiscoveryClient.class); registry = mock(PeerAwareInstanceRegistry.class); awsAsgUtil = spy(new AwsAsgUtil(serverConfig, clientConfig, registry)); } @After public void tearDown() throws Exception { ConfigurationManager.getConfigInstance().clear(); } @Test public void testDefaultAsgStatus() { Assert.assertEquals(true, awsAsgUtil.isASGEnabled(instanceInfo)); } @Test public void testAsyncLoadingFromCache() { // TODO } }
6,882
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/util
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/util/batcher/TaskDispatchersTest.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.eureka.util.batcher; import java.util.Collections; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import com.netflix.eureka.util.batcher.TaskProcessor.ProcessingResult; import org.junit.After; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; /** * @author Tomasz Bak */ public class TaskDispatchersTest { private static final long SERVER_UNAVAILABLE_SLEEP_TIME_MS = 1000; private static final long RETRY_SLEEP_TIME_MS = 100; private static final long MAX_BATCHING_DELAY_MS = 10; private static final int MAX_BUFFER_SIZE = 1000000; private static final int WORK_LOAD_SIZE = 2; private final RecordingProcessor processor = new RecordingProcessor(); private TaskDispatcher<Integer, ProcessingResult> dispatcher; @After public void tearDown() throws Exception { if (dispatcher != null) { dispatcher.shutdown(); } } @Test public void testSingleTaskDispatcher() throws Exception { dispatcher = TaskDispatchers.createNonBatchingTaskDispatcher( "TEST", MAX_BUFFER_SIZE, 1, MAX_BATCHING_DELAY_MS, SERVER_UNAVAILABLE_SLEEP_TIME_MS, RETRY_SLEEP_TIME_MS, processor ); dispatcher.process(1, ProcessingResult.Success, System.currentTimeMillis() + 60 * 1000); ProcessingResult result = processor.completedTasks.poll(5, TimeUnit.SECONDS); assertThat(result, is(equalTo(ProcessingResult.Success))); } @Test public void testBatchingDispatcher() throws Exception { dispatcher = TaskDispatchers.createBatchingTaskDispatcher( "TEST", MAX_BUFFER_SIZE, WORK_LOAD_SIZE, 1, MAX_BATCHING_DELAY_MS, SERVER_UNAVAILABLE_SLEEP_TIME_MS, RETRY_SLEEP_TIME_MS, processor ); dispatcher.process(1, ProcessingResult.Success, System.currentTimeMillis() + 60 * 1000); dispatcher.process(2, ProcessingResult.Success, System.currentTimeMillis() + 60 * 1000); processor.expectSuccesses(2); } @Test public void testTasksAreDistributedAcrossAllWorkerThreads() throws Exception { int threadCount = 3; CountingTaskProcessor countingProcessor = new CountingTaskProcessor(); TaskDispatcher<Integer, Boolean> dispatcher = TaskDispatchers.createBatchingTaskDispatcher( "TEST", MAX_BUFFER_SIZE, WORK_LOAD_SIZE, threadCount, MAX_BATCHING_DELAY_MS, SERVER_UNAVAILABLE_SLEEP_TIME_MS, RETRY_SLEEP_TIME_MS, countingProcessor ); try { int loops = 1000; while (true) { countingProcessor.resetTo(loops); for (int i = 0; i < loops; i++) { dispatcher.process(i, true, System.currentTimeMillis() + 60 * 1000); } countingProcessor.awaitCompletion(); int minHitPerThread = (int) (loops / threadCount * 0.9); if (countingProcessor.lowestHit() < minHitPerThread) { loops *= 2; } else { break; } if (loops > MAX_BUFFER_SIZE) { fail("Uneven load distribution"); } } } finally { dispatcher.shutdown(); } } static class CountingTaskProcessor implements TaskProcessor<Boolean> { final ConcurrentMap<Thread, Integer> threadHits = new ConcurrentHashMap<>(); volatile Semaphore completionGuard; @Override public ProcessingResult process(Boolean task) { throw new IllegalStateException("unexpected"); } @Override public ProcessingResult process(List<Boolean> tasks) { Thread currentThread = Thread.currentThread(); Integer current = threadHits.get(currentThread); if (current == null) { threadHits.put(currentThread, tasks.size()); } else { threadHits.put(currentThread, tasks.size() + current); } completionGuard.release(tasks.size()); return ProcessingResult.Success; } void resetTo(int expectedTasks) { completionGuard = new Semaphore(-expectedTasks + 1); } void awaitCompletion() throws InterruptedException { assertThat(completionGuard.tryAcquire(5, TimeUnit.SECONDS), is(true)); } int lowestHit() { return Collections.min(threadHits.values()); } } }
6,883
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/util
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/util/batcher/AcceptorExecutorTest.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.eureka.util.batcher; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import com.netflix.eureka.util.batcher.TaskProcessor.ProcessingResult; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; /** * @author Tomasz Bak */ public class AcceptorExecutorTest { private static final long SERVER_UNAVAILABLE_SLEEP_TIME_MS = 1000; private static final long RETRY_SLEEP_TIME_MS = 100; private static final long MAX_BATCHING_DELAY_MS = 10; private static final int MAX_BUFFER_SIZE = 3; private static final int WORK_LOAD_SIZE = 2; private AcceptorExecutor<Integer, String> acceptorExecutor; @Before public void setUp() throws Exception { acceptorExecutor = new AcceptorExecutor<>( "TEST", MAX_BUFFER_SIZE, WORK_LOAD_SIZE, MAX_BATCHING_DELAY_MS, SERVER_UNAVAILABLE_SLEEP_TIME_MS, RETRY_SLEEP_TIME_MS ); } @After public void tearDown() throws Exception { acceptorExecutor.shutdown(); } @Test public void testTasksAreDispatchedToWorkers() throws Exception { acceptorExecutor.process(1, "Task1", System.currentTimeMillis() + 60 * 1000); TaskHolder<Integer, String> taskHolder = acceptorExecutor.requestWorkItem().poll(5, TimeUnit.SECONDS); verifyTaskHolder(taskHolder, 1, "Task1"); acceptorExecutor.process(2, "Task2", System.currentTimeMillis() + 60 * 1000); List<TaskHolder<Integer, String>> taskHolders = acceptorExecutor.requestWorkItems().poll(5, TimeUnit.SECONDS); assertThat(taskHolders.size(), is(equalTo(1))); verifyTaskHolder(taskHolders.get(0), 2, "Task2"); } @Test public void testBatchSizeIsConstrainedByConfiguredMaxSize() throws Exception { for (int i = 0; i <= MAX_BUFFER_SIZE; i++) { acceptorExecutor.process(i, "Task" + i, System.currentTimeMillis() + 60 * 1000); } List<TaskHolder<Integer, String>> taskHolders = acceptorExecutor.requestWorkItems().poll(5, TimeUnit.SECONDS); assertThat(taskHolders.size(), is(equalTo(WORK_LOAD_SIZE))); } @Test public void testNewTaskOverridesOldOne() throws Exception { acceptorExecutor.process(1, "Task1", System.currentTimeMillis() + 60 * 1000); acceptorExecutor.process(1, "Task1.1", System.currentTimeMillis() + 60 * 1000); TaskHolder<Integer, String> taskHolder = acceptorExecutor.requestWorkItem().poll(5, TimeUnit.SECONDS); verifyTaskHolder(taskHolder, 1, "Task1.1"); } @Test public void testRepublishedTaskIsHandledFirst() throws Exception { acceptorExecutor.process(1, "Task1", System.currentTimeMillis() + 60 * 1000); acceptorExecutor.process(2, "Task2", System.currentTimeMillis() + 60 * 1000); TaskHolder<Integer, String> firstTaskHolder = acceptorExecutor.requestWorkItem().poll(5, TimeUnit.SECONDS); verifyTaskHolder(firstTaskHolder, 1, "Task1"); acceptorExecutor.reprocess(firstTaskHolder, ProcessingResult.TransientError); TaskHolder<Integer, String> secondTaskHolder = acceptorExecutor.requestWorkItem().poll(5, TimeUnit.SECONDS); verifyTaskHolder(secondTaskHolder, 1, "Task1"); TaskHolder<Integer, String> thirdTaskHolder = acceptorExecutor.requestWorkItem().poll(5, TimeUnit.SECONDS); verifyTaskHolder(thirdTaskHolder, 2, "Task2"); } @Test public void testWhenBufferOverflowsOldestTasksAreRemoved() throws Exception { for (int i = 0; i <= MAX_BUFFER_SIZE; i++) { acceptorExecutor.process(i, "Task" + i, System.currentTimeMillis() + 60 * 1000); } // Task 0 should be dropped out TaskHolder<Integer, String> firstTaskHolder = acceptorExecutor.requestWorkItem().poll(5, TimeUnit.SECONDS); verifyTaskHolder(firstTaskHolder, 1, "Task1"); } @Test public void testTasksAreDelayToMaximizeBatchSize() throws Exception { BlockingQueue<List<TaskHolder<Integer, String>>> taskQueue = acceptorExecutor.requestWorkItems(); acceptorExecutor.process(1, "Task1", System.currentTimeMillis() + 60 * 1000); Thread.sleep(MAX_BATCHING_DELAY_MS / 2); acceptorExecutor.process(2, "Task2", System.currentTimeMillis() + 60 * 1000); List<TaskHolder<Integer, String>> taskHolders = taskQueue.poll(5, TimeUnit.SECONDS); assertThat(taskHolders.size(), is(equalTo(2))); } private static void verifyTaskHolder(TaskHolder<Integer, String> taskHolder, int id, String task) { assertThat(taskHolder, is(notNullValue())); assertThat(taskHolder.getId(), is(equalTo(id))); assertThat(taskHolder.getTask(), is(equalTo(task))); } }
6,884
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/util
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/util/batcher/RecordingProcessor.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.eureka.util.batcher; import java.util.List; import java.util.concurrent.BlockingDeque; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; import com.netflix.eureka.util.batcher.TaskProcessor.ProcessingResult; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; /** * @author Tomasz Bak */ class RecordingProcessor implements TaskProcessor<ProcessingResult> { final BlockingDeque<ProcessingResult> completedTasks = new LinkedBlockingDeque<>(); final BlockingDeque<ProcessingResult> transientErrorTasks = new LinkedBlockingDeque<>(); final BlockingDeque<ProcessingResult> permanentErrorTasks = new LinkedBlockingDeque<>(); @Override public ProcessingResult process(ProcessingResult task) { switch (task) { case Success: completedTasks.add(task); break; case PermanentError: permanentErrorTasks.add(task); break; case TransientError: transientErrorTasks.add(task); break; } return task; } @Override public ProcessingResult process(List<ProcessingResult> tasks) { for (ProcessingResult task : tasks) { process(task); } return tasks.get(0); } public static TaskHolder<Integer, ProcessingResult> successfulTaskHolder(int id) { return new TaskHolder<>(id, ProcessingResult.Success, System.currentTimeMillis() + 60 * 1000); } public static TaskHolder<Integer, ProcessingResult> transientErrorTaskHolder(int id) { return new TaskHolder<>(id, ProcessingResult.TransientError, System.currentTimeMillis() + 60 * 1000); } public static TaskHolder<Integer, ProcessingResult> permanentErrorTaskHolder(int id) { return new TaskHolder<>(id, ProcessingResult.PermanentError, System.currentTimeMillis() + 60 * 1000); } public void expectSuccesses(int count) throws InterruptedException { for (int i = 0; i < count; i++) { ProcessingResult task = completedTasks.poll(5, TimeUnit.SECONDS); assertThat(task, is(notNullValue())); } } public void expectTransientErrors(int count) throws InterruptedException { for (int i = 0; i < count; i++) { ProcessingResult task = transientErrorTasks.poll(5, TimeUnit.SECONDS); assertThat(task, is(notNullValue())); } } public void expectPermanentErrors(int count) throws InterruptedException { for (int i = 0; i < count; i++) { ProcessingResult task = permanentErrorTasks.poll(5, TimeUnit.SECONDS); assertThat(task, is(notNullValue())); } } }
6,885
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/util
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/util/batcher/TaskExecutorsTest.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.eureka.util.batcher; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingDeque; import com.netflix.eureka.util.batcher.TaskProcessor.ProcessingResult; import org.junit.After; import org.junit.Before; import org.junit.Test; import static com.netflix.eureka.util.batcher.RecordingProcessor.permanentErrorTaskHolder; import static com.netflix.eureka.util.batcher.RecordingProcessor.successfulTaskHolder; import static com.netflix.eureka.util.batcher.RecordingProcessor.transientErrorTaskHolder; import static java.util.Arrays.asList; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * @author Tomasz Bak */ public class TaskExecutorsTest { @SuppressWarnings("unchecked") private final AcceptorExecutor<Integer, ProcessingResult> acceptorExecutor = mock(AcceptorExecutor.class); private final RecordingProcessor processor = new RecordingProcessor(); private final BlockingQueue<TaskHolder<Integer, ProcessingResult>> taskQueue = new LinkedBlockingDeque<>(); private final BlockingQueue<List<TaskHolder<Integer, ProcessingResult>>> taskBatchQueue = new LinkedBlockingDeque<>(); private TaskExecutors<Integer, ProcessingResult> taskExecutors; @Before public void setUp() throws Exception { when(acceptorExecutor.requestWorkItem()).thenReturn(taskQueue); when(acceptorExecutor.requestWorkItems()).thenReturn(taskBatchQueue); } @After public void tearDown() throws Exception { taskExecutors.shutdown(); } @Test public void testSingleItemSuccessfulProcessing() throws Exception { taskExecutors = TaskExecutors.singleItemExecutors("TEST", 1, processor, acceptorExecutor); taskQueue.add(successfulTaskHolder(1)); processor.expectSuccesses(1); } @Test public void testBatchSuccessfulProcessing() throws Exception { taskExecutors = TaskExecutors.batchExecutors("TEST", 1, processor, acceptorExecutor); taskBatchQueue.add(asList(successfulTaskHolder(1), successfulTaskHolder(2))); processor.expectSuccesses(2); } @Test public void testSingleItemProcessingWithTransientError() throws Exception { taskExecutors = TaskExecutors.singleItemExecutors("TEST", 1, processor, acceptorExecutor); TaskHolder<Integer, ProcessingResult> taskHolder = transientErrorTaskHolder(1); taskQueue.add(taskHolder); // Verify that transient task is be re-scheduled processor.expectTransientErrors(1); verify(acceptorExecutor, timeout(500).times(1)).reprocess(taskHolder, ProcessingResult.TransientError); } @Test public void testBatchProcessingWithTransientError() throws Exception { taskExecutors = TaskExecutors.batchExecutors("TEST", 1, processor, acceptorExecutor); List<TaskHolder<Integer, ProcessingResult>> taskHolderBatch = asList(transientErrorTaskHolder(1), transientErrorTaskHolder(2)); taskBatchQueue.add(taskHolderBatch); // Verify that transient task is be re-scheduled processor.expectTransientErrors(2); verify(acceptorExecutor, timeout(500).times(1)).reprocess(taskHolderBatch, ProcessingResult.TransientError); } @Test public void testSingleItemProcessingWithPermanentError() throws Exception { taskExecutors = TaskExecutors.singleItemExecutors("TEST", 1, processor, acceptorExecutor); TaskHolder<Integer, ProcessingResult> taskHolder = permanentErrorTaskHolder(1); taskQueue.add(taskHolder); // Verify that transient task is re-scheduled processor.expectPermanentErrors(1); verify(acceptorExecutor, never()).reprocess(taskHolder, ProcessingResult.TransientError); } @Test public void testBatchProcessingWithPermanentError() throws Exception { taskExecutors = TaskExecutors.batchExecutors("TEST", 1, processor, acceptorExecutor); List<TaskHolder<Integer, ProcessingResult>> taskHolderBatch = asList(permanentErrorTaskHolder(1), permanentErrorTaskHolder(2)); taskBatchQueue.add(taskHolderBatch); // Verify that transient task is re-scheduled processor.expectPermanentErrors(2); verify(acceptorExecutor, never()).reprocess(taskHolderBatch, ProcessingResult.TransientError); } }
6,886
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/mock/MockRemoteEurekaServer.java
package com.netflix.eureka.mock; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Map; import com.netflix.appinfo.AbstractEurekaIdentity; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.converters.jackson.EurekaJsonJacksonCodec; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import com.netflix.eureka.*; import org.junit.Assert; import org.junit.rules.ExternalResource; import org.mortbay.jetty.Request; import org.mortbay.jetty.Server; import org.mortbay.jetty.servlet.FilterHolder; import org.mortbay.jetty.servlet.ServletHandler; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * @author Nitesh Kant */ public class MockRemoteEurekaServer extends ExternalResource { public static final String EUREKA_API_BASE_PATH = "/eureka/v2/"; private final Map<String, Application> applicationMap; private final Map<String, Application> applicationDeltaMap; private final Server server; private boolean sentDelta; private int port; private volatile boolean simulateNotReady; public MockRemoteEurekaServer(int port, Map<String, Application> applicationMap, Map<String, Application> applicationDeltaMap) { this.applicationMap = applicationMap; this.applicationDeltaMap = applicationDeltaMap; ServletHandler handler = new AppsResourceHandler(); EurekaServerConfig serverConfig = new DefaultEurekaServerConfig(); EurekaServerContext serverContext = mock(EurekaServerContext.class); when(serverContext.getServerConfig()).thenReturn(serverConfig); handler.addFilterWithMapping(ServerRequestAuthFilter.class, "/*", 1).setFilter(new ServerRequestAuthFilter(serverContext)); handler.addFilterWithMapping(RateLimitingFilter.class, "/*", 1).setFilter(new RateLimitingFilter(serverContext)); server = new Server(port); server.addHandler(handler); System.out.println(String.format( "Created eureka server mock with applications map %s and applications delta map %s", stringifyAppMap(applicationMap), stringifyAppMap(applicationDeltaMap))); } @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.start(); port = server.getConnectors()[0].getLocalPort(); } public void stop() throws Exception { server.stop(); } public boolean isSentDelta() { return sentDelta; } public int getPort() { return port; } public void simulateNotReady(boolean simulateNotReady) { this.simulateNotReady = simulateNotReady; } private static String stringifyAppMap(Map<String, Application> applicationMap) { StringBuilder builder = new StringBuilder(); for (Map.Entry<String, Application> entry : applicationMap.entrySet()) { String entryAsString = String.format("{ name : %s , instance count: %d }", entry.getKey(), entry.getValue().getInstances().size()); builder.append(entryAsString); } return builder.toString(); } private class AppsResourceHandler extends ServletHandler { @Override public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException { if (simulateNotReady) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return; } 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.assertNotNull(authName); Assert.assertNotNull(authVersion); Assert.assertNotNull(authId); Assert.assertTrue(!authName.equals(ServerRequestAuthFilter.UNKNOWN)); Assert.assertTrue(!authVersion.equals(ServerRequestAuthFilter.UNKNOWN)); Assert.assertTrue(!authId.equals(ServerRequestAuthFilter.UNKNOWN)); for (FilterHolder filterHolder : this.getFilters()) { filterHolder.getFilter().doFilter(request, response, new FilterChain() { @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { // do nothing; } }); } String pathInfo = request.getPathInfo(); System.out.println( "Eureka resource mock, received request on path: " + pathInfo + ". HTTP method: |" + request .getMethod() + '|'); boolean handled = false; if (null != pathInfo && pathInfo.startsWith("")) { pathInfo = pathInfo.substring(EUREKA_API_BASE_PATH.length()); if (pathInfo.startsWith("apps/delta")) { Applications apps = new Applications(); for (Application application : applicationDeltaMap.values()) { apps.addApplication(application); } apps.setAppsHashCode(apps.getReconcileHashCode()); sendOkResponseWithContent((Request) request, response, toJson(apps)); handled = true; sentDelta = true; } else if (request.getMethod().equals("PUT") && pathInfo.startsWith("apps")) { InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder() .setAppName("TEST-APP").build(); sendOkResponseWithContent((Request) request, response, new EurekaJsonJacksonCodec().getObjectMapper(Applications.class).writeValueAsString(instanceInfo)); handled = true; } else if (pathInfo.startsWith("apps")) { Applications apps = new Applications(); for (Application application : applicationMap.values()) { apps.addApplication(application); } apps.setAppsHashCode(apps.getReconcileHashCode()); sendOkResponseWithContent((Request) request, response, toJson(apps)); handled = true; } } if (!handled) { response.sendError(HttpServletResponse.SC_NOT_FOUND, "Request path: " + pathInfo + " not supported by eureka resource mock."); } } private void sendOkResponseWithContent(Request request, HttpServletResponse response, String content) throws IOException { response.setContentType("application/json; charset=UTF-8"); response.setStatus(HttpServletResponse.SC_OK); response.getOutputStream().write(content.getBytes("UTF-8")); response.getOutputStream().flush(); request.setHandled(true); System.out.println("Eureka resource mock, sent response for request path: " + request.getPathInfo() + " with content" + content); } } private String toJson(Applications apps) throws IOException { return new EurekaJsonJacksonCodec().getObjectMapper(Applications.class).writeValueAsString(apps); } }
6,887
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/resources/ApplicationsResourceTest.java
package com.netflix.eureka.resources; import com.netflix.appinfo.EurekaAccept; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.util.EurekaEntityComparators; import com.netflix.discovery.converters.wrappers.CodecWrappers; import com.netflix.discovery.converters.wrappers.DecoderWrapper; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.util.InstanceInfoGenerator; import com.netflix.eureka.AbstractTester; import com.netflix.eureka.Version; import org.junit.Before; import org.junit.Test; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; /** * @author David Liu */ public class ApplicationsResourceTest extends AbstractTester { private ApplicationsResource applicationsResource; private Applications testApplications; @Override @Before public void setUp() throws Exception { super.setUp(); InstanceInfoGenerator instanceInfos = InstanceInfoGenerator.newBuilder(20, 6).build(); testApplications = instanceInfos.toApplications(); applicationsResource = new ApplicationsResource(serverContext); for (Application application : testApplications.getRegisteredApplications()) { for (InstanceInfo instanceInfo : application.getInstances()) { registry.register(instanceInfo, false); } } } @Test public void testFullAppsGetJson() throws Exception { Response response = applicationsResource.getContainers( Version.V2.name(), MediaType.APPLICATION_JSON, null, // encoding EurekaAccept.full.name(), null, // uriInfo null // remote regions ); String json = String.valueOf(response.getEntity()); DecoderWrapper decoder = CodecWrappers.getDecoder(CodecWrappers.LegacyJacksonJson.class); Applications decoded = decoder.decode(json, Applications.class); // test per app as the full apps list include the mock server that is not part of the test apps for (Application application : testApplications.getRegisteredApplications()) { Application decodedApp = decoded.getRegisteredApplications(application.getName()); assertThat(EurekaEntityComparators.equal(application, decodedApp), is(true)); } } @Test public void testFullAppsGetGzipJsonHeaderType() throws Exception { Response response = applicationsResource.getContainers( Version.V2.name(), MediaType.APPLICATION_JSON, "gzip", // encoding EurekaAccept.full.name(), null, // uriInfo null // remote regions ); assertThat(response.getMetadata().getFirst("Content-Encoding").toString(), is("gzip")); assertThat(response.getMetadata().getFirst("Content-Type").toString(), is(MediaType.APPLICATION_JSON)); } @Test public void testFullAppsGetGzipXmlHeaderType() throws Exception { Response response = applicationsResource.getContainers( Version.V2.name(), MediaType.APPLICATION_XML, "gzip", // encoding EurekaAccept.full.name(), null, // uriInfo null // remote regions ); assertThat(response.getMetadata().getFirst("Content-Encoding").toString(), is("gzip")); assertThat(response.getMetadata().getFirst("Content-Type").toString(), is(MediaType.APPLICATION_XML)); } @Test public void testMiniAppsGet() throws Exception { Response response = applicationsResource.getContainers( Version.V2.name(), MediaType.APPLICATION_JSON, null, // encoding EurekaAccept.compact.name(), null, // uriInfo null // remote regions ); String json = String.valueOf(response.getEntity()); DecoderWrapper decoder = CodecWrappers.getDecoder(CodecWrappers.LegacyJacksonJson.class); Applications decoded = decoder.decode(json, Applications.class); // test per app as the full apps list include the mock server that is not part of the test apps for (Application application : testApplications.getRegisteredApplications()) { Application decodedApp = decoded.getRegisteredApplications(application.getName()); // assert false as one is mini, so should NOT equal assertThat(EurekaEntityComparators.equal(application, decodedApp), is(false)); } for (Application application : testApplications.getRegisteredApplications()) { Application decodedApp = decoded.getRegisteredApplications(application.getName()); assertThat(application.getName(), is(decodedApp.getName())); // now do mini equals for (InstanceInfo instanceInfo : application.getInstances()) { InstanceInfo decodedInfo = decodedApp.getByInstanceId(instanceInfo.getId()); assertThat(EurekaEntityComparators.equalMini(instanceInfo, decodedInfo), is(true)); } } } }
6,888
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/resources/PeerReplicationResourceTest.java
package com.netflix.eureka.resources; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.shared.transport.ClusterSampleData; import com.netflix.eureka.EurekaServerConfig; import com.netflix.eureka.EurekaServerContext; import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl.Action; 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 org.junit.Before; import org.junit.Test; import static com.netflix.discovery.shared.transport.ClusterSampleData.newReplicationInstanceOf; 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.anyString; 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 PeerReplicationResourceTest { private final ApplicationResource applicationResource = mock(ApplicationResource.class); private final InstanceResource instanceResource = mock(InstanceResource.class); private EurekaServerContext serverContext; private PeerReplicationResource peerReplicationResource; private final InstanceInfo instanceInfo = ClusterSampleData.newInstanceInfo(0); @Before public void setUp() { serverContext = mock(EurekaServerContext.class); when(serverContext.getServerConfig()).thenReturn(mock(EurekaServerConfig.class)); peerReplicationResource = new PeerReplicationResource(serverContext) { @Override ApplicationResource createApplicationResource(ReplicationInstance instanceInfo) { return applicationResource; } @Override InstanceResource createInstanceResource(ReplicationInstance instanceInfo, ApplicationResource applicationResource) { return instanceResource; } }; } @Test public void testRegisterBatching() throws Exception { ReplicationList replicationList = new ReplicationList(newReplicationInstanceOf(Action.Register, instanceInfo)); Response response = peerReplicationResource.batchReplication(replicationList); assertStatusOkReply(response); verify(applicationResource, times(1)).addInstance(instanceInfo, "true"); } @Test public void testCancelBatching() throws Exception { when(instanceResource.cancelLease(anyString())).thenReturn(Response.ok().build()); ReplicationList replicationList = new ReplicationList(newReplicationInstanceOf(Action.Cancel, instanceInfo)); Response response = peerReplicationResource.batchReplication(replicationList); assertStatusOkReply(response); verify(instanceResource, times(1)).cancelLease("true"); } @Test public void testHeartbeat() throws Exception { when(instanceResource.renewLease(anyString(), anyString(), anyString(), anyString())).thenReturn(Response.ok().build()); ReplicationInstance replicationInstance = newReplicationInstanceOf(Action.Heartbeat, instanceInfo); Response response = peerReplicationResource.batchReplication(new ReplicationList(replicationInstance)); assertStatusOkReply(response); verify(instanceResource, times(1)).renewLease( "true", replicationInstance.getOverriddenStatus(), instanceInfo.getStatus().name(), Long.toString(replicationInstance.getLastDirtyTimestamp()) ); } @Test public void testConflictResponseReturnsTheInstanceInfoInTheResponseEntity() throws Exception { when(instanceResource.renewLease(anyString(), anyString(), anyString(), anyString())).thenReturn(Response.status(Status.CONFLICT).entity(instanceInfo).build()); ReplicationInstance replicationInstance = newReplicationInstanceOf(Action.Heartbeat, instanceInfo); Response response = peerReplicationResource.batchReplication(new ReplicationList(replicationInstance)); assertStatusIsConflict(response); assertResponseEntityExist(response); } @Test public void testStatusUpdate() throws Exception { when(instanceResource.statusUpdate(anyString(), anyString(), anyString())).thenReturn(Response.ok().build()); ReplicationInstance replicationInstance = newReplicationInstanceOf(Action.StatusUpdate, instanceInfo); Response response = peerReplicationResource.batchReplication(new ReplicationList(replicationInstance)); assertStatusOkReply(response); verify(instanceResource, times(1)).statusUpdate( replicationInstance.getStatus(), "true", Long.toString(replicationInstance.getLastDirtyTimestamp()) ); } @Test public void testDeleteStatusOverride() throws Exception { when(instanceResource.deleteStatusUpdate(anyString(), anyString(), anyString())).thenReturn(Response.ok().build()); ReplicationInstance replicationInstance = newReplicationInstanceOf(Action.DeleteStatusOverride, instanceInfo); Response response = peerReplicationResource.batchReplication(new ReplicationList(replicationInstance)); assertStatusOkReply(response); verify(instanceResource, times(1)).deleteStatusUpdate( "true", replicationInstance.getStatus(), Long.toString(replicationInstance.getLastDirtyTimestamp()) ); } private static void assertStatusOkReply(Response httpResponse) { assertStatus(httpResponse, 200); } private static void assertStatusIsConflict(Response httpResponse) { assertStatus(httpResponse, 409); } private static void assertStatus(Response httpResponse, int expectedStatusCode) { ReplicationListResponse entity = (ReplicationListResponse) httpResponse.getEntity(); assertThat(entity, is(notNullValue())); ReplicationInstanceResponse replicationResponse = entity.getResponseList().get(0); assertThat(replicationResponse.getStatusCode(), is(equalTo(expectedStatusCode))); } private static void assertResponseEntityExist(Response httpResponse) { ReplicationListResponse entity = (ReplicationListResponse) httpResponse.getEntity(); assertThat(entity, is(notNullValue())); ReplicationInstanceResponse replicationResponse = entity.getResponseList().get(0); assertThat(replicationResponse.getResponseEntity(), is(notNullValue())); } }
6,889
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/resources/AbstractVIPResourceTest.java
package com.netflix.eureka.resources; import com.netflix.appinfo.EurekaAccept; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.converters.wrappers.CodecWrappers; import com.netflix.discovery.converters.wrappers.DecoderWrapper; 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.AbstractTester; import com.netflix.eureka.Version; import com.netflix.eureka.registry.Key; import org.junit.Before; import org.junit.Test; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; /** * @author David Liu */ public class AbstractVIPResourceTest extends AbstractTester { private String vipName; private AbstractVIPResource resource; private Application testApplication; @Override @Before public void setUp() throws Exception { super.setUp(); InstanceInfoGenerator instanceInfos = InstanceInfoGenerator.newBuilder(6, 1).build(); testApplication = instanceInfos.toApplications().getRegisteredApplications().get(0); resource = new AbstractVIPResource(serverContext) { @Override protected Response getVipResponse(String version, String entityName, String acceptHeader, EurekaAccept eurekaAccept, Key.EntityType entityType) { return super.getVipResponse(version, entityName, acceptHeader, eurekaAccept, entityType); } }; vipName = testApplication.getName() + "#VIP"; for (InstanceInfo instanceInfo : testApplication.getInstances()) { InstanceInfo changed = new InstanceInfo.Builder(instanceInfo) .setASGName(null) // null asgName to get around AwsAsgUtil check .setVIPAddress(vipName) // use the same vip address for all the instances in this test .build(); registry.register(changed, false); } } @Test public void testFullVipGet() throws Exception { Response response = resource.getVipResponse( Version.V2.name(), vipName, MediaType.APPLICATION_JSON, EurekaAccept.full, Key.EntityType.VIP ); String json = String.valueOf(response.getEntity()); DecoderWrapper decoder = CodecWrappers.getDecoder(CodecWrappers.LegacyJacksonJson.class); Applications decodedApps = decoder.decode(json, Applications.class); Application decodedApp = decodedApps.getRegisteredApplications(testApplication.getName()); assertThat(EurekaEntityComparators.equal(testApplication, decodedApp), is(true)); } @Test public void testMiniVipGet() throws Exception { Response response = resource.getVipResponse( Version.V2.name(), vipName, MediaType.APPLICATION_JSON, EurekaAccept.compact, Key.EntityType.VIP ); String json = String.valueOf(response.getEntity()); DecoderWrapper decoder = CodecWrappers.getDecoder(CodecWrappers.LegacyJacksonJson.class); Applications decodedApps = decoder.decode(json, Applications.class); Application decodedApp = decodedApps.getRegisteredApplications(testApplication.getName()); // assert false as one is mini, so should NOT equal assertThat(EurekaEntityComparators.equal(testApplication, decodedApp), is(false)); for (InstanceInfo instanceInfo : testApplication.getInstances()) { InstanceInfo decodedInfo = decodedApp.getByInstanceId(instanceInfo.getId()); assertThat(EurekaEntityComparators.equalMini(instanceInfo, decodedInfo), is(true)); } } }
6,890
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/resources/ReplicationConcurrencyTest.java
package com.netflix.eureka.resources; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.MyDataCenterInstanceConfig; import com.netflix.discovery.DefaultEurekaClientConfig; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.util.InstanceInfoGenerator; import com.netflix.eureka.DefaultEurekaServerConfig; import com.netflix.eureka.EurekaServerContext; import com.netflix.eureka.cluster.PeerEurekaNode; import com.netflix.eureka.cluster.PeerEurekaNodes; import com.netflix.eureka.registry.PeerAwareInstanceRegistry; import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import java.util.Collections; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.MatcherAssert.assertThat; /** * A pseudo mock test to test concurrent scenarios to do with registration and replication of cluster setups * with 1+ eureka servers * * @author David Liu */ public class ReplicationConcurrencyTest { private String id; private String appName; private InstanceInfo instance1; private InstanceInfo instance2; private MockServer server1; private MockServer server2; private InstanceInfo server1Sees; private InstanceInfo server2Sees; @Before public void setUp() throws Exception { InstanceInfo seed = InstanceInfoGenerator.takeOne(); id = seed.getId(); appName = seed.getAppName(); // set up test instances instance1 = InstanceInfo.Builder.newBuilder() .setInstanceId(id) .setAppName(appName) .setHostName(seed.getHostName()) .setIPAddr(seed.getIPAddr()) .setDataCenterInfo(seed.getDataCenterInfo()) .setStatus(InstanceInfo.InstanceStatus.STARTING) .setLastDirtyTimestamp(11111l) .build(); instance2 = new InstanceInfo.Builder(seed) .setInstanceId(id) .setAppName(appName) .setHostName(seed.getHostName()) .setIPAddr(seed.getIPAddr()) .setDataCenterInfo(seed.getDataCenterInfo()) .setStatus(InstanceInfo.InstanceStatus.UP) .setLastDirtyTimestamp(22222l) .build(); assertThat(instance1.getStatus(), not(equalTo(instance2.getStatus()))); // set up server1 with no replication anywhere PeerEurekaNodes server1Peers = Mockito.mock(PeerEurekaNodes.class); Mockito.when(server1Peers.getPeerEurekaNodes()).thenReturn(Collections.<PeerEurekaNode>emptyList()); server1 = new MockServer(appName, server1Peers); // set up server2 PeerEurekaNodes server2Peers = Mockito.mock(PeerEurekaNodes.class); Mockito.when(server2Peers.getPeerEurekaNodes()).thenReturn(Collections.<PeerEurekaNode>emptyList()); server2 = new MockServer(appName, server2Peers); // register with server1 server1.applicationResource.addInstance(instance1, "false"/* isReplication */); // STARTING server1Sees = server1.registry.getInstanceByAppAndId(appName, id); assertThat(server1Sees, equalTo(instance1)); // update (via a register) with server2 server2.applicationResource.addInstance(instance2, "false"/* isReplication */); // UP server2Sees = server2.registry.getInstanceByAppAndId(appName, id); assertThat(server2Sees, equalTo(instance2)); // make sure data in server 1 is "older" assertThat(server2Sees.getLastDirtyTimestamp() > server1Sees.getLastDirtyTimestamp(), is(true)); } /** * this test tests a scenario where multiple registration and update requests for a single client is sent to * different eureka servers before replication can occur between them */ @Test public void testReplicationWithRegistrationAndUpdateOnDifferentServers() throws Exception { // now simulate server1 (delayed) replication to server2. // without batching this is done by server1 making a REST call to the register endpoint of server2 with // replication=true server2.applicationResource.addInstance(instance1, "true"); // verify that server2's "newer" info is (or is not) overridden // server2 should still see instance2 even though server1 tried to replicate across server1 InstanceInfo newServer2Sees = server2.registry.getInstanceByAppAndId(appName, id); assertThat(newServer2Sees.getStatus(), equalTo(instance2.getStatus())); // now let server2 replicate to server1 server1.applicationResource.addInstance(newServer2Sees, "true"); // verify that server1 now have the updated info from server2 InstanceInfo newServer1Sees = server1.registry.getInstanceByAppAndId(appName, id); assertThat(newServer1Sees.getStatus(), equalTo(instance2.getStatus())); } private static class MockServer { public final ApplicationResource applicationResource; public final PeerReplicationResource replicationResource; public final PeerAwareInstanceRegistry registry; public MockServer(String appName, PeerEurekaNodes peerEurekaNodes) throws Exception { ApplicationInfoManager infoManager = new ApplicationInfoManager(new MyDataCenterInstanceConfig()); DefaultEurekaServerConfig serverConfig = Mockito.spy(new DefaultEurekaServerConfig()); DefaultEurekaClientConfig clientConfig = new DefaultEurekaClientConfig(); ServerCodecs serverCodecs = new DefaultServerCodecs(serverConfig); EurekaClient eurekaClient = Mockito.mock(EurekaClient.class); Mockito.doReturn("true").when(serverConfig).getExperimental("registry.registration.ignoreIfDirtyTimestampIsOlder"); this.registry = new PeerAwareInstanceRegistryImpl(serverConfig, clientConfig, serverCodecs, eurekaClient); this.registry.init(peerEurekaNodes); this.applicationResource = new ApplicationResource(appName, serverConfig, registry); EurekaServerContext serverContext = Mockito.mock(EurekaServerContext.class); Mockito.when(serverContext.getServerConfig()).thenReturn(serverConfig); Mockito.when(serverContext.getRegistry()).thenReturn(registry); this.replicationResource = new PeerReplicationResource(serverContext); } } }
6,891
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/resources/ApplicationResourceTest.java
package com.netflix.eureka.resources; import com.netflix.appinfo.AmazonInfo; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.EurekaAccept; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.UniqueIdentifier; import com.netflix.config.ConfigurationManager; import com.netflix.discovery.converters.wrappers.CodecWrappers; import com.netflix.discovery.converters.wrappers.DecoderWrapper; import com.netflix.discovery.shared.Application; import com.netflix.discovery.util.EurekaEntityComparators; import com.netflix.discovery.util.InstanceInfoGenerator; import com.netflix.eureka.AbstractTester; import com.netflix.eureka.Version; import org.junit.Before; import org.junit.Test; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; /** * @author David Liu */ public class ApplicationResourceTest extends AbstractTester { private ApplicationResource applicationResource; private Application testApplication; @Override @Before public void setUp() throws Exception { super.setUp(); InstanceInfoGenerator instanceInfos = InstanceInfoGenerator.newBuilder(6, 1).build(); testApplication = instanceInfos.toApplications().getRegisteredApplications().get(0); applicationResource = new ApplicationResource(testApplication.getName(), serverContext.getServerConfig(), serverContext.getRegistry()); for (InstanceInfo instanceInfo : testApplication.getInstances()) { registry.register(instanceInfo, false); } } @Test public void testFullAppGet() throws Exception { Response response = applicationResource.getApplication( Version.V2.name(), MediaType.APPLICATION_JSON, EurekaAccept.full.name() ); String json = String.valueOf(response.getEntity()); DecoderWrapper decoder = CodecWrappers.getDecoder(CodecWrappers.LegacyJacksonJson.class); Application decodedApp = decoder.decode(json, Application.class); assertThat(EurekaEntityComparators.equal(testApplication, decodedApp), is(true)); } @Test public void testMiniAppGet() throws Exception { Response response = applicationResource.getApplication( Version.V2.name(), MediaType.APPLICATION_JSON, EurekaAccept.compact.name() ); String json = String.valueOf(response.getEntity()); DecoderWrapper decoder = CodecWrappers.getDecoder(CodecWrappers.LegacyJacksonJson.class); Application decodedApp = decoder.decode(json, Application.class); // assert false as one is mini, so should NOT equal assertThat(EurekaEntityComparators.equal(testApplication, decodedApp), is(false)); for (InstanceInfo instanceInfo : testApplication.getInstances()) { InstanceInfo decodedInfo = decodedApp.getByInstanceId(instanceInfo.getId()); assertThat(EurekaEntityComparators.equalMini(instanceInfo, decodedInfo), is(true)); } } @Test public void testGoodRegistration() throws Exception { InstanceInfo noIdInfo = InstanceInfoGenerator.takeOne(); Response response = applicationResource.addInstance(noIdInfo, false+""); assertThat(response.getStatus(), is(204)); } @Test public void testBadRegistration() throws Exception { InstanceInfo instanceInfo = spy(InstanceInfoGenerator.takeOne()); when(instanceInfo.getId()).thenReturn(null); Response response = applicationResource.addInstance(instanceInfo, false+""); assertThat(response.getStatus(), is(400)); instanceInfo = spy(InstanceInfoGenerator.takeOne()); when(instanceInfo.getHostName()).thenReturn(null); response = applicationResource.addInstance(instanceInfo, false+""); assertThat(response.getStatus(), is(400)); instanceInfo = spy(InstanceInfoGenerator.takeOne()); when(instanceInfo.getIPAddr()).thenReturn(null); response = applicationResource.addInstance(instanceInfo, false+""); assertThat(response.getStatus(), is(400)); instanceInfo = spy(InstanceInfoGenerator.takeOne()); when(instanceInfo.getAppName()).thenReturn(""); response = applicationResource.addInstance(instanceInfo, false+""); assertThat(response.getStatus(), is(400)); instanceInfo = spy(InstanceInfoGenerator.takeOne()); when(instanceInfo.getAppName()).thenReturn(applicationResource.getName() + "extraExtra"); response = applicationResource.addInstance(instanceInfo, false+""); assertThat(response.getStatus(), is(400)); instanceInfo = spy(InstanceInfoGenerator.takeOne()); when(instanceInfo.getDataCenterInfo()).thenReturn(null); response = applicationResource.addInstance(instanceInfo, false+""); assertThat(response.getStatus(), is(400)); instanceInfo = spy(InstanceInfoGenerator.takeOne()); when(instanceInfo.getDataCenterInfo()).thenReturn(new DataCenterInfo() { @Override public Name getName() { return null; } }); response = applicationResource.addInstance(instanceInfo, false+""); assertThat(response.getStatus(), is(400)); } @Test public void testBadRegistrationOfDataCenterInfo() throws Exception { try { // test 400 when configured to return client error ConfigurationManager.getConfigInstance().setProperty("eureka.experimental.registration.validation.dataCenterInfoId", "true"); InstanceInfo instanceInfo = spy(InstanceInfoGenerator.takeOne()); when(instanceInfo.getDataCenterInfo()).thenReturn(new TestDataCenterInfo()); Response response = applicationResource.addInstance(instanceInfo, false + ""); assertThat(response.getStatus(), is(400)); // test backfill of data for AmazonInfo ConfigurationManager.getConfigInstance().setProperty("eureka.experimental.registration.validation.dataCenterInfoId", "false"); instanceInfo = spy(InstanceInfoGenerator.takeOne()); assertThat(instanceInfo.getDataCenterInfo(), instanceOf(AmazonInfo.class)); ((AmazonInfo) instanceInfo.getDataCenterInfo()).getMetadata().remove(AmazonInfo.MetaDataKey.instanceId.getName()); // clear the Id response = applicationResource.addInstance(instanceInfo, false + ""); assertThat(response.getStatus(), is(204)); } finally { ConfigurationManager.getConfigInstance().clearProperty("eureka.experimental.registration.validation.dataCenterInfoId"); } } private static class TestDataCenterInfo implements DataCenterInfo, UniqueIdentifier { @Override public Name getName() { return Name.MyOwn; } @Override public String getId() { return null; // return null to test } } }
6,892
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/resources/InstanceResourceTest.java
package com.netflix.eureka.resources; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.InstanceStatus; import com.netflix.eureka.AbstractTester; import org.junit.Before; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class InstanceResourceTest extends AbstractTester { private final InstanceInfo testInstanceInfo = createLocalInstance(LOCAL_REGION_INSTANCE_1_HOSTNAME); private ApplicationResource applicationResource; private InstanceResource instanceResource; @Override @Before public void setUp() throws Exception { super.setUp(); applicationResource = new ApplicationResource(testInstanceInfo.getAppName(), serverContext.getServerConfig(), serverContext.getRegistry()); instanceResource = new InstanceResource(applicationResource, testInstanceInfo.getId(), serverContext.getServerConfig(), serverContext.getRegistry()); } @Test public void testStatusOverrideReturnsNotFoundErrorCodeIfInstanceNotRegistered() throws Exception { Response response = instanceResource.statusUpdate(InstanceStatus.OUT_OF_SERVICE.name(), "false", "0"); assertThat(response.getStatus(), is(equalTo(Status.NOT_FOUND.getStatusCode()))); } @Test public void testStatusOverrideDeleteReturnsNotFoundErrorCodeIfInstanceNotRegistered() throws Exception { Response response = instanceResource.deleteStatusUpdate(InstanceStatus.OUT_OF_SERVICE.name(), "false", "0"); assertThat(response.getStatus(), is(equalTo(Status.NOT_FOUND.getStatusCode()))); } @Test public void testStatusOverrideDeleteIsAppliedToRegistry() throws Exception { // Override instance status registry.register(testInstanceInfo, false); registry.statusUpdate(testInstanceInfo.getAppName(), testInstanceInfo.getId(), InstanceStatus.OUT_OF_SERVICE, "0", false); assertThat(testInstanceInfo.getStatus(), is(equalTo(InstanceStatus.OUT_OF_SERVICE))); // Remove the override Response response = instanceResource.deleteStatusUpdate("false", null, "0"); assertThat(response.getStatus(), is(equalTo(200))); assertThat(testInstanceInfo.getStatus(), is(equalTo(InstanceStatus.UNKNOWN))); } @Test public void testStatusOverrideDeleteIsAppliedToRegistryAndProvidedStatusIsSet() throws Exception { // Override instance status registry.register(testInstanceInfo, false); registry.statusUpdate(testInstanceInfo.getAppName(), testInstanceInfo.getId(), InstanceStatus.OUT_OF_SERVICE, "0", false); assertThat(testInstanceInfo.getStatus(), is(equalTo(InstanceStatus.OUT_OF_SERVICE))); // Remove the override Response response = instanceResource.deleteStatusUpdate("false", "DOWN", "0"); assertThat(response.getStatus(), is(equalTo(200))); assertThat(testInstanceInfo.getStatus(), is(equalTo(InstanceStatus.DOWN))); } }
6,893
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/registry/AwsInstanceRegistryTest.java
package com.netflix.eureka.registry; import com.netflix.appinfo.AmazonInfo; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.InstanceStatus; import com.netflix.appinfo.LeaseInfo; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.EurekaClientConfig; import com.netflix.eureka.EurekaServerConfig; import com.netflix.eureka.resources.ServerCodecs; import org.junit.Test; /** * Created by Nikos Michalakis on 7/14/16. */ public class AwsInstanceRegistryTest extends InstanceRegistryTest { @Test public void testOverridesWithAsgEnabledThenDisabled() { // Regular registration first InstanceInfo myInstance = createLocalUpInstanceWithAsg(LOCAL_REGION_INSTANCE_1_HOSTNAME); registerInstanceLocally(myInstance); verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.UP); // Now we disable the ASG and we should expect OUT_OF_SERVICE status. ((AwsInstanceRegistry) registry).getAwsAsgUtil().setStatus(myInstance.getASGName(), false); myInstance = createLocalUpInstanceWithAsg(LOCAL_REGION_INSTANCE_1_HOSTNAME); registerInstanceLocally(myInstance); verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.OUT_OF_SERVICE); // Now we re-enable the ASG and we should expect UP status. ((AwsInstanceRegistry) registry).getAwsAsgUtil().setStatus(myInstance.getASGName(), true); myInstance = createLocalUpInstanceWithAsg(LOCAL_REGION_INSTANCE_1_HOSTNAME); registerInstanceLocally(myInstance); verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.UP); } private static InstanceInfo createLocalUpInstanceWithAsg(String hostname) { InstanceInfo.Builder instanceBuilder = InstanceInfo.Builder.newBuilder(); instanceBuilder.setAppName(LOCAL_REGION_APP_NAME); instanceBuilder.setHostName(hostname); instanceBuilder.setIPAddr("10.10.101.1"); instanceBuilder.setDataCenterInfo(getAmazonInfo(hostname)); instanceBuilder.setLeaseInfo(LeaseInfo.Builder.newBuilder().build()); instanceBuilder.setStatus(InstanceStatus.UP); instanceBuilder.setASGName("ASG-YO-HO"); return instanceBuilder.build(); } private static AmazonInfo getAmazonInfo(String instanceHostName) { AmazonInfo.Builder azBuilder = AmazonInfo.Builder.newBuilder(); azBuilder.addMetadata(AmazonInfo.MetaDataKey.availabilityZone, "us-east-1a"); 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(); } @Override protected DataCenterInfo getDataCenterInfo() { return getAmazonInfo(LOCAL_REGION_INSTANCE_1_HOSTNAME); } @Override protected PeerAwareInstanceRegistryImpl makePeerAwareInstanceRegistry(EurekaServerConfig serverConfig, EurekaClientConfig clientConfig, ServerCodecs serverCodecs, EurekaClient eurekaClient) { return new TestAwsInstanceRegistry(serverConfig, clientConfig, serverCodecs, eurekaClient); } private static class TestAwsInstanceRegistry extends AwsInstanceRegistry { public TestAwsInstanceRegistry(EurekaServerConfig serverConfig, EurekaClientConfig clientConfig, ServerCodecs serverCodecs, EurekaClient eurekaClient) { super(serverConfig, clientConfig, serverCodecs, eurekaClient); } @Override public boolean isLeaseExpirationEnabled() { return false; } @Override public InstanceInfo getNextServerFromEureka(String virtualHostname, boolean secure) { return null; } } }
6,894
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/registry/InstanceRegistryTest.java
package com.netflix.eureka.registry; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; 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.eureka.AbstractTester; import com.netflix.eureka.registry.AbstractInstanceRegistry.CircularQueue; import com.netflix.eureka.registry.AbstractInstanceRegistry.EvictionTask; import org.junit.Assert; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; /** * @author Nitesh Kant */ public class InstanceRegistryTest extends AbstractTester { @Test public void testSoftDepRemoteUp() throws Exception { Assert.assertTrue("Registry access disallowed when remote region is UP.", registry.shouldAllowAccess(false)); Assert.assertTrue("Registry access disallowed when remote region is UP.", registry.shouldAllowAccess(true)); } @Test public void testGetAppsFromAllRemoteRegions() throws Exception { Applications apps = registry.getApplicationsFromAllRemoteRegions(); List<Application> registeredApplications = apps.getRegisteredApplications(); Assert.assertEquals("Apps size from remote regions do not match", 1, registeredApplications.size()); Application app = registeredApplications.iterator().next(); Assert.assertEquals("Added app did not return from remote registry", REMOTE_REGION_APP_NAME, app.getName()); Assert.assertEquals("Returned app did not have the instance", 1, app.getInstances().size()); } @Test public void testGetAppsDeltaFromAllRemoteRegions() throws Exception { registerInstanceLocally(createLocalInstance(LOCAL_REGION_INSTANCE_2_HOSTNAME)); /// local delta waitForDeltaToBeRetrieved(); Applications appDelta = registry.getApplicationDeltasFromMultipleRegions(null); List<Application> registeredApplications = appDelta.getRegisteredApplications(); Assert.assertEquals("Apps size from remote regions do not match", 2, registeredApplications.size()); Application localApplication = null; Application remApplication = null; for (Application registeredApplication : registeredApplications) { if (registeredApplication.getName().equalsIgnoreCase(LOCAL_REGION_APP_NAME)) { localApplication = registeredApplication; } if (registeredApplication.getName().equalsIgnoreCase(REMOTE_REGION_APP_NAME)) { remApplication = registeredApplication; } } Assert.assertNotNull("Did not find local registry app in delta.", localApplication); Assert.assertEquals("Local registry app instance count in delta not as expected.", 1, localApplication.getInstances().size()); Assert.assertNotNull("Did not find remote registry app in delta", remApplication); Assert.assertEquals("Remote registry app instance count in delta not as expected.", 1, remApplication.getInstances().size()); } @Test public void testAppsHashCodeAfterRefresh() throws InterruptedException { Assert.assertEquals("UP_1_", registry.getApplicationsFromAllRemoteRegions().getAppsHashCode()); registerInstanceLocally(createLocalInstance(LOCAL_REGION_INSTANCE_2_HOSTNAME)); waitForDeltaToBeRetrieved(); Assert.assertEquals("UP_2_", registry.getApplicationsFromAllRemoteRegions().getAppsHashCode()); } private void waitForDeltaToBeRetrieved() throws InterruptedException { int count = 0; System.out.println("Sleeping up to 35 seconds to let the remote registry fetch delta."); while (count++ < 35 && !mockRemoteEurekaServer.isSentDelta()) { Thread.sleep(1000); } if (!mockRemoteEurekaServer.isSentDelta()) { System.out.println("Waited for 35 seconds but remote server did not send delta"); } // Wait 2 seconds more to be sure the delta was processed Thread.sleep(2000); } @Test public void testGetAppsFromLocalRegionOnly() throws Exception { registerInstanceLocally(createLocalInstance(LOCAL_REGION_INSTANCE_1_HOSTNAME)); Applications apps = registry.getApplicationsFromLocalRegionOnly(); List<Application> registeredApplications = apps.getRegisteredApplications(); Assert.assertEquals("Apps size from local region do not match", 1, registeredApplications.size()); Application app = registeredApplications.iterator().next(); Assert.assertEquals("Added app did not return from local registry", LOCAL_REGION_APP_NAME, app.getName()); Assert.assertEquals("Returned app did not have the instance", 1, app.getInstances().size()); } @Test public void testGetAppsFromBothRegions() throws Exception { registerInstanceLocally(createRemoteInstance(LOCAL_REGION_INSTANCE_2_HOSTNAME)); registerInstanceLocally(createLocalInstance(LOCAL_REGION_INSTANCE_1_HOSTNAME)); Applications apps = registry.getApplicationsFromAllRemoteRegions(); List<Application> registeredApplications = apps.getRegisteredApplications(); Assert.assertEquals("Apps size from both regions do not match", 2, registeredApplications.size()); Application locaApplication = null; Application remApplication = null; for (Application registeredApplication : registeredApplications) { if (registeredApplication.getName().equalsIgnoreCase(LOCAL_REGION_APP_NAME)) { locaApplication = registeredApplication; } if (registeredApplication.getName().equalsIgnoreCase(REMOTE_REGION_APP_NAME)) { remApplication = registeredApplication; } } Assert.assertNotNull("Did not find local registry app", locaApplication); Assert.assertEquals("Local registry app instance count not as expected.", 1, locaApplication.getInstances().size()); Assert.assertNotNull("Did not find remote registry app", remApplication); Assert.assertEquals("Remote registry app instance count not as expected.", 2, remApplication.getInstances().size()); } @Test public void testStatusOverrideSetAndRemoval() throws Exception { InstanceInfo seed = createLocalInstance(LOCAL_REGION_INSTANCE_1_HOSTNAME); seed.setLastDirtyTimestamp(100l); // Regular registration first InstanceInfo myInstance1 = new InstanceInfo(seed); registerInstanceLocally(myInstance1); verifyLocalInstanceStatus(myInstance1.getId(), InstanceStatus.UP); // Override status boolean statusResult = registry.statusUpdate(LOCAL_REGION_APP_NAME, seed.getId(), InstanceStatus.OUT_OF_SERVICE, "0", false); assertThat("Couldn't override instance status", statusResult, is(true)); verifyLocalInstanceStatus(seed.getId(), InstanceStatus.OUT_OF_SERVICE); // Register again with status UP to verify that the override is still in place even if the dirtytimestamp is higher InstanceInfo myInstance2 = new InstanceInfo(seed); // clone to avoid object state in this test myInstance2.setLastDirtyTimestamp(200l); // use a later 'client side' dirty timestamp registry.register(myInstance2, 10000000, false); verifyLocalInstanceStatus(seed.getId(), InstanceStatus.OUT_OF_SERVICE); // Now remove override statusResult = registry.deleteStatusOverride(LOCAL_REGION_APP_NAME, seed.getId(), InstanceStatus.DOWN, "0", false); assertThat("Couldn't remove status override", statusResult, is(true)); verifyLocalInstanceStatus(seed.getId(), InstanceStatus.DOWN); // Register again with status UP after the override deletion, keeping myInstance2's dirtyTimestamp (== no client side change) InstanceInfo myInstance3 = new InstanceInfo(seed); // clone to avoid object state in this test myInstance3.setLastDirtyTimestamp(200l); // use a later 'client side' dirty timestamp registry.register(myInstance3, 10000000, false); verifyLocalInstanceStatus(seed.getId(), InstanceStatus.UP); } @Test public void testStatusOverrideWithRenewAppliedToAReplica() throws Exception { InstanceInfo seed = createLocalInstance(LOCAL_REGION_INSTANCE_1_HOSTNAME); seed.setLastDirtyTimestamp(100l); // Regular registration first InstanceInfo myInstance1 = new InstanceInfo(seed); registerInstanceLocally(myInstance1); verifyLocalInstanceStatus(myInstance1.getId(), InstanceStatus.UP); // Override status boolean statusResult = registry.statusUpdate(LOCAL_REGION_APP_NAME, seed.getId(), InstanceStatus.OUT_OF_SERVICE, "0", false); assertThat("Couldn't override instance status", statusResult, is(true)); verifyLocalInstanceStatus(seed.getId(), InstanceStatus.OUT_OF_SERVICE); // Send a renew to ensure timestamps are consistent even with the override in existence. // To do this, we get hold of the registry local InstanceInfo and reset its status to before an override // has been applied // (this is to simulate a case in a replica server where the override has been replicated, but not yet // applied to the local InstanceInfo) InstanceInfo registeredInstance = registry.getInstanceByAppAndId(seed.getAppName(), seed.getId()); registeredInstance.setStatusWithoutDirty(InstanceStatus.UP); verifyLocalInstanceStatus(seed.getId(), InstanceStatus.UP); registry.renew(seed.getAppName(), seed.getId(), false); verifyLocalInstanceStatus(seed.getId(), InstanceStatus.OUT_OF_SERVICE); // Now remove override statusResult = registry.deleteStatusOverride(LOCAL_REGION_APP_NAME, seed.getId(), InstanceStatus.DOWN, "0", false); assertThat("Couldn't remove status override", statusResult, is(true)); verifyLocalInstanceStatus(seed.getId(), InstanceStatus.DOWN); // Register again with status UP after the override deletion, keeping myInstance2's dirtyTimestamp (== no client side change) InstanceInfo myInstance3 = new InstanceInfo(seed); // clone to avoid object state in this test myInstance3.setLastDirtyTimestamp(200l); // use a later 'client side' dirty timestamp registry.register(myInstance3, 10000000, false); verifyLocalInstanceStatus(seed.getId(), InstanceStatus.UP); } @Test public void testStatusOverrideStartingStatus() throws Exception { // Regular registration first InstanceInfo myInstance = createLocalInstance(LOCAL_REGION_INSTANCE_1_HOSTNAME); registerInstanceLocally(myInstance); verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.UP); // Override status boolean statusResult = registry.statusUpdate(LOCAL_REGION_APP_NAME, myInstance.getId(), InstanceStatus.OUT_OF_SERVICE, "0", false); assertThat("Couldn't override instance status", statusResult, is(true)); verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.OUT_OF_SERVICE); // If we are not UP or OUT_OF_SERVICE, the OUT_OF_SERVICE override does not apply. It gets trumped by the current // status (STARTING or DOWN). Here we test with STARTING. myInstance = createLocalStartingInstance(LOCAL_REGION_INSTANCE_1_HOSTNAME); registerInstanceLocally(myInstance); verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.STARTING); } @Test public void testStatusOverrideWithExistingLeaseUp() throws Exception { // Without an override we expect to get the existing UP lease when we re-register with OUT_OF_SERVICE. // First, we are "up". InstanceInfo myInstance = createLocalInstance(LOCAL_REGION_INSTANCE_1_HOSTNAME); registerInstanceLocally(myInstance); verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.UP); // Then, we re-register with "out of service". InstanceInfo sameInstance = createLocalOutOfServiceInstance(LOCAL_REGION_INSTANCE_1_HOSTNAME); registry.register(sameInstance, 10000000, false); verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.UP); // Let's try again. We shouldn't see a difference. sameInstance = createLocalOutOfServiceInstance(LOCAL_REGION_INSTANCE_1_HOSTNAME); registry.register(sameInstance, 10000000, false); verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.UP); } @Test public void testStatusOverrideWithExistingLeaseOutOfService() throws Exception { // Without an override we expect to get the existing OUT_OF_SERVICE lease when we re-register with UP. // First, we are "out of service". InstanceInfo myInstance = createLocalOutOfServiceInstance(LOCAL_REGION_INSTANCE_1_HOSTNAME); registerInstanceLocally(myInstance); verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.OUT_OF_SERVICE); // Then, we re-register with "UP". InstanceInfo sameInstance = createLocalInstance(LOCAL_REGION_INSTANCE_1_HOSTNAME); registry.register(sameInstance, 10000000, false); verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.OUT_OF_SERVICE); // Let's try again. We shouldn't see a difference. sameInstance = createLocalInstance(LOCAL_REGION_INSTANCE_1_HOSTNAME); registry.register(sameInstance, 10000000, false); verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.OUT_OF_SERVICE); } @Test public void testEvictionTaskCompensationTime() throws Exception { long evictionTaskPeriodNanos = serverConfig.getEvictionIntervalTimerInMs() * 1000000; AbstractInstanceRegistry.EvictionTask testTask = spy(registry.new EvictionTask()); when(testTask.getCurrentTimeNano()) .thenReturn(1l) // less than the period .thenReturn(1l + evictionTaskPeriodNanos) // exactly 1 period .thenReturn(1l + evictionTaskPeriodNanos*2 + 10000000l) // 10ms longer than 1 period .thenReturn(1l + evictionTaskPeriodNanos*3 - 1l); // less than 1 period assertThat(testTask.getCompensationTimeMs(), is(0l)); assertThat(testTask.getCompensationTimeMs(), is(0l)); assertThat(testTask.getCompensationTimeMs(), is(10l)); assertThat(testTask.getCompensationTimeMs(), is(0l)); } @Test public void testCircularQueue() throws Exception { CircularQueue<Integer> queue = new CircularQueue<>(5); Assert.assertEquals(0, queue.size()); Assert.assertNull(queue.peek()); Assert.assertEquals(Collections.emptyList(), new ArrayList<>(queue)); queue.add(1); queue.add(2); queue.add(3); queue.add(4); Assert.assertEquals(4, queue.size()); Assert.assertEquals(Arrays.asList(1, 2, 3, 4), new ArrayList<>(queue)); queue.offer(5); Assert.assertEquals(5, queue.size()); Assert.assertEquals(Arrays.asList(1, 2, 3, 4, 5), new ArrayList<>(queue)); queue.offer(6); Assert.assertEquals(5, queue.size()); Assert.assertEquals(Arrays.asList(2, 3, 4, 5, 6), new ArrayList<>(queue)); Integer poll = queue.poll(); Assert.assertEquals(4, queue.size()); Assert.assertEquals((Object) 2, poll); Assert.assertEquals(Arrays.asList(3, 4, 5, 6), new ArrayList<>(queue)); queue.add(7); Assert.assertEquals(5, queue.size()); Assert.assertEquals(Arrays.asList(3, 4, 5, 6, 7), new ArrayList<>(queue)); queue.clear(); Assert.assertEquals(0, queue.size()); Assert.assertEquals(Collections.emptyList(), new ArrayList<>(queue)); } }
6,895
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/registry/TimeConsumingInstanceRegistryTest.java
package com.netflix.eureka.registry; import com.google.common.base.Preconditions; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.InstanceStatus; import com.netflix.eureka.AbstractTester; import com.netflix.eureka.EurekaServerConfig; import com.netflix.eureka.test.async.executor.AsyncResult; import com.netflix.eureka.test.async.executor.AsyncSequentialExecutor; import com.netflix.eureka.test.async.executor.SequentialEvents; import com.netflix.eureka.test.async.executor.SingleEvent; import org.junit.Assert; import org.junit.Test; /** * Time consuming test case for {@link InstanceRegistry}. * * @author neoremind */ public class TimeConsumingInstanceRegistryTest extends AbstractTester { /** * Verify the following behaviors, the test case will run for 2 minutes. * <ul> * <li>1. Registration of new instances.</li> * <li>2. Lease expiration.</li> * <li>3. NumOfRenewsPerMinThreshold will be updated. Since this threshold will be updated according to * {@link EurekaServerConfig#getRenewalThresholdUpdateIntervalMs()}, and discovery client will try to get * applications count from peer or remote Eureka servers, the count number will be used to update threshold.</li> * </ul> * </p> * Below shows the time line of a bunch of events in 120 seconds. Here the following setting are configured during registry startup: * <code>eureka.renewalThresholdUpdateIntervalMs=5000</code>, * <code>eureka.evictionIntervalTimerInMs=10000</code>, * <code>eureka.renewalPercentThreshold=0.85</code> * </p> * <pre> * TimeInSecs 0 15 30 40 45 60 75 80 90 105 120 * |----------|----------|------|----|----------|---------|----|-------|----------|---------| * Events (1) (2) (3) (4) (5) (6) (7) (8) (9) * </pre> * </p> * <ul> * <li>(1). Remote server started on random port, local registry started as well. * 50 instances will be registered to local registry with application name of {@link #LOCAL_REGION_APP_NAME} * and lease duration set to 30 seconds. * At this time isLeaseExpirationEnabled=false, getNumOfRenewsPerMinThreshold= * (50*2 + 1(initial value))*85%=86</li> * <li>(2). 45 out of the 50 instances send heartbeats to local registry.</li> * <li>(3). Check registry status, isLeaseExpirationEnabled=false, getNumOfRenewsInLastMin=0, * getNumOfRenewsPerMinThreshold=86, registeredInstancesNumberOfMYLOCALAPP=50</li> * <li>(4). 45 out of the 50 instances send heartbeats to local registry.</li> * <li>(5). Accumulate one minutes data, and from now on, isLeaseExpirationEnabled=true, * getNumOfRenewsInLastMin=90. Because lease expiration is enabled, and lease for 5 instance are expired, * so when eviction thread is working, the 5 instances will be marked as deleted.</li> * <li>(6). 45 out of the 50 instances send heartbeats to local registry.</li> * <li>(7). Check registry status, isLeaseExpirationEnabled=true, getNumOfRenewsInLastMin=90, * getNumOfRenewsPerMinThreshold=86, registeredInstancesNumberOfMYLOCALAPP=45</li> * Remote region add another 150 instances to application of {@link #LOCAL_REGION_APP_NAME}. * This will make {@link PeerAwareInstanceRegistryImpl#updateRenewalThreshold()} to refresh * {@link AbstractInstanceRegistry#numberOfRenewsPerMinThreshold}.</li> * <li>(8). 45 out of the 50 instances send heartbeats to local registry.</li> * <li>(9). Check registry status, isLeaseExpirationEnabled=false, getNumOfRenewsInLastMin=90, * getNumOfRenewsPerMinThreshold=256, registeredInstancesNumberOfMYLOCALAPP=45</li> * </ul> * </p> * Note that there is a thread retrieving and printing out registry status for debugging purpose. */ @Test public void testLeaseExpirationAndUpdateRenewalThreshold() throws InterruptedException { final int registeredInstanceCount = 50; final int leaseDurationInSecs = 30; AsyncSequentialExecutor executor = new AsyncSequentialExecutor(); SequentialEvents registerMyLocalAppAndInstancesEvents = SequentialEvents.of( buildEvent(0, new SingleEvent.Action() { @Override public void execute() { for (int j = 0; j < registeredInstanceCount; j++) { registerInstanceLocallyWithLeaseDurationInSecs(createLocalInstanceWithIdAndStatus(LOCAL_REGION_APP_NAME, LOCAL_REGION_INSTANCE_1_HOSTNAME + j, InstanceStatus.UP), leaseDurationInSecs); } } }) ); SequentialEvents showRegistryStatusEvents = SequentialEvents.of( buildEvents(5, 24, new SingleEvent.Action() { @Override public void execute() { System.out.println(String.format("isLeaseExpirationEnabled=%s, getNumOfRenewsInLastMin=%d, " + "getNumOfRenewsPerMinThreshold=%s, instanceNumberOfMYLOCALAPP=%d", registry.isLeaseExpirationEnabled(), registry.getNumOfRenewsInLastMin(), registry.getNumOfRenewsPerMinThreshold(), registry.getApplication(LOCAL_REGION_APP_NAME).getInstances().size())); } }) ); SequentialEvents renewEvents = SequentialEvents.of( buildEvent(15, renewPartOfTheWholeInstancesAction()), buildEvent(30, renewPartOfTheWholeInstancesAction()), buildEvent(30, renewPartOfTheWholeInstancesAction()), buildEvent(30, renewPartOfTheWholeInstancesAction()) ); SequentialEvents remoteRegionAddMoreInstancesEvents = SequentialEvents.of( buildEvent(90, new SingleEvent.Action() { @Override public void execute() { for (int i = 0; i < 150; i++) { InstanceInfo newlyCreatedInstance = createLocalInstanceWithIdAndStatus(REMOTE_REGION_APP_NAME, LOCAL_REGION_INSTANCE_1_HOSTNAME + i, InstanceStatus.UP); remoteRegionApps.get(REMOTE_REGION_APP_NAME).addInstance(newlyCreatedInstance); remoteRegionAppsDelta.get(REMOTE_REGION_APP_NAME).addInstance(newlyCreatedInstance); } } }) ); SequentialEvents checkEvents = SequentialEvents.of( buildEvent(40, new SingleEvent.Action() { @Override public void execute() { System.out.println("checking on 40s"); Preconditions.checkState(Boolean.FALSE.equals(registry.isLeaseExpirationEnabled()), "Lease expiration should be disabled"); Preconditions.checkState(registry.getNumOfRenewsInLastMin() == 0, "Renewals in last min should be 0"); Preconditions.checkState(registry.getApplication(LOCAL_REGION_APP_NAME).getInstances().size() == 50, "There should be 50 instances in application - MYLOCAPP"); } }), buildEvent(40, new SingleEvent.Action() { @Override public void execute() { System.out.println("checking on 80s"); Preconditions.checkState(Boolean.TRUE.equals(registry.isLeaseExpirationEnabled()), "Lease expiration should be enabled"); Preconditions.checkState(registry.getNumOfRenewsInLastMin() == 90, "Renewals in last min should be 90"); Preconditions.checkState(registry.getApplication(LOCAL_REGION_APP_NAME).getInstances().size() == 45, "There should be 45 instances in application - MYLOCAPP"); } }), buildEvent(40, new SingleEvent.Action() { @Override public void execute() { System.out.println("checking on 120s"); System.out.println("getNumOfRenewsPerMinThreshold=" + registry.getNumOfRenewsPerMinThreshold()); Preconditions.checkState(registry.getNumOfRenewsPerMinThreshold() == 256, "NumOfRenewsPerMinThreshold should be updated to 256"); Preconditions.checkState(registry.getApplication(LOCAL_REGION_APP_NAME).getInstances().size() == 45, "There should be 45 instances in application - MYLOCAPP"); } }) ); AsyncResult<AsyncSequentialExecutor.ResultStatus> registerMyLocalAppAndInstancesResult = executor.run(registerMyLocalAppAndInstancesEvents); AsyncResult<AsyncSequentialExecutor.ResultStatus> showRegistryStatusEventResult = executor.run(showRegistryStatusEvents); AsyncResult<AsyncSequentialExecutor.ResultStatus> renewResult = executor.run(renewEvents); AsyncResult<AsyncSequentialExecutor.ResultStatus> remoteRegionAddMoreInstancesResult = executor.run(remoteRegionAddMoreInstancesEvents); AsyncResult<AsyncSequentialExecutor.ResultStatus> checkResult = executor.run(checkEvents); Assert.assertEquals("Register application and instances failed", AsyncSequentialExecutor.ResultStatus.DONE, registerMyLocalAppAndInstancesResult.getResult()); Assert.assertEquals("Show registry status failed", AsyncSequentialExecutor.ResultStatus.DONE, showRegistryStatusEventResult.getResult()); Assert.assertEquals("Renew lease did not succeed", AsyncSequentialExecutor.ResultStatus.DONE, renewResult.getResult()); Assert.assertEquals("More instances are registered to remote region did not succeed", AsyncSequentialExecutor.ResultStatus.DONE, remoteRegionAddMoreInstancesResult.getResult()); Assert.assertEquals("Check failed", AsyncSequentialExecutor.ResultStatus.DONE, checkResult.getResult()); } }
6,896
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/registry/ResponseCacheTest.java
package com.netflix.eureka.registry; import com.netflix.appinfo.EurekaAccept; import com.netflix.discovery.DefaultEurekaClientConfig; import com.netflix.eureka.AbstractTester; import com.netflix.eureka.DefaultEurekaServerConfig; import com.netflix.eureka.EurekaServerConfig; import com.netflix.eureka.Version; import com.netflix.eureka.resources.DefaultServerCodecs; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; /** * @author Nitesh Kant */ public class ResponseCacheTest extends AbstractTester { private static final String REMOTE_REGION = "myremote"; private PeerAwareInstanceRegistry testRegistry; @Override @Before public void setUp() throws Exception { super.setUp(); // create a new registry that is sync'ed up with the default registry in the AbstractTester, // but disable transparent fetch to the remote for gets EurekaServerConfig serverConfig = spy(new DefaultEurekaServerConfig()); doReturn(true).when(serverConfig).disableTransparentFallbackToOtherRegion(); testRegistry = new PeerAwareInstanceRegistryImpl( serverConfig, new DefaultEurekaClientConfig(), new DefaultServerCodecs(serverConfig), client ); testRegistry.init(serverContext.getPeerEurekaNodes()); testRegistry.syncUp(); } @Test public void testInvalidate() throws Exception { ResponseCacheImpl cache = (ResponseCacheImpl) testRegistry.getResponseCache(); Key key = new Key(Key.EntityType.Application, REMOTE_REGION_APP_NAME, Key.KeyType.JSON, Version.V1, EurekaAccept.full); String response = cache.get(key, false); Assert.assertNotNull("Cache get returned null.", response); testRegistry.cancel(REMOTE_REGION_APP_NAME, REMOTE_REGION_INSTANCE_1_HOSTNAME, true); Assert.assertNull("Cache after invalidate did not return null for write view.", cache.get(key, true)); } @Test public void testInvalidateWithRemoteRegion() throws Exception { ResponseCacheImpl cache = (ResponseCacheImpl) testRegistry.getResponseCache(); Key key = new Key( Key.EntityType.Application, REMOTE_REGION_APP_NAME, Key.KeyType.JSON, Version.V1, EurekaAccept.full, new String[]{REMOTE_REGION} ); Assert.assertNotNull("Cache get returned null.", cache.get(key, false)); testRegistry.cancel(REMOTE_REGION_APP_NAME, REMOTE_REGION_INSTANCE_1_HOSTNAME, true); Assert.assertNull("Cache after invalidate did not return null.", cache.get(key)); } @Test public void testInvalidateWithMultipleRemoteRegions() throws Exception { ResponseCacheImpl cache = (ResponseCacheImpl) testRegistry.getResponseCache(); Key key1 = new Key( Key.EntityType.Application, REMOTE_REGION_APP_NAME, Key.KeyType.JSON, Version.V1, EurekaAccept.full, new String[]{REMOTE_REGION, "myregion2"} ); Key key2 = new Key( Key.EntityType.Application, REMOTE_REGION_APP_NAME, Key.KeyType.JSON, Version.V1, EurekaAccept.full, new String[]{REMOTE_REGION} ); Assert.assertNotNull("Cache get returned null.", cache.get(key1, false)); Assert.assertNotNull("Cache get returned null.", cache.get(key2, false)); testRegistry.cancel(REMOTE_REGION_APP_NAME, REMOTE_REGION_INSTANCE_1_HOSTNAME, true); Assert.assertNull("Cache after invalidate did not return null.", cache.get(key1, true)); Assert.assertNull("Cache after invalidate did not return null.", cache.get(key2, true)); } }
6,897
0
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka
Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/aws/EIPManagerTest.java
/* * Copyright 2018 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.eureka.aws; import com.google.common.collect.Lists; import com.netflix.discovery.EurekaClientConfig; import org.junit.Before; import org.junit.Test; import java.util.Collection; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * @author Joseph Witthuhn */ public class EIPManagerTest { private EurekaClientConfig config = mock(EurekaClientConfig.class); private EIPManager eipManager; @Before public void setUp() { when(config.shouldUseDnsForFetchingServiceUrls()).thenReturn(Boolean.FALSE); eipManager = new EIPManager(null, config, null, null); } @Test public void shouldFilterNonElasticNames() { when(config.getRegion()).thenReturn("us-east-1"); List<String> hosts = Lists.newArrayList("example.com", "ec2-1-2-3-4.compute.amazonaws.com", "5.6.7.8", "ec2-101-202-33-44.compute.amazonaws.com"); when(config.getEurekaServerServiceUrls(any(String.class))).thenReturn(hosts); Collection<String> returnValue = eipManager.getCandidateEIPs("i-123", "us-east-1d"); assertEquals(2, returnValue.size()); assertTrue(returnValue.contains("1.2.3.4")); assertTrue(returnValue.contains("101.202.33.44")); } @Test public void shouldFilterNonElasticNamesInOtherRegion() { when(config.getRegion()).thenReturn("eu-west-1"); List<String> hosts = Lists.newArrayList("example.com", "ec2-1-2-3-4.eu-west-1.compute.amazonaws.com", "5.6.7.8", "ec2-101-202-33-44.eu-west-1.compute.amazonaws.com"); when(config.getEurekaServerServiceUrls(any(String.class))).thenReturn(hosts); Collection<String> returnValue = eipManager.getCandidateEIPs("i-123", "eu-west-1a"); assertEquals(2, returnValue.size()); assertTrue(returnValue.contains("1.2.3.4")); assertTrue(returnValue.contains("101.202.33.44")); } @Test(expected = RuntimeException.class) public void shouldThrowExceptionWhenNoElasticNames() { when(config.getRegion()).thenReturn("eu-west-1"); List<String> hosts = Lists.newArrayList("example.com", "5.6.7.8"); when(config.getEurekaServerServiceUrls(any(String.class))).thenReturn(hosts); eipManager.getCandidateEIPs("i-123", "eu-west-1a"); } }
6,898
0
Create_ds/eureka/eureka-core/src/main/java/com/netflix
Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/EurekaServerContext.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.eureka; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.eureka.cluster.PeerEurekaNodes; import com.netflix.eureka.registry.PeerAwareInstanceRegistry; import com.netflix.eureka.resources.ServerCodecs; /** * @author David Liu */ public interface EurekaServerContext { void initialize() throws Exception; void shutdown() throws Exception; EurekaServerConfig getServerConfig(); PeerEurekaNodes getPeerEurekaNodes(); ServerCodecs getServerCodecs(); PeerAwareInstanceRegistry getRegistry(); ApplicationInfoManager getApplicationInfoManager(); }
6,899