index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/MonitoredConnectionManager.java | package com.netflix.discovery.shared;
import java.util.concurrent.TimeUnit;
import com.google.common.annotations.VisibleForTesting;
import org.apache.http.conn.ClientConnectionRequest;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.conn.tsccm.AbstractConnPool;
import org.apache.http.impl.conn.tsccm.ConnPoolByRoute;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.HttpParams;
/**
* A connection manager that uses {@link NamedConnectionPool}, which provides
* connection reuse statistics, as its underlying connection pool.
*
* @author awang
*
*/
public class MonitoredConnectionManager extends ThreadSafeClientConnManager {
public MonitoredConnectionManager(String name) {
super();
initMonitors(name);
}
public MonitoredConnectionManager(String name, SchemeRegistry schreg, long connTTL,
TimeUnit connTTLTimeUnit) {
super(schreg, connTTL, connTTLTimeUnit);
initMonitors(name);
}
public MonitoredConnectionManager(String name, SchemeRegistry schreg) {
super(schreg);
initMonitors(name);
}
void initMonitors(String name) {
if (this.pool instanceof NamedConnectionPool) {
((NamedConnectionPool) this.pool).initMonitors(name);
}
}
@Override
@Deprecated
protected AbstractConnPool createConnectionPool(HttpParams params) {
return new NamedConnectionPool(connOperator, params);
}
@Override
protected ConnPoolByRoute createConnectionPool(long connTTL,
TimeUnit connTTLTimeUnit) {
return new NamedConnectionPool(connOperator, connPerRoute, 20, connTTL, connTTLTimeUnit);
}
@VisibleForTesting
ConnPoolByRoute getConnectionPool() {
return this.pool;
}
@Override
public ClientConnectionRequest requestConnection(HttpRoute route,
Object state) {
// TODO Auto-generated method stub
return super.requestConnection(route, state);
}
}
| 8,000 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/NamedConnectionPool.java | package com.netflix.discovery.shared;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Preconditions;
import com.netflix.servo.annotations.DataSourceType;
import com.netflix.servo.annotations.Monitor;
import com.netflix.servo.monitor.Counter;
import com.netflix.servo.monitor.Monitors;
import com.netflix.servo.monitor.Stopwatch;
import com.netflix.servo.monitor.Timer;
import org.apache.http.conn.ClientConnectionOperator;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.conn.params.ConnPerRoute;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.impl.conn.tsccm.BasicPoolEntry;
import org.apache.http.impl.conn.tsccm.ConnPoolByRoute;
import org.apache.http.impl.conn.tsccm.PoolEntryRequest;
import org.apache.http.impl.conn.tsccm.RouteSpecificPool;
import org.apache.http.impl.conn.tsccm.WaitingThreadAborter;
import org.apache.http.params.HttpParams;
/**
* A connection pool that provides Servo counters to monitor the efficiency.
* Three counters are provided: counter for getting free entries (or reusing entries),
* counter for creating new entries, and counter for every connection request.
*
* @author awang
*
*/
public class NamedConnectionPool extends ConnPoolByRoute {
private Counter freeEntryCounter;
private Counter createEntryCounter;
private Counter requestCounter;
private Counter releaseCounter;
private Counter deleteCounter;
private Timer requestTimer;
private Timer creationTimer;
private String name;
public NamedConnectionPool(String name, ClientConnectionOperator operator,
ConnPerRoute connPerRoute, int maxTotalConnections, long connTTL,
TimeUnit connTTLTimeUnit) {
super(operator, connPerRoute, maxTotalConnections, connTTL, connTTLTimeUnit);
initMonitors(name);
}
public NamedConnectionPool(String name, ClientConnectionOperator operator,
ConnPerRoute connPerRoute, int maxTotalConnections) {
super(operator, connPerRoute, maxTotalConnections);
initMonitors(name);
}
public NamedConnectionPool(String name, ClientConnectionOperator operator,
HttpParams params) {
super(operator, params);
initMonitors(name);
}
NamedConnectionPool(ClientConnectionOperator operator,
ConnPerRoute connPerRoute, int maxTotalConnections, long connTTL,
TimeUnit connTTLTimeUnit) {
super(operator, connPerRoute, maxTotalConnections, connTTL, connTTLTimeUnit);
}
NamedConnectionPool(ClientConnectionOperator operator,
ConnPerRoute connPerRoute, int maxTotalConnections) {
super(operator, connPerRoute, maxTotalConnections);
}
NamedConnectionPool(ClientConnectionOperator operator,
HttpParams params) {
super(operator, params);
}
void initMonitors(String name) {
Preconditions.checkNotNull(name);
freeEntryCounter = Monitors.newCounter(name + "_Reuse");
createEntryCounter = Monitors.newCounter(name + "_CreateNew");
requestCounter = Monitors.newCounter(name + "_Request");
releaseCounter = Monitors.newCounter(name + "_Release");
deleteCounter = Monitors.newCounter(name + "_Delete");
requestTimer = Monitors.newTimer(name + "_RequestConnectionTimer", TimeUnit.MILLISECONDS);
creationTimer = Monitors.newTimer(name + "_CreateConnectionTimer", TimeUnit.MILLISECONDS);
this.name = name;
Monitors.registerObject(name, this);
}
@Override
public PoolEntryRequest requestPoolEntry(HttpRoute route, Object state) {
requestCounter.increment();
return super.requestPoolEntry(route, state);
}
@Override
protected BasicPoolEntry getFreeEntry(RouteSpecificPool rospl, Object state) {
BasicPoolEntry entry = super.getFreeEntry(rospl, state);
if (entry != null) {
freeEntryCounter.increment();
}
return entry;
}
@Override
protected BasicPoolEntry createEntry(RouteSpecificPool rospl,
ClientConnectionOperator op) {
createEntryCounter.increment();
Stopwatch stopWatch = creationTimer.start();
try {
return super.createEntry(rospl, op);
} finally {
stopWatch.stop();
}
}
@Override
protected BasicPoolEntry getEntryBlocking(HttpRoute route, Object state,
long timeout, TimeUnit tunit, WaitingThreadAborter aborter)
throws ConnectionPoolTimeoutException, InterruptedException {
Stopwatch stopWatch = requestTimer.start();
try {
return super.getEntryBlocking(route, state, timeout, tunit, aborter);
} finally {
stopWatch.stop();
}
}
@Override
public void freeEntry(BasicPoolEntry entry, boolean reusable,
long validDuration, TimeUnit timeUnit) {
releaseCounter.increment();
super.freeEntry(entry, reusable, validDuration, timeUnit);
}
@Override
protected void deleteEntry(BasicPoolEntry entry) {
deleteCounter.increment();
super.deleteEntry(entry);
}
public final long getFreeEntryCount() {
return freeEntryCounter.getValue().longValue();
}
public final long getCreatedEntryCount() {
return createEntryCounter.getValue().longValue();
}
public final long getRequestsCount() {
return requestCounter.getValue().longValue();
}
public final long getReleaseCount() {
return releaseCounter.getValue().longValue();
}
public final long getDeleteCount() {
return deleteCounter.getValue().longValue();
}
@Monitor(name = "connectionCount", type = DataSourceType.GAUGE)
public int getConnectionCount() {
return this.getConnectionsInPool();
}
@Override
public void shutdown() {
super.shutdown();
if(Monitors.isObjectRegistered(name, this)) {
Monitors.unregisterObject(name, this);
}
}
}
| 8,001 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/LookupService.java | /*
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery.shared;
import java.util.List;
import com.netflix.appinfo.InstanceInfo;
/**
* Lookup service for finding active instances.
*
* @author Karthik Ranganathan, Greg Kim.
* @param <T> for backward compatibility
*/
public interface LookupService<T> {
/**
* Returns the corresponding {@link Application} object which is basically a
* container of all registered <code>appName</code> {@link InstanceInfo}s.
*
* @param appName
* @return a {@link Application} or null if we couldn't locate any app of
* the requested appName
*/
Application getApplication(String appName);
/**
* Returns the {@link Applications} object which is basically a container of
* all currently registered {@link Application}s.
*
* @return {@link Applications}
*/
Applications getApplications();
/**
* Returns the {@link List} of {@link InstanceInfo}s matching the the passed
* in id. A single {@link InstanceInfo} can possibly be registered w/ more
* than one {@link Application}s
*
* @param id
* @return {@link List} of {@link InstanceInfo}s or
* {@link java.util.Collections#emptyList()}
*/
List<InstanceInfo> getInstancesById(String id);
/**
* Gets the next possible server to process the requests from the registry
* information received from eureka.
*
* <p>
* The next server is picked on a round-robin fashion. By default, this
* method just returns the servers that are currently with
* {@link com.netflix.appinfo.InstanceInfo.InstanceStatus#UP} status.
* This configuration can be controlled by overriding the
* {@link com.netflix.discovery.EurekaClientConfig#shouldFilterOnlyUpInstances()}.
*
* Note that in some cases (Eureka emergency mode situation), the instances
* that are returned may not be unreachable, it is solely up to the client
* at that point to timeout quickly and retry the next server.
* </p>
*
* @param virtualHostname
* the virtual host name that is associated to the servers.
* @param secure
* indicates whether this is a HTTP or a HTTPS request - secure
* means HTTPS.
* @return the {@link InstanceInfo} information which contains the public
* host name of the next server in line to process the request based
* on the round-robin algorithm.
* @throws java.lang.RuntimeException if the virtualHostname does not exist
*/
InstanceInfo getNextServerFromEureka(String virtualHostname, boolean secure);
}
| 8,002 |
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/transport/TransportException.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery.shared.transport;
/**
* @author Tomasz Bak
*/
public class TransportException extends RuntimeException {
public TransportException(String message) {
super(message);
}
public TransportException(String message, Throwable cause) {
super(message, cause);
}
}
| 8,003 |
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/transport/EurekaHttpClient.java | package com.netflix.discovery.shared.transport;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import com.netflix.discovery.shared.Application;
import com.netflix.discovery.shared.Applications;
/**
* Low level Eureka HTTP client API.
*
* @author Tomasz Bak
*/
public interface EurekaHttpClient {
EurekaHttpResponse<Void> register(InstanceInfo info);
EurekaHttpResponse<Void> cancel(String appName, String id);
EurekaHttpResponse<InstanceInfo> sendHeartBeat(String appName, String id, InstanceInfo info, InstanceStatus overriddenStatus);
EurekaHttpResponse<Void> statusUpdate(String appName, String id, InstanceStatus newStatus, InstanceInfo info);
EurekaHttpResponse<Void> deleteStatusOverride(String appName, String id, InstanceInfo info);
EurekaHttpResponse<Applications> getApplications(String... regions);
EurekaHttpResponse<Applications> getDelta(String... regions);
EurekaHttpResponse<Applications> getVip(String vipAddress, String... regions);
EurekaHttpResponse<Applications> getSecureVip(String secureVipAddress, String... regions);
EurekaHttpResponse<Application> getApplication(String appName);
EurekaHttpResponse<InstanceInfo> getInstance(String appName, String id);
EurekaHttpResponse<InstanceInfo> getInstance(String id);
void shutdown();
}
| 8,004 |
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/transport/PropertyBasedTransportConfigConstants.java | package com.netflix.discovery.shared.transport;
/**
* constants pertaining to property based transport configs
*
* @author David Liu
*/
final class PropertyBasedTransportConfigConstants {
// NOTE: all keys are before any prefixes are applied
static final String SESSION_RECONNECT_INTERVAL_KEY = "sessionedClientReconnectIntervalSeconds";
static final String QUARANTINE_REFRESH_PERCENTAGE_KEY = "retryableClientQuarantineRefreshPercentage";
static final String DATA_STALENESS_THRESHOLD_KEY = "applicationsResolverDataStalenessThresholdSeconds";
static final String APPLICATION_RESOLVER_USE_IP_KEY = "applicationsResolverUseIp";
static final String ASYNC_RESOLVER_REFRESH_INTERVAL_KEY = "asyncResolverRefreshIntervalMs";
static final String ASYNC_RESOLVER_WARMUP_TIMEOUT_KEY = "asyncResolverWarmupTimeoutMs";
static final String ASYNC_EXECUTOR_THREADPOOL_SIZE_KEY = "asyncExecutorThreadPoolSize";
static final String WRITE_CLUSTER_VIP_KEY = "writeClusterVip";
static final String READ_CLUSTER_VIP_KEY = "readClusterVip";
static final String BOOTSTRAP_RESOLVER_STRATEGY_KEY = "bootstrapResolverStrategy";
static final String USE_BOOTSTRAP_RESOLVER_FOR_QUERY = "useBootstrapResolverForQuery";
static final String TRANSPORT_CONFIG_SUB_NAMESPACE = "transport";
static class Values {
static final int SESSION_RECONNECT_INTERVAL = 20*60;
static final double QUARANTINE_REFRESH_PERCENTAGE = 0.66;
static final int DATA_STALENESS_TRHESHOLD = 5*60;
static final int ASYNC_RESOLVER_REFRESH_INTERVAL = 5*60*1000;
static final int ASYNC_RESOLVER_WARMUP_TIMEOUT = 5000;
static final int ASYNC_EXECUTOR_THREADPOOL_SIZE = 5;
}
}
| 8,005 |
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/transport/EurekaHttpClients.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery.shared.transport;
import java.util.List;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.discovery.EurekaClientNames;
import com.netflix.discovery.shared.resolver.AsyncResolver;
import com.netflix.discovery.shared.resolver.ClosableResolver;
import com.netflix.discovery.shared.resolver.ClusterResolver;
import com.netflix.discovery.shared.resolver.EndpointRandomizer;
import com.netflix.discovery.shared.resolver.EurekaEndpoint;
import com.netflix.discovery.shared.resolver.aws.ApplicationsResolver;
import com.netflix.discovery.shared.resolver.aws.AwsEndpoint;
import com.netflix.discovery.shared.resolver.aws.ConfigClusterResolver;
import com.netflix.discovery.shared.resolver.aws.EurekaHttpResolver;
import com.netflix.discovery.shared.resolver.aws.ZoneAffinityClusterResolver;
import com.netflix.discovery.shared.transport.decorator.SessionedEurekaHttpClient;
import com.netflix.discovery.shared.transport.decorator.RedirectingEurekaHttpClient;
import com.netflix.discovery.shared.transport.decorator.RetryableEurekaHttpClient;
import com.netflix.discovery.shared.transport.decorator.ServerStatusEvaluators;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Tomasz Bak
*/
public final class EurekaHttpClients {
private static final Logger logger = LoggerFactory.getLogger(EurekaHttpClients.class);
private EurekaHttpClients() {
}
public static EurekaHttpClientFactory queryClientFactory(ClusterResolver bootstrapResolver,
TransportClientFactory transportClientFactory,
EurekaClientConfig clientConfig,
EurekaTransportConfig transportConfig,
InstanceInfo myInstanceInfo,
ApplicationsResolver.ApplicationsSource applicationsSource,
EndpointRandomizer randomizer
) {
ClosableResolver queryResolver = transportConfig.useBootstrapResolverForQuery()
? wrapClosable(bootstrapResolver)
: queryClientResolver(bootstrapResolver, transportClientFactory,
clientConfig, transportConfig, myInstanceInfo, applicationsSource, randomizer);
return canonicalClientFactory(EurekaClientNames.QUERY, transportConfig, queryResolver, transportClientFactory);
}
public static EurekaHttpClientFactory registrationClientFactory(ClusterResolver bootstrapResolver,
TransportClientFactory transportClientFactory,
EurekaTransportConfig transportConfig) {
return canonicalClientFactory(EurekaClientNames.REGISTRATION, transportConfig, bootstrapResolver, transportClientFactory);
}
static EurekaHttpClientFactory canonicalClientFactory(final String name,
final EurekaTransportConfig transportConfig,
final ClusterResolver<EurekaEndpoint> clusterResolver,
final TransportClientFactory transportClientFactory) {
return new EurekaHttpClientFactory() {
@Override
public EurekaHttpClient newClient() {
return new SessionedEurekaHttpClient(
name,
RetryableEurekaHttpClient.createFactory(
name,
transportConfig,
clusterResolver,
RedirectingEurekaHttpClient.createFactory(transportClientFactory),
ServerStatusEvaluators.legacyEvaluator()),
transportConfig.getSessionedClientReconnectIntervalSeconds() * 1000
);
}
@Override
public void shutdown() {
wrapClosable(clusterResolver).shutdown();
}
};
}
// ==================================
// Resolvers for the client factories
// ==================================
public static final String COMPOSITE_BOOTSTRAP_STRATEGY = "composite";
public static ClosableResolver<AwsEndpoint> newBootstrapResolver(
final EurekaClientConfig clientConfig,
final EurekaTransportConfig transportConfig,
final TransportClientFactory transportClientFactory,
final InstanceInfo myInstanceInfo,
final ApplicationsResolver.ApplicationsSource applicationsSource,
final EndpointRandomizer randomizer) {
if (COMPOSITE_BOOTSTRAP_STRATEGY.equals(transportConfig.getBootstrapResolverStrategy())) {
if (clientConfig.shouldFetchRegistry()) {
return compositeBootstrapResolver(
clientConfig,
transportConfig,
transportClientFactory,
myInstanceInfo,
applicationsSource,
randomizer
);
} else {
logger.warn("Cannot create a composite bootstrap resolver if registry fetch is disabled." +
" Falling back to using a default bootstrap resolver.");
}
}
// if all else fails, return the default
return defaultBootstrapResolver(clientConfig, myInstanceInfo, randomizer);
}
/**
* @return a bootstrap resolver that resolves eureka server endpoints based on either DNS or static config,
* depending on configuration for one or the other. This resolver will warm up at the start.
*/
static ClosableResolver<AwsEndpoint> defaultBootstrapResolver(final EurekaClientConfig clientConfig,
final InstanceInfo myInstanceInfo,
final EndpointRandomizer randomizer) {
String[] availZones = clientConfig.getAvailabilityZones(clientConfig.getRegion());
String myZone = InstanceInfo.getZone(availZones, myInstanceInfo);
ClusterResolver<AwsEndpoint> delegateResolver = new ZoneAffinityClusterResolver(
new ConfigClusterResolver(clientConfig, myInstanceInfo),
myZone,
true,
randomizer
);
List<AwsEndpoint> initialValue = delegateResolver.getClusterEndpoints();
if (initialValue.isEmpty()) {
String msg = "Initial resolution of Eureka server endpoints failed. Check ConfigClusterResolver logs for more info";
logger.error(msg);
failFastOnInitCheck(clientConfig, msg);
}
return new AsyncResolver<>(
EurekaClientNames.BOOTSTRAP,
delegateResolver,
initialValue,
1,
clientConfig.getEurekaServiceUrlPollIntervalSeconds() * 1000
);
}
/**
* @return a bootstrap resolver that resolves eureka server endpoints via a remote call to a "vip source"
* the local registry, where the source is found from a rootResolver (dns or config)
*/
static ClosableResolver<AwsEndpoint> compositeBootstrapResolver(
final EurekaClientConfig clientConfig,
final EurekaTransportConfig transportConfig,
final TransportClientFactory transportClientFactory,
final InstanceInfo myInstanceInfo,
final ApplicationsResolver.ApplicationsSource applicationsSource,
final EndpointRandomizer randomizer)
{
final ClusterResolver rootResolver = new ConfigClusterResolver(clientConfig, myInstanceInfo);
final EurekaHttpResolver remoteResolver = new EurekaHttpResolver(
clientConfig,
transportConfig,
rootResolver,
transportClientFactory,
transportConfig.getWriteClusterVip()
);
final ApplicationsResolver localResolver = new ApplicationsResolver(
clientConfig,
transportConfig,
applicationsSource,
transportConfig.getWriteClusterVip()
);
ClusterResolver<AwsEndpoint> compositeResolver = new ClusterResolver<AwsEndpoint>() {
@Override
public String getRegion() {
return clientConfig.getRegion();
}
@Override
public List<AwsEndpoint> getClusterEndpoints() {
List<AwsEndpoint> result = localResolver.getClusterEndpoints();
if (result.isEmpty()) {
result = remoteResolver.getClusterEndpoints();
}
return result;
}
};
List<AwsEndpoint> initialValue = compositeResolver.getClusterEndpoints();
if (initialValue.isEmpty()) {
String msg = "Initial resolution of Eureka endpoints failed. Check ConfigClusterResolver logs for more info";
logger.error(msg);
failFastOnInitCheck(clientConfig, msg);
}
String[] availZones = clientConfig.getAvailabilityZones(clientConfig.getRegion());
String myZone = InstanceInfo.getZone(availZones, myInstanceInfo);
return new AsyncResolver<>(
EurekaClientNames.BOOTSTRAP,
new ZoneAffinityClusterResolver(compositeResolver, myZone, true, randomizer),
initialValue,
transportConfig.getAsyncExecutorThreadPoolSize(),
transportConfig.getAsyncResolverRefreshIntervalMs()
);
}
/**
* @return a resolver that resolves eureka server endpoints for query operations
*/
static ClosableResolver<AwsEndpoint> queryClientResolver(final ClusterResolver bootstrapResolver,
final TransportClientFactory transportClientFactory,
final EurekaClientConfig clientConfig,
final EurekaTransportConfig transportConfig,
final InstanceInfo myInstanceInfo,
final ApplicationsResolver.ApplicationsSource applicationsSource,
final EndpointRandomizer randomizer) {
final EurekaHttpResolver remoteResolver = new EurekaHttpResolver(
clientConfig,
transportConfig,
bootstrapResolver,
transportClientFactory,
transportConfig.getReadClusterVip()
);
final ApplicationsResolver localResolver = new ApplicationsResolver(
clientConfig,
transportConfig,
applicationsSource,
transportConfig.getReadClusterVip()
);
return compositeQueryResolver(
remoteResolver,
localResolver,
clientConfig,
transportConfig,
myInstanceInfo,
randomizer
);
}
/**
* @return a composite resolver that resolves eureka server endpoints for query operations, given two resolvers:
* a resolver that can resolve targets via a remote call to a remote source, and a resolver that
* can resolve targets via data in the local registry.
*/
/* testing */ static ClosableResolver<AwsEndpoint> compositeQueryResolver(
final ClusterResolver<AwsEndpoint> remoteResolver,
final ClusterResolver<AwsEndpoint> localResolver,
final EurekaClientConfig clientConfig,
final EurekaTransportConfig transportConfig,
final InstanceInfo myInstanceInfo,
final EndpointRandomizer randomizer) {
String[] availZones = clientConfig.getAvailabilityZones(clientConfig.getRegion());
String myZone = InstanceInfo.getZone(availZones, myInstanceInfo);
ClusterResolver<AwsEndpoint> compositeResolver = new ClusterResolver<AwsEndpoint>() {
@Override
public String getRegion() {
return clientConfig.getRegion();
}
@Override
public List<AwsEndpoint> getClusterEndpoints() {
List<AwsEndpoint> result = localResolver.getClusterEndpoints();
if (result.isEmpty()) {
result = remoteResolver.getClusterEndpoints();
}
return result;
}
};
return new AsyncResolver<>(
EurekaClientNames.QUERY,
new ZoneAffinityClusterResolver(compositeResolver, myZone, true, randomizer),
transportConfig.getAsyncExecutorThreadPoolSize(),
transportConfig.getAsyncResolverRefreshIntervalMs(),
transportConfig.getAsyncResolverWarmUpTimeoutMs()
);
}
static <T extends EurekaEndpoint> ClosableResolver<T> wrapClosable(final ClusterResolver<T> clusterResolver) {
if (clusterResolver instanceof ClosableResolver) {
return (ClosableResolver) clusterResolver;
}
return new ClosableResolver<T>() {
@Override
public void shutdown() {
// no-op
}
@Override
public String getRegion() {
return clusterResolver.getRegion();
}
@Override
public List<T> getClusterEndpoints() {
return clusterResolver.getClusterEndpoints();
}
};
}
// potential future feature, guarding with experimental flag for now
private static void failFastOnInitCheck(EurekaClientConfig clientConfig, String msg) {
if ("true".equals(clientConfig.getExperimental("clientTransportFailFastOnInit"))) {
throw new RuntimeException(msg);
}
}
}
| 8,006 |
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/transport/TransportUtils.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery.shared.transport;
import java.util.concurrent.atomic.AtomicReference;
/**
* @author Tomasz Bak
*/
public final class TransportUtils {
private TransportUtils() {
}
public static EurekaHttpClient getOrSetAnotherClient(AtomicReference<EurekaHttpClient> eurekaHttpClientRef, EurekaHttpClient another) {
EurekaHttpClient existing = eurekaHttpClientRef.get();
if (eurekaHttpClientRef.compareAndSet(null, another)) {
return another;
}
another.shutdown();
return existing;
}
public static void shutdown(EurekaHttpClient eurekaHttpClient) {
if (eurekaHttpClient != null) {
eurekaHttpClient.shutdown();
}
}
}
| 8,007 |
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/transport/EurekaClientFactoryBuilder.java | package com.netflix.discovery.shared.transport;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import com.netflix.appinfo.AbstractEurekaIdentity;
import com.netflix.appinfo.EurekaAccept;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.discovery.converters.wrappers.CodecWrappers;
import com.netflix.discovery.converters.wrappers.DecoderWrapper;
import com.netflix.discovery.converters.wrappers.EncoderWrapper;
/**
* @author Tomasz Bak
*/
public abstract class EurekaClientFactoryBuilder<F, B extends EurekaClientFactoryBuilder<F, B>> {
private static final int DEFAULT_MAX_CONNECTIONS_PER_HOST = 50;
private static final int DEFAULT_MAX_TOTAL_CONNECTIONS = 200;
private static final long DEFAULT_CONNECTION_IDLE_TIMEOUT = 30;
protected InstanceInfo myInstanceInfo;
protected boolean allowRedirect;
protected boolean systemSSL;
protected String clientName;
protected EurekaAccept eurekaAccept;
protected int maxConnectionsPerHost = DEFAULT_MAX_CONNECTIONS_PER_HOST;
protected int maxTotalConnections = DEFAULT_MAX_TOTAL_CONNECTIONS;
protected SSLContext sslContext;
protected String trustStoreFileName;
protected String trustStorePassword;
protected String userAgent;
protected String proxyUserName;
protected String proxyPassword;
protected String proxyHost;
protected int proxyPort;
protected int connectionTimeout;
protected int readTimeout;
protected long connectionIdleTimeout = DEFAULT_CONNECTION_IDLE_TIMEOUT;
protected EncoderWrapper encoderWrapper;
protected DecoderWrapper decoderWrapper;
protected AbstractEurekaIdentity clientIdentity;
protected HostnameVerifier hostnameVerifier;
public B withClientConfig(EurekaClientConfig clientConfig) {
withClientAccept(EurekaAccept.fromString(clientConfig.getClientDataAccept()));
withAllowRedirect(clientConfig.allowRedirects());
withConnectionTimeout(clientConfig.getEurekaServerConnectTimeoutSeconds() * 1000);
withReadTimeout(clientConfig.getEurekaServerReadTimeoutSeconds() * 1000);
withMaxConnectionsPerHost(clientConfig.getEurekaServerTotalConnectionsPerHost());
withMaxTotalConnections(clientConfig.getEurekaServerTotalConnections());
withConnectionIdleTimeout(clientConfig.getEurekaConnectionIdleTimeoutSeconds());
withEncoder(clientConfig.getEncoderName());
return withDecoder(clientConfig.getDecoderName(), clientConfig.getClientDataAccept());
}
public B withMyInstanceInfo(InstanceInfo myInstanceInfo) {
this.myInstanceInfo = myInstanceInfo;
return self();
}
public B withClientName(String clientName) {
this.clientName = clientName;
return self();
}
public B withClientAccept(EurekaAccept eurekaAccept) {
this.eurekaAccept = eurekaAccept;
return self();
}
public B withUserAgent(String userAgent) {
this.userAgent = userAgent;
return self();
}
public B withAllowRedirect(boolean allowRedirect) {
this.allowRedirect = allowRedirect;
return self();
}
public B withConnectionTimeout(int connectionTimeout) {
this.connectionTimeout = connectionTimeout;
return self();
}
public B withReadTimeout(int readTimeout) {
this.readTimeout = readTimeout;
return self();
}
public B withConnectionIdleTimeout(long connectionIdleTimeout) {
this.connectionIdleTimeout = connectionIdleTimeout;
return self();
}
public B withMaxConnectionsPerHost(int maxConnectionsPerHost) {
this.maxConnectionsPerHost = maxConnectionsPerHost;
return self();
}
public B withMaxTotalConnections(int maxTotalConnections) {
this.maxTotalConnections = maxTotalConnections;
return self();
}
public B withProxy(String proxyHost, int proxyPort, String user, String password) {
this.proxyHost = proxyHost;
this.proxyPort = proxyPort;
this.proxyUserName = user;
this.proxyPassword = password;
return self();
}
public B withSSLContext(SSLContext sslContext) {
this.sslContext = sslContext;
return self();
}
public B withHostnameVerifier(HostnameVerifier hostnameVerifier) {
this.hostnameVerifier = hostnameVerifier;
return self();
}
/**
* Use {@link #withSSLContext(SSLContext)}
*/
@Deprecated
public B withSystemSSLConfiguration() {
this.systemSSL = true;
return self();
}
/**
* Use {@link #withSSLContext(SSLContext)}
*/
@Deprecated
public B withTrustStoreFile(String trustStoreFileName, String trustStorePassword) {
this.trustStoreFileName = trustStoreFileName;
this.trustStorePassword = trustStorePassword;
return self();
}
public B withEncoder(String encoderName) {
return this.withEncoderWrapper(CodecWrappers.getEncoder(encoderName));
}
public B withEncoderWrapper(EncoderWrapper encoderWrapper) {
this.encoderWrapper = encoderWrapper;
return self();
}
public B withDecoder(String decoderName, String clientDataAccept) {
return this.withDecoderWrapper(CodecWrappers.resolveDecoder(decoderName, clientDataAccept));
}
public B withDecoderWrapper(DecoderWrapper decoderWrapper) {
this.decoderWrapper = decoderWrapper;
return self();
}
public B withClientIdentity(AbstractEurekaIdentity clientIdentity) {
this.clientIdentity = clientIdentity;
return self();
}
public abstract F build();
@SuppressWarnings("unchecked")
protected B self() {
return (B) this;
}
}
| 8,008 |
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/transport/EurekaHttpClientFactory.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery.shared.transport;
/**
* A top level factory to create http clients for application/eurekaClient use
*
* @author Tomasz Bak
*/
public interface EurekaHttpClientFactory {
EurekaHttpClient newClient();
void shutdown();
}
| 8,009 |
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/transport/EurekaHttpResponse.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery.shared.transport;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* @author Tomasz Bak
*/
public class EurekaHttpResponse<T> {
private final int statusCode;
private final T entity;
private final Map<String, String> headers;
private final URI location;
protected EurekaHttpResponse(int statusCode, T entity) {
this.statusCode = statusCode;
this.entity = entity;
this.headers = null;
this.location = null;
}
private EurekaHttpResponse(EurekaHttpResponseBuilder<T> builder) {
this.statusCode = builder.statusCode;
this.entity = builder.entity;
this.headers = builder.headers;
if (headers != null) {
String locationValue = headers.get(HttpHeaders.LOCATION);
try {
this.location = locationValue == null ? null : new URI(locationValue);
} catch (URISyntaxException e) {
throw new TransportException("Invalid Location header value in response; cannot complete the request (location="
+ locationValue + ')', e);
}
} else {
this.location = null;
}
}
public int getStatusCode() {
return statusCode;
}
public URI getLocation() {
return location;
}
public Map<String, String> getHeaders() {
return headers == null ? Collections.<String, String>emptyMap() : headers;
}
public T getEntity() {
return entity;
}
public static EurekaHttpResponse<Void> status(int status) {
return new EurekaHttpResponse<>(status, null);
}
public static EurekaHttpResponseBuilder<Void> anEurekaHttpResponse(int statusCode) {
return new EurekaHttpResponseBuilder<>(statusCode);
}
public static <T> EurekaHttpResponseBuilder<T> anEurekaHttpResponse(int statusCode, Class<T> entityType) {
return new EurekaHttpResponseBuilder<T>(statusCode);
}
public static <T> EurekaHttpResponseBuilder<T> anEurekaHttpResponse(int statusCode, T entity) {
return new EurekaHttpResponseBuilder<T>(statusCode).entity(entity);
}
public static class EurekaHttpResponseBuilder<T> {
private final int statusCode;
private T entity;
private Map<String, String> headers;
private EurekaHttpResponseBuilder(int statusCode) {
this.statusCode = statusCode;
}
public EurekaHttpResponseBuilder<T> entity(T entity) {
this.entity = entity;
return this;
}
public EurekaHttpResponseBuilder<T> entity(T entity, MediaType contentType) {
return entity(entity).type(contentType);
}
public EurekaHttpResponseBuilder<T> type(MediaType contentType) {
headers(HttpHeaders.CONTENT_TYPE, contentType.toString());
return this;
}
public EurekaHttpResponseBuilder<T> headers(String name, Object value) {
if (headers == null) {
headers = new HashMap<>();
}
headers.put(name, value.toString());
return this;
}
public EurekaHttpResponseBuilder<T> headers(Map<String, String> headers) {
this.headers = headers;
return this;
}
public EurekaHttpResponse<T> build() {
return new EurekaHttpResponse<T>(this);
}
}
}
| 8,010 |
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/transport/TransportClientFactory.java | package com.netflix.discovery.shared.transport;
import com.netflix.discovery.shared.resolver.EurekaEndpoint;
/**
* A low level client factory interface. Not advised to be used by top level consumers.
*
* @author David Liu
*/
public interface TransportClientFactory {
EurekaHttpClient newClient(EurekaEndpoint serviceUrl);
void shutdown();
}
| 8,011 |
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/transport/EurekaTransportConfig.java | package com.netflix.discovery.shared.transport;
/**
* Config class that governs configurations relevant to the transport layer
*
* @author David Liu
*/
public interface EurekaTransportConfig {
/**
* @return the reconnect inverval to use for sessioned clients
*/
int getSessionedClientReconnectIntervalSeconds();
/**
* @return the percentage of the full endpoints set above which the quarantine set is cleared in the range [0, 1.0]
*/
double getRetryableClientQuarantineRefreshPercentage();
/**
* @return the max staleness threshold tolerated by the applications resolver
*/
int getApplicationsResolverDataStalenessThresholdSeconds();
/**
* By default, the applications resolver extracts the public hostname from internal InstanceInfos for resolutions.
* Set this to true to change this behaviour to use ip addresses instead (private ip if ip type can be determined).
*
* @return false by default
*/
boolean applicationsResolverUseIp();
/**
* @return the interval to poll for the async resolver.
*/
int getAsyncResolverRefreshIntervalMs();
/**
* @return the async refresh timeout threshold in ms.
*/
int getAsyncResolverWarmUpTimeoutMs();
/**
* @return the max threadpool size for the async resolver's executor
*/
int getAsyncExecutorThreadPoolSize();
/**
* The remote vipAddress of the primary eureka cluster to register with.
*
* @return the vipAddress for the write cluster to register with
*/
String getWriteClusterVip();
/**
* The remote vipAddress of the eureka cluster (either the primaries or a readonly replica) to fetch registry
* data from.
*
* @return the vipAddress for the readonly cluster to redirect to, if applicable (can be the same as the bootstrap)
*/
String getReadClusterVip();
/**
* Can be used to specify different bootstrap resolve strategies. Current supported strategies are:
* - default (if no match): bootstrap from dns txt records or static config hostnames
* - composite: bootstrap from local registry if data is available
* and warm (see {@link #getApplicationsResolverDataStalenessThresholdSeconds()}, otherwise
* fall back to a backing default
*
* @return null for the default strategy, by default
*/
String getBootstrapResolverStrategy();
/**
* By default, the transport uses the same (bootstrap) resolver for queries.
*
* Set this property to false to use an indirect resolver to resolve query targets
* via {@link #getReadClusterVip()}. This indirect resolver may or may not return the same
* targets as the bootstrap servers depending on how servers are setup.
*
* @return true by default.
*/
boolean useBootstrapResolverForQuery();
}
| 8,012 |
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/transport/DefaultEurekaTransportConfig.java | package com.netflix.discovery.shared.transport;
import com.netflix.config.DynamicPropertyFactory;
import static com.netflix.discovery.shared.transport.PropertyBasedTransportConfigConstants.*;
/**
* @author David Liu
*/
public class DefaultEurekaTransportConfig implements EurekaTransportConfig {
private static final String SUB_NAMESPACE = TRANSPORT_CONFIG_SUB_NAMESPACE + ".";
private final String namespace;
private final DynamicPropertyFactory configInstance;
public DefaultEurekaTransportConfig(String parentNamespace, DynamicPropertyFactory configInstance) {
this.namespace = parentNamespace == null
? SUB_NAMESPACE
: (parentNamespace.endsWith(".")
? parentNamespace + SUB_NAMESPACE
: parentNamespace + "." + SUB_NAMESPACE);
this.configInstance = configInstance;
}
@Override
public int getSessionedClientReconnectIntervalSeconds() {
return configInstance.getIntProperty(namespace + SESSION_RECONNECT_INTERVAL_KEY, Values.SESSION_RECONNECT_INTERVAL).get();
}
@Override
public double getRetryableClientQuarantineRefreshPercentage() {
return configInstance.getDoubleProperty(namespace + QUARANTINE_REFRESH_PERCENTAGE_KEY, Values.QUARANTINE_REFRESH_PERCENTAGE).get();
}
@Override
public int getApplicationsResolverDataStalenessThresholdSeconds() {
return configInstance.getIntProperty(namespace + DATA_STALENESS_THRESHOLD_KEY, Values.DATA_STALENESS_TRHESHOLD).get();
}
@Override
public boolean applicationsResolverUseIp() {
return configInstance.getBooleanProperty(namespace + APPLICATION_RESOLVER_USE_IP_KEY, false).get();
}
@Override
public int getAsyncResolverRefreshIntervalMs() {
return configInstance.getIntProperty(namespace + ASYNC_RESOLVER_REFRESH_INTERVAL_KEY, Values.ASYNC_RESOLVER_REFRESH_INTERVAL).get();
}
@Override
public int getAsyncResolverWarmUpTimeoutMs() {
return configInstance.getIntProperty(namespace + ASYNC_RESOLVER_WARMUP_TIMEOUT_KEY, Values.ASYNC_RESOLVER_WARMUP_TIMEOUT).get();
}
@Override
public int getAsyncExecutorThreadPoolSize() {
return configInstance.getIntProperty(namespace + ASYNC_EXECUTOR_THREADPOOL_SIZE_KEY, Values.ASYNC_EXECUTOR_THREADPOOL_SIZE).get();
}
@Override
public String getWriteClusterVip() {
return configInstance.getStringProperty(namespace + WRITE_CLUSTER_VIP_KEY, null).get();
}
@Override
public String getReadClusterVip() {
return configInstance.getStringProperty(namespace + READ_CLUSTER_VIP_KEY, null).get();
}
@Override
public String getBootstrapResolverStrategy() {
return configInstance.getStringProperty(namespace + BOOTSTRAP_RESOLVER_STRATEGY_KEY, null).get();
}
@Override
public boolean useBootstrapResolverForQuery() {
return configInstance.getBooleanProperty(namespace + USE_BOOTSTRAP_RESOLVER_FOR_QUERY, true).get();
}
}
| 8,013 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport/jersey/Jersey1TransportClientFactories.java | package com.netflix.discovery.shared.transport.jersey;
import java.util.Collection;
import java.util.Optional;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import com.netflix.appinfo.EurekaClientIdentity;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.discovery.shared.resolver.EurekaEndpoint;
import com.netflix.discovery.shared.transport.EurekaHttpClient;
import com.netflix.discovery.shared.transport.TransportClientFactory;
import com.netflix.discovery.shared.transport.decorator.MetricsCollectingEurekaHttpClient;
import com.sun.jersey.api.client.filter.ClientFilter;
import com.sun.jersey.client.apache4.ApacheHttpClient4;
public class Jersey1TransportClientFactories implements TransportClientFactories<ClientFilter> {
@Deprecated
public TransportClientFactory newTransportClientFactory(final Collection<ClientFilter> additionalFilters,
final EurekaJerseyClient providedJerseyClient) {
ApacheHttpClient4 apacheHttpClient = providedJerseyClient.getClient();
if (additionalFilters != null) {
for (ClientFilter filter : additionalFilters) {
if (filter != null) {
apacheHttpClient.addFilter(filter);
}
}
}
final TransportClientFactory jerseyFactory = new JerseyEurekaHttpClientFactory(providedJerseyClient, false);
final TransportClientFactory metricsFactory = MetricsCollectingEurekaHttpClient.createFactory(jerseyFactory);
return new TransportClientFactory() {
@Override
public EurekaHttpClient newClient(EurekaEndpoint serviceUrl) {
return metricsFactory.newClient(serviceUrl);
}
@Override
public void shutdown() {
metricsFactory.shutdown();
jerseyFactory.shutdown();
}
};
}
public TransportClientFactory newTransportClientFactory(final EurekaClientConfig clientConfig,
final Collection<ClientFilter> additionalFilters,
final InstanceInfo myInstanceInfo) {
return newTransportClientFactory(clientConfig, additionalFilters, myInstanceInfo, Optional.empty(), Optional.empty());
}
@Override
public TransportClientFactory newTransportClientFactory(EurekaClientConfig clientConfig,
Collection<ClientFilter> additionalFilters, InstanceInfo myInstanceInfo, Optional<SSLContext> sslContext,
Optional<HostnameVerifier> hostnameVerifier) {
final TransportClientFactory jerseyFactory = JerseyEurekaHttpClientFactory.create(
clientConfig,
additionalFilters,
myInstanceInfo,
new EurekaClientIdentity(myInstanceInfo.getIPAddr()),
sslContext,
hostnameVerifier
);
final TransportClientFactory metricsFactory = MetricsCollectingEurekaHttpClient.createFactory(jerseyFactory);
return new TransportClientFactory() {
@Override
public EurekaHttpClient newClient(EurekaEndpoint serviceUrl) {
return metricsFactory.newClient(serviceUrl);
}
@Override
public void shutdown() {
metricsFactory.shutdown();
jerseyFactory.shutdown();
}
};
}
} | 8,014 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport/jersey/TransportClientFactories.java | package com.netflix.discovery.shared.transport.jersey;
import java.util.Collection;
import java.util.Optional;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.discovery.shared.transport.TransportClientFactory;
public interface TransportClientFactories<F> {
@Deprecated
public TransportClientFactory newTransportClientFactory(final Collection<F> additionalFilters,
final EurekaJerseyClient providedJerseyClient);
public TransportClientFactory newTransportClientFactory(final EurekaClientConfig clientConfig,
final Collection<F> additionalFilters,
final InstanceInfo myInstanceInfo);
public TransportClientFactory newTransportClientFactory(final EurekaClientConfig clientConfig,
final Collection<F> additionalFilters,
final InstanceInfo myInstanceInfo,
final Optional<SSLContext> sslContext,
final Optional<HostnameVerifier> hostnameVerifier);
} | 8,015 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport/jersey/JerseyApplicationClient.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery.shared.transport.jersey;
import com.netflix.discovery.shared.transport.EurekaHttpClient;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource.Builder;
import java.util.Map;
/**
* A version of Jersey1 {@link EurekaHttpClient} to be used by applications.
*
* @author Tomasz Bak
*/
public class JerseyApplicationClient extends AbstractJerseyEurekaHttpClient {
private final Map<String, String> additionalHeaders;
public JerseyApplicationClient(Client jerseyClient, String serviceUrl, Map<String, String> additionalHeaders) {
super(jerseyClient, serviceUrl);
this.additionalHeaders = additionalHeaders;
}
@Override
protected void addExtraHeaders(Builder webResource) {
if (additionalHeaders != null) {
for (Map.Entry<String, String> entry : additionalHeaders.entrySet()) {
webResource.header(entry.getKey(), entry.getValue());
}
}
}
}
| 8,016 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport/jersey/AbstractJerseyEurekaHttpClient.java | package com.netflix.discovery.shared.transport.jersey;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import com.netflix.discovery.shared.Application;
import com.netflix.discovery.shared.Applications;
import com.netflix.discovery.shared.transport.EurekaHttpClient;
import com.netflix.discovery.shared.transport.EurekaHttpResponse;
import com.netflix.discovery.shared.transport.EurekaHttpResponse.EurekaHttpResponseBuilder;
import com.netflix.discovery.util.StringUtil;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response.Status;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import static com.netflix.discovery.shared.transport.EurekaHttpResponse.anEurekaHttpResponse;
/**
* @author Tomasz Bak
*/
public abstract class AbstractJerseyEurekaHttpClient implements EurekaHttpClient {
private static final Logger logger = LoggerFactory.getLogger(AbstractJerseyEurekaHttpClient.class);
protected static final String HTML = "html";
protected final Client jerseyClient;
protected final String serviceUrl;
protected AbstractJerseyEurekaHttpClient(Client jerseyClient, String serviceUrl) {
this.jerseyClient = jerseyClient;
this.serviceUrl = serviceUrl;
logger.debug("Created client for url: {}", serviceUrl);
}
@Override
public EurekaHttpResponse<Void> register(InstanceInfo info) {
String urlPath = "apps/" + info.getAppName();
ClientResponse response = null;
try {
Builder resourceBuilder = jerseyClient.resource(serviceUrl).path(urlPath).getRequestBuilder();
addExtraHeaders(resourceBuilder);
response = resourceBuilder
.header("Accept-Encoding", "gzip")
.type(MediaType.APPLICATION_JSON_TYPE)
.accept(MediaType.APPLICATION_JSON)
.post(ClientResponse.class, info);
return anEurekaHttpResponse(response.getStatus()).headers(headersOf(response)).build();
} finally {
if (logger.isDebugEnabled()) {
logger.debug("Jersey HTTP POST {}{} with instance {}; statusCode={}", serviceUrl, urlPath, info.getId(),
response == null ? "N/A" : response.getStatus());
}
if (response != null) {
response.close();
}
}
}
@Override
public EurekaHttpResponse<Void> cancel(String appName, String id) {
String urlPath = "apps/" + appName + '/' + id;
ClientResponse response = null;
try {
Builder resourceBuilder = jerseyClient.resource(serviceUrl).path(urlPath).getRequestBuilder();
addExtraHeaders(resourceBuilder);
response = resourceBuilder.delete(ClientResponse.class);
return anEurekaHttpResponse(response.getStatus()).headers(headersOf(response)).build();
} finally {
if (logger.isDebugEnabled()) {
logger.debug("Jersey HTTP DELETE {}{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus());
}
if (response != null) {
response.close();
}
}
}
@Override
public EurekaHttpResponse<InstanceInfo> sendHeartBeat(String appName, String id, InstanceInfo info, InstanceStatus overriddenStatus) {
String urlPath = "apps/" + appName + '/' + id;
ClientResponse response = null;
try {
WebResource webResource = jerseyClient.resource(serviceUrl)
.path(urlPath)
.queryParam("status", info.getStatus().toString())
.queryParam("lastDirtyTimestamp", info.getLastDirtyTimestamp().toString());
if (overriddenStatus != null) {
webResource = webResource.queryParam("overriddenstatus", overriddenStatus.name());
}
Builder requestBuilder = webResource.getRequestBuilder();
addExtraHeaders(requestBuilder);
response = requestBuilder.put(ClientResponse.class);
EurekaHttpResponseBuilder<InstanceInfo> eurekaResponseBuilder = anEurekaHttpResponse(response.getStatus(), InstanceInfo.class).headers(headersOf(response));
if (response.hasEntity() &&
!HTML.equals(response.getType().getSubtype())) { //don't try and deserialize random html errors from the server
eurekaResponseBuilder.entity(response.getEntity(InstanceInfo.class));
}
return eurekaResponseBuilder.build();
} finally {
if (logger.isDebugEnabled()) {
logger.debug("Jersey HTTP PUT {}{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus());
}
if (response != null) {
response.close();
}
}
}
@Override
public EurekaHttpResponse<Void> statusUpdate(String appName, String id, InstanceStatus newStatus, InstanceInfo info) {
String urlPath = "apps/" + appName + '/' + id + "/status";
ClientResponse response = null;
try {
Builder requestBuilder = jerseyClient.resource(serviceUrl)
.path(urlPath)
.queryParam("value", newStatus.name())
.queryParam("lastDirtyTimestamp", info.getLastDirtyTimestamp().toString())
.getRequestBuilder();
addExtraHeaders(requestBuilder);
response = requestBuilder.put(ClientResponse.class);
return anEurekaHttpResponse(response.getStatus()).headers(headersOf(response)).build();
} finally {
if (logger.isDebugEnabled()) {
logger.debug("Jersey HTTP PUT {}{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus());
}
if (response != null) {
response.close();
}
}
}
@Override
public EurekaHttpResponse<Void> deleteStatusOverride(String appName, String id, InstanceInfo info) {
String urlPath = "apps/" + appName + '/' + id + "/status";
ClientResponse response = null;
try {
Builder requestBuilder = jerseyClient.resource(serviceUrl)
.path(urlPath)
.queryParam("lastDirtyTimestamp", info.getLastDirtyTimestamp().toString())
.getRequestBuilder();
addExtraHeaders(requestBuilder);
response = requestBuilder.delete(ClientResponse.class);
return anEurekaHttpResponse(response.getStatus()).headers(headersOf(response)).build();
} finally {
if (logger.isDebugEnabled()) {
logger.debug("Jersey HTTP DELETE {}{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus());
}
if (response != null) {
response.close();
}
}
}
@Override
public EurekaHttpResponse<Applications> getApplications(String... regions) {
return getApplicationsInternal("apps/", regions);
}
@Override
public EurekaHttpResponse<Applications> getDelta(String... regions) {
return getApplicationsInternal("apps/delta", regions);
}
@Override
public EurekaHttpResponse<Applications> getVip(String vipAddress, String... regions) {
return getApplicationsInternal("vips/" + vipAddress, regions);
}
@Override
public EurekaHttpResponse<Applications> getSecureVip(String secureVipAddress, String... regions) {
return getApplicationsInternal("svips/" + secureVipAddress, regions);
}
private EurekaHttpResponse<Applications> getApplicationsInternal(String urlPath, String[] regions) {
ClientResponse response = null;
String regionsParamValue = null;
try {
WebResource webResource = jerseyClient.resource(serviceUrl).path(urlPath);
if (regions != null && regions.length > 0) {
regionsParamValue = StringUtil.join(regions);
webResource = webResource.queryParam("regions", regionsParamValue);
}
Builder requestBuilder = webResource.getRequestBuilder();
addExtraHeaders(requestBuilder);
response = requestBuilder.accept(MediaType.APPLICATION_JSON_TYPE).get(ClientResponse.class);
Applications applications = null;
if (response.getStatus() == Status.OK.getStatusCode() && response.hasEntity()) {
applications = response.getEntity(Applications.class);
}
return anEurekaHttpResponse(response.getStatus(), Applications.class)
.headers(headersOf(response))
.entity(applications)
.build();
} finally {
if (logger.isDebugEnabled()) {
logger.debug("Jersey HTTP GET {}{}?{}; statusCode={}",
serviceUrl, urlPath,
regionsParamValue == null ? "" : "regions=" + regionsParamValue,
response == null ? "N/A" : response.getStatus()
);
}
if (response != null) {
response.close();
}
}
}
@Override
public EurekaHttpResponse<Application> getApplication(String appName) {
String urlPath = "apps/" + appName;
ClientResponse response = null;
try {
Builder requestBuilder = jerseyClient.resource(serviceUrl).path(urlPath).getRequestBuilder();
addExtraHeaders(requestBuilder);
response = requestBuilder.accept(MediaType.APPLICATION_JSON_TYPE).get(ClientResponse.class);
Application application = null;
if (response.getStatus() == Status.OK.getStatusCode() && response.hasEntity()) {
application = response.getEntity(Application.class);
}
return anEurekaHttpResponse(response.getStatus(), Application.class)
.headers(headersOf(response))
.entity(application)
.build();
} finally {
if (logger.isDebugEnabled()) {
logger.debug("Jersey HTTP GET {}{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus());
}
if (response != null) {
response.close();
}
}
}
@Override
public EurekaHttpResponse<InstanceInfo> getInstance(String id) {
return getInstanceInternal("instances/" + id);
}
@Override
public EurekaHttpResponse<InstanceInfo> getInstance(String appName, String id) {
return getInstanceInternal("apps/" + appName + '/' + id);
}
private EurekaHttpResponse<InstanceInfo> getInstanceInternal(String urlPath) {
ClientResponse response = null;
try {
Builder requestBuilder = jerseyClient.resource(serviceUrl).path(urlPath).getRequestBuilder();
addExtraHeaders(requestBuilder);
response = requestBuilder.accept(MediaType.APPLICATION_JSON_TYPE).get(ClientResponse.class);
InstanceInfo infoFromPeer = null;
if (response.getStatus() == Status.OK.getStatusCode() && response.hasEntity()) {
infoFromPeer = response.getEntity(InstanceInfo.class);
}
return anEurekaHttpResponse(response.getStatus(), InstanceInfo.class)
.headers(headersOf(response))
.entity(infoFromPeer)
.build();
} finally {
if (logger.isDebugEnabled()) {
logger.debug("Jersey HTTP GET {}{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus());
}
if (response != null) {
response.close();
}
}
}
@Override
public void shutdown() {
// Do not destroy jerseyClient, as it is owned by the corresponding EurekaHttpClientFactory
}
protected abstract void addExtraHeaders(Builder webResource);
private static Map<String, String> headersOf(ClientResponse response) {
MultivaluedMap<String, String> jerseyHeaders = response.getHeaders();
if (jerseyHeaders == null || jerseyHeaders.isEmpty()) {
return Collections.emptyMap();
}
Map<String, String> headers = new HashMap<>();
for (Entry<String, List<String>> entry : jerseyHeaders.entrySet()) {
if (!entry.getValue().isEmpty()) {
headers.put(entry.getKey(), entry.getValue().get(0));
}
}
return headers;
}
}
| 8,017 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport/jersey/EurekaJerseyClient.java | package com.netflix.discovery.shared.transport.jersey;
import com.sun.jersey.client.apache4.ApacheHttpClient4;
/**
* @author David Liu
*/
public interface EurekaJerseyClient {
ApacheHttpClient4 getClient();
/**
* Clean up resources.
*/
void destroyResources();
}
| 8,018 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport/jersey/JerseyEurekaHttpClientFactory.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery.shared.transport.jersey;
import com.netflix.appinfo.AbstractEurekaIdentity;
import com.netflix.appinfo.EurekaAccept;
import com.netflix.appinfo.EurekaClientIdentity;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.discovery.EurekaIdentityHeaderFilter;
import com.netflix.discovery.provider.DiscoveryJerseyProvider;
import com.netflix.discovery.shared.resolver.EurekaEndpoint;
import com.netflix.discovery.shared.transport.EurekaClientFactoryBuilder;
import com.netflix.discovery.shared.transport.EurekaHttpClient;
import com.netflix.discovery.shared.transport.TransportClientFactory;
import com.netflix.discovery.shared.transport.jersey.EurekaJerseyClientImpl.EurekaJerseyClientBuilder;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.filter.ClientFilter;
import com.sun.jersey.api.client.filter.GZIPContentEncodingFilter;
import com.sun.jersey.client.apache4.ApacheHttpClient4;
import com.sun.jersey.client.apache4.config.ApacheHttpClient4Config;
import com.sun.jersey.client.apache4.config.DefaultApacheHttpClient4Config;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SchemeSocketFactory;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.CoreProtocolPNames;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import static com.netflix.discovery.util.DiscoveryBuildInfo.buildVersion;
/**
* @author Tomasz Bak
*/
public class JerseyEurekaHttpClientFactory implements TransportClientFactory {
public static final String HTTP_X_DISCOVERY_ALLOW_REDIRECT = "X-Discovery-AllowRedirect";
private final EurekaJerseyClient jerseyClient;
private final ApacheHttpClient4 apacheClient;
private final ApacheHttpClientConnectionCleaner cleaner;
private final Map<String, String> additionalHeaders;
/**
* @deprecated {@link EurekaJerseyClient} is deprecated and will be removed
*/
@Deprecated
public JerseyEurekaHttpClientFactory(EurekaJerseyClient jerseyClient, boolean allowRedirects) {
this(
jerseyClient,
null,
-1,
Collections.singletonMap(HTTP_X_DISCOVERY_ALLOW_REDIRECT, allowRedirects ? "true" : "false")
);
}
@Deprecated
public JerseyEurekaHttpClientFactory(EurekaJerseyClient jerseyClient, Map<String, String> additionalHeaders) {
this(jerseyClient, null, -1, additionalHeaders);
}
public JerseyEurekaHttpClientFactory(ApacheHttpClient4 apacheClient, long connectionIdleTimeout, Map<String, String> additionalHeaders) {
this(null, apacheClient, connectionIdleTimeout, additionalHeaders);
}
private JerseyEurekaHttpClientFactory(EurekaJerseyClient jerseyClient,
ApacheHttpClient4 apacheClient,
long connectionIdleTimeout,
Map<String, String> additionalHeaders) {
this.jerseyClient = jerseyClient;
this.apacheClient = jerseyClient != null ? jerseyClient.getClient() : apacheClient;
this.additionalHeaders = additionalHeaders;
if (jerseyClient == null) {
// the jersey client contains a cleaner already so only create this cleaner if we don't have a jersey client
this.cleaner = new ApacheHttpClientConnectionCleaner(this.apacheClient, connectionIdleTimeout);
} else {
this.cleaner = null;
}
}
@Override
public EurekaHttpClient newClient(EurekaEndpoint endpoint) {
return new JerseyApplicationClient(apacheClient, endpoint.getServiceUrl(), additionalHeaders);
}
@Override
public void shutdown() {
if (cleaner != null) {
cleaner.shutdown();
}
if (jerseyClient != null) {
jerseyClient.destroyResources();
} else {
apacheClient.destroy();
}
}
public static JerseyEurekaHttpClientFactory create(EurekaClientConfig clientConfig,
Collection<ClientFilter> additionalFilters,
InstanceInfo myInstanceInfo,
AbstractEurekaIdentity clientIdentity) {
return create(clientConfig, additionalFilters, myInstanceInfo, clientIdentity, Optional.empty(), Optional.empty());
}
public static JerseyEurekaHttpClientFactory create(EurekaClientConfig clientConfig,
Collection<ClientFilter> additionalFilters,
InstanceInfo myInstanceInfo,
AbstractEurekaIdentity clientIdentity,
Optional<SSLContext> sslContext,
Optional<HostnameVerifier> hostnameVerifier) {
boolean useExperimental = "true".equals(clientConfig.getExperimental("JerseyEurekaHttpClientFactory.useNewBuilder"));
JerseyEurekaHttpClientFactoryBuilder clientBuilder = (useExperimental ? experimentalBuilder() : newBuilder())
.withAdditionalFilters(additionalFilters)
.withMyInstanceInfo(myInstanceInfo)
.withUserAgent("Java-EurekaClient")
.withClientConfig(clientConfig)
.withClientIdentity(clientIdentity);
sslContext.ifPresent(clientBuilder::withSSLContext);
hostnameVerifier.ifPresent(clientBuilder::withHostnameVerifier);
if ("true".equals(System.getProperty("com.netflix.eureka.shouldSSLConnectionsUseSystemSocketFactory"))) {
clientBuilder.withClientName("DiscoveryClient-HTTPClient-System").withSystemSSLConfiguration();
} else if (clientConfig.getProxyHost() != null && clientConfig.getProxyPort() != null) {
clientBuilder.withClientName("Proxy-DiscoveryClient-HTTPClient")
.withProxy(
clientConfig.getProxyHost(), Integer.parseInt(clientConfig.getProxyPort()),
clientConfig.getProxyUserName(), clientConfig.getProxyPassword()
);
} else {
clientBuilder.withClientName("DiscoveryClient-HTTPClient");
}
return clientBuilder.build();
}
public static JerseyEurekaHttpClientFactoryBuilder newBuilder() {
return new JerseyEurekaHttpClientFactoryBuilder().withExperimental(false);
}
public static JerseyEurekaHttpClientFactoryBuilder experimentalBuilder() {
return new JerseyEurekaHttpClientFactoryBuilder().withExperimental(true);
}
/**
* Currently use EurekaJerseyClientBuilder. Once old transport in DiscoveryClient is removed, incorporate
* EurekaJerseyClientBuilder here, and remove it.
*/
public static class JerseyEurekaHttpClientFactoryBuilder extends EurekaClientFactoryBuilder<JerseyEurekaHttpClientFactory, JerseyEurekaHttpClientFactoryBuilder> {
private Collection<ClientFilter> additionalFilters = Collections.emptyList();
private boolean experimental = false;
public JerseyEurekaHttpClientFactoryBuilder withAdditionalFilters(Collection<ClientFilter> additionalFilters) {
this.additionalFilters = additionalFilters;
return this;
}
public JerseyEurekaHttpClientFactoryBuilder withExperimental(boolean experimental) {
this.experimental = experimental;
return this;
}
@Override
public JerseyEurekaHttpClientFactory build() {
Map<String, String> additionalHeaders = new HashMap<>();
if (allowRedirect) {
additionalHeaders.put(HTTP_X_DISCOVERY_ALLOW_REDIRECT, "true");
}
if (EurekaAccept.compact == eurekaAccept) {
additionalHeaders.put(EurekaAccept.HTTP_X_EUREKA_ACCEPT, eurekaAccept.name());
}
if (experimental) {
return buildExperimental(additionalHeaders);
}
return buildLegacy(additionalHeaders, systemSSL);
}
private JerseyEurekaHttpClientFactory buildLegacy(Map<String, String> additionalHeaders, boolean systemSSL) {
EurekaJerseyClientBuilder clientBuilder = new EurekaJerseyClientBuilder()
.withClientName(clientName)
.withUserAgent("Java-EurekaClient")
.withConnectionTimeout(connectionTimeout)
.withReadTimeout(readTimeout)
.withMaxConnectionsPerHost(maxConnectionsPerHost)
.withMaxTotalConnections(maxTotalConnections)
.withConnectionIdleTimeout((int) connectionIdleTimeout)
.withEncoderWrapper(encoderWrapper)
.withDecoderWrapper(decoderWrapper)
.withProxy(proxyHost,String.valueOf(proxyPort),proxyUserName,proxyPassword);
if (systemSSL) {
clientBuilder.withSystemSSLConfiguration();
} else if (sslContext != null) {
clientBuilder.withCustomSSL(sslContext);
}
if (hostnameVerifier != null) {
clientBuilder.withHostnameVerifier(hostnameVerifier);
}
EurekaJerseyClient jerseyClient = clientBuilder.build();
ApacheHttpClient4 discoveryApacheClient = jerseyClient.getClient();
addFilters(discoveryApacheClient);
return new JerseyEurekaHttpClientFactory(jerseyClient, additionalHeaders);
}
private JerseyEurekaHttpClientFactory buildExperimental(Map<String, String> additionalHeaders) {
ThreadSafeClientConnManager cm = createConnectionManager();
ClientConfig clientConfig = new DefaultApacheHttpClient4Config();
if (proxyHost != null) {
addProxyConfiguration(clientConfig);
}
DiscoveryJerseyProvider discoveryJerseyProvider = new DiscoveryJerseyProvider(encoderWrapper, decoderWrapper);
clientConfig.getSingletons().add(discoveryJerseyProvider);
// Common properties to all clients
cm.setDefaultMaxPerRoute(maxConnectionsPerHost);
cm.setMaxTotal(maxTotalConnections);
clientConfig.getProperties().put(ApacheHttpClient4Config.PROPERTY_CONNECTION_MANAGER, cm);
String fullUserAgentName = (userAgent == null ? clientName : userAgent) + "/v" + buildVersion();
clientConfig.getProperties().put(CoreProtocolPNames.USER_AGENT, fullUserAgentName);
// To pin a client to specific server in case redirect happens, we handle redirects directly
// (see DiscoveryClient.makeRemoteCall methods).
clientConfig.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, Boolean.FALSE);
clientConfig.getProperties().put(ClientPNames.HANDLE_REDIRECTS, Boolean.FALSE);
ApacheHttpClient4 apacheClient = ApacheHttpClient4.create(clientConfig);
addFilters(apacheClient);
return new JerseyEurekaHttpClientFactory(apacheClient, connectionIdleTimeout, additionalHeaders);
}
/**
* Since Jersey 1.19 depends on legacy apache http-client API, we have to as well.
*/
private ThreadSafeClientConnManager createConnectionManager() {
try {
ThreadSafeClientConnManager connectionManager;
if (sslContext != null) {
SchemeSocketFactory socketFactory = new SSLSocketFactory(sslContext, new AllowAllHostnameVerifier());
SchemeRegistry sslSchemeRegistry = new SchemeRegistry();
sslSchemeRegistry.register(new Scheme("https", 443, socketFactory));
connectionManager = new ThreadSafeClientConnManager(sslSchemeRegistry);
} else {
connectionManager = new ThreadSafeClientConnManager();
}
return connectionManager;
} catch (Exception e) {
throw new IllegalStateException("Cannot initialize Apache connection manager", e);
}
}
private void addProxyConfiguration(ClientConfig clientConfig) {
if (proxyUserName != null && proxyPassword != null) {
clientConfig.getProperties().put(ApacheHttpClient4Config.PROPERTY_PROXY_USERNAME, proxyUserName);
clientConfig.getProperties().put(ApacheHttpClient4Config.PROPERTY_PROXY_PASSWORD, proxyPassword);
} else {
// Due to bug in apache client, user name/password must always be set.
// Otherwise proxy configuration is ignored.
clientConfig.getProperties().put(ApacheHttpClient4Config.PROPERTY_PROXY_USERNAME, "guest");
clientConfig.getProperties().put(ApacheHttpClient4Config.PROPERTY_PROXY_PASSWORD, "guest");
}
clientConfig.getProperties().put(DefaultApacheHttpClient4Config.PROPERTY_PROXY_URI, "http://" + proxyHost + ':' + proxyPort);
}
private void addFilters(ApacheHttpClient4 discoveryApacheClient) {
// Add gzip content encoding support
discoveryApacheClient.addFilter(new GZIPContentEncodingFilter(false));
// always enable client identity headers
String ip = myInstanceInfo == null ? null : myInstanceInfo.getIPAddr();
AbstractEurekaIdentity identity = clientIdentity == null ? new EurekaClientIdentity(ip) : clientIdentity;
discoveryApacheClient.addFilter(new EurekaIdentityHeaderFilter(identity));
if (additionalFilters != null) {
for (ClientFilter filter : additionalFilters) {
if (filter != null) {
discoveryApacheClient.addFilter(filter);
}
}
}
}
}
} | 8,019 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport/jersey/Jersey1DiscoveryClientOptionalArgs.java | package com.netflix.discovery.shared.transport.jersey;
import com.netflix.discovery.AbstractDiscoveryClientOptionalArgs;
import com.sun.jersey.api.client.filter.ClientFilter;
/**
* Jersey1 implementation of DiscoveryClientOptionalArg.
*
* @author Matt Nelson
*/
public class Jersey1DiscoveryClientOptionalArgs extends AbstractDiscoveryClientOptionalArgs<ClientFilter> {
}
| 8,020 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport/jersey/ApacheHttpClientConnectionCleaner.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery.shared.transport.jersey;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import com.netflix.servo.monitor.BasicCounter;
import com.netflix.servo.monitor.BasicTimer;
import com.netflix.servo.monitor.Counter;
import com.netflix.servo.monitor.MonitorConfig;
import com.netflix.servo.monitor.Monitors;
import com.netflix.servo.monitor.Stopwatch;
import com.sun.jersey.client.apache4.ApacheHttpClient4;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A periodic process running in background cleaning Apache http client connection pool out of idle connections.
* This prevents from accumulating unused connections in half-closed state.
*/
public class ApacheHttpClientConnectionCleaner {
private static final Logger logger = LoggerFactory.getLogger(ApacheHttpClientConnectionCleaner.class);
private static final int HTTP_CONNECTION_CLEANER_INTERVAL_MS = 30 * 1000;
private final ScheduledExecutorService eurekaConnCleaner =
Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
private final AtomicInteger threadNumber = new AtomicInteger(1);
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r, "Apache-HttpClient-Conn-Cleaner" + threadNumber.incrementAndGet());
thread.setDaemon(true);
return thread;
}
});
private final ApacheHttpClient4 apacheHttpClient;
private final BasicTimer executionTimeStats;
private final Counter cleanupFailed;
public ApacheHttpClientConnectionCleaner(ApacheHttpClient4 apacheHttpClient, final long connectionIdleTimeout) {
this.apacheHttpClient = apacheHttpClient;
this.eurekaConnCleaner.scheduleWithFixedDelay(
new Runnable() {
@Override
public void run() {
cleanIdle(connectionIdleTimeout);
}
},
HTTP_CONNECTION_CLEANER_INTERVAL_MS,
HTTP_CONNECTION_CLEANER_INTERVAL_MS,
TimeUnit.MILLISECONDS
);
MonitorConfig.Builder monitorConfigBuilder = MonitorConfig.builder("Eureka-Connection-Cleaner-Time");
executionTimeStats = new BasicTimer(monitorConfigBuilder.build());
cleanupFailed = new BasicCounter(MonitorConfig.builder("Eureka-Connection-Cleaner-Failure").build());
try {
Monitors.registerObject(this);
} catch (Exception e) {
logger.error("Unable to register with servo.", e);
}
}
public void shutdown() {
cleanIdle(0);
eurekaConnCleaner.shutdown();
Monitors.unregisterObject(this);
}
public void cleanIdle(long delayMs) {
Stopwatch start = executionTimeStats.start();
try {
apacheHttpClient.getClientHandler().getHttpClient()
.getConnectionManager()
.closeIdleConnections(delayMs, TimeUnit.SECONDS);
} catch (Throwable e) {
logger.error("Cannot clean connections", e);
cleanupFailed.increment();
} finally {
if (null != start) {
start.stop();
}
}
}
}
| 8,021 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport/jersey/EurekaJerseyClientImpl.java | package com.netflix.discovery.shared.transport.jersey;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;
import com.netflix.discovery.converters.wrappers.CodecWrappers;
import com.netflix.discovery.converters.wrappers.DecoderWrapper;
import com.netflix.discovery.converters.wrappers.EncoderWrapper;
import com.netflix.discovery.provider.DiscoveryJerseyProvider;
import com.netflix.discovery.shared.MonitoredConnectionManager;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.client.apache4.ApacheHttpClient4;
import com.sun.jersey.client.apache4.config.ApacheHttpClient4Config;
import com.sun.jersey.client.apache4.config.DefaultApacheHttpClient4Config;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.conn.SchemeRegistryFactory;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import static com.netflix.discovery.util.DiscoveryBuildInfo.buildVersion;
/**
* @author Tomasz Bak
*/
public class EurekaJerseyClientImpl implements EurekaJerseyClient {
private static final String PROTOCOL = "https";
private static final String PROTOCOL_SCHEME = "SSL";
private static final int HTTPS_PORT = 443;
private static final String KEYSTORE_TYPE = "JKS";
private final ApacheHttpClient4 apacheHttpClient;
private final ApacheHttpClientConnectionCleaner apacheHttpClientConnectionCleaner;
ClientConfig jerseyClientConfig;
public EurekaJerseyClientImpl(int connectionTimeout, int readTimeout, final int connectionIdleTimeout,
ClientConfig clientConfig) {
try {
jerseyClientConfig = clientConfig;
apacheHttpClient = ApacheHttpClient4.create(jerseyClientConfig);
HttpParams params = apacheHttpClient.getClientHandler().getHttpClient().getParams();
HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);
HttpConnectionParams.setSoTimeout(params, readTimeout);
this.apacheHttpClientConnectionCleaner = new ApacheHttpClientConnectionCleaner(apacheHttpClient, connectionIdleTimeout);
} catch (Throwable e) {
throw new RuntimeException("Cannot create Jersey client", e);
}
}
@Override
public ApacheHttpClient4 getClient() {
return apacheHttpClient;
}
/**
* Clean up resources.
*/
@Override
public void destroyResources() {
apacheHttpClientConnectionCleaner.shutdown();
apacheHttpClient.destroy();
final Object connectionManager =
jerseyClientConfig.getProperty(ApacheHttpClient4Config.PROPERTY_CONNECTION_MANAGER);
if (connectionManager instanceof MonitoredConnectionManager) {
((MonitoredConnectionManager) connectionManager).shutdown();
}
}
public static class EurekaJerseyClientBuilder {
private boolean systemSSL;
private String clientName;
private int maxConnectionsPerHost;
private int maxTotalConnections;
private String trustStoreFileName;
private String trustStorePassword;
private String userAgent;
private String proxyUserName;
private String proxyPassword;
private String proxyHost;
private String proxyPort;
private int connectionTimeout;
private int readTimeout;
private int connectionIdleTimeout;
private EncoderWrapper encoderWrapper;
private DecoderWrapper decoderWrapper;
private SSLContext sslContext;
private HostnameVerifier hostnameVerifier;
public EurekaJerseyClientBuilder withClientName(String clientName) {
this.clientName = clientName;
return this;
}
public EurekaJerseyClientBuilder withUserAgent(String userAgent) {
this.userAgent = userAgent;
return this;
}
public EurekaJerseyClientBuilder withConnectionTimeout(int connectionTimeout) {
this.connectionTimeout = connectionTimeout;
return this;
}
public EurekaJerseyClientBuilder withReadTimeout(int readTimeout) {
this.readTimeout = readTimeout;
return this;
}
public EurekaJerseyClientBuilder withConnectionIdleTimeout(int connectionIdleTimeout) {
this.connectionIdleTimeout = connectionIdleTimeout;
return this;
}
public EurekaJerseyClientBuilder withMaxConnectionsPerHost(int maxConnectionsPerHost) {
this.maxConnectionsPerHost = maxConnectionsPerHost;
return this;
}
public EurekaJerseyClientBuilder withMaxTotalConnections(int maxTotalConnections) {
this.maxTotalConnections = maxTotalConnections;
return this;
}
public EurekaJerseyClientBuilder withProxy(String proxyHost, String proxyPort, String user, String password) {
this.proxyHost = proxyHost;
this.proxyPort = proxyPort;
this.proxyUserName = user;
this.proxyPassword = password;
return this;
}
public EurekaJerseyClientBuilder withSystemSSLConfiguration() {
this.systemSSL = true;
return this;
}
public EurekaJerseyClientBuilder withTrustStoreFile(String trustStoreFileName, String trustStorePassword) {
this.trustStoreFileName = trustStoreFileName;
this.trustStorePassword = trustStorePassword;
return this;
}
public EurekaJerseyClientBuilder withEncoder(String encoderName) {
return this.withEncoderWrapper(CodecWrappers.getEncoder(encoderName));
}
public EurekaJerseyClientBuilder withEncoderWrapper(EncoderWrapper encoderWrapper) {
this.encoderWrapper = encoderWrapper;
return this;
}
public EurekaJerseyClientBuilder withDecoder(String decoderName, String clientDataAccept) {
return this.withDecoderWrapper(CodecWrappers.resolveDecoder(decoderName, clientDataAccept));
}
public EurekaJerseyClientBuilder withDecoderWrapper(DecoderWrapper decoderWrapper) {
this.decoderWrapper = decoderWrapper;
return this;
}
public EurekaJerseyClientBuilder withCustomSSL(SSLContext sslContext) {
this.sslContext = sslContext;
return this;
}
public EurekaJerseyClient build() {
MyDefaultApacheHttpClient4Config config = new MyDefaultApacheHttpClient4Config();
try {
return new EurekaJerseyClientImpl(connectionTimeout, readTimeout, connectionIdleTimeout, config);
} catch (Throwable e) {
throw new RuntimeException("Cannot create Jersey client ", e);
}
}
class MyDefaultApacheHttpClient4Config extends DefaultApacheHttpClient4Config {
MyDefaultApacheHttpClient4Config() {
MonitoredConnectionManager cm;
if (systemSSL) {
cm = createSystemSslCM();
} else if (sslContext != null || hostnameVerifier != null || trustStoreFileName != null) {
cm = createCustomSslCM();
} else {
cm = createDefaultSslCM();
}
if (proxyHost != null) {
addProxyConfiguration(cm);
}
DiscoveryJerseyProvider discoveryJerseyProvider = new DiscoveryJerseyProvider(encoderWrapper, decoderWrapper);
getSingletons().add(discoveryJerseyProvider);
// Common properties to all clients
cm.setDefaultMaxPerRoute(maxConnectionsPerHost);
cm.setMaxTotal(maxTotalConnections);
getProperties().put(ApacheHttpClient4Config.PROPERTY_CONNECTION_MANAGER, cm);
String fullUserAgentName = (userAgent == null ? clientName : userAgent) + "/v" + buildVersion();
getProperties().put(CoreProtocolPNames.USER_AGENT, fullUserAgentName);
// To pin a client to specific server in case redirect happens, we handle redirects directly
// (see DiscoveryClient.makeRemoteCall methods).
getProperties().put(PROPERTY_FOLLOW_REDIRECTS, Boolean.FALSE);
getProperties().put(ClientPNames.HANDLE_REDIRECTS, Boolean.FALSE);
}
private void addProxyConfiguration(MonitoredConnectionManager cm) {
if (proxyUserName != null && proxyPassword != null) {
getProperties().put(ApacheHttpClient4Config.PROPERTY_PROXY_USERNAME, proxyUserName);
getProperties().put(ApacheHttpClient4Config.PROPERTY_PROXY_PASSWORD, proxyPassword);
} else {
// Due to bug in apache client, user name/password must always be set.
// Otherwise proxy configuration is ignored.
getProperties().put(ApacheHttpClient4Config.PROPERTY_PROXY_USERNAME, "guest");
getProperties().put(ApacheHttpClient4Config.PROPERTY_PROXY_PASSWORD, "guest");
}
getProperties().put(DefaultApacheHttpClient4Config.PROPERTY_PROXY_URI, "http://" + proxyHost + ":" + proxyPort);
}
private MonitoredConnectionManager createSystemSslCM() {
MonitoredConnectionManager cm;
SSLConnectionSocketFactory systemSocketFactory = SSLConnectionSocketFactory.getSystemSocketFactory();
SSLSocketFactory sslSocketFactory = new SSLSocketFactoryAdapter(systemSocketFactory);
SchemeRegistry sslSchemeRegistry = new SchemeRegistry();
sslSchemeRegistry.register(new Scheme(PROTOCOL, HTTPS_PORT, sslSocketFactory));
cm = new MonitoredConnectionManager(clientName, sslSchemeRegistry);
return cm;
}
private MonitoredConnectionManager createCustomSslCM() {
FileInputStream fin = null;
try {
if (sslContext == null) {
sslContext = SSLContext.getInstance(PROTOCOL_SCHEME);
KeyStore sslKeyStore = KeyStore.getInstance(KEYSTORE_TYPE);
fin = new FileInputStream(trustStoreFileName);
sslKeyStore.load(fin, trustStorePassword.toCharArray());
TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init(sslKeyStore);
TrustManager[] trustManagers = factory.getTrustManagers();
sslContext.init(null, trustManagers, null);
}
if (hostnameVerifier == null) {
hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
}
SSLConnectionSocketFactory customSslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
SSLSocketFactory sslSocketFactory = new SSLSocketFactoryAdapter(customSslSocketFactory);
SchemeRegistry sslSchemeRegistry = new SchemeRegistry();
sslSchemeRegistry.register(new Scheme(PROTOCOL, HTTPS_PORT, sslSocketFactory));
return new MonitoredConnectionManager(clientName, sslSchemeRegistry);
} catch (Exception ex) {
throw new IllegalStateException("SSL configuration issue", ex);
} finally {
if (fin != null) {
try {
fin.close();
} catch (IOException ignore) {
}
}
}
}
/**
* @see SchemeRegistryFactory#createDefault()
*/
private MonitoredConnectionManager createDefaultSslCM() {
final SchemeRegistry registry = new SchemeRegistry();
registry.register(
new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
registry.register(
new Scheme("https", 443, new SSLSocketFactoryAdapter(SSLConnectionSocketFactory.getSocketFactory())));
return new MonitoredConnectionManager(clientName, registry);
}
}
/**
* @param hostnameVerifier
*/
public void withHostnameVerifier(HostnameVerifier hostnameVerifier) {
this.hostnameVerifier = hostnameVerifier;
}
}
}
| 8,022 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport/jersey/SSLSocketFactoryAdapter.java | package com.netflix.discovery.shared.transport.jersey;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import org.apache.http.HttpHost;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.protocol.HttpContext;
/**
* Adapts a version 4.3+ {@link SSLConnectionSocketFactory} to a pre 4.3
* {@link SSLSocketFactory}. This allows {@link HttpClient}s built using the
* deprecated pre 4.3 APIs to use SSL improvements from 4.3, e.g. SNI.
*
* @author William Tran
*
*/
public class SSLSocketFactoryAdapter extends SSLSocketFactory {
private final SSLConnectionSocketFactory factory;
public SSLSocketFactoryAdapter(SSLConnectionSocketFactory factory) {
// super's dependencies are dummies, and will delegate all calls to the
// to the overridden methods
super(DummySSLSocketFactory.INSTANCE, DummyX509HostnameVerifier.INSTANCE);
this.factory = factory;
}
public SSLSocketFactoryAdapter(SSLConnectionSocketFactory factory, HostnameVerifier hostnameVerifier) {
super(DummySSLSocketFactory.INSTANCE, new WrappedX509HostnameVerifier(hostnameVerifier));
this.factory = factory;
}
@Override
public Socket createSocket(final HttpContext context) throws IOException {
return factory.createSocket(context);
}
@Override
public Socket connectSocket(
final int connectTimeout,
final Socket socket,
final HttpHost host,
final InetSocketAddress remoteAddress,
final InetSocketAddress localAddress,
final HttpContext context) throws IOException {
return factory.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context);
}
@Override
public Socket createLayeredSocket(
final Socket socket,
final String target,
final int port,
final HttpContext context) throws IOException {
return factory.createLayeredSocket(socket, target, port, context);
}
private static class DummySSLSocketFactory extends javax.net.ssl.SSLSocketFactory {
private static final DummySSLSocketFactory INSTANCE = new DummySSLSocketFactory();
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public String[] getDefaultCipherSuites() {
throw new UnsupportedOperationException();
}
@Override
public String[] getSupportedCipherSuites() {
throw new UnsupportedOperationException();
}
@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
throw new UnsupportedOperationException();
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
throws IOException, UnknownHostException {
throw new UnsupportedOperationException();
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort)
throws IOException {
throw new UnsupportedOperationException();
}
}
private static class DummyX509HostnameVerifier implements X509HostnameVerifier {
private static final DummyX509HostnameVerifier INSTANCE = new DummyX509HostnameVerifier();
@Override
public boolean verify(String hostname, SSLSession session) {
throw new UnsupportedOperationException();
}
@Override
public void verify(String host, SSLSocket ssl) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public void verify(String host, X509Certificate cert) throws SSLException {
throw new UnsupportedOperationException();
}
@Override
public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
throw new UnsupportedOperationException();
}
}
private static class WrappedX509HostnameVerifier extends DummyX509HostnameVerifier {
HostnameVerifier hostnameVerifier;
private WrappedX509HostnameVerifier(HostnameVerifier hostnameVerifier) {
this.hostnameVerifier = hostnameVerifier;
}
@Override
public boolean verify(String hostname, SSLSession session) {
return hostnameVerifier.verify(hostname, session);
}
}
}
| 8,023 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport/decorator/MetricsCollectingEurekaHttpClient.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery.shared.transport.decorator;
import java.util.EnumMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import com.netflix.discovery.EurekaClientNames;
import com.netflix.discovery.shared.resolver.EurekaEndpoint;
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.TransportClientFactory;
import com.netflix.discovery.shared.transport.decorator.MetricsCollectingEurekaHttpClient.EurekaHttpClientRequestMetrics.Status;
import com.netflix.discovery.util.ExceptionsMetric;
import com.netflix.discovery.util.ServoUtil;
import com.netflix.servo.monitor.BasicCounter;
import com.netflix.servo.monitor.BasicTimer;
import com.netflix.servo.monitor.Counter;
import com.netflix.servo.monitor.MonitorConfig;
import com.netflix.servo.monitor.Stopwatch;
import com.netflix.servo.monitor.Timer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Tomasz Bak
*/
public class MetricsCollectingEurekaHttpClient extends EurekaHttpClientDecorator {
private static final Logger logger = LoggerFactory.getLogger(MetricsCollectingEurekaHttpClient.class);
private final EurekaHttpClient delegate;
private final Map<RequestType, EurekaHttpClientRequestMetrics> metricsByRequestType;
private final ExceptionsMetric exceptionsMetric;
private final boolean shutdownMetrics;
public MetricsCollectingEurekaHttpClient(EurekaHttpClient delegate) {
this(delegate, initializeMetrics(), new ExceptionsMetric(EurekaClientNames.METRIC_TRANSPORT_PREFIX + "exceptions"), true);
}
private MetricsCollectingEurekaHttpClient(EurekaHttpClient delegate,
Map<RequestType, EurekaHttpClientRequestMetrics> metricsByRequestType,
ExceptionsMetric exceptionsMetric,
boolean shutdownMetrics) {
this.delegate = delegate;
this.metricsByRequestType = metricsByRequestType;
this.exceptionsMetric = exceptionsMetric;
this.shutdownMetrics = shutdownMetrics;
}
@Override
protected <R> EurekaHttpResponse<R> execute(RequestExecutor<R> requestExecutor) {
EurekaHttpClientRequestMetrics requestMetrics = metricsByRequestType.get(requestExecutor.getRequestType());
Stopwatch stopwatch = requestMetrics.latencyTimer.start();
try {
EurekaHttpResponse<R> httpResponse = requestExecutor.execute(delegate);
requestMetrics.countersByStatus.get(mappedStatus(httpResponse)).increment();
return httpResponse;
} catch (Exception e) {
requestMetrics.connectionErrors.increment();
exceptionsMetric.count(e);
throw e;
} finally {
stopwatch.stop();
}
}
@Override
public void shutdown() {
if (shutdownMetrics) {
shutdownMetrics(metricsByRequestType);
exceptionsMetric.shutdown();
}
}
public static EurekaHttpClientFactory createFactory(final EurekaHttpClientFactory delegateFactory) {
final Map<RequestType, EurekaHttpClientRequestMetrics> metricsByRequestType = initializeMetrics();
final ExceptionsMetric exceptionMetrics = new ExceptionsMetric(EurekaClientNames.METRIC_TRANSPORT_PREFIX + "exceptions");
return new EurekaHttpClientFactory() {
@Override
public EurekaHttpClient newClient() {
return new MetricsCollectingEurekaHttpClient(
delegateFactory.newClient(),
metricsByRequestType,
exceptionMetrics,
false
);
}
@Override
public void shutdown() {
shutdownMetrics(metricsByRequestType);
exceptionMetrics.shutdown();
}
};
}
public static TransportClientFactory createFactory(final TransportClientFactory delegateFactory) {
final Map<RequestType, EurekaHttpClientRequestMetrics> metricsByRequestType = initializeMetrics();
final ExceptionsMetric exceptionMetrics = new ExceptionsMetric(EurekaClientNames.METRIC_TRANSPORT_PREFIX + "exceptions");
return new TransportClientFactory() {
@Override
public EurekaHttpClient newClient(EurekaEndpoint endpoint) {
return new MetricsCollectingEurekaHttpClient(
delegateFactory.newClient(endpoint),
metricsByRequestType,
exceptionMetrics,
false
);
}
@Override
public void shutdown() {
shutdownMetrics(metricsByRequestType);
exceptionMetrics.shutdown();
}
};
}
private static Map<RequestType, EurekaHttpClientRequestMetrics> initializeMetrics() {
Map<RequestType, EurekaHttpClientRequestMetrics> result = new EnumMap<>(RequestType.class);
try {
for (RequestType requestType : RequestType.values()) {
result.put(requestType, new EurekaHttpClientRequestMetrics(requestType.name()));
}
} catch (Exception e) {
logger.warn("Metrics initialization failure", e);
}
return result;
}
private static void shutdownMetrics(Map<RequestType, EurekaHttpClientRequestMetrics> metricsByRequestType) {
for (EurekaHttpClientRequestMetrics metrics : metricsByRequestType.values()) {
metrics.shutdown();
}
}
private static Status mappedStatus(EurekaHttpResponse<?> httpResponse) {
int category = httpResponse.getStatusCode() / 100;
switch (category) {
case 1:
return Status.x100;
case 2:
return Status.x200;
case 3:
return Status.x300;
case 4:
return Status.x400;
case 5:
return Status.x500;
}
return Status.Unknown;
}
static class EurekaHttpClientRequestMetrics {
enum Status {x100, x200, x300, x400, x500, Unknown}
private final Timer latencyTimer;
private final Counter connectionErrors;
private final Map<Status, Counter> countersByStatus;
EurekaHttpClientRequestMetrics(String resourceName) {
this.countersByStatus = createStatusCounters(resourceName);
latencyTimer = new BasicTimer(
MonitorConfig.builder(EurekaClientNames.METRIC_TRANSPORT_PREFIX + "latency")
.withTag("id", resourceName)
.withTag("class", MetricsCollectingEurekaHttpClient.class.getSimpleName())
.build(),
TimeUnit.MILLISECONDS
);
ServoUtil.register(latencyTimer);
this.connectionErrors = new BasicCounter(
MonitorConfig.builder(EurekaClientNames.METRIC_TRANSPORT_PREFIX + "connectionErrors")
.withTag("id", resourceName)
.withTag("class", MetricsCollectingEurekaHttpClient.class.getSimpleName())
.build()
);
ServoUtil.register(connectionErrors);
}
void shutdown() {
ServoUtil.unregister(latencyTimer, connectionErrors);
ServoUtil.unregister(countersByStatus.values());
}
private static Map<Status, Counter> createStatusCounters(String resourceName) {
Map<Status, Counter> result = new EnumMap<>(Status.class);
for (Status status : Status.values()) {
BasicCounter counter = new BasicCounter(
MonitorConfig.builder(EurekaClientNames.METRIC_TRANSPORT_PREFIX + "request")
.withTag("id", resourceName)
.withTag("class", MetricsCollectingEurekaHttpClient.class.getSimpleName())
.withTag("status", status.name())
.build()
);
ServoUtil.register(counter);
result.put(status, counter);
}
return result;
}
}
}
| 8,024 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport/decorator/RetryableEurekaHttpClient.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery.shared.transport.decorator;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.atomic.AtomicReference;
import com.netflix.discovery.shared.resolver.ClusterResolver;
import com.netflix.discovery.shared.resolver.EurekaEndpoint;
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.TransportException;
import com.netflix.discovery.shared.transport.TransportUtils;
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 static com.netflix.discovery.EurekaClientNames.METRIC_TRANSPORT_PREFIX;
/**
* {@link RetryableEurekaHttpClient} retries failed requests on subsequent servers in the cluster.
* It maintains also simple quarantine list, so operations are not retried again on servers
* that are not reachable at the moment.
* <h3>Quarantine</h3>
* All the servers to which communication failed are put on the quarantine list. First successful execution
* clears this list, which makes those server eligible for serving future requests.
* The list is also cleared once all available servers are exhausted.
* <h3>5xx</h3>
* If 5xx status code is returned, {@link ServerStatusEvaluator} predicate evaluates if the retries should be
* retried on another server, or the response with this status code returned to the client.
*
* @author Tomasz Bak
* @author Li gang
*/
public class RetryableEurekaHttpClient extends EurekaHttpClientDecorator {
private static final Logger logger = LoggerFactory.getLogger(RetryableEurekaHttpClient.class);
public static final int DEFAULT_NUMBER_OF_RETRIES = 3;
private final String name;
private final EurekaTransportConfig transportConfig;
private final ClusterResolver clusterResolver;
private final TransportClientFactory clientFactory;
private final ServerStatusEvaluator serverStatusEvaluator;
private final int numberOfRetries;
private final AtomicReference<EurekaHttpClient> delegate = new AtomicReference<>();
private final Set<EurekaEndpoint> quarantineSet = new ConcurrentSkipListSet<>();
public RetryableEurekaHttpClient(String name,
EurekaTransportConfig transportConfig,
ClusterResolver clusterResolver,
TransportClientFactory clientFactory,
ServerStatusEvaluator serverStatusEvaluator,
int numberOfRetries) {
this.name = name;
this.transportConfig = transportConfig;
this.clusterResolver = clusterResolver;
this.clientFactory = clientFactory;
this.serverStatusEvaluator = serverStatusEvaluator;
this.numberOfRetries = numberOfRetries;
Monitors.registerObject(name, this);
}
@Override
public void shutdown() {
TransportUtils.shutdown(delegate.get());
if(Monitors.isObjectRegistered(name, this)) {
Monitors.unregisterObject(name, this);
}
}
@Override
protected <R> EurekaHttpResponse<R> execute(RequestExecutor<R> requestExecutor) {
List<EurekaEndpoint> candidateHosts = null;
int endpointIdx = 0;
for (int retry = 0; retry < numberOfRetries; retry++) {
EurekaHttpClient currentHttpClient = delegate.get();
EurekaEndpoint currentEndpoint = null;
if (currentHttpClient == null) {
if (candidateHosts == null) {
candidateHosts = getHostCandidates();
if (candidateHosts.isEmpty()) {
throw new TransportException("There is no known eureka server; cluster server list is empty");
}
}
if (endpointIdx >= candidateHosts.size()) {
throw new TransportException("Cannot execute request on any known server");
}
currentEndpoint = candidateHosts.get(endpointIdx++);
currentHttpClient = clientFactory.newClient(currentEndpoint);
}
try {
EurekaHttpResponse<R> response = requestExecutor.execute(currentHttpClient);
if (serverStatusEvaluator.accept(response.getStatusCode(), requestExecutor.getRequestType())) {
delegate.set(currentHttpClient);
if (retry > 0) {
logger.info("Request execution succeeded on retry #{}", retry);
}
return response;
}
logger.warn("Request execution failure with status code {}; retrying on another server if available", response.getStatusCode());
} catch (Exception e) {
logger.warn("Request execution failed with message: {}", e.getMessage()); // just log message as the underlying client should log the stacktrace
}
// Connection error or 5xx from the server that must be retried on another server
delegate.compareAndSet(currentHttpClient, null);
if (currentEndpoint != null) {
quarantineSet.add(currentEndpoint);
}
}
throw new TransportException("Retry limit reached; giving up on completing the request");
}
public static EurekaHttpClientFactory createFactory(final String name,
final EurekaTransportConfig transportConfig,
final ClusterResolver<EurekaEndpoint> clusterResolver,
final TransportClientFactory delegateFactory,
final ServerStatusEvaluator serverStatusEvaluator) {
return new EurekaHttpClientFactory() {
@Override
public EurekaHttpClient newClient() {
return new RetryableEurekaHttpClient(name, transportConfig, clusterResolver, delegateFactory,
serverStatusEvaluator, DEFAULT_NUMBER_OF_RETRIES);
}
@Override
public void shutdown() {
delegateFactory.shutdown();
}
};
}
private List<EurekaEndpoint> getHostCandidates() {
List<EurekaEndpoint> candidateHosts = clusterResolver.getClusterEndpoints();
quarantineSet.retainAll(candidateHosts);
// If enough hosts are bad, we have no choice but start over again
int threshold = (int) (candidateHosts.size() * transportConfig.getRetryableClientQuarantineRefreshPercentage());
//Prevent threshold is too large
if (threshold > candidateHosts.size()) {
threshold = candidateHosts.size();
}
if (quarantineSet.isEmpty()) {
// no-op
} else if (quarantineSet.size() >= threshold) {
logger.debug("Clearing quarantined list of size {}", quarantineSet.size());
quarantineSet.clear();
} else {
List<EurekaEndpoint> remainingHosts = new ArrayList<>(candidateHosts.size());
for (EurekaEndpoint endpoint : candidateHosts) {
if (!quarantineSet.contains(endpoint)) {
remainingHosts.add(endpoint);
}
}
candidateHosts = remainingHosts;
}
return candidateHosts;
}
@Monitor(name = METRIC_TRANSPORT_PREFIX + "quarantineSize",
description = "number of servers quarantined", type = DataSourceType.GAUGE)
public long getQuarantineSetSize() {
return quarantineSet.size();
}
}
| 8,025 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport/decorator/SessionedEurekaHttpClient.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery.shared.transport.decorator;
import java.util.Random;
import java.util.concurrent.atomic.AtomicReference;
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.TransportUtils;
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 static com.netflix.discovery.EurekaClientNames.METRIC_TRANSPORT_PREFIX;
/**
* {@link SessionedEurekaHttpClient} enforces full reconnect at a regular interval (a session), preventing
* a client to sticking to a particular Eureka server instance forever. This in turn guarantees even
* load distribution in case of cluster topology change.
*
* @author Tomasz Bak
*/
public class SessionedEurekaHttpClient extends EurekaHttpClientDecorator {
private static final Logger logger = LoggerFactory.getLogger(SessionedEurekaHttpClient.class);
private final Random random = new Random();
private final String name;
private final EurekaHttpClientFactory clientFactory;
private final long sessionDurationMs;
private volatile long currentSessionDurationMs;
private volatile long lastReconnectTimeStamp = -1;
private final AtomicReference<EurekaHttpClient> eurekaHttpClientRef = new AtomicReference<>();
public SessionedEurekaHttpClient(String name, EurekaHttpClientFactory clientFactory, long sessionDurationMs) {
this.name = name;
this.clientFactory = clientFactory;
this.sessionDurationMs = sessionDurationMs;
this.currentSessionDurationMs = randomizeSessionDuration(sessionDurationMs);
Monitors.registerObject(name, this);
}
@Override
protected <R> EurekaHttpResponse<R> execute(RequestExecutor<R> requestExecutor) {
long now = System.currentTimeMillis();
long delay = now - lastReconnectTimeStamp;
if (delay >= currentSessionDurationMs) {
logger.debug("Ending a session and starting anew");
lastReconnectTimeStamp = now;
currentSessionDurationMs = randomizeSessionDuration(sessionDurationMs);
TransportUtils.shutdown(eurekaHttpClientRef.getAndSet(null));
}
EurekaHttpClient eurekaHttpClient = eurekaHttpClientRef.get();
if (eurekaHttpClient == null) {
eurekaHttpClient = TransportUtils.getOrSetAnotherClient(eurekaHttpClientRef, clientFactory.newClient());
}
return requestExecutor.execute(eurekaHttpClient);
}
@Override
public void shutdown() {
if(Monitors.isObjectRegistered(name, this)) {
Monitors.unregisterObject(name, this);
}
TransportUtils.shutdown(eurekaHttpClientRef.getAndSet(null));
}
/**
* @return a randomized sessionDuration in ms calculated as +/- an additional amount in [0, sessionDurationMs/2]
*/
protected long randomizeSessionDuration(long sessionDurationMs) {
long delta = (long) (sessionDurationMs * (random.nextDouble() - 0.5));
return sessionDurationMs + delta;
}
@Monitor(name = METRIC_TRANSPORT_PREFIX + "currentSessionDuration",
description = "Duration of the current session", type = DataSourceType.GAUGE)
public long getCurrentSessionDuration() {
return lastReconnectTimeStamp < 0 ? 0 : System.currentTimeMillis() - lastReconnectTimeStamp;
}
}
| 8,026 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport/decorator/EurekaHttpClientDecorator.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery.shared.transport.decorator;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import com.netflix.discovery.shared.Application;
import com.netflix.discovery.shared.Applications;
import com.netflix.discovery.shared.transport.EurekaHttpClient;
import com.netflix.discovery.shared.transport.EurekaHttpResponse;
/**
* @author Tomasz Bak
*/
public abstract class EurekaHttpClientDecorator implements EurekaHttpClient {
public enum RequestType {
Register,
Cancel,
SendHeartBeat,
StatusUpdate,
DeleteStatusOverride,
GetApplications,
GetDelta,
GetVip,
GetSecureVip,
GetApplication,
GetInstance,
GetApplicationInstance
}
public interface RequestExecutor<R> {
EurekaHttpResponse<R> execute(EurekaHttpClient delegate);
RequestType getRequestType();
}
protected abstract <R> EurekaHttpResponse<R> execute(RequestExecutor<R> requestExecutor);
@Override
public EurekaHttpResponse<Void> register(final InstanceInfo info) {
return execute(new RequestExecutor<Void>() {
@Override
public EurekaHttpResponse<Void> execute(EurekaHttpClient delegate) {
return delegate.register(info);
}
@Override
public RequestType getRequestType() {
return RequestType.Register;
}
});
}
@Override
public EurekaHttpResponse<Void> cancel(final String appName, final String id) {
return execute(new RequestExecutor<Void>() {
@Override
public EurekaHttpResponse<Void> execute(EurekaHttpClient delegate) {
return delegate.cancel(appName, id);
}
@Override
public RequestType getRequestType() {
return RequestType.Cancel;
}
});
}
@Override
public EurekaHttpResponse<InstanceInfo> sendHeartBeat(final String appName,
final String id,
final InstanceInfo info,
final InstanceStatus overriddenStatus) {
return execute(new RequestExecutor<InstanceInfo>() {
@Override
public EurekaHttpResponse<InstanceInfo> execute(EurekaHttpClient delegate) {
return delegate.sendHeartBeat(appName, id, info, overriddenStatus);
}
@Override
public RequestType getRequestType() {
return RequestType.SendHeartBeat;
}
});
}
@Override
public EurekaHttpResponse<Void> statusUpdate(final String appName, final String id, final InstanceStatus newStatus, final InstanceInfo info) {
return execute(new RequestExecutor<Void>() {
@Override
public EurekaHttpResponse<Void> execute(EurekaHttpClient delegate) {
return delegate.statusUpdate(appName, id, newStatus, info);
}
@Override
public RequestType getRequestType() {
return RequestType.StatusUpdate;
}
});
}
@Override
public EurekaHttpResponse<Void> deleteStatusOverride(final String appName, final String id, final InstanceInfo info) {
return execute(new RequestExecutor<Void>() {
@Override
public EurekaHttpResponse<Void> execute(EurekaHttpClient delegate) {
return delegate.deleteStatusOverride(appName, id, info);
}
@Override
public RequestType getRequestType() {
return RequestType.DeleteStatusOverride;
}
});
}
@Override
public EurekaHttpResponse<Applications> getApplications(final String... regions) {
return execute(new RequestExecutor<Applications>() {
@Override
public EurekaHttpResponse<Applications> execute(EurekaHttpClient delegate) {
return delegate.getApplications(regions);
}
@Override
public RequestType getRequestType() {
return RequestType.GetApplications;
}
});
}
@Override
public EurekaHttpResponse<Applications> getDelta(final String... regions) {
return execute(new RequestExecutor<Applications>() {
@Override
public EurekaHttpResponse<Applications> execute(EurekaHttpClient delegate) {
return delegate.getDelta(regions);
}
@Override
public RequestType getRequestType() {
return RequestType.GetDelta;
}
});
}
@Override
public EurekaHttpResponse<Applications> getVip(final String vipAddress, final String... regions) {
return execute(new RequestExecutor<Applications>() {
@Override
public EurekaHttpResponse<Applications> execute(EurekaHttpClient delegate) {
return delegate.getVip(vipAddress, regions);
}
@Override
public RequestType getRequestType() {
return RequestType.GetVip;
}
});
}
@Override
public EurekaHttpResponse<Applications> getSecureVip(final String secureVipAddress, final String... regions) {
return execute(new RequestExecutor<Applications>() {
@Override
public EurekaHttpResponse<Applications> execute(EurekaHttpClient delegate) {
return delegate.getVip(secureVipAddress, regions);
}
@Override
public RequestType getRequestType() {
return RequestType.GetSecureVip;
}
});
}
@Override
public EurekaHttpResponse<Application> getApplication(final String appName) {
return execute(new RequestExecutor<Application>() {
@Override
public EurekaHttpResponse<Application> execute(EurekaHttpClient delegate) {
return delegate.getApplication(appName);
}
@Override
public RequestType getRequestType() {
return RequestType.GetApplication;
}
});
}
@Override
public EurekaHttpResponse<InstanceInfo> getInstance(final String id) {
return execute(new RequestExecutor<InstanceInfo>() {
@Override
public EurekaHttpResponse<InstanceInfo> execute(EurekaHttpClient delegate) {
return delegate.getInstance(id);
}
@Override
public RequestType getRequestType() {
return RequestType.GetInstance;
}
});
}
@Override
public EurekaHttpResponse<InstanceInfo> getInstance(final String appName, final String id) {
return execute(new RequestExecutor<InstanceInfo>() {
@Override
public EurekaHttpResponse<InstanceInfo> execute(EurekaHttpClient delegate) {
return delegate.getInstance(appName, id);
}
@Override
public RequestType getRequestType() {
return RequestType.GetApplicationInstance;
}
});
}
}
| 8,027 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport/decorator/ServerStatusEvaluators.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery.shared.transport.decorator;
import com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.RequestType;
/**
* @author Tomasz Bak
*/
public final class ServerStatusEvaluators {
private static final ServerStatusEvaluator LEGACY_EVALUATOR = new ServerStatusEvaluator() {
@Override
public boolean accept(int statusCode, RequestType requestType) {
if (statusCode >= 200 && statusCode < 300 || statusCode == 302) {
return true;
} else if (requestType == RequestType.Register && statusCode == 404) {
return true;
} else if (requestType == RequestType.SendHeartBeat && statusCode == 404) {
return true;
} else if (requestType == RequestType.Cancel) { // cancel is best effort
return true;
} else if (requestType == RequestType.GetDelta && (statusCode == 403 || statusCode == 404)) {
return true;
}
return false;
}
};
private static final ServerStatusEvaluator HTTP_SUCCESS_EVALUATOR = new ServerStatusEvaluator() {
@Override
public boolean accept(int statusCode, RequestType requestType) {
return statusCode >= 200 && statusCode < 300;
}
};
private ServerStatusEvaluators() {
}
/**
* Evaluation rules implemented in com.netflix.discovery.DiscoveryClient#isOk(...) method.
*/
public static ServerStatusEvaluator legacyEvaluator() {
return LEGACY_EVALUATOR;
}
/**
* An evaluator that only care about http 2xx responses
*/
public static ServerStatusEvaluator httpSuccessEvaluator() {
return HTTP_SUCCESS_EVALUATOR;
}
}
| 8,028 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport/decorator/ServerStatusEvaluator.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery.shared.transport.decorator;
import com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.RequestType;
/**
* HTTP status code evaluator, that can be used to make a decision whether it makes sense to
* immediately retry a request on another server or stick to the current one.
* Registration requests are critical to complete as soon as possible, so any server error should be followed
* by retry on another one. Registry fetch/delta fetch should stick to the same server, to avoid delta hash code
* mismatches. See https://github.com/Netflix/eureka/issues/628.
*
* @author Tomasz Bak
*/
public interface ServerStatusEvaluator {
boolean accept(int statusCode, RequestType requestType);
}
| 8,029 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/transport/decorator/RedirectingEurekaHttpClient.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery.shared.transport.decorator;
import javax.ws.rs.core.UriBuilder;
import java.net.URI;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.netflix.discovery.shared.dns.DnsService;
import com.netflix.discovery.shared.dns.DnsServiceImpl;
import com.netflix.discovery.shared.resolver.DefaultEndpoint;
import com.netflix.discovery.shared.resolver.EurekaEndpoint;
import com.netflix.discovery.shared.transport.EurekaHttpClient;
import com.netflix.discovery.shared.transport.EurekaHttpResponse;
import com.netflix.discovery.shared.transport.TransportClientFactory;
import com.netflix.discovery.shared.transport.TransportException;
import com.netflix.discovery.shared.transport.TransportUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* {@link EurekaHttpClient} that follows redirect links, and executes the requests against
* the finally resolved endpoint.
* If registration and query requests must handled separately, two different instances shall be created.
* <h3>Thread safety</h3>
* Methods in this class may be called concurrently.
*
* @author Tomasz Bak
*/
public class RedirectingEurekaHttpClient extends EurekaHttpClientDecorator {
private static final Logger logger = LoggerFactory.getLogger(RedirectingEurekaHttpClient.class);
public static final int MAX_FOLLOWED_REDIRECTS = 10;
private static final Pattern REDIRECT_PATH_REGEX = Pattern.compile("(.*/v2/)apps(/.*)?$");
private final EurekaEndpoint serviceEndpoint;
private final TransportClientFactory factory;
private final DnsService dnsService;
private final AtomicReference<EurekaHttpClient> delegateRef = new AtomicReference<>();
/**
* The delegate client should pass through 3xx responses without further processing.
*/
public RedirectingEurekaHttpClient(String serviceUrl, TransportClientFactory factory, DnsService dnsService) {
this.serviceEndpoint = new DefaultEndpoint(serviceUrl);
this.factory = factory;
this.dnsService = dnsService;
}
@Override
public void shutdown() {
TransportUtils.shutdown(delegateRef.getAndSet(null));
}
@Override
protected <R> EurekaHttpResponse<R> execute(RequestExecutor<R> requestExecutor) {
EurekaHttpClient currentEurekaClient = delegateRef.get();
if (currentEurekaClient == null) {
AtomicReference<EurekaHttpClient> currentEurekaClientRef = new AtomicReference<>(factory.newClient(serviceEndpoint));
try {
EurekaHttpResponse<R> response = executeOnNewServer(requestExecutor, currentEurekaClientRef);
TransportUtils.shutdown(delegateRef.getAndSet(currentEurekaClientRef.get()));
return response;
} catch (Exception e) {
logger.info("Request execution error. endpoint={}, exception={} stacktrace={}", serviceEndpoint,
e.getMessage(), ExceptionUtils.getStackTrace(e));
TransportUtils.shutdown(currentEurekaClientRef.get());
throw e;
}
} else {
try {
return requestExecutor.execute(currentEurekaClient);
} catch (Exception e) {
logger.info("Request execution error. endpoint={} exception={} stacktrace={}", serviceEndpoint,
e.getMessage(), ExceptionUtils.getStackTrace(e));
delegateRef.compareAndSet(currentEurekaClient, null);
currentEurekaClient.shutdown();
throw e;
}
}
}
public static TransportClientFactory createFactory(final TransportClientFactory delegateFactory) {
final DnsServiceImpl dnsService = new DnsServiceImpl();
return new TransportClientFactory() {
@Override
public EurekaHttpClient newClient(EurekaEndpoint endpoint) {
return new RedirectingEurekaHttpClient(endpoint.getServiceUrl(), delegateFactory, dnsService);
}
@Override
public void shutdown() {
delegateFactory.shutdown();
}
};
}
private <R> EurekaHttpResponse<R> executeOnNewServer(RequestExecutor<R> requestExecutor,
AtomicReference<EurekaHttpClient> currentHttpClientRef) {
URI targetUrl = null;
for (int followRedirectCount = 0; followRedirectCount < MAX_FOLLOWED_REDIRECTS; followRedirectCount++) {
EurekaHttpResponse<R> httpResponse = requestExecutor.execute(currentHttpClientRef.get());
if (httpResponse.getStatusCode() != 302) {
if (followRedirectCount == 0) {
logger.debug("Pinning to endpoint {}", targetUrl);
} else {
logger.info("Pinning to endpoint {}, after {} redirect(s)", targetUrl, followRedirectCount);
}
return httpResponse;
}
targetUrl = getRedirectBaseUri(httpResponse.getLocation());
if (targetUrl == null) {
throw new TransportException("Invalid redirect URL " + httpResponse.getLocation());
}
currentHttpClientRef.getAndSet(null).shutdown();
currentHttpClientRef.set(factory.newClient(new DefaultEndpoint(targetUrl.toString())));
}
String message = "Follow redirect limit crossed for URI " + serviceEndpoint.getServiceUrl();
logger.warn(message);
throw new TransportException(message);
}
private URI getRedirectBaseUri(URI locationURI) {
if (locationURI == null) {
throw new TransportException("Missing Location header in the redirect reply");
}
Matcher pathMatcher = REDIRECT_PATH_REGEX.matcher(locationURI.getPath());
if (pathMatcher.matches()) {
return UriBuilder.fromUri(locationURI)
.host(dnsService.resolveIp(locationURI.getHost()))
.replacePath(pathMatcher.group(1))
.replaceQuery(null)
.build();
}
logger.warn("Invalid redirect URL {}", locationURI);
return null;
}
}
| 8,030 |
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/dns/DnsServiceImpl.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.dns;
import javax.annotation.Nullable;
import java.util.List;
import com.netflix.discovery.endpoint.DnsResolver;
/**
* @author Tomasz Bak
*/
public class DnsServiceImpl implements DnsService {
@Override
public String resolveIp(String hostName) {
return DnsResolver.resolve(hostName);
}
@Nullable
@Override
public List<String> resolveARecord(String rootDomainName) {
return DnsResolver.resolveARecord(rootDomainName);
}
}
| 8,031 |
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/dns/DnsService.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.dns;
import javax.annotation.Nullable;
import java.util.List;
/**
* @author Tomasz Bak
*/
public interface DnsService {
/**
* Resolve host name to the bottom A-Record or the latest available CNAME
*
* @return IP address
*/
String resolveIp(String hostName);
/**
* Resolve A-record entry for a given domain name.
*/
@Nullable
List<String> resolveARecord(String rootDomainName);
} | 8,032 |
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/ReloadingClusterResolver.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery.shared.resolver;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
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 static com.netflix.discovery.EurekaClientNames.METRIC_RESOLVER_PREFIX;
/**
* A cluster resolver implementation that periodically creates a new {@link ClusterResolver} instance that
* swaps the previous value. If the new resolver cannot be created or contains empty server list, the previous
* one is used. Failed requests are retried using exponential back-off strategy.
* <br/>
* It provides more insight in form of additional logging and metrics, as it is supposed to be used as a top
* level resolver.
*
* @author Tomasz Bak
*/
public class ReloadingClusterResolver<T extends EurekaEndpoint> implements ClusterResolver<T> {
private static final Logger logger = LoggerFactory.getLogger(ReloadingClusterResolver.class);
private static final long MAX_RELOAD_INTERVAL_MULTIPLIER = 5;
private final ClusterResolverFactory<T> factory;
private final long reloadIntervalMs;
private final long maxReloadIntervalMs;
private final AtomicReference<ClusterResolver<T>> delegateRef;
private volatile long lastUpdateTime;
private volatile long currentReloadIntervalMs;
// Metric timestamp, tracking last time when data were effectively changed.
private volatile long lastReloadTimestamp = -1;
public ReloadingClusterResolver(final ClusterResolverFactory<T> factory, final long reloadIntervalMs) {
this.factory = factory;
this.reloadIntervalMs = reloadIntervalMs;
this.maxReloadIntervalMs = MAX_RELOAD_INTERVAL_MULTIPLIER * reloadIntervalMs;
this.delegateRef = new AtomicReference<>(factory.createClusterResolver());
this.lastUpdateTime = System.currentTimeMillis();
this.currentReloadIntervalMs = reloadIntervalMs;
List<T> clusterEndpoints = delegateRef.get().getClusterEndpoints();
if (clusterEndpoints.isEmpty()) {
logger.error("Empty Eureka server endpoint list during initialization process");
throw new ClusterResolverException("Resolved to an empty endpoint list");
}
if (logger.isInfoEnabled()) {
logger.info("Initiated with delegate resolver of type {}; next reload in {}[sec]. Loaded endpoints={}",
delegateRef.get().getClass(), currentReloadIntervalMs / 1000, clusterEndpoints);
}
try {
Monitors.registerObject(this);
} catch (Throwable e) {
logger.warn("Cannot register metrics", e);
}
}
@Override
public String getRegion() {
ClusterResolver delegate = delegateRef.get();
return delegate == null ? null : delegate.getRegion();
}
@Override
public List<T> getClusterEndpoints() {
long expiryTime = lastUpdateTime + currentReloadIntervalMs;
if (expiryTime <= System.currentTimeMillis()) {
try {
ClusterResolver<T> newDelegate = reload();
this.lastUpdateTime = System.currentTimeMillis();
this.currentReloadIntervalMs = reloadIntervalMs;
if (newDelegate != null) {
delegateRef.set(newDelegate);
lastReloadTimestamp = System.currentTimeMillis();
if (logger.isInfoEnabled()) {
logger.info("Reload endpoints differ from the original list; next reload in {}[sec], Loaded endpoints={}",
currentReloadIntervalMs / 1000, newDelegate.getClusterEndpoints());
}
}
} catch (Exception e) {
this.currentReloadIntervalMs = Math.min(maxReloadIntervalMs, currentReloadIntervalMs * 2);
logger.warn("Cluster resolve error; keeping the current Eureka endpoints; next reload in "
+ "{}[sec]", currentReloadIntervalMs / 1000, e);
}
}
return delegateRef.get().getClusterEndpoints();
}
private ClusterResolver<T> reload() {
ClusterResolver<T> newDelegate = factory.createClusterResolver();
List<T> newEndpoints = newDelegate.getClusterEndpoints();
if (newEndpoints.isEmpty()) {
logger.info("Tried to reload but empty endpoint list returned; keeping the current endpoints");
return null;
}
// If no change in the server pool, shutdown the new delegate
if (ResolverUtils.identical(delegateRef.get().getClusterEndpoints(), newEndpoints)) {
logger.debug("Loaded cluster server list identical to the current one; no update required");
return null;
}
return newDelegate;
}
@Monitor(name = METRIC_RESOLVER_PREFIX + "lastReloadTimestamp",
description = "How much time has passed from last successful cluster configuration resolve", type = DataSourceType.GAUGE)
public long getLastReloadTimestamp() {
return lastReloadTimestamp < 0 ? 0 : System.currentTimeMillis() - lastReloadTimestamp;
}
}
| 8,033 |
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/DefaultEndpoint.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery.shared.resolver;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author Tomasz Bak
*/
public class DefaultEndpoint implements EurekaEndpoint {
protected final String networkAddress;
protected final int port;
protected final boolean isSecure;
protected final String relativeUri;
protected final String serviceUrl;
public DefaultEndpoint(String serviceUrl) {
this.serviceUrl = serviceUrl;
try {
URL url = new URL(serviceUrl);
this.networkAddress = url.getHost();
this.port = url.getPort();
this.isSecure = "https".equals(url.getProtocol());
this.relativeUri = url.getPath();
} catch (Exception e) {
throw new IllegalArgumentException("Malformed serviceUrl: " + serviceUrl);
}
}
public DefaultEndpoint(String networkAddress, int port, boolean isSecure, String relativeUri) {
this.networkAddress = networkAddress;
this.port = port;
this.isSecure = isSecure;
this.relativeUri = relativeUri;
StringBuilder sb = new StringBuilder()
.append(isSecure ? "https" : "http")
.append("://")
.append(networkAddress);
if (port >= 0) {
sb.append(':')
.append(port);
}
if (relativeUri != null) {
if (!relativeUri.startsWith("/")) {
sb.append('/');
}
sb.append(relativeUri);
}
this.serviceUrl = sb.toString();
}
@Override
public String getServiceUrl() {
return serviceUrl;
}
@Deprecated
@Override
public String getHostName() {
return networkAddress;
}
@Override
public String getNetworkAddress() {
return networkAddress;
}
@Override
public int getPort() {
return port;
}
@Override
public boolean isSecure() {
return isSecure;
}
@Override
public String getRelativeUri() {
return relativeUri;
}
public static List<EurekaEndpoint> createForServerList(
List<String> hostNames, int port, boolean isSecure, String relativeUri) {
if (hostNames.isEmpty()) {
return Collections.emptyList();
}
List<EurekaEndpoint> eurekaEndpoints = new ArrayList<>(hostNames.size());
for (String hostName : hostNames) {
eurekaEndpoints.add(new DefaultEndpoint(hostName, port, isSecure, relativeUri));
}
return eurekaEndpoints;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof DefaultEndpoint)) return false;
DefaultEndpoint that = (DefaultEndpoint) o;
if (isSecure != that.isSecure) return false;
if (port != that.port) return false;
if (networkAddress != null ? !networkAddress.equals(that.networkAddress) : that.networkAddress != null) return false;
if (relativeUri != null ? !relativeUri.equals(that.relativeUri) : that.relativeUri != null) return false;
if (serviceUrl != null ? !serviceUrl.equals(that.serviceUrl) : that.serviceUrl != null) return false;
return true;
}
@Override
public int hashCode() {
int result = networkAddress != null ? networkAddress.hashCode() : 0;
result = 31 * result + port;
result = 31 * result + (isSecure ? 1 : 0);
result = 31 * result + (relativeUri != null ? relativeUri.hashCode() : 0);
result = 31 * result + (serviceUrl != null ? serviceUrl.hashCode() : 0);
return result;
}
@Override
public int compareTo(Object that) {
return serviceUrl.compareTo(((DefaultEndpoint) that).getServiceUrl());
}
@Override
public String toString() {
return "DefaultEndpoint{ serviceUrl='" + serviceUrl + '}';
}
}
| 8,034 |
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/ClusterResolver.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery.shared.resolver;
import java.util.List;
/**
* @author Tomasz Bak
*/
public interface ClusterResolver<T extends EurekaEndpoint> {
String getRegion();
List<T> getClusterEndpoints();
}
| 8,035 |
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/ResolverUtils.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery.shared.resolver;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.netflix.appinfo.AmazonInfo;
import com.netflix.appinfo.DataCenterInfo;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.discovery.shared.resolver.aws.AwsEndpoint;
import com.netflix.discovery.shared.transport.EurekaTransportConfig;
import com.netflix.discovery.util.SystemUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Tomasz Bak
*/
public final class ResolverUtils {
private static final Logger logger = LoggerFactory.getLogger(ResolverUtils.class);
private static final Pattern ZONE_RE = Pattern.compile("(txt\\.)?([^.]+).*");
private ResolverUtils() {
}
/**
* @return returns two element array with first item containing list of endpoints from client's zone,
* and in the second list all the remaining ones
*/
public static List<AwsEndpoint>[] splitByZone(List<AwsEndpoint> eurekaEndpoints, String myZone) {
if (eurekaEndpoints.isEmpty()) {
return new List[]{Collections.emptyList(), Collections.emptyList()};
}
if (myZone == null) {
return new List[]{Collections.emptyList(), new ArrayList<>(eurekaEndpoints)};
}
List<AwsEndpoint> myZoneList = new ArrayList<>(eurekaEndpoints.size());
List<AwsEndpoint> remainingZonesList = new ArrayList<>(eurekaEndpoints.size());
for (AwsEndpoint endpoint : eurekaEndpoints) {
if (myZone.equalsIgnoreCase(endpoint.getZone())) {
myZoneList.add(endpoint);
} else {
remainingZonesList.add(endpoint);
}
}
return new List[]{myZoneList, remainingZonesList};
}
public static String extractZoneFromHostName(String hostName) {
Matcher matcher = ZONE_RE.matcher(hostName);
if (matcher.matches()) {
return matcher.group(2);
}
return null;
}
/**
* Randomize server list.
*
* @return a copy of the original list with elements in the random order
*/
public static <T extends EurekaEndpoint> List<T> randomize(List<T> list) {
List<T> randomList = new ArrayList<>(list);
if (randomList.size() < 2) {
return randomList;
}
Collections.shuffle(randomList,ThreadLocalRandom.current());
return randomList;
}
/**
* @return true if both list are the same, possibly in a different order
*/
public static <T extends EurekaEndpoint> boolean identical(List<T> firstList, List<T> secondList) {
if (firstList.size() != secondList.size()) {
return false;
}
HashSet<T> compareSet = new HashSet<>(firstList);
compareSet.removeAll(secondList);
return compareSet.isEmpty();
}
public static AwsEndpoint instanceInfoToEndpoint(EurekaClientConfig clientConfig,
EurekaTransportConfig transportConfig,
InstanceInfo instanceInfo) {
String zone = null;
DataCenterInfo dataCenterInfo = instanceInfo.getDataCenterInfo();
if (dataCenterInfo instanceof AmazonInfo) {
zone = ((AmazonInfo) dataCenterInfo).get(AmazonInfo.MetaDataKey.availabilityZone);
} else {
zone = instanceInfo.getMetadata().get("zone");
}
String networkAddress;
if (transportConfig.applicationsResolverUseIp()) {
if (instanceInfo.getDataCenterInfo() instanceof AmazonInfo) {
networkAddress = ((AmazonInfo) instanceInfo.getDataCenterInfo()).get(AmazonInfo.MetaDataKey.localIpv4);
} else {
networkAddress = instanceInfo.getIPAddr();
}
} else {
networkAddress = instanceInfo.getHostName();
}
if (networkAddress == null) { // final check
logger.error("Cannot resolve InstanceInfo {} to a proper resolver endpoint, skipping", instanceInfo);
return null;
}
return new AwsEndpoint(
networkAddress,
instanceInfo.getPort(),
false,
clientConfig.getEurekaServerURLContext(),
clientConfig.getRegion(),
zone
);
}
}
| 8,036 |
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/EurekaEndpoint.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;
public interface EurekaEndpoint extends Comparable<Object> {
String getServiceUrl();
/**
* @deprecated use {@link #getNetworkAddress()}
*/
@Deprecated
String getHostName();
String getNetworkAddress();
int getPort();
boolean isSecure();
String getRelativeUri();
}
| 8,037 |
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/StaticClusterResolver.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery.shared.resolver;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Statically configured Eureka server pool.
*
* @author Tomasz Bak
*/
public class StaticClusterResolver<T extends EurekaEndpoint> implements ClusterResolver<T> {
private static final Logger logger = LoggerFactory.getLogger(StaticClusterResolver.class);
private final List<T> eurekaEndpoints;
private final String region;
@SafeVarargs
public StaticClusterResolver(String region, T... eurekaEndpoints) {
this(region, Arrays.asList(eurekaEndpoints));
}
public StaticClusterResolver(String region, List<T> eurekaEndpoints) {
this.eurekaEndpoints = eurekaEndpoints;
this.region = region;
logger.debug("Fixed resolver configuration: {}", eurekaEndpoints);
}
@Override
public String getRegion() {
return region;
}
@Override
public List<T> getClusterEndpoints() {
return eurekaEndpoints;
}
public static ClusterResolver<EurekaEndpoint> fromURL(String regionName, URL serviceUrl) {
boolean isSecure = "https".equalsIgnoreCase(serviceUrl.getProtocol());
int defaultPort = isSecure ? 443 : 80;
int port = serviceUrl.getPort() == -1 ? defaultPort : serviceUrl.getPort();
return new StaticClusterResolver<EurekaEndpoint>(
regionName,
new DefaultEndpoint(serviceUrl.getHost(), port, isSecure, serviceUrl.getPath())
);
}
}
| 8,038 |
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/DnsClusterResolver.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery.shared.resolver;
import java.util.Collections;
import java.util.List;
import com.netflix.discovery.shared.dns.DnsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Resolves cluster addresses from DNS. If the provided name contains only CNAME entry, the cluster server pool
* contains effectively single item, that may however resolve to different IPs. This is not recommended configuration.
* In the configuration where DNS name points to A record, all IPs from that record are loaded. This resolver
* is not zone aware.
*
* @author Tomasz Bak
*/
public class DnsClusterResolver implements ClusterResolver<EurekaEndpoint> {
private static final Logger logger = LoggerFactory.getLogger(DnsClusterResolver.class);
private final List<EurekaEndpoint> eurekaEndpoints;
private final String region;
/**
* @param rootClusterDNS cluster DNS name containing CNAME or A record.
* @param port Eureka sever port number
* @param relativeUri service relative URI that will be appended to server address
*/
public DnsClusterResolver(DnsService dnsService, String region, String rootClusterDNS, int port, boolean isSecure, String relativeUri) {
this.region = region;
List<String> addresses = dnsService.resolveARecord(rootClusterDNS);
if (addresses == null) {
this.eurekaEndpoints = Collections.<EurekaEndpoint>singletonList(new DefaultEndpoint(rootClusterDNS, port, isSecure, relativeUri));
} else {
this.eurekaEndpoints = DefaultEndpoint.createForServerList(addresses, port, isSecure, relativeUri);
}
logger.debug("Resolved {} to {}", rootClusterDNS, eurekaEndpoints);
}
@Override
public String getRegion() {
return region;
}
@Override
public List<EurekaEndpoint> getClusterEndpoints() {
return eurekaEndpoints;
}
}
| 8,039 |
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);
}
}
};
}
| 8,040 |
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;
}
}
}
| 8,041 |
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();
}
| 8,042 |
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);
}
| 8,043 |
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();
}
| 8,044 |
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);
}
}
| 8,045 |
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);
}
}
| 8,046 |
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();
}
}
| 8,047 |
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+'\''+'}';
}
} | 8,048 |
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;
}
}
| 8,049 |
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;
}
}
| 8,050 |
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;
}
}
| 8,051 |
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;
}
}
| 8,052 |
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;
}
}
| 8,053 |
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);
}
| 8,054 |
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();
}
| 8,055 |
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();
}
| 8,056 |
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;
}
}
| 8,057 |
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);
}
| 8,058 |
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;
}
}
| 8,059 |
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";
}
}
| 8,060 |
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();
}
}
}
| 8,061 |
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);
}
}
| 8,062 |
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);
}
}
| 8,063 |
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();
}
}
| 8,064 |
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;
}
}
| 8,065 |
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();
}
| 8,066 |
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;
}
}
| 8,067 |
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;
}
}
}
| 8,068 |
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;
}
}
| 8,069 |
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();
}
| 8,070 |
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();
}
| 8,071 |
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();
}
}
| 8,072 |
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);
}
}
| 8,073 |
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();
}
| 8,074 |
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;
}
}
| 8,075 |
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;
}
}
| 8,076 |
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;
}
}
| 8,077 |
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 +
'}';
}
}
| 8,078 |
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);
}
| 8,079 |
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;
}
}
| 8,080 |
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;
}
}
| 8,081 |
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;
}
}
| 8,082 |
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;
}
}
| 8,083 |
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());
}
}
| 8,084 |
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);
}
}
| 8,085 |
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());
}
}
| 8,086 |
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());
}
}
| 8,087 |
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;
}
};
}
}
| 8,088 |
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;
}
}
| 8,089 |
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 {
}
}
| 8,090 |
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() {
}
}
| 8,091 |
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, "");
}
};
}
}
| 8,092 |
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);
}
}
| 8,093 |
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);
}
}
| 8,094 |
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;
}
}
| 8,095 |
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;
}
}
| 8,096 |
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;
}
}
| 8,097 |
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;
}
}
| 8,098 |
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);
}
}
| 8,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.