index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/AzToRegionMapper.java
package com.netflix.discovery; /** * An interface that contains a contract of mapping availability zone to region mapping. An implementation will always * know before hand which zone to region mapping will be queried from the mapper, this will aid caching of this * information before hand. * * @author Nitesh Kant */ public interface AzToRegionMapper { /** * Returns the region for the passed availability zone. * * @param availabilityZone Availability zone for which the region is to be retrieved. * * @return The region for the passed zone. */ String getRegionForAvailabilityZone(String availabilityZone); /** * Update the regions that this mapper knows about. * * @param regionsToFetch Regions to fetch. This should be the super set of all regions that this mapper should know. */ void setRegionsToFetch(String[] regionsToFetch); /** * Updates the mappings it has if they depend on an external source. */ void refreshMapping(); }
6,700
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/AbstractAzToRegionMapper.java
package com.netflix.discovery; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import com.google.common.base.Supplier; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.netflix.discovery.DefaultEurekaClientConfig.DEFAULT_ZONE; /** * @author Nitesh Kant */ public abstract class AbstractAzToRegionMapper implements AzToRegionMapper { private static final Logger logger = LoggerFactory.getLogger(InstanceRegionChecker.class); private static final String[] EMPTY_STR_ARRAY = new String[0]; protected final EurekaClientConfig clientConfig; /** * A default for the mapping that we know of, if a remote region is configured to be fetched but does not have * any availability zone mapping, we will use these defaults. OTOH, if the remote region has any mapping defaults * will not be used. */ private final Multimap<String, String> defaultRegionVsAzMap = Multimaps.newListMultimap(new HashMap<String, Collection<String>>(), new Supplier<List<String>>() { @Override public List<String> get() { return new ArrayList<String>(); } }); private final Map<String, String> availabilityZoneVsRegion = new ConcurrentHashMap<String, String>(); private String[] regionsToFetch; protected AbstractAzToRegionMapper(EurekaClientConfig clientConfig) { this.clientConfig = clientConfig; populateDefaultAZToRegionMap(); } @Override public synchronized void setRegionsToFetch(String[] regionsToFetch) { if (null != regionsToFetch) { this.regionsToFetch = regionsToFetch; logger.info("Fetching availability zone to region mapping for regions {}", (Object) regionsToFetch); availabilityZoneVsRegion.clear(); for (String remoteRegion : regionsToFetch) { Set<String> availabilityZones = getZonesForARegion(remoteRegion); if (null == availabilityZones || (availabilityZones.size() == 1 && availabilityZones.contains(DEFAULT_ZONE)) || availabilityZones.isEmpty()) { logger.info("No availability zone information available for remote region: {}" + ". Now checking in the default mapping.", remoteRegion); if (defaultRegionVsAzMap.containsKey(remoteRegion)) { Collection<String> defaultAvailabilityZones = defaultRegionVsAzMap.get(remoteRegion); for (String defaultAvailabilityZone : defaultAvailabilityZones) { availabilityZoneVsRegion.put(defaultAvailabilityZone, remoteRegion); } } else { String msg = "No availability zone information available for remote region: " + remoteRegion + ". This is required if registry information for this region is configured to be " + "fetched."; logger.error(msg); throw new RuntimeException(msg); } } else { for (String availabilityZone : availabilityZones) { availabilityZoneVsRegion.put(availabilityZone, remoteRegion); } } } logger.info("Availability zone to region mapping for all remote regions: {}", availabilityZoneVsRegion); } else { logger.info("Regions to fetch is null. Erasing older mapping if any."); availabilityZoneVsRegion.clear(); this.regionsToFetch = EMPTY_STR_ARRAY; } } /** * Returns all the zones in the provided region. * @param region the region whose zones you want * @return a set of zones */ protected abstract Set<String> getZonesForARegion(String region); @Override public String getRegionForAvailabilityZone(String availabilityZone) { String region = availabilityZoneVsRegion.get(availabilityZone); if (null == region) { return parseAzToGetRegion(availabilityZone); } return region; } @Override public synchronized void refreshMapping() { logger.info("Refreshing availability zone to region mappings."); setRegionsToFetch(regionsToFetch); } /** * Tries to determine what region we're in, based on the provided availability zone. * @param availabilityZone the availability zone to inspect * @return the region, if available; null otherwise */ protected String parseAzToGetRegion(String availabilityZone) { // Here we see that whether the availability zone is following a pattern like <region><single letter> // If it is then we take ignore the last letter and check if the remaining part is actually a known remote // region. If yes, then we return that region, else null which means local region. if (!availabilityZone.isEmpty()) { String possibleRegion = availabilityZone.substring(0, availabilityZone.length() - 1); if (availabilityZoneVsRegion.containsValue(possibleRegion)) { return possibleRegion; } } return null; } private void populateDefaultAZToRegionMap() { defaultRegionVsAzMap.put("us-east-1", "us-east-1a"); defaultRegionVsAzMap.put("us-east-1", "us-east-1c"); defaultRegionVsAzMap.put("us-east-1", "us-east-1d"); defaultRegionVsAzMap.put("us-east-1", "us-east-1e"); defaultRegionVsAzMap.put("us-west-1", "us-west-1a"); defaultRegionVsAzMap.put("us-west-1", "us-west-1c"); defaultRegionVsAzMap.put("us-west-2", "us-west-2a"); defaultRegionVsAzMap.put("us-west-2", "us-west-2b"); defaultRegionVsAzMap.put("us-west-2", "us-west-2c"); defaultRegionVsAzMap.put("eu-west-1", "eu-west-1a"); defaultRegionVsAzMap.put("eu-west-1", "eu-west-1b"); defaultRegionVsAzMap.put("eu-west-1", "eu-west-1c"); } }
6,701
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/util/StringCache.java
package com.netflix.discovery.util; import java.lang.ref.WeakReference; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * An alternative to {@link String#intern()} with no capacity constraints. * * @author Tomasz Bak */ public class StringCache { public static final int LENGTH_LIMIT = 38; private static final StringCache INSTANCE = new StringCache(); private final ReadWriteLock lock = new ReentrantReadWriteLock(); private final Map<String, WeakReference<String>> cache = new WeakHashMap<String, WeakReference<String>>(); private final int lengthLimit; public StringCache() { this(LENGTH_LIMIT); } public StringCache(int lengthLimit) { this.lengthLimit = lengthLimit; } public String cachedValueOf(final String str) { if (str != null && (lengthLimit < 0 || str.length() <= lengthLimit)) { // Return value from cache if available lock.readLock().lock(); try { WeakReference<String> ref = cache.get(str); if (ref != null) { return ref.get(); } } finally { lock.readLock().unlock(); } // Update cache with new content lock.writeLock().lock(); try { WeakReference<String> ref = cache.get(str); if (ref != null) { return ref.get(); } cache.put(str, new WeakReference<>(str)); } finally { lock.writeLock().unlock(); } return str; } return str; } public int size() { lock.readLock().lock(); try { return cache.size(); } finally { lock.readLock().unlock(); } } public static String intern(String original) { return INSTANCE.cachedValueOf(original); } }
6,702
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/util/ServoUtil.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.util; import java.util.Collection; import com.netflix.servo.DefaultMonitorRegistry; import com.netflix.servo.monitor.Monitor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Tomasz Bak */ public final class ServoUtil { private static final Logger logger = LoggerFactory.getLogger(ServoUtil.class); private ServoUtil() { } public static <T> boolean register(Monitor<T> monitor) { try { DefaultMonitorRegistry.getInstance().register(monitor); } catch (Exception e) { logger.warn("Cannot register monitor {}", monitor.getConfig().getName()); if (logger.isDebugEnabled()) { logger.debug(e.getMessage(), e); } return false; } return true; } public static <T> void unregister(Monitor<T> monitor) { if (monitor != null) { try { DefaultMonitorRegistry.getInstance().unregister(monitor); } catch (Exception ignore) { } } } public static void unregister(Monitor... monitors) { for (Monitor monitor : monitors) { unregister(monitor); } } public static <M extends Monitor> void unregister(Collection<M> monitors) { for (M monitor : monitors) { unregister(monitor); } } }
6,703
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/util/ThresholdLevelsMetric.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.util; import com.netflix.servo.DefaultMonitorRegistry; import com.netflix.servo.monitor.LongGauge; import com.netflix.servo.monitor.MonitorConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A collection of gauges that represent different threshold levels over which measurement is mapped to. * Value 1 denotes a lowest threshold level that is reached. * For example eureka client registry data staleness defines thresholds 30s, 60s, 120s, 240s, 480s. Delay of 90s * would be mapped to gauge values {30s=0, 60s=1, 120=0, 240s=0, 480s=0, unlimited=0}. * * @author Tomasz Bak */ public class ThresholdLevelsMetric { public static final ThresholdLevelsMetric NO_OP_METRIC = new NoOpThresholdLevelMetric(); private static final Logger logger = LoggerFactory.getLogger(ThresholdLevelsMetric.class); private final long[] levels; private final LongGauge[] gauges; public ThresholdLevelsMetric(Object owner, String prefix, long[] levels) { this.levels = levels; this.gauges = new LongGauge[levels.length]; for (int i = 0; i < levels.length; i++) { String name = prefix + String.format("%05d", levels[i]); MonitorConfig config = new MonitorConfig.Builder(name) .withTag("class", owner.getClass().getName()) .build(); gauges[i] = new LongGauge(config); try { DefaultMonitorRegistry.getInstance().register(gauges[i]); } catch (Throwable e) { logger.warn("Cannot register metric {}", name, e); } } } public void update(long delayMs) { long delaySec = delayMs / 1000; long matchedIdx; if (levels[0] > delaySec) { matchedIdx = -1; } else { matchedIdx = levels.length - 1; for (int i = 0; i < levels.length - 1; i++) { if (levels[i] <= delaySec && delaySec < levels[i + 1]) { matchedIdx = i; break; } } } for (int i = 0; i < levels.length; i++) { if (i == matchedIdx) { gauges[i].set(1L); } else { gauges[i].set(0L); } } } public void shutdown() { for (LongGauge gauge : gauges) { try { DefaultMonitorRegistry.getInstance().unregister(gauge); } catch (Throwable ignore) { } } } public static class NoOpThresholdLevelMetric extends ThresholdLevelsMetric { public NoOpThresholdLevelMetric() { super(null, null, new long[]{}); } public void update(long delayMs) { } public void shutdown() { } } }
6,704
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/util/EurekaUtils.java
package com.netflix.discovery.util; import com.netflix.appinfo.AmazonInfo; import com.netflix.appinfo.InstanceInfo; /** * A collection of utility functions that is useful to simplify operations on * {@link com.netflix.appinfo.ApplicationInfoManager}, {@link com.netflix.appinfo.InstanceInfo} * and {@link com.netflix.discovery.EurekaClient} * * @author David Liu */ public final class EurekaUtils { /** * return the privateIp address of the given InstanceInfo record. The record could be for the local server * or a remote server. * * @param instanceInfo * @return the private Ip (also known as localIpv4 in ec2) */ public static String getPrivateIp(InstanceInfo instanceInfo) { String defaultPrivateIp = null; if (instanceInfo.getDataCenterInfo() instanceof AmazonInfo) { defaultPrivateIp = ((AmazonInfo) instanceInfo.getDataCenterInfo()).get(AmazonInfo.MetaDataKey.localIpv4); } if (isNullOrEmpty(defaultPrivateIp)) { // no other information, best effort defaultPrivateIp = instanceInfo.getIPAddr(); } return defaultPrivateIp; } /** * check to see if the instanceInfo record is of a server that is deployed within EC2 (best effort check based * on assumptions of underlying id). This check could be for the local server or a remote server. * * @param instanceInfo * @return true if the record contains an EC2 style "i-*" id */ public static boolean isInEc2(InstanceInfo instanceInfo) { if (instanceInfo.getDataCenterInfo() instanceof AmazonInfo) { String instanceId = ((AmazonInfo) instanceInfo.getDataCenterInfo()).getId(); if (instanceId != null && instanceId.startsWith("i-")) { return true; } } return false; } /** * check to see if the instanceInfo record is of a server that is deployed within EC2 VPC (best effort check * based on assumption of existing vpcId). This check could be for the local server or a remote server. * * @param instanceInfo * @return true if the record contains a non null, non empty AWS vpcId */ public static boolean isInVpc(InstanceInfo instanceInfo) { if (instanceInfo.getDataCenterInfo() instanceof AmazonInfo) { AmazonInfo info = (AmazonInfo) instanceInfo.getDataCenterInfo(); String vpcId = info.get(AmazonInfo.MetaDataKey.vpcId); return !isNullOrEmpty(vpcId); } return false; } private static boolean isNullOrEmpty(String str) { return str == null || str.isEmpty(); } }
6,705
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/util/StringUtil.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.util; public final class StringUtil { private StringUtil() { } /** * Join all values separating them with a comma. */ public static String join(String... values) { if (values == null || values.length == 0) { return null; } StringBuilder sb = new StringBuilder(); for (String value : values) { sb.append(',').append(value); } return sb.substring(1); } }
6,706
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/util/SystemUtil.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.util; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; /** * @author Tomasz Bak */ public final class SystemUtil { private SystemUtil() { } /** * Returns server IP address (v4 or v6) bound to local NIC. If multiple NICs are present, choose 'eth0' or 'en0' or * any one with name ending with 0. If non found, take first on the list that is not localhost. If no NIC * present (relevant only for desktop deployments), return loopback address. */ public static String getServerIPv4() { String candidateAddress = null; try { Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces(); while (nics.hasMoreElements()) { NetworkInterface nic = nics.nextElement(); Enumeration<InetAddress> inetAddresses = nic.getInetAddresses(); while (inetAddresses.hasMoreElements()) { String address = inetAddresses.nextElement().getHostAddress(); String nicName = nic.getName(); if (nicName.startsWith("eth0") || nicName.startsWith("en0")) { return address; } if (nicName.endsWith("0") || candidateAddress == null) { candidateAddress = address; } } } } catch (SocketException e) { throw new RuntimeException("Cannot resolve local network address", e); } return candidateAddress == null ? "127.0.0.1" : candidateAddress; } public static void main(String[] args) { System.out.println("Found IP=" + getServerIPv4()); } }
6,707
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/util/RateLimiter.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery.util; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; /** * Rate limiter implementation is based on token bucket algorithm. There are two parameters: * <ul> * <li> * burst size - maximum number of requests allowed into the system as a burst * </li> * <li> * average rate - expected number of requests per second (RateLimiters using MINUTES is also supported) * </li> * </ul> * * @author Tomasz Bak */ public class RateLimiter { private final long rateToMsConversion; private final AtomicInteger consumedTokens = new AtomicInteger(); private final AtomicLong lastRefillTime = new AtomicLong(0); @Deprecated public RateLimiter() { this(TimeUnit.SECONDS); } public RateLimiter(TimeUnit averageRateUnit) { switch (averageRateUnit) { case SECONDS: rateToMsConversion = 1000; break; case MINUTES: rateToMsConversion = 60 * 1000; break; default: throw new IllegalArgumentException("TimeUnit of " + averageRateUnit + " is not supported"); } } public boolean acquire(int burstSize, long averageRate) { return acquire(burstSize, averageRate, System.currentTimeMillis()); } public boolean acquire(int burstSize, long averageRate, long currentTimeMillis) { if (burstSize <= 0 || averageRate <= 0) { // Instead of throwing exception, we just let all the traffic go return true; } refillToken(burstSize, averageRate, currentTimeMillis); return consumeToken(burstSize); } private void refillToken(int burstSize, long averageRate, long currentTimeMillis) { long refillTime = lastRefillTime.get(); long timeDelta = currentTimeMillis - refillTime; long newTokens = timeDelta * averageRate / rateToMsConversion; if (newTokens > 0) { long newRefillTime = refillTime == 0 ? currentTimeMillis : refillTime + newTokens * rateToMsConversion / averageRate; if (lastRefillTime.compareAndSet(refillTime, newRefillTime)) { while (true) { int currentLevel = consumedTokens.get(); int adjustedLevel = Math.min(currentLevel, burstSize); // In case burstSize decreased int newLevel = (int) Math.max(0, adjustedLevel - newTokens); if (consumedTokens.compareAndSet(currentLevel, newLevel)) { return; } } } } } private boolean consumeToken(int burstSize) { while (true) { int currentLevel = consumedTokens.get(); if (currentLevel >= burstSize) { return false; } if (consumedTokens.compareAndSet(currentLevel, currentLevel + 1)) { return true; } } } public void reset() { consumedTokens.set(0); lastRefillTime.set(0); } }
6,708
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/util/ExceptionsMetric.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.util; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import com.netflix.servo.DefaultMonitorRegistry; import com.netflix.servo.monitor.BasicCounter; import com.netflix.servo.monitor.Counter; import com.netflix.servo.monitor.MonitorConfig; /** * Counters for exceptions. * * @author Tomasz Bak */ public class ExceptionsMetric { private final String name; private final ConcurrentHashMap<String, Counter> exceptionCounters = new ConcurrentHashMap<>(); public ExceptionsMetric(String name) { this.name = name; } public void count(Throwable ex) { getOrCreateCounter(extractName(ex)).increment(); } public void shutdown() { ServoUtil.unregister(exceptionCounters.values()); } private Counter getOrCreateCounter(String exceptionName) { Counter counter = exceptionCounters.get(exceptionName); if (counter == null) { counter = new BasicCounter(MonitorConfig.builder(name).withTag("id", exceptionName).build()); if (exceptionCounters.putIfAbsent(exceptionName, counter) == null) { DefaultMonitorRegistry.getInstance().register(counter); } else { counter = exceptionCounters.get(exceptionName); } } return counter; } private static String extractName(Throwable ex) { Throwable cause = ex; while (cause.getCause() != null) { cause = cause.getCause(); } return cause.getClass().getSimpleName(); } }
6,709
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/util/EurekaEntityTransformers.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.util; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.ActionType; /** * @author Tomasz Bak */ public class EurekaEntityTransformers { /** * Interface for Eureka entity transforming operators. */ public interface Transformer<T> { T apply(T value); } public static <T> Transformer<T> identity() { return (Transformer<T>) IDENTITY_TRANSFORMER; } public static Transformer<InstanceInfo> actionTypeSetter(ActionType actionType) { switch (actionType) { case ADDED: return ADD_ACTION_SETTER_TRANSFORMER; case MODIFIED: return MODIFIED_ACTION_SETTER_TRANSFORMER; case DELETED: return DELETED_ACTION_SETTER_TRANSFORMER; } throw new IllegalStateException("Unhandled ActionType value " + actionType); } private static final Transformer<Object> IDENTITY_TRANSFORMER = new Transformer<Object>() { @Override public Object apply(Object value) { return value; } }; private static final Transformer<InstanceInfo> ADD_ACTION_SETTER_TRANSFORMER = new Transformer<InstanceInfo>() { @Override public InstanceInfo apply(InstanceInfo instance) { InstanceInfo copy = new InstanceInfo(instance); copy.setActionType(ActionType.ADDED); return copy; } }; private static final Transformer<InstanceInfo> MODIFIED_ACTION_SETTER_TRANSFORMER = new Transformer<InstanceInfo>() { @Override public InstanceInfo apply(InstanceInfo instance) { InstanceInfo copy = new InstanceInfo(instance); copy.setActionType(ActionType.MODIFIED); return copy; } }; private static final Transformer<InstanceInfo> DELETED_ACTION_SETTER_TRANSFORMER = new Transformer<InstanceInfo>() { @Override public InstanceInfo apply(InstanceInfo instance) { InstanceInfo copy = new InstanceInfo(instance); copy.setActionType(ActionType.DELETED); return copy; } }; }
6,710
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/util/EurekaEntityFunctions.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.util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.ActionType; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.util.EurekaEntityTransformers.Transformer; /** * Collection of functions operating on {@link Applications} and {@link Application} data * structures. The functions are organized into groups with common prefix name: * <ul> * <li>select, take - queries over Eureka entity objects</li> * <li>to - Eureka entity object transformers</li> * <li>copy - copy Eureka entities, with aggregated {@link InstanceInfo} objects copied by reference</li> * <li>deepCopy - copy Eureka entities, with aggregated {@link InstanceInfo} objects copied by value</li> * <li>merge - merge two identical data structures</li> * <li>count - statistical functions</li> * <li>comparator - comparators for the domain objects</li> * </ul> * * @author Tomasz Bak */ public final class EurekaEntityFunctions { private EurekaEntityFunctions() { } public static Set<String> selectApplicationNames(Applications applications) { Set<String> result = new HashSet<>(); for (Application app : applications.getRegisteredApplications()) { result.add(app.getName()); } return result; } public static Map<String, InstanceInfo> selectInstancesMappedById(Application application) { Map<String, InstanceInfo> result = new HashMap<>(); for (InstanceInfo instance : application.getInstances()) { result.put(instance.getId(), instance); } return result; } public static InstanceInfo selectInstance(Applications applications, String id) { for (Application application : applications.getRegisteredApplications()) { for (InstanceInfo instance : application.getInstances()) { if (instance.getId().equals(id)) { return instance; } } } return null; } public static InstanceInfo selectInstance(Applications applications, String appName, String id) { Application application = applications.getRegisteredApplications(appName); if (application != null) { for (InstanceInfo instance : application.getInstances()) { if (instance.getId().equals(id)) { return instance; } } } return null; } public static InstanceInfo takeFirst(Applications applications) { for (Application application : applications.getRegisteredApplications()) { if (!application.getInstances().isEmpty()) { return application.getInstances().get(0); } } return null; } public static Collection<InstanceInfo> selectAll(Applications applications) { List<InstanceInfo> all = new ArrayList<>(); for (Application a : applications.getRegisteredApplications()) { all.addAll(a.getInstances()); } return all; } public static Map<String, Application> toApplicationMap(List<InstanceInfo> instances) { Map<String, Application> applicationMap = new HashMap<String, Application>(); for (InstanceInfo instance : instances) { String appName = instance.getAppName(); Application application = applicationMap.get(appName); if (application == null) { applicationMap.put(appName, application = new Application(appName)); } application.addInstance(instance); } return applicationMap; } public static Applications toApplications(Map<String, Application> applicationMap) { Applications applications = new Applications(); for (Application application : applicationMap.values()) { applications.addApplication(application); } return updateMeta(applications); } public static Applications toApplications(InstanceInfo... instances) { return toApplications(Arrays.asList(instances)); } public static Applications toApplications(List<InstanceInfo> instances) { Applications result = new Applications(); for (InstanceInfo instance : instances) { Application app = result.getRegisteredApplications(instance.getAppName()); if (app == null) { app = new Application(instance.getAppName()); result.addApplication(app); } app.addInstance(instance); } return updateMeta(result); } public static Applications copyApplications(Applications source) { Applications result = new Applications(); copyApplications(source, result); return updateMeta(result); } public static void copyApplications(Applications source, Applications result) { if (source != null) { for (Application app : source.getRegisteredApplications()) { result.addApplication(new Application(app.getName(), app.getInstances())); } } } public static Application copyApplication(Application application) { Application copy = new Application(application.getName()); for (InstanceInfo instance : application.getInstances()) { copy.addInstance(instance); } return copy; } public static void copyApplication(Application source, Application result) { if (source != null) { for (InstanceInfo instance : source.getInstances()) { result.addInstance(instance); } } } public static void copyInstances(Collection<InstanceInfo> instances, Applications result) { if (instances != null) { for (InstanceInfo instance : instances) { Application app = result.getRegisteredApplications(instance.getAppName()); if (app == null) { app = new Application(instance.getAppName()); result.addApplication(app); } app.addInstance(instance); } } } public static Collection<InstanceInfo> copyInstances(Collection<InstanceInfo> instances, ActionType actionType) { List<InstanceInfo> result = new ArrayList<>(); for (InstanceInfo instance : instances) { result.add(copyInstance(instance, actionType)); } return result; } public static InstanceInfo copyInstance(InstanceInfo original, ActionType actionType) { InstanceInfo copy = new InstanceInfo(original); copy.setActionType(actionType); return copy; } public static void deepCopyApplication(Application source, Application result, Transformer<InstanceInfo> transformer) { for (InstanceInfo instance : source.getInstances()) { InstanceInfo copy = transformer.apply(instance); if (copy == instance) { copy = new InstanceInfo(instance); } result.addInstance(copy); } } public static Application deepCopyApplication(Application source) { Application result = new Application(source.getName()); deepCopyApplication(source, result, EurekaEntityTransformers.<InstanceInfo>identity()); return result; } public static Applications deepCopyApplications(Applications source) { Applications result = new Applications(); for (Application application : source.getRegisteredApplications()) { result.addApplication(deepCopyApplication(application)); } return updateMeta(result); } public static Applications mergeApplications(Applications first, Applications second) { Set<String> firstNames = selectApplicationNames(first); Set<String> secondNames = selectApplicationNames(second); Set<String> allNames = new HashSet<>(firstNames); allNames.addAll(secondNames); Applications merged = new Applications(); for (String appName : allNames) { if (firstNames.contains(appName)) { if (secondNames.contains(appName)) { merged.addApplication(mergeApplication(first.getRegisteredApplications(appName), second.getRegisteredApplications(appName))); } else { merged.addApplication(copyApplication(first.getRegisteredApplications(appName))); } } else { merged.addApplication(copyApplication(second.getRegisteredApplications(appName))); } } return updateMeta(merged); } public static Application mergeApplication(Application first, Application second) { if (!first.getName().equals(second.getName())) { throw new IllegalArgumentException("Cannot merge applications with different names"); } Application merged = copyApplication(first); for (InstanceInfo instance : second.getInstances()) { switch (instance.getActionType()) { case ADDED: case MODIFIED: merged.addInstance(instance); break; case DELETED: merged.removeInstance(instance); } } return merged; } public static Applications updateMeta(Applications applications) { applications.setVersion(1L); applications.setAppsHashCode(applications.getReconcileHashCode()); return applications; } public static int countInstances(Applications applications) { int count = 0; for (Application application : applications.getRegisteredApplications()) { count += application.getInstances().size(); } return count; } public static Comparator<InstanceInfo> comparatorByAppNameAndId() { return INSTANCE_APP_ID_COMPARATOR; } private static class InstanceAppIdComparator implements Comparator<InstanceInfo> { @Override public int compare(InstanceInfo o1, InstanceInfo o2) { int ac = compareStrings(o1.getAppName(), o2.getAppName()); if (ac != 0) { return ac; } return compareStrings(o1.getId(), o2.getId()); } private int compareStrings(String s1, String s2) { if (s1 == null) { if (s2 != null) { return -1; } } if (s2 == null) { return 1; } return s1.compareTo(s2); } } private static final Comparator<InstanceInfo> INSTANCE_APP_ID_COMPARATOR = new InstanceAppIdComparator(); }
6,711
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/util/DiscoveryBuildInfo.java
package com.netflix.discovery.util; import java.io.InputStream; import java.net.URL; import java.util.jar.Attributes.Name; import java.util.jar.Manifest; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Tomasz Bak */ public final class DiscoveryBuildInfo { private static final Logger logger = LoggerFactory.getLogger(DiscoveryBuildInfo.class); private static final DiscoveryBuildInfo INSTANCE = new DiscoveryBuildInfo(DiscoveryBuildInfo.class); private final Manifest manifest; /* Visible for testing. */ DiscoveryBuildInfo(Class<?> clazz) { Manifest resolvedManifest = null; try { String jarUrl = resolveJarUrl(clazz); if (jarUrl != null) { resolvedManifest = loadManifest(jarUrl); } } catch (Throwable e) { logger.warn("Cannot load eureka-client manifest file; no build meta data are available", e); } this.manifest = resolvedManifest; } String getBuildVersion() { return getManifestAttribute("Implementation-Version", "<version_unknown>"); } String getManifestAttribute(String name, String defaultValue) { if (manifest == null) { return defaultValue; } Name attrName = new Name(name); Object value = manifest.getMainAttributes().get(attrName); return value == null ? defaultValue : value.toString(); } public static String buildVersion() { return INSTANCE.getBuildVersion(); } private static Manifest loadManifest(String jarUrl) throws Exception { InputStream is = new URL(jarUrl + "!/META-INF/MANIFEST.MF").openStream(); try { return new Manifest(is); } finally { is.close(); } } private static String resolveJarUrl(Class<?> clazz) { URL location = clazz.getResource('/' + clazz.getName().replace('.', '/') + ".class"); if (location != null) { Matcher matcher = Pattern.compile("(jar:file.*-[\\d.]+(-rc[\\d]+|-SNAPSHOT)?.jar)!.*$").matcher(location.toString()); if (matcher.matches()) { return matcher.group(1); } } return null; } }
6,712
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/util/DeserializerStringCache.java
package com.netflix.discovery.util; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.PrimitiveIterator.OfInt; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.function.Supplier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.ObjectReader; /** * A non-locking alternative to {@link String#intern()} and {@link StringCache} * that works with Jackson's DeserializationContext. Definitely NOT thread-safe, * intended to avoid the costs associated with thread synchronization and * short-lived heap allocations (e.g., Strings) * */ public class DeserializerStringCache implements Function<String, String> { public enum CacheScope { // Strings in this scope are freed on deserialization of each // Application element APPLICATION_SCOPE, // Strings in this scope are freed when overall deserialization is // completed GLOBAL_SCOPE } private static final Logger logger = LoggerFactory.getLogger(DeserializerStringCache.class); private static final boolean debugLogEnabled = logger.isDebugEnabled(); private static final String ATTR_STRING_CACHE = "deserInternCache"; private static final int LENGTH_LIMIT = 256; private static final int LRU_LIMIT = 1024 * 40; private final Map<CharBuffer, String> globalCache; private final Map<CharBuffer, String> applicationCache; private final int lengthLimit = LENGTH_LIMIT; /** * adds a new DeserializerStringCache to the passed-in ObjectReader * * @param reader * @return a wrapped ObjectReader with the string cache attribute */ public static ObjectReader init(ObjectReader reader) { return reader.withAttribute(ATTR_STRING_CACHE, new DeserializerStringCache( new HashMap<CharBuffer, String>(2048), new LinkedHashMap<CharBuffer, String>(4096, 0.75f, true) { @Override protected boolean removeEldestEntry(Entry<CharBuffer, String> eldest) { return size() > LRU_LIMIT; } })); } /** * adds an existing DeserializerStringCache from the DeserializationContext * to an ObjectReader * * @param reader * a new ObjectReader * @param context * an existing DeserializationContext containing a * DeserializerStringCache * @return a wrapped ObjectReader with the string cache attribute */ public static ObjectReader init(ObjectReader reader, DeserializationContext context) { return withCache(context, cache -> { if (cache == null) throw new IllegalStateException(); return reader.withAttribute(ATTR_STRING_CACHE, cache); }); } /** * extracts a DeserializerStringCache from the DeserializationContext * * @param context * an existing DeserializationContext containing a * DeserializerStringCache * @return a wrapped ObjectReader with the string cache attribute */ public static DeserializerStringCache from(DeserializationContext context) { return withCache(context, cache -> { if (cache == null) { cache = new DeserializerStringCache(new HashMap<CharBuffer, String>(), new HashMap<CharBuffer, String>()); } return cache; }); } /** * clears app-scoped cache entries from the specified ObjectReader * * @param reader */ public static void clear(ObjectReader reader) { clear(reader, CacheScope.APPLICATION_SCOPE); } /** * clears cache entries in the given scope from the specified ObjectReader. * Always clears app-scoped entries. * * @param reader * @param scope */ public static void clear(ObjectReader reader, final CacheScope scope) { withCache(reader, cache -> { if (scope == CacheScope.GLOBAL_SCOPE) { if (debugLogEnabled) logger.debug("clearing global-level cache with size {}", cache.globalCache.size()); cache.globalCache.clear(); } if (debugLogEnabled) logger.debug("clearing app-level serialization cache with size {}", cache.applicationCache.size()); cache.applicationCache.clear(); return null; }); } /** * clears app-scoped cache entries from the specified DeserializationContext * * @param context */ public static void clear(DeserializationContext context) { clear(context, CacheScope.APPLICATION_SCOPE); } /** * clears cache entries in the given scope from the specified * DeserializationContext. Always clears app-scoped entries. * * @param context * @param scope */ public static void clear(DeserializationContext context, CacheScope scope) { withCache(context, cache -> { if (scope == CacheScope.GLOBAL_SCOPE) { if (debugLogEnabled) logger.debug("clearing global-level serialization cache with size {}", cache.globalCache.size()); cache.globalCache.clear(); } if (debugLogEnabled) logger.debug("clearing app-level serialization cache with size {}", cache.applicationCache.size()); cache.applicationCache.clear(); return null; }); } private static <T> T withCache(DeserializationContext context, Function<DeserializerStringCache, T> consumer) { DeserializerStringCache cache = (DeserializerStringCache) context.getAttribute(ATTR_STRING_CACHE); return consumer.apply(cache); } private static <T> T withCache(ObjectReader reader, Function<DeserializerStringCache, T> consumer) { DeserializerStringCache cache = (DeserializerStringCache) reader.getAttributes() .getAttribute(ATTR_STRING_CACHE); return consumer.apply(cache); } private DeserializerStringCache(Map<CharBuffer, String> globalCache, Map<CharBuffer, String> applicationCache) { this.globalCache = globalCache; this.applicationCache = applicationCache; } public ObjectReader initReader(ObjectReader reader) { return reader.withAttribute(ATTR_STRING_CACHE, this); } /** * returns a String read from the JsonParser argument's current position. * The returned value may be interned at the app scope to reduce heap * consumption * * @param jp * @return a possibly interned String * @throws IOException */ public String apply(final JsonParser jp) throws IOException { return apply(jp, CacheScope.APPLICATION_SCOPE, null); } public String apply(final JsonParser jp, CacheScope cacheScope) throws IOException { return apply(jp, cacheScope, null); } /** * returns a String read from the JsonParser argument's current position. * The returned value may be interned at the given cacheScope to reduce heap * consumption * * @param jp * @param cacheScope * @return a possibly interned String * @throws IOException */ public String apply(final JsonParser jp, CacheScope cacheScope, Supplier<String> source) throws IOException { return apply(CharBuffer.wrap(jp, source), cacheScope); } /** * returns a String that may be interned at app-scope to reduce heap * consumption * * @param charValue * @return a possibly interned String */ public String apply(final CharBuffer charValue) { return apply(charValue, CacheScope.APPLICATION_SCOPE); } /** * returns a object of type T that may be interned at the specified scope to * reduce heap consumption * * @param charValue * @param cacheScope * @param trabsform * @return a possibly interned instance of T */ public String apply(CharBuffer charValue, CacheScope cacheScope) { int keyLength = charValue.length(); if ((lengthLimit < 0 || keyLength <= lengthLimit)) { Map<CharBuffer, String> cache = (cacheScope == CacheScope.GLOBAL_SCOPE) ? globalCache : applicationCache; String value = cache.get(charValue); if (value == null) { value = charValue.consume((k, v) -> { cache.put(k, v); }); } else { // System.out.println("cache hit"); } return value; } return charValue.toString(); } /** * returns a String that may be interned at the app-scope to reduce heap * consumption * * @param stringValue * @return a possibly interned String */ @Override public String apply(final String stringValue) { return apply(stringValue, CacheScope.APPLICATION_SCOPE); } /** * returns a String that may be interned at the given scope to reduce heap * consumption * * @param stringValue * @param cacheScope * @return a possibly interned String */ public String apply(final String stringValue, CacheScope cacheScope) { if (stringValue != null && (lengthLimit < 0 || stringValue.length() <= lengthLimit)) { return (String) (cacheScope == CacheScope.GLOBAL_SCOPE ? globalCache : applicationCache) .computeIfAbsent(CharBuffer.wrap(stringValue), s -> { logger.trace(" (string) writing new interned value {} into {} cache scope", stringValue, cacheScope); return stringValue; }); } return stringValue; } public int size() { return globalCache.size() + applicationCache.size(); } private interface CharBuffer { static final int DEFAULT_VARIANT = -1; public static CharBuffer wrap(JsonParser source, Supplier<String> stringSource) throws IOException { return new ArrayCharBuffer(source, stringSource); } public static CharBuffer wrap(JsonParser source) throws IOException { return new ArrayCharBuffer(source); } public static CharBuffer wrap(String source) { return new StringCharBuffer(source); } String consume(BiConsumer<CharBuffer, String> valueConsumer); int length(); int variant(); OfInt chars(); static class ArrayCharBuffer implements CharBuffer { private final char[] source; private final int offset; private final int length; private final Supplier<String> valueTransform; private final int variant; private final int hash; ArrayCharBuffer(JsonParser source) throws IOException { this(source, null); } ArrayCharBuffer(JsonParser source, Supplier<String> valueTransform) throws IOException { this.source = source.getTextCharacters(); this.offset = source.getTextOffset(); this.length = source.getTextLength(); this.valueTransform = valueTransform; this.variant = valueTransform == null ? DEFAULT_VARIANT : System.identityHashCode(valueTransform.getClass()); this.hash = 31 * arrayHash(this.source, offset, length) + variant; } @Override public int length() { return length; } @Override public int variant() { return variant; } @Override public int hashCode() { return hash; } @Override public boolean equals(Object other) { if (other instanceof CharBuffer) { CharBuffer otherBuffer = (CharBuffer) other; if (otherBuffer.length() == length) { if (otherBuffer.variant() == variant) { OfInt otherText = otherBuffer.chars(); for (int i = offset; i < length; i++) { if (source[i] != otherText.nextInt()) { return false; } } return true; } } } return false; } @Override public OfInt chars() { return new OfInt() { int index = offset; int limit = index + length; @Override public boolean hasNext() { return index < limit; } @Override public int nextInt() { return source[index++]; } }; } @Override public String toString() { return valueTransform == null ? new String(this.source, offset, length) : valueTransform.get(); } @Override public String consume(BiConsumer<CharBuffer, String> valueConsumer) { String key = new String(this.source, offset, length); String value = valueTransform == null ? key : valueTransform.get(); valueConsumer.accept(new StringCharBuffer(key, variant), value); return value; } private static int arrayHash(char[] a, int offset, int length) { if (a == null) return 0; int result = 0; int limit = offset + length; for (int i = offset; i < limit; i++) { result = 31 * result + a[i]; } return result; } } static class StringCharBuffer implements CharBuffer { private final String source; private final int variant; private final int hashCode; StringCharBuffer(String source) { this(source, -1); } StringCharBuffer(String source, int variant) { this.source = source; this.variant = variant; this.hashCode = 31 * source.hashCode() + variant; } @Override public int hashCode() { return hashCode; } @Override public int variant() { return variant; } @Override public boolean equals(Object other) { if (other instanceof CharBuffer) { CharBuffer otherBuffer = (CharBuffer) other; if (otherBuffer.variant() == variant) { int length = source.length(); if (otherBuffer.length() == length) { OfInt otherText = otherBuffer.chars(); for (int i = 0; i < length; i++) { if (source.charAt(i) != otherText.nextInt()) { return false; } } return true; } } } return false; } @Override public int length() { return source.length(); } @Override public String toString() { return source; } @Override public OfInt chars() { return new OfInt() { int index; @Override public boolean hasNext() { return index < source.length(); } @Override public int nextInt() { return source.charAt(index++); } }; } @Override public String consume(BiConsumer<CharBuffer, String> valueConsumer) { valueConsumer.accept(this, source); return source; } } } }
6,713
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/util/EurekaEntityComparators.java
package com.netflix.discovery.util; import java.util.List; import java.util.Map; import com.netflix.appinfo.AmazonInfo; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.LeaseInfo; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; /** * For test use. * * @author Tomasz Bak */ public final class EurekaEntityComparators { private EurekaEntityComparators() { } public static boolean equal(DataCenterInfo first, DataCenterInfo second) { if (first == second) { return true; } if (first == null || first == null && second != null) { return false; } if (first.getClass() != second.getClass()) { return false; } if (first instanceof AmazonInfo) { return equal((AmazonInfo) first, (AmazonInfo) second); } return first.getName() == second.getName(); } public static boolean equal(AmazonInfo first, AmazonInfo second) { if (first == second) { return true; } if (first == null || first == null && second != null) { return false; } return equal(first.getMetadata(), second.getMetadata()); } public static boolean subsetOf(DataCenterInfo first, DataCenterInfo second) { if (first == second) { return true; } if (first == null || first == null && second != null) { return false; } if (first.getClass() != second.getClass()) { return false; } if (first instanceof AmazonInfo) { return subsetOf((AmazonInfo) first, (AmazonInfo) second); } return first.getName() == second.getName(); } public static boolean subsetOf(AmazonInfo first, AmazonInfo second) { if (first == second) { return true; } if (first == null || first == null && second != null) { return false; } return first.getMetadata().entrySet().containsAll(second.getMetadata().entrySet()); } public static boolean equal(LeaseInfo first, LeaseInfo second) { if (first == second) { return true; } if (first == null || first == null && second != null) { return false; } if (first.getDurationInSecs() != second.getDurationInSecs()) { return false; } if (first.getEvictionTimestamp() != second.getEvictionTimestamp()) { return false; } if (first.getRegistrationTimestamp() != second.getRegistrationTimestamp()) { return false; } if (first.getRenewalIntervalInSecs() != second.getRenewalIntervalInSecs()) { return false; } if (first.getRenewalTimestamp() != second.getRenewalTimestamp()) { return false; } if (first.getServiceUpTimestamp() != second.getServiceUpTimestamp()) { return false; } return true; } public static boolean equal(InstanceInfo first, InstanceInfo second) { return equal(first, second, new ResolvedIdEqualFunc()); } public static boolean equal(InstanceInfo first, InstanceInfo second, EqualFunc<InstanceInfo> idEqualFunc) { if (first == second) { return true; } if (first == null || first == null && second != null) { return false; } if (first.getCountryId() != second.getCountryId()) { return false; } if (first.getPort() != second.getPort()) { return false; } if (first.getSecurePort() != second.getSecurePort()) { return false; } if (first.getActionType() != second.getActionType()) { return false; } if (first.getAppGroupName() != null ? !first.getAppGroupName().equals(second.getAppGroupName()) : second.getAppGroupName() != null) { return false; } if (!idEqualFunc.equals(first, second)) { return false; } if (first.getSID() != null ? !first.getSID().equals(second.getSID()) : second.getSID() != null) { return false; } if (first.getAppName() != null ? !first.getAppName().equals(second.getAppName()) : second.getAppName() != null) { return false; } if (first.getASGName() != null ? !first.getASGName().equals(second.getASGName()) : second.getASGName() != null) { return false; } if (!equal(first.getDataCenterInfo(), second.getDataCenterInfo())) { return false; } if (first.getHealthCheckUrls() != null ? !first.getHealthCheckUrls().equals(second.getHealthCheckUrls()) : second.getHealthCheckUrls() != null) { return false; } if (first.getHomePageUrl() != null ? !first.getHomePageUrl().equals(second.getHomePageUrl()) : second.getHomePageUrl() != null) { return false; } if (first.getHostName() != null ? !first.getHostName().equals(second.getHostName()) : second.getHostName() != null) { return false; } if (first.getIPAddr() != null ? !first.getIPAddr().equals(second.getIPAddr()) : second.getIPAddr() != null) { return false; } if (!equal(first.getLeaseInfo(), second.getLeaseInfo())) { return false; } if (!equal(first.getMetadata(), second.getMetadata())) { return false; } if (first.getHealthCheckUrls() != null ? !first.getHealthCheckUrls().equals(second.getHealthCheckUrls()) : second.getHealthCheckUrls() != null) { return false; } if (first.getVIPAddress() != null ? !first.getVIPAddress().equals(second.getVIPAddress()) : second.getVIPAddress() != null) { return false; } if (first.getSecureVipAddress() != null ? !first.getSecureVipAddress().equals(second.getSecureVipAddress()) : second.getSecureVipAddress() != null) { return false; } if (first.getStatus() != null ? !first.getStatus().equals(second.getStatus()) : second.getStatus() != null) { return false; } if (first.getOverriddenStatus() != null ? !first.getOverriddenStatus().equals(second.getOverriddenStatus()) : second.getOverriddenStatus() != null) { return false; } if (first.getStatusPageUrl() != null ? !first.getStatusPageUrl().equals(second.getStatusPageUrl()) : second.getStatusPageUrl() != null) { return false; } if (first.getLastDirtyTimestamp() != null ? !first.getLastDirtyTimestamp().equals(second.getLastDirtyTimestamp()) : second.getLastDirtyTimestamp() != null) { return false; } if (first.getLastUpdatedTimestamp()!= second.getLastUpdatedTimestamp()) { return false; } if (first.isCoordinatingDiscoveryServer() != null ? !first.isCoordinatingDiscoveryServer().equals(second.isCoordinatingDiscoveryServer()) : second.isCoordinatingDiscoveryServer() != null) { return false; } return true; } private static boolean idEqual(InstanceInfo first, InstanceInfo second) { return first.getId().equals(second.getId()); } public static boolean equalMini(InstanceInfo first, InstanceInfo second) { if (first == second) { return true; } if (first == null || first == null && second != null) { return false; } if (first.getPort() != second.getPort()) { return false; } if (first.getSecurePort() != second.getSecurePort()) { return false; } if (first.getActionType() != second.getActionType()) { return false; } if (first.getInstanceId() != null ? !first.getInstanceId().equals(second.getInstanceId()) : second.getInstanceId() != null) { return false; } if (first.getAppName() != null ? !first.getAppName().equals(second.getAppName()) : second.getAppName() != null) { return false; } if (first.getASGName() != null ? !first.getASGName().equals(second.getASGName()) : second.getASGName() != null) { return false; } if (!subsetOf(first.getDataCenterInfo(), second.getDataCenterInfo())) { return false; } if (first.getHostName() != null ? !first.getHostName().equals(second.getHostName()) : second.getHostName() != null) { return false; } if (first.getIPAddr() != null ? !first.getIPAddr().equals(second.getIPAddr()) : second.getIPAddr() != null) { return false; } if (first.getVIPAddress() != null ? !first.getVIPAddress().equals(second.getVIPAddress()) : second.getVIPAddress() != null) { return false; } if (first.getSecureVipAddress() != null ? !first.getSecureVipAddress().equals(second.getSecureVipAddress()) : second.getSecureVipAddress() != null) { return false; } if (first.getStatus() != null ? !first.getStatus().equals(second.getStatus()) : second.getStatus() != null) { return false; } if (first.getLastUpdatedTimestamp()!= second.getLastUpdatedTimestamp()) { return false; } return true; } public static boolean equal(Application first, Application second) { if (first == second) { return true; } if (first == null || first == null && second != null) { return false; } if (first.getName() != null ? !first.getName().equals(second.getName()) : second.getName() != null) { return false; } List<InstanceInfo> firstInstanceInfos = first.getInstances(); List<InstanceInfo> secondInstanceInfos = second.getInstances(); if (firstInstanceInfos == null && secondInstanceInfos == null) { return true; } if (firstInstanceInfos == null || secondInstanceInfos == null || firstInstanceInfos.size() != secondInstanceInfos.size()) { return false; } for (InstanceInfo firstInstanceInfo : firstInstanceInfos) { InstanceInfo secondInstanceInfo = second.getByInstanceId(firstInstanceInfo.getId()); if (!equal(firstInstanceInfo, secondInstanceInfo)) { return false; } } return true; } public static boolean equal(Applications first, Applications second) { if (first == second) { return true; } if (first == null || first == null && second != null) { return false; } List<Application> firstApps = first.getRegisteredApplications(); List<Application> secondApps = second.getRegisteredApplications(); if (firstApps == null && secondApps == null) { return true; } if (firstApps == null || secondApps == null || firstApps.size() != secondApps.size()) { return false; } for (Application firstApp : firstApps) { Application secondApp = second.getRegisteredApplications(firstApp.getName()); if (!equal(firstApp, secondApp)) { return false; } } return true; } private static boolean equal(Map<String, String> first, Map<String, String> second) { if (first == second) { return true; } if (first == null || first == null && second != null || first.size() != second.size()) { return false; } for (Map.Entry<String, String> entry : first.entrySet()) { if (!second.containsKey(entry.getKey())) { return false; } String firstValue = entry.getValue(); String secondValue = second.get(entry.getKey()); if (!firstValue.equals(secondValue)) { return false; } } return true; } public interface EqualFunc<T> { boolean equals(T first, T second); } public static class RawIdEqualFunc implements EqualFunc<InstanceInfo> { @Override public boolean equals(InstanceInfo first, InstanceInfo second) { return first.getInstanceId() != null ? first.getInstanceId().equals(second.getInstanceId()) : second.getInstanceId() == null; } } public static class RawIdHandleEmptyEqualFunc implements EqualFunc<InstanceInfo> { @Override public boolean equals(InstanceInfo first, InstanceInfo second) { String firstId = (first.getInstanceId() == null || first.getInstanceId().isEmpty()) ? null : first.getInstanceId(); String secondId = (second.getInstanceId() == null || second.getInstanceId().isEmpty()) ? null : second.getInstanceId(); return firstId != null ? firstId.equals(secondId) : secondId == null; } } public static class ResolvedIdEqualFunc implements EqualFunc<InstanceInfo> { @Override public boolean equals(InstanceInfo first, InstanceInfo second) { return first.getId() != null ? first.getId().equals(second.getId()) : second.getId() == null; } } }
6,714
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/providers/DefaultEurekaClientConfigProvider.java
package com.netflix.discovery.providers; import javax.inject.Provider; import com.google.inject.Inject; import com.netflix.discovery.DefaultEurekaClientConfig; import com.netflix.discovery.DiscoveryManager; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.EurekaNamespace; /** * This provider is necessary because the namespace is optional. * @author elandau */ public class DefaultEurekaClientConfigProvider implements Provider<EurekaClientConfig> { @Inject(optional = true) @EurekaNamespace private String namespace; private DefaultEurekaClientConfig config; @Override public synchronized EurekaClientConfig get() { if (config == null) { config = (namespace == null) ? new DefaultEurekaClientConfig() : new DefaultEurekaClientConfig(namespace); // TODO: Remove this when DiscoveryManager is finally no longer used DiscoveryManager.getInstance().setEurekaClientConfig(config); } return config; } }
6,715
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/guice/EurekaModule.java
package com.netflix.discovery.guice; import com.google.inject.AbstractModule; 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.CloudInstanceConfigProvider; import com.netflix.appinfo.providers.EurekaConfigBasedInstanceInfoProvider; import com.netflix.discovery.DiscoveryClient; import com.netflix.discovery.AbstractDiscoveryClientOptionalArgs; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.providers.DefaultEurekaClientConfigProvider; import com.netflix.discovery.shared.resolver.EndpointRandomizer; import com.netflix.discovery.shared.resolver.ResolverUtils; import com.netflix.discovery.shared.transport.jersey.Jersey1DiscoveryClientOptionalArgs; /** * @author David Liu */ public final class EurekaModule extends AbstractModule { @Override protected void configure() { // need to eagerly initialize bind(ApplicationInfoManager.class).asEagerSingleton(); // // override these in additional modules if necessary with Modules.override() // bind(EurekaInstanceConfig.class).toProvider(CloudInstanceConfigProvider.class).in(Scopes.SINGLETON); bind(EurekaClientConfig.class).toProvider(DefaultEurekaClientConfigProvider.class).in(Scopes.SINGLETON); // this is the self instanceInfo used for registration purposes bind(InstanceInfo.class).toProvider(EurekaConfigBasedInstanceInfoProvider.class).in(Scopes.SINGLETON); bind(EurekaClient.class).to(DiscoveryClient.class).in(Scopes.SINGLETON); bind(EndpointRandomizer.class).toInstance(ResolverUtils::randomize); // Default to the jersey1 discovery client optional args bind(AbstractDiscoveryClientOptionalArgs.class).to(Jersey1DiscoveryClientOptionalArgs.class).in(Scopes.SINGLETON); } @Override public boolean equals(Object obj) { return obj != null && getClass().equals(obj.getClass()); } @Override public int hashCode() { return getClass().hashCode(); } }
6,716
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/internal
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/internal/util/AmazonInfoUtils.java
package com.netflix.discovery.internal.util; import com.netflix.appinfo.AmazonInfo.MetaDataKey; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; /** * This is an INTERNAL class not for public use. * * @author David Liu */ public final class AmazonInfoUtils { public static String readEc2MetadataUrl(MetaDataKey metaDataKey, URL url, int connectionTimeoutMs, int readTimeoutMs) throws IOException { HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setConnectTimeout(connectionTimeoutMs); uc.setReadTimeout(readTimeoutMs); uc.setRequestProperty("User-Agent", "eureka-java-client"); if (uc.getResponseCode() != HttpURLConnection.HTTP_OK) { // need to read the error for clean connection close BufferedReader br = new BufferedReader(new InputStreamReader(uc.getErrorStream())); try { while (br.readLine() != null) { // do nothing but keep reading the line } } finally { br.close(); } } else { return metaDataKey.read(uc.getInputStream()); } return null; } }
6,717
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/internal
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/internal/util/Archaius1Utils.java
package com.netflix.discovery.internal.util; import com.netflix.config.ConfigurationManager; import com.netflix.config.DynamicPropertyFactory; import com.netflix.config.DynamicStringProperty; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; /** * This is an INTERNAL class not for public use. * * @author David Liu */ public final class Archaius1Utils { private static final Logger logger = LoggerFactory.getLogger(Archaius1Utils.class); private static final String ARCHAIUS_DEPLOYMENT_ENVIRONMENT = "archaius.deployment.environment"; private static final String EUREKA_ENVIRONMENT = "eureka.environment"; public static DynamicPropertyFactory initConfig(String configName) { DynamicPropertyFactory configInstance = DynamicPropertyFactory.getInstance(); DynamicStringProperty EUREKA_PROPS_FILE = configInstance.getStringProperty("eureka.client.props", configName); String env = ConfigurationManager.getConfigInstance().getString(EUREKA_ENVIRONMENT, "test"); ConfigurationManager.getConfigInstance().setProperty(ARCHAIUS_DEPLOYMENT_ENVIRONMENT, env); String eurekaPropsFile = EUREKA_PROPS_FILE.get(); try { ConfigurationManager.loadCascadedPropertiesFromResources(eurekaPropsFile); } catch (IOException e) { logger.warn( "Cannot find the properties specified : {}. This may be okay if there are other environment " + "specific properties or the configuration is installed with a different mechanism.", eurekaPropsFile); } return configInstance; } }
6,718
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/provider/DiscoveryJerseyProvider.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.provider; import javax.ws.rs.Consumes; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.Map; import com.netflix.discovery.converters.wrappers.CodecWrappers; import com.netflix.discovery.converters.wrappers.CodecWrappers.LegacyJacksonJson; import com.netflix.discovery.converters.wrappers.DecoderWrapper; import com.netflix.discovery.converters.wrappers.EncoderWrapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A custom provider implementation for Jersey that dispatches to the * implementation that serializes/deserializes objects sent to and from eureka * server. * * @author Karthik Ranganathan */ @Provider @Produces({"application/json", "application/xml"}) @Consumes("*/*") public class DiscoveryJerseyProvider implements MessageBodyWriter<Object>, MessageBodyReader<Object> { private static final Logger LOGGER = LoggerFactory.getLogger(DiscoveryJerseyProvider.class); private final EncoderWrapper jsonEncoder; private final DecoderWrapper jsonDecoder; // XML support is maintained for legacy/custom clients. These codecs are used only on the server side only, while // Eureka client is using JSON only. private final EncoderWrapper xmlEncoder; private final DecoderWrapper xmlDecoder; public DiscoveryJerseyProvider() { this(null, null); } public DiscoveryJerseyProvider(EncoderWrapper jsonEncoder, DecoderWrapper jsonDecoder) { this.jsonEncoder = jsonEncoder == null ? CodecWrappers.getEncoder(LegacyJacksonJson.class) : jsonEncoder; this.jsonDecoder = jsonDecoder == null ? CodecWrappers.getDecoder(LegacyJacksonJson.class) : jsonDecoder; LOGGER.info("Using JSON encoding codec {}", this.jsonEncoder.codecName()); LOGGER.info("Using JSON decoding codec {}", this.jsonDecoder.codecName()); if (jsonEncoder instanceof CodecWrappers.JacksonJsonMini) { throw new UnsupportedOperationException("Encoder: " + jsonEncoder.codecName() + "is not supported for the client"); } this.xmlEncoder = CodecWrappers.getEncoder(CodecWrappers.XStreamXml.class); this.xmlDecoder = CodecWrappers.getDecoder(CodecWrappers.XStreamXml.class); LOGGER.info("Using XML encoding codec {}", this.xmlEncoder.codecName()); LOGGER.info("Using XML decoding codec {}", this.xmlDecoder.codecName()); } @Override public boolean isReadable(Class serializableClass, Type type, Annotation[] annotations, MediaType mediaType) { return isSupportedMediaType(mediaType) && isSupportedCharset(mediaType) && isSupportedEntity(serializableClass); } @Override public Object readFrom(Class serializableClass, Type type, Annotation[] annotations, MediaType mediaType, MultivaluedMap headers, InputStream inputStream) throws IOException { DecoderWrapper decoder; if (MediaType.MEDIA_TYPE_WILDCARD.equals(mediaType.getSubtype())) { decoder = xmlDecoder; } else if ("json".equalsIgnoreCase(mediaType.getSubtype())) { decoder = jsonDecoder; } else { decoder = xmlDecoder; // default } try { return decoder.decode(inputStream, serializableClass); } catch (Throwable e) { if (e instanceof Error) { // See issue: https://github.com/Netflix/eureka/issues/72 on why we catch Error here. closeInputOnError(inputStream); throw new WebApplicationException(e, createErrorReply(500, e, mediaType)); } LOGGER.debug("Cannot parse request body", e); throw new WebApplicationException(e, createErrorReply(400, "cannot parse request body", mediaType)); } } @Override public long getSize(Object serializableObject, Class serializableClass, Type type, Annotation[] annotations, MediaType mediaType) { return -1; } @Override public boolean isWriteable(Class serializableClass, Type type, Annotation[] annotations, MediaType mediaType) { return isSupportedMediaType(mediaType) && isSupportedEntity(serializableClass); } @Override public void writeTo(Object serializableObject, Class serializableClass, Type type, Annotation[] annotations, MediaType mediaType, MultivaluedMap headers, OutputStream outputStream) throws IOException, WebApplicationException { EncoderWrapper encoder = "json".equalsIgnoreCase(mediaType.getSubtype()) ? jsonEncoder : xmlEncoder; // XML codec may not be available if (encoder == null) { throw new WebApplicationException(createErrorReply(400, "No codec available to serialize content type " + mediaType, mediaType)); } encoder.encode(serializableObject, outputStream); } private boolean isSupportedMediaType(MediaType mediaType) { if (MediaType.APPLICATION_JSON_TYPE.isCompatible(mediaType)) { return true; } if (MediaType.APPLICATION_XML_TYPE.isCompatible(mediaType)) { return xmlDecoder != null; } return false; } /** * As content is cached, we expect both ends use UTF-8 always. If no content charset encoding is explicitly * defined, UTF-8 is assumed as a default. * As legacy clients may use ISO 8859-1 we accept it as well, although result may be unspecified if * characters out of ASCII 0-127 range are used. */ private static boolean isSupportedCharset(MediaType mediaType) { Map<String, String> parameters = mediaType.getParameters(); if (parameters == null || parameters.isEmpty()) { return true; } String charset = parameters.get("charset"); return charset == null || "UTF-8".equalsIgnoreCase(charset) || "ISO-8859-1".equalsIgnoreCase(charset); } /** * Checks for the {@link Serializer} annotation for the given class. * * @param entityType The class to be serialized/deserialized. * @return true if the annotation is present, false otherwise. */ private static boolean isSupportedEntity(Class<?> entityType) { try { Annotation annotation = entityType.getAnnotation(Serializer.class); if (annotation != null) { return true; } } catch (Throwable th) { LOGGER.warn("Exception in checking for annotations", th); } return false; } private static Response createErrorReply(int status, Throwable cause, MediaType mediaType) { StringBuilder sb = new StringBuilder(cause.getClass().getName()); if (cause.getMessage() != null) { sb.append(": ").append(cause.getMessage()); } return createErrorReply(status, sb.toString(), mediaType); } private static Response createErrorReply(int status, String errorMessage, MediaType mediaType) { String message; if (MediaType.APPLICATION_JSON_TYPE.equals(mediaType)) { message = "{\"error\": \"" + errorMessage + "\"}"; } else { message = "<error><message>" + errorMessage + "</message></error>"; } return Response.status(status).entity(message).type(mediaType).build(); } private static void closeInputOnError(InputStream inputStream) { if (inputStream != null) { LOGGER.error("Unexpected error occurred during de-serialization of discovery data, done connection cleanup"); try { inputStream.close(); } catch (IOException e) { LOGGER.debug("Cannot close input", e); } } } }
6,719
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/provider/ISerializer.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.provider; import javax.ws.rs.core.MediaType; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * A contract for dispatching to a custom serialization/de-serialization mechanism from jersey. * * @author Karthik Ranganathan * */ public interface ISerializer { Object read(InputStream is, Class type, MediaType mediaType) throws IOException; void write(Object object, OutputStream os, MediaType mediaType) throws IOException; }
6,720
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/provider/Serializer.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.provider; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * * An annotation that helps in specifying the custom serializer/de-serialization * implementation for jersey. * * <p> * Once the annotation is specified, a custom jersey provider invokes an * instance of the class specified as the value and dispatches all objects that * needs to be serialized/de-serialized to handle them as and only when it is * responsible for handling those. * </p> * * @author Karthik Ranganathan * */ @Documented @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface Serializer { String value() default ""; }
6,721
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/XmlXStream.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.converters; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.DiscoveryManager; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder; /** * An <tt>Xstream</tt> specific implementation for serializing and deserializing * to/from XML format. * * <p> * This class also allows configuration of custom serializers with Xstream. * </p> * * @author Karthik Ranganathan, Greg Kim * */ public class XmlXStream extends XStream { private static final XmlXStream s_instance = new XmlXStream(); static { XStream.setupDefaultSecurity(s_instance); s_instance.allowTypesByWildcard(new String[] { "com.netflix.discovery.**", "com.netflix.appinfo.**" }); } public XmlXStream() { super(new DomDriver(null, initializeNameCoder())); registerConverter(new Converters.ApplicationConverter()); registerConverter(new Converters.ApplicationsConverter()); registerConverter(new Converters.DataCenterInfoConverter()); registerConverter(new Converters.InstanceInfoConverter()); registerConverter(new Converters.LeaseInfoConverter()); registerConverter(new Converters.MetadataConverter()); setMode(XStream.NO_REFERENCES); processAnnotations(new Class[]{InstanceInfo.class, Application.class, Applications.class}); } public static XmlXStream getInstance() { return s_instance; } private static XmlFriendlyNameCoder initializeNameCoder() { EurekaClientConfig clientConfig = DiscoveryManager .getInstance().getEurekaClientConfig(); if (clientConfig == null) { return new XmlFriendlyNameCoder(); } return new XmlFriendlyNameCoder(clientConfig.getDollarReplacement(), clientConfig.getEscapeCharReplacement()); } }
6,722
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/Converters.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.converters; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import com.netflix.appinfo.AmazonInfo; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.DataCenterInfo.Name; 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.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.util.StringCache; import com.netflix.servo.monitor.Counter; import com.netflix.servo.monitor.Monitors; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The custom {@link com.netflix.discovery.provider.Serializer} for serializing and deserializing the registry * information from and to the eureka server. * * <p> * The {@link com.netflix.discovery.provider.Serializer} used here is an <tt>Xstream</tt> serializer which uses * the <tt>JSON</tt> format and custom fields.The XStream deserialization does * not handle removal of fields and hence this custom mechanism. Since then * {@link Auto} annotation introduced handles any fields that does not exist * gracefully and is the recommended mechanism. If the user wishes to override * the whole XStream serialization/deserialization mechanism with their own * alternatives they can do so my implementing their own providers in * {@link EntityBodyConverter}. * </p> * * @author Karthik Ranganathan, Greg Kim * */ public final class Converters { private static final String UNMARSHAL_ERROR = "UNMARSHAL_ERROR"; public static final String NODE_LEASE = "leaseInfo"; public static final String NODE_METADATA = "metadata"; public static final String NODE_DATACENTER = "dataCenterInfo"; public static final String NODE_INSTANCE = "instance"; public static final String NODE_APP = "application"; private static final Logger logger = LoggerFactory.getLogger(Converters.class); private static final Counter UNMARSHALL_ERROR_COUNTER = Monitors.newCounter(UNMARSHAL_ERROR); /** * Serialize/deserialize {@link Applications} object types. */ public static class ApplicationsConverter implements Converter { private static final String VERSIONS_DELTA = "versions_delta"; private static final String APPS_HASHCODE = "apps_hashcode"; /* * (non-Javadoc) * * @see * com.thoughtworks.xstream.converters.ConverterMatcher#canConvert(java * .lang.Class) */ @Override public boolean canConvert(@SuppressWarnings("rawtypes") Class clazz) { return Applications.class == clazz; } /* * (non-Javadoc) * * @see * com.thoughtworks.xstream.converters.Converter#marshal(java.lang.Object * , com.thoughtworks.xstream.io.HierarchicalStreamWriter, * com.thoughtworks.xstream.converters.MarshallingContext) */ @Override public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { Applications apps = (Applications) source; writer.startNode(VERSIONS_DELTA); writer.setValue(apps.getVersion().toString()); writer.endNode(); writer.startNode(APPS_HASHCODE); writer.setValue(apps.getAppsHashCode()); writer.endNode(); for (Application app : apps.getRegisteredApplications()) { writer.startNode(NODE_APP); context.convertAnother(app); writer.endNode(); } } /* * (non-Javadoc) * * @see * com.thoughtworks.xstream.converters.Converter#unmarshal(com.thoughtworks * .xstream.io.HierarchicalStreamReader, * com.thoughtworks.xstream.converters.UnmarshallingContext) */ @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { Applications apps = new Applications(); while (reader.hasMoreChildren()) { reader.moveDown(); String nodeName = reader.getNodeName(); if (NODE_APP.equals(nodeName)) { apps.addApplication((Application) context.convertAnother( apps, Application.class)); } else if (VERSIONS_DELTA.equals(nodeName)) { apps.setVersion(Long.valueOf(reader.getValue())); } else if (APPS_HASHCODE.equals(nodeName)) { apps.setAppsHashCode(reader.getValue()); } reader.moveUp(); } return apps; } } /** * Serialize/deserialize {@link Applications} object types. */ public static class ApplicationConverter implements Converter { private static final String ELEM_NAME = "name"; /* * (non-Javadoc) * * @see * com.thoughtworks.xstream.converters.ConverterMatcher#canConvert(java * .lang.Class) */ public boolean canConvert(@SuppressWarnings("rawtypes") Class clazz) { return Application.class == clazz; } /* * (non-Javadoc) * * @see * com.thoughtworks.xstream.converters.Converter#marshal(java.lang.Object * , com.thoughtworks.xstream.io.HierarchicalStreamWriter, * com.thoughtworks.xstream.converters.MarshallingContext) */ @Override public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { Application app = (Application) source; writer.startNode(ELEM_NAME); writer.setValue(app.getName()); writer.endNode(); for (InstanceInfo instanceInfo : app.getInstances()) { writer.startNode(NODE_INSTANCE); context.convertAnother(instanceInfo); writer.endNode(); } } /* * (non-Javadoc) * * @see * com.thoughtworks.xstream.converters.Converter#unmarshal(com.thoughtworks * .xstream.io.HierarchicalStreamReader, * com.thoughtworks.xstream.converters.UnmarshallingContext) */ @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { Application app = new Application(); while (reader.hasMoreChildren()) { reader.moveDown(); String nodeName = reader.getNodeName(); if (ELEM_NAME.equals(nodeName)) { app.setName(reader.getValue()); } else if (NODE_INSTANCE.equals(nodeName)) { app.addInstance((InstanceInfo) context.convertAnother(app, InstanceInfo.class)); } reader.moveUp(); } return app; } } /** * Serialize/deserialize {@link InstanceInfo} object types. */ public static class InstanceInfoConverter implements Converter { private static final String ELEM_OVERRIDDEN_STATUS = "overriddenstatus"; private static final String ELEM_OVERRIDDEN_STATUS_ALT = "overriddenStatus"; private static final String ELEM_HOST = "hostName"; private static final String ELEM_INSTANCE_ID = "instanceId"; private static final String ELEM_APP = "app"; private static final String ELEM_IP = "ipAddr"; private static final String ELEM_SID = "sid"; private static final String ELEM_STATUS = "status"; private static final String ELEM_PORT = "port"; private static final String ELEM_SECURE_PORT = "securePort"; private static final String ELEM_COUNTRY_ID = "countryId"; private static final String ELEM_IDENTIFYING_ATTR = "identifyingAttribute"; private static final String ATTR_ENABLED = "enabled"; /* * (non-Javadoc) * * @see * com.thoughtworks.xstream.converters.ConverterMatcher#canConvert(java * .lang.Class) */ @Override public boolean canConvert(@SuppressWarnings("rawtypes") Class clazz) { return InstanceInfo.class == clazz; } /* * (non-Javadoc) * * @see * com.thoughtworks.xstream.converters.Converter#marshal(java.lang.Object * , com.thoughtworks.xstream.io.HierarchicalStreamWriter, * com.thoughtworks.xstream.converters.MarshallingContext) */ @Override public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { InstanceInfo info = (InstanceInfo) source; if (info.getInstanceId() != null) { writer.startNode(ELEM_INSTANCE_ID); writer.setValue(info.getInstanceId()); writer.endNode(); } writer.startNode(ELEM_HOST); writer.setValue(info.getHostName()); writer.endNode(); writer.startNode(ELEM_APP); writer.setValue(info.getAppName()); writer.endNode(); writer.startNode(ELEM_IP); writer.setValue(info.getIPAddr()); writer.endNode(); if (!("unknown".equals(info.getSID()) || "na".equals(info.getSID()))) { writer.startNode(ELEM_SID); writer.setValue(info.getSID()); writer.endNode(); } writer.startNode(ELEM_STATUS); writer.setValue(getStatus(info)); writer.endNode(); writer.startNode(ELEM_OVERRIDDEN_STATUS); writer.setValue(info.getOverriddenStatus().name()); writer.endNode(); writer.startNode(ELEM_PORT); writer.addAttribute(ATTR_ENABLED, String.valueOf(info.isPortEnabled(PortType.UNSECURE))); writer.setValue(String.valueOf(info.getPort())); writer.endNode(); writer.startNode(ELEM_SECURE_PORT); writer.addAttribute(ATTR_ENABLED, String.valueOf(info.isPortEnabled(PortType.SECURE))); writer.setValue(String.valueOf(info.getSecurePort())); writer.endNode(); writer.startNode(ELEM_COUNTRY_ID); writer.setValue(String.valueOf(info.getCountryId())); writer.endNode(); if (info.getDataCenterInfo() != null) { writer.startNode(NODE_DATACENTER); // This is needed for backward compat. for now. if (info.getDataCenterInfo().getName() == Name.Amazon) { writer.addAttribute("class", "com.netflix.appinfo.AmazonInfo"); } else { writer.addAttribute("class", "com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo"); } context.convertAnother(info.getDataCenterInfo()); writer.endNode(); } if (info.getLeaseInfo() != null) { writer.startNode(NODE_LEASE); context.convertAnother(info.getLeaseInfo()); writer.endNode(); } if (info.getMetadata() != null) { writer.startNode(NODE_METADATA); // for backward compat. for now if (info.getMetadata().size() == 0) { writer.addAttribute("class", "java.util.Collections$EmptyMap"); } context.convertAnother(info.getMetadata()); writer.endNode(); } autoMarshalEligible(source, writer); } public String getStatus(InstanceInfo info) { return info.getStatus().name(); } /* * (non-Javadoc) * * @see * com.thoughtworks.xstream.converters.Converter#unmarshal(com.thoughtworks * .xstream.io.HierarchicalStreamReader, * com.thoughtworks.xstream.converters.UnmarshallingContext) */ @Override @SuppressWarnings("unchecked") public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { InstanceInfo.Builder builder = InstanceInfo.Builder.newBuilder(); while (reader.hasMoreChildren()) { reader.moveDown(); String nodeName = reader.getNodeName(); if (ELEM_HOST.equals(nodeName)) { builder.setHostName(reader.getValue()); } else if (ELEM_INSTANCE_ID.equals(nodeName)) { builder.setInstanceId(reader.getValue()); } else if (ELEM_APP.equals(nodeName)) { builder.setAppName(reader.getValue()); } else if (ELEM_IP.equals(nodeName)) { builder.setIPAddr(reader.getValue()); } else if (ELEM_SID.equals(nodeName)) { builder.setSID(reader.getValue()); } else if (ELEM_IDENTIFYING_ATTR.equals(nodeName)) { // nothing; } else if (ELEM_STATUS.equals(nodeName)) { builder.setStatus(InstanceStatus.toEnum(reader.getValue())); } else if (ELEM_OVERRIDDEN_STATUS.equals(nodeName)) { builder.setOverriddenStatus(InstanceStatus.toEnum(reader .getValue())); } else if (ELEM_OVERRIDDEN_STATUS_ALT.equals(nodeName)) { builder.setOverriddenStatus(InstanceStatus.toEnum(reader .getValue())); } else if (ELEM_PORT.equals(nodeName)) { builder.setPort(Integer.valueOf(reader.getValue()) .intValue()); // Defaults to true builder.enablePort(PortType.UNSECURE, !"false".equals(reader.getAttribute(ATTR_ENABLED))); } else if (ELEM_SECURE_PORT.equals(nodeName)) { builder.setSecurePort(Integer.valueOf(reader.getValue()) .intValue()); // Defaults to false builder.enablePort(PortType.SECURE, "true".equals(reader.getAttribute(ATTR_ENABLED))); } else if (ELEM_COUNTRY_ID.equals(nodeName)) { builder.setCountryId(Integer.valueOf(reader.getValue()) .intValue()); } else if (NODE_DATACENTER.equals(nodeName)) { builder.setDataCenterInfo((DataCenterInfo) context .convertAnother(builder, DataCenterInfo.class)); } else if (NODE_LEASE.equals(nodeName)) { builder.setLeaseInfo((LeaseInfo) context.convertAnother( builder, LeaseInfo.class)); } else if (NODE_METADATA.equals(nodeName)) { builder.setMetadata((Map<String, String>) context .convertAnother(builder, Map.class)); } else { autoUnmarshalEligible(reader, builder.getRawInstance()); } reader.moveUp(); } return builder.build(); } } /** * Serialize/deserialize {@link DataCenterInfo} object types. */ public static class DataCenterInfoConverter implements Converter { private static final String ELEM_NAME = "name"; /* * (non-Javadoc) * * @see * com.thoughtworks.xstream.converters.ConverterMatcher#canConvert(java * .lang.Class) */ @Override public boolean canConvert(@SuppressWarnings("rawtypes") Class clazz) { return DataCenterInfo.class.isAssignableFrom(clazz); } /* * (non-Javadoc) * * @see * com.thoughtworks.xstream.converters.Converter#marshal(java.lang.Object * , com.thoughtworks.xstream.io.HierarchicalStreamWriter, * com.thoughtworks.xstream.converters.MarshallingContext) */ @Override public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { DataCenterInfo info = (DataCenterInfo) source; writer.startNode(ELEM_NAME); // For backward compat. for now writer.setValue(info.getName().name()); writer.endNode(); if (info.getName() == Name.Amazon) { AmazonInfo aInfo = (AmazonInfo) info; writer.startNode(NODE_METADATA); // for backward compat. for now if (aInfo.getMetadata().size() == 0) { writer.addAttribute("class", "java.util.Collections$EmptyMap"); } context.convertAnother(aInfo.getMetadata()); writer.endNode(); } } /* * (non-Javadoc) * * @see * com.thoughtworks.xstream.converters.Converter#unmarshal(com.thoughtworks * .xstream.io.HierarchicalStreamReader, * com.thoughtworks.xstream.converters.UnmarshallingContext) */ @Override @SuppressWarnings("unchecked") public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { DataCenterInfo info = null; while (reader.hasMoreChildren()) { reader.moveDown(); if (ELEM_NAME.equals(reader.getNodeName())) { final String dataCenterName = reader.getValue(); if (DataCenterInfo.Name.Amazon.name().equalsIgnoreCase( dataCenterName)) { info = new AmazonInfo(); } else { final DataCenterInfo.Name name = DataCenterInfo.Name.valueOf(dataCenterName); info = new DataCenterInfo() { @Override public Name getName() { return name; } }; } } else if (NODE_METADATA.equals(reader.getNodeName())) { if (info.getName() == Name.Amazon) { Map<String, String> metadataMap = (Map<String, String>) context .convertAnother(info, Map.class); Map<String, String> metadataMapInter = new HashMap<>(metadataMap.size()); for (Map.Entry<String, String> entry : metadataMap.entrySet()) { metadataMapInter.put(StringCache.intern(entry.getKey()), StringCache.intern(entry.getValue())); } ((AmazonInfo) info).setMetadata(metadataMapInter); } } reader.moveUp(); } return info; } } /** * Serialize/deserialize {@link LeaseInfo} object types. */ public static class LeaseInfoConverter implements Converter { private static final String ELEM_RENEW_INT = "renewalIntervalInSecs"; private static final String ELEM_DURATION = "durationInSecs"; private static final String ELEM_REG_TIMESTAMP = "registrationTimestamp"; private static final String ELEM_LAST_RENEW_TIMETSTAMP = "lastRenewalTimestamp"; private static final String ELEM_EVICTION_TIMESTAMP = "evictionTimestamp"; private static final String ELEM_SERVICE_UP_TIMESTAMP = "serviceUpTimestamp"; /* * (non-Javadoc) * * @see * com.thoughtworks.xstream.converters.ConverterMatcher#canConvert(java * .lang.Class) */ @Override @SuppressWarnings("unchecked") public boolean canConvert(Class clazz) { return LeaseInfo.class == clazz; } /* * (non-Javadoc) * * @see * com.thoughtworks.xstream.converters.Converter#marshal(java.lang.Object * , com.thoughtworks.xstream.io.HierarchicalStreamWriter, * com.thoughtworks.xstream.converters.MarshallingContext) */ @Override public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { LeaseInfo info = (LeaseInfo) source; writer.startNode(ELEM_RENEW_INT); writer.setValue(String.valueOf(info.getRenewalIntervalInSecs())); writer.endNode(); writer.startNode(ELEM_DURATION); writer.setValue(String.valueOf(info.getDurationInSecs())); writer.endNode(); writer.startNode(ELEM_REG_TIMESTAMP); writer.setValue(String.valueOf(info.getRegistrationTimestamp())); writer.endNode(); writer.startNode(ELEM_LAST_RENEW_TIMETSTAMP); writer.setValue(String.valueOf(info.getRenewalTimestamp())); writer.endNode(); writer.startNode(ELEM_EVICTION_TIMESTAMP); writer.setValue(String.valueOf(info.getEvictionTimestamp())); writer.endNode(); writer.startNode(ELEM_SERVICE_UP_TIMESTAMP); writer.setValue(String.valueOf(info.getServiceUpTimestamp())); writer.endNode(); } /* * (non-Javadoc) * * @see * com.thoughtworks.xstream.converters.Converter#unmarshal(com.thoughtworks * .xstream.io.HierarchicalStreamReader, * com.thoughtworks.xstream.converters.UnmarshallingContext) */ @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { LeaseInfo.Builder builder = LeaseInfo.Builder.newBuilder(); while (reader.hasMoreChildren()) { reader.moveDown(); String nodeName = reader.getNodeName(); String nodeValue = reader.getValue(); if (nodeValue == null) { continue; } long longValue = 0; try { longValue = Long.parseLong(nodeValue); } catch (NumberFormatException ne) { continue; } if (ELEM_DURATION.equals(nodeName)) { builder.setDurationInSecs((int) longValue); } else if (ELEM_EVICTION_TIMESTAMP.equals(nodeName)) { builder.setEvictionTimestamp(longValue); } else if (ELEM_LAST_RENEW_TIMETSTAMP.equals(nodeName)) { builder.setRenewalTimestamp(longValue); } else if (ELEM_REG_TIMESTAMP.equals(nodeName)) { builder.setRegistrationTimestamp(longValue); } else if (ELEM_RENEW_INT.equals(nodeName)) { builder.setRenewalIntervalInSecs((int) longValue); } else if (ELEM_SERVICE_UP_TIMESTAMP.equals(nodeName)) { builder.setServiceUpTimestamp(longValue); } reader.moveUp(); } return builder.build(); } } /** * Serialize/deserialize application metadata. */ public static class MetadataConverter implements Converter { /* * (non-Javadoc) * * @see * com.thoughtworks.xstream.converters.ConverterMatcher#canConvert(java * .lang.Class) */ @Override public boolean canConvert(@SuppressWarnings("rawtypes") Class type) { return Map.class.isAssignableFrom(type); } /* * (non-Javadoc) * * @see * com.thoughtworks.xstream.converters.Converter#marshal(java.lang.Object * , com.thoughtworks.xstream.io.HierarchicalStreamWriter, * com.thoughtworks.xstream.converters.MarshallingContext) */ @Override @SuppressWarnings("unchecked") public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { Map<String, String> map = (Map<String, String>) source; for (Iterator<Entry<String, String>> iter = map.entrySet() .iterator(); iter.hasNext(); ) { Entry<String, String> entry = iter.next(); writer.startNode(entry.getKey()); writer.setValue(entry.getValue()); writer.endNode(); } } /* * (non-Javadoc) * * @see * com.thoughtworks.xstream.converters.Converter#unmarshal(com.thoughtworks * .xstream.io.HierarchicalStreamReader, * com.thoughtworks.xstream.converters.UnmarshallingContext) */ @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { return unmarshalMap(reader, context); } private Map<String, String> unmarshalMap( HierarchicalStreamReader reader, UnmarshallingContext context) { Map<String, String> map = Collections.emptyMap(); while (reader.hasMoreChildren()) { if (map == Collections.EMPTY_MAP) { map = new HashMap<String, String>(); } reader.moveDown(); String key = reader.getNodeName(); String value = reader.getValue(); reader.moveUp(); map.put(StringCache.intern(key), value); } return map; } } /** * Marshal all the objects containing an {@link Auto} annotation * automatically. * * @param o * - The object's fields that needs to be marshalled. * @param writer * - The writer for which to write the information to. */ private static void autoMarshalEligible(Object o, HierarchicalStreamWriter writer) { try { Class c = o.getClass(); Field[] fields = c.getDeclaredFields(); Annotation annotation = null; for (Field f : fields) { annotation = f.getAnnotation(Auto.class); if (annotation != null) { f.setAccessible(true); if (f.get(o) != null) { writer.startNode(f.getName()); writer.setValue(String.valueOf(f.get(o))); writer.endNode(); } } } } catch (Throwable th) { logger.error("Error in marshalling the object", th); } } /** * Unmarshal all the elements to their field values if the fields have the * {@link Auto} annotation defined. * * @param reader * - The reader where the elements can be read. * @param o * - The object for which the value of fields need to be * populated. */ private static void autoUnmarshalEligible(HierarchicalStreamReader reader, Object o) { try { String nodeName = reader.getNodeName(); Class c = o.getClass(); Field f = null; try { f = c.getDeclaredField(nodeName); } catch (NoSuchFieldException e) { UNMARSHALL_ERROR_COUNTER.increment(); } if (f == null) { return; } Annotation annotation = f.getAnnotation(Auto.class); if (annotation == null) { return; } f.setAccessible(true); String value = reader.getValue(); Class returnClass = f.getType(); if (value != null) { if (!String.class.equals(returnClass)) { Method method = returnClass.getDeclaredMethod("valueOf", java.lang.String.class); Object valueObject = method.invoke(returnClass, value); f.set(o, valueObject); } else { f.set(o, value); } } } catch (Throwable th) { logger.error("Error in unmarshalling the object:", th); } } }
6,723
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/Auto.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.converters; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * A field annotation which helps in avoiding changes to * {@link com.netflix.discovery.converters.Converters.InstanceInfoConverter} every time additional fields are added to * {@link com.netflix.appinfo.InstanceInfo}. * * <p> * This annotation informs the {@link com.netflix.discovery.converters.Converters.InstanceInfoConverter} to * automatically marshall most primitive fields declared in the {@link com.netflix.appinfo.InstanceInfo} class. * </p> * * @author Karthik Ranganathan * */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) public @interface Auto { }
6,724
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/EurekaJacksonCodec.java
package com.netflix.discovery.converters; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.function.Supplier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.RuntimeJsonMappingException; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import com.fasterxml.jackson.databind.module.SimpleModule; import com.netflix.appinfo.AmazonInfo; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.DataCenterInfo.Name; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.ActionType; import com.netflix.appinfo.InstanceInfo.InstanceStatus; import com.netflix.appinfo.InstanceInfo.PortType; import com.netflix.appinfo.LeaseInfo; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import com.netflix.discovery.util.DeserializerStringCache; import com.netflix.discovery.util.DeserializerStringCache.CacheScope; import vlsi.utils.CompactHashMap; /** * @author Tomasz Bak * @author Spencer Gibb */ public class EurekaJacksonCodec { private static final Logger logger = LoggerFactory.getLogger(EurekaJacksonCodec.class); private static final Version VERSION = new Version(1, 1, 0, null); public static final String NODE_LEASE = "leaseInfo"; public static final String NODE_METADATA = "metadata"; public static final String NODE_DATACENTER = "dataCenterInfo"; public static final String NODE_APP = "application"; protected static final String ELEM_INSTANCE = "instance"; protected static final String ELEM_OVERRIDDEN_STATUS = "overriddenStatus"; // the casing of this field was accidentally changed in commit // https://github.com/Netflix/eureka/commit/939957124a8f055c7d343d67d0842ae06cf59530#diff-1e0de94c9faa44a518abe30d94744178L63 // we need to look for both during deser for compatibility // see https://github.com/Netflix/eureka/issues/1051 protected static final String ELEM_OVERRIDDEN_STATUS_LEGACY = "overriddenstatus"; protected static final String ELEM_HOST = "hostName"; protected static final String ELEM_INSTANCE_ID = "instanceId"; protected static final String ELEM_APP = "app"; protected static final String ELEM_IP = "ipAddr"; protected static final String ELEM_SID = "sid"; protected static final String ELEM_STATUS = "status"; protected static final String ELEM_PORT = "port"; protected static final String ELEM_SECURE_PORT = "securePort"; protected static final String ELEM_COUNTRY_ID = "countryId"; protected static final String ELEM_IDENTIFYING_ATTR = "identifyingAttribute"; protected static final String ELEM_HEALTHCHECKURL = "healthCheckUrl"; protected static final String ELEM_SECHEALTHCHECKURL = "secureHealthCheckUrl"; protected static final String ELEM_APPGROUPNAME = "appGroupName"; protected static final String ELEM_HOMEPAGEURL = "homePageUrl"; protected static final String ELEM_STATUSPAGEURL = "statusPageUrl"; protected static final String ELEM_VIPADDRESS = "vipAddress"; protected static final String ELEM_SECVIPADDRESS = "secureVipAddress"; protected static final String ELEM_ISCOORDINATINGDISCSOERVER = "isCoordinatingDiscoveryServer"; protected static final String ELEM_LASTUPDATEDTS = "lastUpdatedTimestamp"; protected static final String ELEM_LASTDIRTYTS = "lastDirtyTimestamp"; protected static final String ELEM_ACTIONTYPE = "actionType"; protected static final String ELEM_ASGNAME = "asgName"; protected static final String ELEM_NAME = "name"; protected static final String DATACENTER_METADATA = "metadata"; protected static final String VERSIONS_DELTA_TEMPLATE = "versions_delta"; protected static final String APPS_HASHCODE_TEMPTE = "apps_hashcode"; public static EurekaJacksonCodec INSTANCE = new EurekaJacksonCodec(); public static final Supplier<? extends Map<String, String>> METADATA_MAP_SUPPLIER; static { boolean useCompact = true; try { Class.forName("vlsi.utils.CompactHashMap"); } catch (ClassNotFoundException e) { useCompact = false; } if (useCompact) { METADATA_MAP_SUPPLIER = CompactHashMap::new; } else { METADATA_MAP_SUPPLIER = HashMap::new; } } /** * XStream codec supports character replacement in field names to generate XML friendly * names. This feature is also configurable, and replacement strings can be provided by a user. * To obey these rules, version and appsHash key field names must be formatted according to the provided * configuration, which by default replaces '_' with '__' (double underscores). */ private final String versionDeltaKey; private final String appHashCodeKey; private final ObjectMapper mapper; private final Map<Class<?>, Supplier<ObjectReader>> objectReaderByClass; private final Map<Class<?>, ObjectWriter> objectWriterByClass; static EurekaClientConfig loadConfig() { return com.netflix.discovery.DiscoveryManager.getInstance().getEurekaClientConfig(); } public EurekaJacksonCodec() { this(formatKey(loadConfig(), VERSIONS_DELTA_TEMPLATE), formatKey(loadConfig(), APPS_HASHCODE_TEMPTE)); } public EurekaJacksonCodec(String versionDeltaKey, String appsHashCodeKey) { this.versionDeltaKey = versionDeltaKey; this.appHashCodeKey = appsHashCodeKey; this.mapper = new ObjectMapper(); this.mapper.setSerializationInclusion(Include.NON_NULL); SimpleModule module = new SimpleModule("eureka1.x", VERSION); module.addSerializer(DataCenterInfo.class, new DataCenterInfoSerializer()); module.addSerializer(InstanceInfo.class, new InstanceInfoSerializer()); module.addSerializer(Application.class, new ApplicationSerializer()); module.addSerializer(Applications.class, new ApplicationsSerializer(this.versionDeltaKey, this.appHashCodeKey)); module.addDeserializer(LeaseInfo.class, new LeaseInfoDeserializer()); module.addDeserializer(InstanceInfo.class, new InstanceInfoDeserializer(this.mapper)); module.addDeserializer(Application.class, new ApplicationDeserializer(this.mapper)); module.addDeserializer(Applications.class, new ApplicationsDeserializer(this.mapper, this.versionDeltaKey, this.appHashCodeKey)); this.mapper.registerModule(module); Map<Class<?>, Supplier<ObjectReader>> readers = new HashMap<>(); readers.put(InstanceInfo.class, ()->mapper.reader().forType(InstanceInfo.class).withRootName("instance")); readers.put(Application.class, ()->mapper.reader().forType(Application.class).withRootName("application")); readers.put(Applications.class, ()->mapper.reader().forType(Applications.class).withRootName("applications")); this.objectReaderByClass = readers; Map<Class<?>, ObjectWriter> writers = new HashMap<>(); writers.put(InstanceInfo.class, mapper.writer().forType(InstanceInfo.class).withRootName("instance")); writers.put(Application.class, mapper.writer().forType(Application.class).withRootName("application")); writers.put(Applications.class, mapper.writer().forType(Applications.class).withRootName("applications")); this.objectWriterByClass = writers; } protected ObjectMapper getMapper() { return mapper; } protected String getVersionDeltaKey() { return versionDeltaKey; } protected String getAppHashCodeKey() { return appHashCodeKey; } protected static String formatKey(EurekaClientConfig clientConfig, String keyTemplate) { String replacement; if (clientConfig == null) { replacement = "__"; } else { replacement = clientConfig.getEscapeCharReplacement(); } StringBuilder sb = new StringBuilder(keyTemplate.length() + 1); for (char c : keyTemplate.toCharArray()) { if (c == '_') { sb.append(replacement); } else { sb.append(c); } } return sb.toString(); } public <T> T readValue(Class<T> type, InputStream entityStream) throws IOException { ObjectReader reader = DeserializerStringCache.init( Optional.ofNullable(objectReaderByClass.get(type)).map(Supplier::get).orElseGet(()->mapper.readerFor(type)) ); try { return reader.readValue(entityStream); } finally { DeserializerStringCache.clear(reader, CacheScope.GLOBAL_SCOPE); } } public <T> T readValue(Class<T> type, String text) throws IOException { ObjectReader reader = DeserializerStringCache.init( Optional.ofNullable(objectReaderByClass.get(type)).map(Supplier::get).orElseGet(()->mapper.readerFor(type)) ); try { return reader.readValue(text); } finally { DeserializerStringCache.clear(reader, CacheScope.GLOBAL_SCOPE); } } public <T> void writeTo(T object, OutputStream entityStream) throws IOException { ObjectWriter writer = objectWriterByClass.get(object.getClass()); if (writer == null) { mapper.writeValue(entityStream, object); } else { writer.writeValue(entityStream, object); } } public <T> String writeToString(T object) { try { ObjectWriter writer = objectWriterByClass.get(object.getClass()); if (writer == null) { return mapper.writeValueAsString(object); } return writer.writeValueAsString(object); } catch (IOException e) { throw new IllegalArgumentException("Cannot encode provided object", e); } } public static EurekaJacksonCodec getInstance() { return INSTANCE; } public static void setInstance(EurekaJacksonCodec instance) { INSTANCE = instance; } public static class DataCenterInfoSerializer extends JsonSerializer<DataCenterInfo> { @Override public void serializeWithType(DataCenterInfo dataCenterInfo, JsonGenerator jgen, SerializerProvider provider, TypeSerializer typeSer) throws IOException, JsonProcessingException { jgen.writeStartObject(); // XStream encoded adds this for backwards compatibility issue. Not sure if needed anymore if (dataCenterInfo.getName() == Name.Amazon) { jgen.writeStringField("@class", "com.netflix.appinfo.AmazonInfo"); } else { jgen.writeStringField("@class", "com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo"); } jgen.writeStringField(ELEM_NAME, dataCenterInfo.getName().name()); if (dataCenterInfo.getName() == Name.Amazon) { AmazonInfo aInfo = (AmazonInfo) dataCenterInfo; jgen.writeObjectField(DATACENTER_METADATA, aInfo.getMetadata()); } jgen.writeEndObject(); } @Override public void serialize(DataCenterInfo dataCenterInfo, JsonGenerator jgen, SerializerProvider provider) throws IOException { serializeWithType(dataCenterInfo, jgen, provider, null); } } public static class LeaseInfoDeserializer extends JsonDeserializer<LeaseInfo> { enum LeaseInfoField { DURATION("durationInSecs"), EVICTION_TIMESTAMP("evictionTimestamp"), LAST_RENEW_TIMESTAMP("lastRenewalTimestamp"), REG_TIMESTAMP("registrationTimestamp"), RENEW_INTERVAL("renewalIntervalInSecs"), SERVICE_UP_TIMESTAMP("serviceUpTimestamp") ; private final char[] fieldName; private LeaseInfoField(String fieldName) { this.fieldName = fieldName.toCharArray(); } public char[] getFieldName() { return fieldName; } } private static EnumLookup<LeaseInfoField> fieldLookup = new EnumLookup<>(LeaseInfoField.class, LeaseInfoField::getFieldName); @Override public LeaseInfo deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { LeaseInfo.Builder builder = LeaseInfo.Builder.newBuilder(); JsonToken jsonToken; while ((jsonToken = jp.nextToken()) != JsonToken.END_OBJECT) { LeaseInfoField field = fieldLookup.find(jp); jsonToken = jp.nextToken(); if (field != null && jsonToken != JsonToken.VALUE_NULL) { switch(field) { case DURATION: builder.setDurationInSecs(jp.getValueAsInt()); break; case EVICTION_TIMESTAMP: builder.setEvictionTimestamp(jp.getValueAsLong()); break; case LAST_RENEW_TIMESTAMP: builder.setRenewalTimestamp(jp.getValueAsLong()); break; case REG_TIMESTAMP: builder.setRegistrationTimestamp(jp.getValueAsLong()); break; case RENEW_INTERVAL: builder.setRenewalIntervalInSecs(jp.getValueAsInt()); break; case SERVICE_UP_TIMESTAMP: builder.setServiceUpTimestamp(jp.getValueAsLong()); break; } } } return builder.build(); } } public static class InstanceInfoSerializer extends JsonSerializer<InstanceInfo> { // For backwards compatibility public static final String METADATA_COMPATIBILITY_KEY = "@class"; public static final String METADATA_COMPATIBILITY_VALUE = "java.util.Collections$EmptyMap"; protected static final Object EMPTY_METADATA = Collections.singletonMap(METADATA_COMPATIBILITY_KEY, METADATA_COMPATIBILITY_VALUE); @Override public void serialize(InstanceInfo info, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeStartObject(); if (info.getInstanceId() != null) { jgen.writeStringField(ELEM_INSTANCE_ID, info.getInstanceId()); } jgen.writeStringField(ELEM_HOST, info.getHostName()); jgen.writeStringField(ELEM_APP, info.getAppName()); jgen.writeStringField(ELEM_IP, info.getIPAddr()); @SuppressWarnings("deprecation") String sid = info.getSID(); if (!("unknown".equals(sid) || "na".equals(sid))) { jgen.writeStringField(ELEM_SID, sid); } jgen.writeStringField(ELEM_STATUS, info.getStatus().name()); jgen.writeStringField(ELEM_OVERRIDDEN_STATUS, info.getOverriddenStatus().name()); jgen.writeFieldName(ELEM_PORT); jgen.writeStartObject(); jgen.writeNumberField("$", info.getPort()); jgen.writeStringField("@enabled", Boolean.toString(info.isPortEnabled(PortType.UNSECURE))); jgen.writeEndObject(); jgen.writeFieldName(ELEM_SECURE_PORT); jgen.writeStartObject(); jgen.writeNumberField("$", info.getSecurePort()); jgen.writeStringField("@enabled", Boolean.toString(info.isPortEnabled(PortType.SECURE))); jgen.writeEndObject(); jgen.writeNumberField(ELEM_COUNTRY_ID, info.getCountryId()); if (info.getDataCenterInfo() != null) { jgen.writeObjectField(NODE_DATACENTER, info.getDataCenterInfo()); } if (info.getLeaseInfo() != null) { jgen.writeObjectField(NODE_LEASE, info.getLeaseInfo()); } Map<String, String> metadata = info.getMetadata(); if (metadata != null) { if (metadata.isEmpty()) { jgen.writeObjectField(NODE_METADATA, EMPTY_METADATA); } else { jgen.writeObjectField(NODE_METADATA, metadata); } } autoMarshalEligible(info, jgen); jgen.writeEndObject(); } protected void autoMarshalEligible(Object o, JsonGenerator jgen) { try { Class<?> c = o.getClass(); Field[] fields = c.getDeclaredFields(); Annotation annotation; for (Field f : fields) { annotation = f.getAnnotation(Auto.class); if (annotation != null) { f.setAccessible(true); if (f.get(o) != null) { jgen.writeStringField(f.getName(), String.valueOf(f.get(o))); } } } } catch (Throwable th) { logger.error("Error in marshalling the object", th); } } } public static class InstanceInfoDeserializer extends JsonDeserializer<InstanceInfo> { private static char[] BUF_AT_CLASS = "@class".toCharArray(); enum InstanceInfoField { HOSTNAME(ELEM_HOST), INSTANCE_ID(ELEM_INSTANCE_ID), APP(ELEM_APP), IP(ELEM_IP), SID(ELEM_SID), ID_ATTR(ELEM_IDENTIFYING_ATTR),// nothing STATUS(ELEM_STATUS), OVERRIDDEN_STATUS(ELEM_OVERRIDDEN_STATUS), OVERRIDDEN_STATUS_LEGACY(ELEM_OVERRIDDEN_STATUS_LEGACY), PORT(ELEM_PORT), SECURE_PORT(ELEM_SECURE_PORT), COUNTRY_ID(ELEM_COUNTRY_ID), DATACENTER(NODE_DATACENTER), LEASE(NODE_LEASE), HEALTHCHECKURL(ELEM_HEALTHCHECKURL), SECHEALTHCHECKURL(ELEM_SECHEALTHCHECKURL), APPGROUPNAME(ELEM_APPGROUPNAME), HOMEPAGEURL(ELEM_HOMEPAGEURL), STATUSPAGEURL(ELEM_STATUSPAGEURL), VIPADDRESS(ELEM_VIPADDRESS), SECVIPADDRESS(ELEM_SECVIPADDRESS), ISCOORDINATINGDISCSERVER(ELEM_ISCOORDINATINGDISCSOERVER), LASTUPDATEDTS(ELEM_LASTUPDATEDTS), LASTDIRTYTS(ELEM_LASTDIRTYTS), ACTIONTYPE(ELEM_ACTIONTYPE), ASGNAME(ELEM_ASGNAME), METADATA(NODE_METADATA) ; private final char[] elementName; private InstanceInfoField(String elementName) { this.elementName = elementName.toCharArray(); } public char[] getElementName() { return elementName; } public static EnumLookup<InstanceInfoField> lookup = new EnumLookup<>(InstanceInfoField.class, InstanceInfoField::getElementName); } enum PortField { PORT("$"), ENABLED("@enabled"); private final char[] fieldName; private PortField(String name) { this.fieldName = name.toCharArray(); } public char[] getFieldName() { return fieldName; } public static EnumLookup<PortField> lookup = new EnumLookup<>(PortField.class, PortField::getFieldName); } private final ObjectMapper mapper; private final ConcurrentMap<String, BiConsumer<Object, String>> autoUnmarshalActions = new ConcurrentHashMap<>(); private static EnumLookup<InstanceStatus> statusLookup = new EnumLookup<>(InstanceStatus.class); private static EnumLookup<ActionType> actionTypeLookup = new EnumLookup<>(ActionType.class); static Set<String> globalCachedMetadata = new HashSet<>(); static { globalCachedMetadata.add("route53Type"); globalCachedMetadata.add("enableRoute53"); globalCachedMetadata.add("netflix.stack"); globalCachedMetadata.add("netflix.detail"); globalCachedMetadata.add("NETFLIX_ENVIRONMENT"); globalCachedMetadata.add("transportPort"); } protected InstanceInfoDeserializer(ObjectMapper mapper) { this.mapper = mapper; } final static Function<String,String> self = s->s; @SuppressWarnings("deprecation") @Override public InstanceInfo deserialize(JsonParser jp, DeserializationContext context) throws IOException { if (Thread.currentThread().isInterrupted()) { throw new JsonParseException(jp, "processing aborted"); } DeserializerStringCache intern = DeserializerStringCache.from(context); InstanceInfo.Builder builder = InstanceInfo.Builder.newBuilder(self); JsonToken jsonToken; while ((jsonToken = jp.nextToken()) != JsonToken.END_OBJECT) { InstanceInfoField instanceInfoField = InstanceInfoField.lookup.find(jp); jsonToken = jp.nextToken(); if (instanceInfoField != null && jsonToken != JsonToken.VALUE_NULL) { switch(instanceInfoField) { case HOSTNAME: builder.setHostName(intern.apply(jp)); break; case INSTANCE_ID: builder.setInstanceId(intern.apply(jp)); break; case APP: builder.setAppNameForDeser( intern.apply(jp, CacheScope.APPLICATION_SCOPE, ()->{ try { return jp.getText().toUpperCase(); } catch (IOException e) { throw new RuntimeJsonMappingException(e.getMessage()); } })); break; case IP: builder.setIPAddr(intern.apply(jp)); break; case SID: builder.setSID(intern.apply(jp, CacheScope.GLOBAL_SCOPE)); break; case ID_ATTR: // nothing break; case STATUS: builder.setStatus(statusLookup.find(jp, InstanceStatus.UNKNOWN)); break; case OVERRIDDEN_STATUS: builder.setOverriddenStatus(statusLookup.find(jp, InstanceStatus.UNKNOWN)); break; case OVERRIDDEN_STATUS_LEGACY: builder.setOverriddenStatus(statusLookup.find(jp, InstanceStatus.UNKNOWN)); break; case PORT: while ((jsonToken = jp.nextToken()) != JsonToken.END_OBJECT) { PortField field = PortField.lookup.find(jp); switch(field) { case PORT: if (jsonToken == JsonToken.FIELD_NAME) jp.nextToken(); builder.setPort(jp.getValueAsInt()); break; case ENABLED: if (jsonToken == JsonToken.FIELD_NAME) jp.nextToken(); builder.enablePort(PortType.UNSECURE, jp.getValueAsBoolean()); break; default: } } break; case SECURE_PORT: while ((jsonToken = jp.nextToken()) != JsonToken.END_OBJECT) { PortField field = PortField.lookup.find(jp); switch(field) { case PORT: if (jsonToken == JsonToken.FIELD_NAME) jp.nextToken(); builder.setSecurePort(jp.getValueAsInt()); break; case ENABLED: if (jsonToken == JsonToken.FIELD_NAME) jp.nextToken(); builder.enablePort(PortType.SECURE, jp.getValueAsBoolean()); break; default: } } break; case COUNTRY_ID: builder.setCountryId(jp.getValueAsInt()); break; case DATACENTER: builder.setDataCenterInfo(DeserializerStringCache.init(mapper.readerFor(DataCenterInfo.class), context).readValue(jp)); break; case LEASE: builder.setLeaseInfo(mapper.readerFor(LeaseInfo.class).readValue(jp)); break; case HEALTHCHECKURL: builder.setHealthCheckUrlsForDeser(intern.apply(jp.getText()), null); break; case SECHEALTHCHECKURL: builder.setHealthCheckUrlsForDeser(null, intern.apply(jp.getText())); break; case APPGROUPNAME: builder.setAppGroupNameForDeser(intern.apply(jp, CacheScope.GLOBAL_SCOPE, ()->{ try { return jp.getText().toUpperCase(); } catch (IOException e) { throw new RuntimeJsonMappingException(e.getMessage()); } })); break; case HOMEPAGEURL: builder.setHomePageUrlForDeser(intern.apply(jp.getText())); break; case STATUSPAGEURL: builder.setStatusPageUrlForDeser(intern.apply(jp.getText())); break; case VIPADDRESS: builder.setVIPAddressDeser(intern.apply(jp)); break; case SECVIPADDRESS: builder.setSecureVIPAddressDeser(intern.apply(jp)); break; case ISCOORDINATINGDISCSERVER: builder.setIsCoordinatingDiscoveryServer(jp.getValueAsBoolean()); break; case LASTUPDATEDTS: builder.setLastUpdatedTimestamp(jp.getValueAsLong()); break; case LASTDIRTYTS: builder.setLastDirtyTimestamp(jp.getValueAsLong()); break; case ACTIONTYPE: builder.setActionType(actionTypeLookup.find(jp.getTextCharacters(), jp.getTextOffset(), jp.getTextLength())); break; case ASGNAME: builder.setASGName(intern.apply(jp)); break; case METADATA: Map<String, String> metadataMap = null; while ((jsonToken = jp.nextToken()) != JsonToken.END_OBJECT) { char[] parserChars = jp.getTextCharacters(); if (parserChars[0] == '@' && EnumLookup.equals(BUF_AT_CLASS, parserChars, jp.getTextOffset(), jp.getTextLength())) { // skip this jsonToken = jp.nextToken(); } else { // For backwards compatibility String key = intern.apply(jp, CacheScope.GLOBAL_SCOPE); jsonToken = jp.nextToken(); String value = intern.apply(jp, CacheScope.APPLICATION_SCOPE ); metadataMap = Optional.ofNullable(metadataMap).orElseGet(METADATA_MAP_SUPPLIER); metadataMap.put(key, value); } }; builder.setMetadata(metadataMap == null ? Collections.emptyMap() : metadataMap); break; default: autoUnmarshalEligible(jp.getCurrentName(), jp.getValueAsString(), builder.getRawInstance()); } } else { autoUnmarshalEligible(jp.getCurrentName(), jp.getValueAsString(), builder.getRawInstance()); } } return builder.build(); } void autoUnmarshalEligible(String fieldName, String value, Object o) { if (value == null || o == null) return; // early out Class<?> c = o.getClass(); String cacheKey = c.getName() + ":" + fieldName; BiConsumer<Object, String> action = autoUnmarshalActions.computeIfAbsent(cacheKey, k-> { try { Field f = null; try { f = c.getDeclaredField(fieldName); } catch (NoSuchFieldException e) { // TODO XStream version increments metrics counter here } if (f == null) { return (t,v)->{}; } Annotation annotation = f.getAnnotation(Auto.class); if (annotation == null) { return (t,v)->{}; } f.setAccessible(true); final Field setterField = f; Class<?> returnClass = setterField.getType(); if (!String.class.equals(returnClass)) { Method method = returnClass.getDeclaredMethod("valueOf", java.lang.String.class); return (t, v) -> tryCatchLog(()->{ setterField.set(t, method.invoke(returnClass, v)); return null; }); } else { return (t, v) -> tryCatchLog(()->{ setterField.set(t, v); return null; }); } } catch (Exception ex) { logger.error("Error in unmarshalling the object:", ex); return null; } }); action.accept(o, value); } } private static void tryCatchLog(Callable<Void> callable) { try { callable.call(); } catch (Exception ex) { logger.error("Error in unmarshalling the object:", ex); } } public static class ApplicationSerializer extends JsonSerializer<Application> { @Override public void serialize(Application value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeStringField(ELEM_NAME, value.getName()); jgen.writeObjectField(ELEM_INSTANCE, value.getInstances()); jgen.writeEndObject(); } } public static class ApplicationDeserializer extends JsonDeserializer<Application> { enum ApplicationField { NAME(ELEM_NAME), INSTANCE(ELEM_INSTANCE); private final char[] fieldName; private ApplicationField(String name) { this.fieldName = name.toCharArray(); } public char[] getFieldName() { return fieldName; } public static EnumLookup<ApplicationField> lookup = new EnumLookup<>(ApplicationField.class, ApplicationField::getFieldName); } private final ObjectMapper mapper; public ApplicationDeserializer(ObjectMapper mapper) { this.mapper = mapper; } @Override public Application deserialize(JsonParser jp, DeserializationContext context) throws IOException { if (Thread.currentThread().isInterrupted()) { throw new JsonParseException(jp, "processing aborted"); } Application application = new Application(); JsonToken jsonToken; try { while((jsonToken = jp.nextToken()) != JsonToken.END_OBJECT){ if(JsonToken.FIELD_NAME == jsonToken){ ApplicationField field = ApplicationField.lookup.find(jp); jsonToken = jp.nextToken(); if (field != null) { switch(field) { case NAME: application.setName(jp.getText()); break; case INSTANCE: ObjectReader instanceInfoReader = DeserializerStringCache.init(mapper.readerFor(InstanceInfo.class), context); if (jsonToken == JsonToken.START_ARRAY) { // messages is array, loop until token equal to "]" while (jp.nextToken() != JsonToken.END_ARRAY) { application.addInstance(instanceInfoReader.readValue(jp)); } } else if (jsonToken == JsonToken.START_OBJECT) { application.addInstance(instanceInfoReader.readValue(jp)); } break; } } } } } finally { // DeserializerStringCache.clear(context, CacheScope.APPLICATION_SCOPE); } return application; } } public static class ApplicationsSerializer extends JsonSerializer<Applications> { protected String versionDeltaKey; protected String appHashCodeKey; public ApplicationsSerializer(String versionDeltaKey, String appHashCodeKey) { this.versionDeltaKey = versionDeltaKey; this.appHashCodeKey = appHashCodeKey; } @Override public void serialize(Applications applications, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeStartObject(); jgen.writeStringField(versionDeltaKey, applications.getVersion().toString()); jgen.writeStringField(appHashCodeKey, applications.getAppsHashCode()); jgen.writeObjectField(NODE_APP, applications.getRegisteredApplications()); } } public static class ApplicationsDeserializer extends JsonDeserializer<Applications> { protected ObjectMapper mapper; protected String versionDeltaKey; protected String appHashCodeKey; public ApplicationsDeserializer(ObjectMapper mapper, String versionDeltaKey, String appHashCodeKey) { this.mapper = mapper; this.versionDeltaKey = versionDeltaKey; this.appHashCodeKey = appHashCodeKey; } @Override public Applications deserialize(JsonParser jp, DeserializationContext context) throws IOException { if (Thread.currentThread().isInterrupted()) { throw new JsonParseException(jp, "processing aborted"); } Applications apps = new Applications(); JsonToken jsonToken; while((jsonToken = jp.nextToken()) != JsonToken.END_OBJECT){ if(JsonToken.FIELD_NAME == jsonToken){ String fieldName = jp.getCurrentName(); jsonToken = jp.nextToken(); if(versionDeltaKey.equals(fieldName)){ apps.setVersion(jp.getValueAsLong()); } else if (appHashCodeKey.equals(fieldName)){ apps.setAppsHashCode(jp.getValueAsString()); } else if (NODE_APP.equals(fieldName)) { ObjectReader applicationReader = DeserializerStringCache.init(mapper.readerFor(Application.class), context); if (jsonToken == JsonToken.START_ARRAY) { while (jp.nextToken() != JsonToken.END_ARRAY) { apps.addApplication(applicationReader.readValue(jp)); } } else if (jsonToken == JsonToken.START_OBJECT) { apps.addApplication(applicationReader.readValue(jp)); } } } } return apps; } } }
6,725
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/KeyFormatter.java
package com.netflix.discovery.converters; import javax.inject.Inject; import javax.inject.Singleton; import com.netflix.discovery.EurekaClientConfig; /** * Due to backwards compatibility some names in JSON/XML documents have to be formatted * according to a given configuration rules. The formatting functionality is provided by this class. * * @author Tomasz Bak */ @Singleton public class KeyFormatter { public static final String DEFAULT_REPLACEMENT = "__"; private static final KeyFormatter DEFAULT_KEY_FORMATTER = new KeyFormatter(DEFAULT_REPLACEMENT); private final String replacement; public KeyFormatter(String replacement) { this.replacement = replacement; } @Inject public KeyFormatter(EurekaClientConfig eurekaClientConfig) { if (eurekaClientConfig == null) { this.replacement = DEFAULT_REPLACEMENT; } else { this.replacement = eurekaClientConfig.getEscapeCharReplacement(); } } public String formatKey(String keyTemplate) { StringBuilder sb = new StringBuilder(keyTemplate.length() + 1); for (char c : keyTemplate.toCharArray()) { if (c == '_') { sb.append(replacement); } else { sb.append(c); } } return sb.toString(); } public static KeyFormatter defaultKeyFormatter() { return DEFAULT_KEY_FORMATTER; } }
6,726
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/EnumLookup.java
package com.netflix.discovery.converters; import java.io.IOException; import java.lang.reflect.Array; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.function.Function; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; /** * utility class for matching a Enum value to a region of a char[] without * allocating any new objects on the heap. */ public class EnumLookup<T extends Enum<T>> { private final int[] sortedHashes; private final char[][] sortedNames; private final Map<String, T> stringLookup; private final T[] sortedValues; private final int minLength; private final int maxLength; EnumLookup(Class<T> enumType) { this(enumType, t -> t.name().toCharArray()); } @SuppressWarnings("unchecked") EnumLookup(Class<T> enumType, Function<T, char[]> namer) { this.sortedValues = (T[]) Array.newInstance(enumType, enumType.getEnumConstants().length); System.arraycopy(enumType.getEnumConstants(), 0, sortedValues, 0, sortedValues.length); Arrays.sort(sortedValues, (o1, o2) -> Integer.compare(Arrays.hashCode(namer.apply(o1)), Arrays.hashCode(namer.apply(o2)))); this.sortedHashes = new int[sortedValues.length]; this.sortedNames = new char[sortedValues.length][]; int i = 0; int minLength = Integer.MAX_VALUE; int maxLength = Integer.MIN_VALUE; stringLookup = new HashMap<>(); for (T te : sortedValues) { char[] name = namer.apply(te); int hash = Arrays.hashCode(name); sortedNames[i] = name; sortedHashes[i++] = hash; stringLookup.put(String.valueOf(name), te); maxLength = Math.max(maxLength, name.length); minLength = Math.min(minLength, name.length); } this.minLength = minLength; this.maxLength = maxLength; } public T find(JsonParser jp) throws IOException { return find(jp, null); } public T find(JsonParser jp, T defaultValue) throws IOException { if (jp.getCurrentToken() == JsonToken.FIELD_NAME) { return stringLookup.getOrDefault(jp.getCurrentName(), defaultValue); } return find(jp.getTextCharacters(), jp.getTextOffset(), jp.getTextLength(), defaultValue); } public T find(char[] a, int offset, int length) { return find(a, offset, length, null); } public T find(char[] a, int offset, int length, T defaultValue) { if (length < this.minLength || length > this.maxLength) return defaultValue; int hash = hashCode(a, offset, length); int index = Arrays.binarySearch(sortedHashes, hash); if (index >= 0) { for (int i = index; i < sortedValues.length && sortedHashes[index] == hash; i++) { if (equals(sortedNames[i], a, offset, length)) { return sortedValues[i]; } } } return defaultValue; } public static boolean equals(char[] a1, char[] a2, int a2Offset, int a2Length) { if (a1.length != a2Length) return false; for (int i = 0; i < a2Length; i++) { if (a1[i] != a2[i + a2Offset]) return false; } return true; } public static int hashCode(char[] a, int offset, int length) { if (a == null) return 0; int result = 1; for (int i = 0; i < length; i++) { result = 31 * result + a[i + offset]; } return result; } }
6,727
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/EntityBodyConverter.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.converters; import javax.ws.rs.core.MediaType; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import com.netflix.discovery.provider.ISerializer; import com.thoughtworks.xstream.XStream; /** * A custom <tt>jersey</tt> provider implementation for eureka. * * <p> * The implementation uses <tt>Xstream</tt> to provide * serialization/deserialization capabilities. If the users to wish to provide * their own implementation they can do so by plugging in their own provider * here and annotating their classes with that provider by specifying the * {@link com.netflix.discovery.provider.Serializer} annotation. * <p> * * @author Karthik Ranganathan, Greg Kim. * */ public class EntityBodyConverter implements ISerializer { private static final String XML = "xml"; private static final String JSON = "json"; /* * (non-Javadoc) * * @see com.netflix.discovery.provider.ISerializer#read(java.io.InputStream, * java.lang.Class, javax.ws.rs.core.MediaType) */ public Object read(InputStream is, Class type, MediaType mediaType) throws IOException { XStream xstream = getXStreamInstance(mediaType); if (xstream != null) { return xstream.fromXML(is); } else { throw new IllegalArgumentException("Content-type: " + mediaType.getType() + " is currently not supported for " + type.getName()); } } /* * (non-Javadoc) * * @see com.netflix.discovery.provider.ISerializer#write(java.lang.Object, * java.io.OutputStream, javax.ws.rs.core.MediaType) */ public void write(Object object, OutputStream os, MediaType mediaType) throws IOException { XStream xstream = getXStreamInstance(mediaType); if (xstream != null) { xstream.toXML(object, os); } else { throw new IllegalArgumentException("Content-type: " + mediaType.getType() + " is currently not supported for " + object.getClass().getName()); } } private XStream getXStreamInstance(MediaType mediaType) { XStream xstream = null; if (JSON.equalsIgnoreCase(mediaType.getSubtype())) { xstream = JsonXStream.getInstance(); } else if (XML.equalsIgnoreCase(mediaType.getSubtype())) { xstream = XmlXStream.getInstance(); } return xstream; } }
6,728
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/JsonXStream.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.converters; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.DiscoveryManager; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver; import com.thoughtworks.xstream.io.naming.NameCoder; import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder; /** * An <tt>Xstream</tt> specific implementation for serializing and deserializing * to/from JSON format. * * <p> * This class also allows configuration of custom serializers with Xstream. * </p> * * @author Karthik Ranganathan * */ public class JsonXStream extends XStream { private static final JsonXStream s_instance = new JsonXStream(); static { XStream.setupDefaultSecurity(s_instance); s_instance.allowTypesByWildcard(new String[] { "com.netflix.discovery.**", "com.netflix.appinfo.**" }); } public JsonXStream() { super(new JettisonMappedXmlDriver() { private final NameCoder coder = initializeNameCoder(); protected NameCoder getNameCoder() { return this.coder; } }); registerConverter(new Converters.ApplicationConverter()); registerConverter(new Converters.ApplicationsConverter()); registerConverter(new Converters.DataCenterInfoConverter()); registerConverter(new Converters.InstanceInfoConverter()); registerConverter(new Converters.LeaseInfoConverter()); registerConverter(new Converters.MetadataConverter()); setMode(XStream.NO_REFERENCES); processAnnotations(new Class[]{InstanceInfo.class, Application.class, Applications.class}); } public static JsonXStream getInstance() { return s_instance; } private static XmlFriendlyNameCoder initializeNameCoder() { EurekaClientConfig clientConfig = DiscoveryManager .getInstance().getEurekaClientConfig(); if (clientConfig == null) { return new XmlFriendlyNameCoder(); } return new XmlFriendlyNameCoder(clientConfig.getDollarReplacement(), clientConfig.getEscapeCharReplacement()); } }
6,729
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/wrappers/DecoderWrapper.java
package com.netflix.discovery.converters.wrappers; import java.io.IOException; import java.io.InputStream; /** * @author David Liu */ public interface DecoderWrapper extends CodecWrapperBase { <T> T decode(String textValue, Class<T> type) throws IOException; <T> T decode(InputStream inputStream, Class<T> type) throws IOException; }
6,730
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/wrappers/EncoderWrapper.java
package com.netflix.discovery.converters.wrappers; import java.io.IOException; import java.io.OutputStream; /** * @author David Liu */ public interface EncoderWrapper extends CodecWrapperBase { <T> String encode(T object) throws IOException; <T> void encode(T object, OutputStream outputStream) throws IOException; }
6,731
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/wrappers/CodecWrapperBase.java
package com.netflix.discovery.converters.wrappers; import javax.ws.rs.core.MediaType; /** * @author David Liu */ public interface CodecWrapperBase { String codecName(); boolean support(MediaType mediaType); }
6,732
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/wrappers/CodecWrapper.java
package com.netflix.discovery.converters.wrappers; /** * Interface for more useable reference * * @author David Liu */ public interface CodecWrapper extends EncoderWrapper, DecoderWrapper { }
6,733
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/wrappers/CodecWrappers.java
package com.netflix.discovery.converters.wrappers; import javax.ws.rs.core.MediaType; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import com.netflix.appinfo.EurekaAccept; import com.netflix.discovery.converters.EurekaJacksonCodec; import com.netflix.discovery.converters.JsonXStream; import com.netflix.discovery.converters.KeyFormatter; import com.netflix.discovery.converters.XmlXStream; import com.netflix.discovery.converters.jackson.EurekaJsonJacksonCodec; import com.netflix.discovery.converters.jackson.EurekaXmlJacksonCodec; import com.netflix.discovery.shared.transport.jersey.EurekaJerseyClientImpl; /** * This is just a helper class during transition when multiple codecs are supported. One day this should all go away * when there is only 1 type of json and xml codecs each. * * For adding custom codecs to Discovery, prefer creating a custom EurekaJerseyClient to added to DiscoveryClient * either completely independently or via * {@link EurekaJerseyClientImpl.EurekaJerseyClientBuilder#withDecoderWrapper(DecoderWrapper)} * and * {@link EurekaJerseyClientImpl.EurekaJerseyClientBuilder#withEncoderWrapper(EncoderWrapper)} * * @author David Liu */ public final class CodecWrappers { private static final Map<String, CodecWrapper> CODECS = new ConcurrentHashMap<>(); /** * For transition use: register a new codec wrapper. */ public static void registerWrapper(CodecWrapper wrapper) { CODECS.put(wrapper.codecName(), wrapper); } public static <T extends CodecWrapperBase> String getCodecName(Class<T> clazz) { return clazz.getSimpleName(); } public static <T extends CodecWrapper> CodecWrapper getCodec(Class<T> clazz) { return getCodec(getCodecName(clazz)); } public static synchronized CodecWrapper getCodec(String name) { if (name == null) { return null; } if (!CODECS.containsKey(name)) { CodecWrapper wrapper = create(name); if (wrapper != null) { CODECS.put(wrapper.codecName(), wrapper); } } return CODECS.get(name); } public static <T extends EncoderWrapper> EncoderWrapper getEncoder(Class<T> clazz) { return getEncoder(getCodecName(clazz)); } public static synchronized EncoderWrapper getEncoder(String name) { if (name == null) { return null; } if (!CODECS.containsKey(name)) { CodecWrapper wrapper = create(name); if (wrapper != null) { CODECS.put(wrapper.codecName(), wrapper); } } return CODECS.get(name); } public static <T extends DecoderWrapper> DecoderWrapper getDecoder(Class<T> clazz) { return getDecoder(getCodecName(clazz)); } /** * Resolve the decoder to use based on the specified decoder name, as well as the specified eurekaAccept. * The eurekAccept trumps the decoder name if the decoder specified is one that is not valid for use for the * specified eurekaAccept. */ public static synchronized DecoderWrapper resolveDecoder(String name, String eurekaAccept) { EurekaAccept accept = EurekaAccept.fromString(eurekaAccept); switch (accept) { case compact: return getDecoder(JacksonJsonMini.class); case full: default: return getDecoder(name); } } public static synchronized DecoderWrapper getDecoder(String name) { if (name == null) { return null; } if (!CODECS.containsKey(name)) { CodecWrapper wrapper = create(name); if (wrapper != null) { CODECS.put(wrapper.codecName(), wrapper); } } return CODECS.get(name); } private static CodecWrapper create(String name) { if (getCodecName(JacksonJson.class).equals(name)) { return new JacksonJson(); } else if (getCodecName(JacksonJsonMini.class).equals(name)) { return new JacksonJsonMini(); } else if (getCodecName(LegacyJacksonJson.class).equals(name)) { return new LegacyJacksonJson(); } else if (getCodecName(XStreamJson.class).equals(name)) { return new XStreamJson(); } else if (getCodecName(JacksonXml.class).equals(name)) { return new JacksonXml(); } else if (getCodecName(JacksonXmlMini.class).equals(name)) { return new JacksonXmlMini(); } else if (getCodecName(XStreamXml.class).equals(name)) { return new XStreamXml(); } else { return null; } } // ======================== // wrapper definitions // ======================== public static class JacksonJson implements CodecWrapper { protected final EurekaJsonJacksonCodec codec = new EurekaJsonJacksonCodec(); @Override public String codecName() { return getCodecName(this.getClass()); } @Override public boolean support(MediaType mediaType) { return mediaType.equals(MediaType.APPLICATION_JSON_TYPE); } @Override public <T> String encode(T object) throws IOException { return codec.getObjectMapper(object.getClass()).writeValueAsString(object); } @Override public <T> void encode(T object, OutputStream outputStream) throws IOException { codec.writeTo(object, outputStream); } @Override public <T> T decode(String textValue, Class<T> type) throws IOException { return codec.getObjectMapper(type).readValue(textValue, type); } @Override public <T> T decode(InputStream inputStream, Class<T> type) throws IOException { return codec.getObjectMapper(type).readValue(inputStream, type); } } public static class JacksonJsonMini implements CodecWrapper { protected final EurekaJsonJacksonCodec codec = new EurekaJsonJacksonCodec(KeyFormatter.defaultKeyFormatter(), true); @Override public String codecName() { return getCodecName(this.getClass()); } @Override public boolean support(MediaType mediaType) { return mediaType.equals(MediaType.APPLICATION_JSON_TYPE); } @Override public <T> String encode(T object) throws IOException { return codec.getObjectMapper(object.getClass()).writeValueAsString(object); } @Override public <T> void encode(T object, OutputStream outputStream) throws IOException { codec.writeTo(object, outputStream); } @Override public <T> T decode(String textValue, Class<T> type) throws IOException { return codec.getObjectMapper(type).readValue(textValue, type); } @Override public <T> T decode(InputStream inputStream, Class<T> type) throws IOException { return codec.getObjectMapper(type).readValue(inputStream, type); } } public static class JacksonXml implements CodecWrapper { protected final EurekaXmlJacksonCodec codec = new EurekaXmlJacksonCodec(); @Override public String codecName() { return getCodecName(this.getClass()); } @Override public boolean support(MediaType mediaType) { return mediaType.equals(MediaType.APPLICATION_XML_TYPE); } @Override public <T> String encode(T object) throws IOException { return codec.getObjectMapper(object.getClass()).writeValueAsString(object); } @Override public <T> void encode(T object, OutputStream outputStream) throws IOException { codec.writeTo(object, outputStream); } @Override public <T> T decode(String textValue, Class<T> type) throws IOException { return codec.getObjectMapper(type).readValue(textValue, type); } @Override public <T> T decode(InputStream inputStream, Class<T> type) throws IOException { return codec.getObjectMapper(type).readValue(inputStream, type); } } public static class JacksonXmlMini implements CodecWrapper { protected final EurekaXmlJacksonCodec codec = new EurekaXmlJacksonCodec(KeyFormatter.defaultKeyFormatter(), true); @Override public String codecName() { return getCodecName(this.getClass()); } @Override public boolean support(MediaType mediaType) { return mediaType.equals(MediaType.APPLICATION_XML_TYPE); } @Override public <T> String encode(T object) throws IOException { return codec.getObjectMapper(object.getClass()).writeValueAsString(object); } @Override public <T> void encode(T object, OutputStream outputStream) throws IOException { codec.writeTo(object, outputStream); } @Override public <T> T decode(String textValue, Class<T> type) throws IOException { return codec.getObjectMapper(type).readValue(textValue, type); } @Override public <T> T decode(InputStream inputStream, Class<T> type) throws IOException { return codec.getObjectMapper(type).readValue(inputStream, type); } } public static class LegacyJacksonJson implements CodecWrapper { protected final EurekaJacksonCodec codec = new EurekaJacksonCodec(); @Override public String codecName() { return getCodecName(this.getClass()); } @Override public boolean support(MediaType mediaType) { return mediaType.equals(MediaType.APPLICATION_JSON_TYPE); } @Override public <T> String encode(T object) throws IOException { return codec.writeToString(object); } @Override public <T> void encode(T object, OutputStream outputStream) throws IOException { codec.writeTo(object, outputStream); } @Override public <T> T decode(String textValue, Class<T> type) throws IOException { return codec.readValue(type, textValue); } @Override public <T> T decode(InputStream inputStream, Class<T> type) throws IOException { return codec.readValue(type, inputStream); } } public static class XStreamJson implements CodecWrapper { protected final JsonXStream codec = JsonXStream.getInstance(); @Override public String codecName() { return getCodecName(this.getClass()); } @Override public boolean support(MediaType mediaType) { return mediaType.equals(MediaType.APPLICATION_JSON_TYPE); } @Override public <T> String encode(T object) throws IOException { return codec.toXML(object); } @Override public <T> void encode(T object, OutputStream outputStream) throws IOException { codec.toXML(object, outputStream); } @Override public <T> T decode(String textValue, Class<T> type) throws IOException { return (T) codec.fromXML(textValue, type); } @Override public <T> T decode(InputStream inputStream, Class<T> type) throws IOException { return (T) codec.fromXML(inputStream, type); } } /** * @author David Liu */ public static class XStreamXml implements CodecWrapper { protected final XmlXStream codec = XmlXStream.getInstance(); @Override public String codecName() { return CodecWrappers.getCodecName(this.getClass()); } @Override public boolean support(MediaType mediaType) { return mediaType.equals(MediaType.APPLICATION_XML_TYPE); } @Override public <T> String encode(T object) throws IOException { return codec.toXML(object); } @Override public <T> void encode(T object, OutputStream outputStream) throws IOException { codec.toXML(object, outputStream); } @Override public <T> T decode(String textValue, Class<T> type) throws IOException { return (T) codec.fromXML(textValue, type); } @Override public <T> T decode(InputStream inputStream, Class<T> type) throws IOException { return (T) codec.fromXML(inputStream, type); } } }
6,734
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson/DataCenterTypeInfoResolver.java
package com.netflix.discovery.converters.jackson; import com.fasterxml.jackson.databind.DatabindContext; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.jsontype.impl.ClassNameIdResolver; import com.fasterxml.jackson.databind.type.TypeFactory; import com.netflix.appinfo.AmazonInfo; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.MyDataCenterInfo; import java.io.IOException; /** * @author Tomasz Bak */ public class DataCenterTypeInfoResolver extends ClassNameIdResolver { /** * This phantom class name is kept for backwards compatibility. Internally it is mapped to * {@link MyDataCenterInfo} during the deserialization process. */ public static final String MY_DATA_CENTER_INFO_TYPE_MARKER = "com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo"; public DataCenterTypeInfoResolver() { super(TypeFactory.defaultInstance().constructType(DataCenterInfo.class), TypeFactory.defaultInstance()); } @Override public JavaType typeFromId(DatabindContext context, String id) throws IOException { if (MY_DATA_CENTER_INFO_TYPE_MARKER.equals(id)) { return context.getTypeFactory().constructType(MyDataCenterInfo.class); } return super.typeFromId(context, id); } @Override public String idFromValue(Object value) { if (value.getClass().equals(AmazonInfo.class)) { return AmazonInfo.class.getName(); } return MY_DATA_CENTER_INFO_TYPE_MARKER; } }
6,735
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson/EurekaXmlJacksonCodec.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.converters.jackson; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.converters.KeyFormatter; import com.netflix.discovery.converters.jackson.mixin.ApplicationXmlMixIn; import com.netflix.discovery.converters.jackson.mixin.ApplicationsXmlMixIn; import com.netflix.discovery.converters.jackson.mixin.DataCenterInfoXmlMixIn; import com.netflix.discovery.converters.jackson.mixin.PortWrapperXmlMixIn; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; /** * @author Tomasz Bak */ public class EurekaXmlJacksonCodec extends AbstractEurekaJacksonCodec { private final XmlMapper xmlMapper; public EurekaXmlJacksonCodec() { this(KeyFormatter.defaultKeyFormatter(), false); } public EurekaXmlJacksonCodec(final KeyFormatter keyFormatter, boolean compact) { xmlMapper = new XmlMapper() { public ObjectMapper registerModule(Module module) { setSerializerFactory( getSerializerFactory().withSerializerModifier(EurekaJacksonXmlModifiers.createXmlSerializerModifier(keyFormatter)) ); return super.registerModule(module); } }; xmlMapper.setSerializationInclusion(Include.NON_NULL); xmlMapper.addMixIn(DataCenterInfo.class, DataCenterInfoXmlMixIn.class); xmlMapper.addMixIn(InstanceInfo.PortWrapper.class, PortWrapperXmlMixIn.class); xmlMapper.addMixIn(Application.class, ApplicationXmlMixIn.class); xmlMapper.addMixIn(Applications.class, ApplicationsXmlMixIn.class); SimpleModule xmlModule = new SimpleModule(); xmlMapper.registerModule(xmlModule); if (compact) { addMiniConfig(xmlMapper); } } @Override public <T> ObjectMapper getObjectMapper(Class<T> type) { return xmlMapper; } }
6,736
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson/EurekaJacksonXmlModifiers.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.converters.jackson; import com.fasterxml.jackson.databind.BeanDescription; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializationConfig; import com.fasterxml.jackson.databind.ser.BeanSerializerModifier; import com.fasterxml.jackson.databind.ser.std.BeanSerializerBase; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.converters.KeyFormatter; import com.netflix.discovery.converters.jackson.serializer.ApplicationsXmlBeanSerializer; import com.netflix.discovery.converters.jackson.serializer.InstanceInfoXmlBeanSerializer; import com.netflix.discovery.shared.Applications; /** * @author Tomasz Bak */ public final class EurekaJacksonXmlModifiers { private EurekaJacksonXmlModifiers() { } public static BeanSerializerModifier createXmlSerializerModifier(final KeyFormatter keyFormatter) { return new BeanSerializerModifier() { @Override public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) { if (beanDesc.getBeanClass().isAssignableFrom(Applications.class)) { return new ApplicationsXmlBeanSerializer((BeanSerializerBase) serializer, keyFormatter); } if (beanDesc.getBeanClass().isAssignableFrom(InstanceInfo.class)) { return new InstanceInfoXmlBeanSerializer((BeanSerializerBase) serializer); } return serializer; } }; } }
6,737
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson/EurekaJacksonJsonModifiers.java
package com.netflix.discovery.converters.jackson; import com.fasterxml.jackson.databind.BeanDescription; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializationConfig; import com.fasterxml.jackson.databind.ser.BeanSerializerModifier; import com.fasterxml.jackson.databind.ser.std.BeanSerializerBase; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.converters.KeyFormatter; import com.netflix.discovery.converters.jackson.serializer.ApplicationsJsonBeanSerializer; import com.netflix.discovery.converters.jackson.serializer.InstanceInfoJsonBeanSerializer; import com.netflix.discovery.shared.Applications; /** * @author Tomasz Bak */ final class EurekaJacksonJsonModifiers { private EurekaJacksonJsonModifiers() { } public static BeanSerializerModifier createJsonSerializerModifier(final KeyFormatter keyFormatter, final boolean compactMode) { return new BeanSerializerModifier() { @Override public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) { if (beanDesc.getBeanClass().isAssignableFrom(Applications.class)) { return new ApplicationsJsonBeanSerializer((BeanSerializerBase) serializer, keyFormatter); } if (beanDesc.getBeanClass().isAssignableFrom(InstanceInfo.class)) { return new InstanceInfoJsonBeanSerializer((BeanSerializerBase) serializer, compactMode); } return serializer; } }; } }
6,738
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson/EurekaJsonJacksonCodec.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.converters.jackson; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.module.SimpleModule; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.converters.KeyFormatter; import com.netflix.discovery.converters.jackson.mixin.ApplicationsJsonMixIn; import com.netflix.discovery.converters.jackson.mixin.InstanceInfoJsonMixIn; import com.netflix.discovery.shared.Applications; /** * JSON codec defaults to unwrapped mode, as ReplicationList in the replication channel, must be serialized * unwrapped. The wrapping mode is configured separately for each type, based on presence of * {@link com.fasterxml.jackson.annotation.JsonRootName} annotation. * * @author Tomasz Bak */ public class EurekaJsonJacksonCodec extends AbstractEurekaJacksonCodec { private final ObjectMapper wrappedJsonMapper; private final ObjectMapper unwrappedJsonMapper; private final Map<Class<?>, ObjectMapper> mappers = new ConcurrentHashMap<>(); public EurekaJsonJacksonCodec() { this(KeyFormatter.defaultKeyFormatter(), false); } public EurekaJsonJacksonCodec(final KeyFormatter keyFormatter, boolean compact) { this.unwrappedJsonMapper = createObjectMapper(keyFormatter, compact, false); this.wrappedJsonMapper = createObjectMapper(keyFormatter, compact, true); } private ObjectMapper createObjectMapper(KeyFormatter keyFormatter, boolean compact, boolean wrapped) { ObjectMapper newMapper = new ObjectMapper(); SimpleModule jsonModule = new SimpleModule(); jsonModule.setSerializerModifier(EurekaJacksonJsonModifiers.createJsonSerializerModifier(keyFormatter, compact)); newMapper.registerModule(jsonModule); newMapper.setSerializationInclusion(Include.NON_NULL); newMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, wrapped); newMapper.configure(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED, false); newMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, wrapped); newMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); newMapper.addMixIn(Applications.class, ApplicationsJsonMixIn.class); if (compact) { addMiniConfig(newMapper); } else { newMapper.addMixIn(InstanceInfo.class, InstanceInfoJsonMixIn.class); } return newMapper; } @Override public <T> ObjectMapper getObjectMapper(Class<T> type) { ObjectMapper mapper = mappers.get(type); if (mapper == null) { mapper = hasJsonRootName(type) ? wrappedJsonMapper : unwrappedJsonMapper; mappers.put(type, mapper); } return mapper; } }
6,739
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson/AbstractEurekaJacksonCodec.java
package com.netflix.discovery.converters.jackson; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; import java.util.HashSet; import java.util.Map; import java.util.Set; import com.fasterxml.jackson.annotation.JsonRootName; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.introspect.Annotated; import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; import com.fasterxml.jackson.databind.ser.BeanPropertyWriter; import com.fasterxml.jackson.databind.ser.PropertyWriter; import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.converters.jackson.mixin.MiniInstanceInfoMixIn; /** * @author Tomasz Bak */ public abstract class AbstractEurekaJacksonCodec { protected static final Set<String> MINI_AMAZON_INFO_INCLUDE_KEYS = new HashSet<>( Arrays.asList("instance-id", "public-ipv4", "public-hostname", "local-ipv4", "availability-zone") ); public abstract <T> ObjectMapper getObjectMapper(Class<T> type); public <T> void writeTo(T object, OutputStream entityStream) throws IOException { getObjectMapper(object.getClass()).writeValue(entityStream, object); } protected void addMiniConfig(ObjectMapper mapper) { mapper.addMixIn(InstanceInfo.class, MiniInstanceInfoMixIn.class); bindAmazonInfoFilter(mapper); } private void bindAmazonInfoFilter(ObjectMapper mapper) { SimpleFilterProvider filters = new SimpleFilterProvider(); final String filterName = "exclude-amazon-info-entries"; mapper.setAnnotationIntrospector(new JacksonAnnotationIntrospector() { @Override public Object findFilterId(Annotated a) { if (Map.class.isAssignableFrom(a.getRawType())) { return filterName; } return super.findFilterId(a); } }); filters.addFilter(filterName, new SimpleBeanPropertyFilter() { @Override protected boolean include(BeanPropertyWriter writer) { return true; } @Override protected boolean include(PropertyWriter writer) { return MINI_AMAZON_INFO_INCLUDE_KEYS.contains(writer.getName()); } }); mapper.setFilters(filters); } static boolean hasJsonRootName(Class<?> type) { return type.getAnnotation(JsonRootName.class) != null; } }
6,740
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson/serializer/PortWrapperXmlDeserializer.java
/* * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery.converters.jackson.serializer; import java.io.IOException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.netflix.appinfo.InstanceInfo; /** * Due to issues with properly mapping port XML sub-document, handle deserialization directly. */ public class PortWrapperXmlDeserializer extends StdDeserializer<InstanceInfo.PortWrapper> { public PortWrapperXmlDeserializer() { super(InstanceInfo.PortWrapper.class); } @Override public InstanceInfo.PortWrapper deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { boolean enabled = false; int port = 0; while (jp.nextToken() == JsonToken.FIELD_NAME) { String fieldName = jp.getCurrentName(); jp.nextToken(); // to point to value if ("enabled".equals(fieldName)) { enabled = Boolean.valueOf(jp.getValueAsString()); } else if (fieldName == null || "".equals(fieldName)) { String value = jp.getValueAsString(); port = value == null ? 0 : Integer.parseInt(value); } else { throw new JsonMappingException("Unexpected field " + fieldName, jp.getCurrentLocation()); } } return new InstanceInfo.PortWrapper(enabled, port); } }
6,741
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson/serializer/InstanceInfoJsonBeanSerializer.java
/* * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery.converters.jackson.serializer; import java.io.IOException; import java.util.Collections; import java.util.Map; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.BeanSerializer; import com.fasterxml.jackson.databind.ser.std.BeanSerializerBase; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.PortType; /** * Custom bean serializer to deal with legacy port layout (check {@link InstanceInfo.PortWrapper} for more information). */ public class InstanceInfoJsonBeanSerializer extends BeanSerializer { private static final Map<String, String> EMPTY_MAP = Collections.singletonMap("@class", "java.util.Collections$EmptyMap"); /** * As root mapper is wrapping values, we need a dedicated instance for map serialization. */ private final ObjectMapper stringMapObjectMapper = new ObjectMapper(); private final boolean compactMode; public InstanceInfoJsonBeanSerializer(BeanSerializerBase src, boolean compactMode) { super(src); this.compactMode = compactMode; } @Override protected void serializeFields(Object bean, JsonGenerator jgen0, SerializerProvider provider) throws IOException { super.serializeFields(bean, jgen0, provider); InstanceInfo instanceInfo = (InstanceInfo) bean; jgen0.writeFieldName("port"); jgen0.writeStartObject(); jgen0.writeNumberField("$", instanceInfo.getPort()); jgen0.writeStringField("@enabled", Boolean.toString(instanceInfo.isPortEnabled(PortType.UNSECURE))); jgen0.writeEndObject(); jgen0.writeFieldName("securePort"); jgen0.writeStartObject(); jgen0.writeNumberField("$", instanceInfo.getSecurePort()); jgen0.writeStringField("@enabled", Boolean.toString(instanceInfo.isPortEnabled(PortType.SECURE))); jgen0.writeEndObject(); // Save @class field for backward compatibility. Remove once all clients are migrated to the new codec if (!compactMode) { jgen0.writeFieldName("metadata"); if (instanceInfo.getMetadata() == null || instanceInfo.getMetadata().isEmpty()) { stringMapObjectMapper.writeValue(jgen0, EMPTY_MAP); } else { stringMapObjectMapper.writeValue(jgen0, instanceInfo.getMetadata()); } } } }
6,742
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson/serializer/ApplicationsJsonBeanSerializer.java
/* * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery.converters.jackson.serializer; import java.io.IOException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.BeanSerializer; import com.fasterxml.jackson.databind.ser.std.BeanSerializerBase; import com.netflix.discovery.converters.KeyFormatter; import com.netflix.discovery.shared.Applications; /** * Support custom formatting of {@link Applications#appsHashCode} and {@link Applications#versionDelta}. */ public class ApplicationsJsonBeanSerializer extends BeanSerializer { private final String versionKey; private final String appsHashCodeKey; public ApplicationsJsonBeanSerializer(BeanSerializerBase src, KeyFormatter keyFormatter) { super(src); versionKey = keyFormatter.formatKey("versions_delta"); appsHashCodeKey = keyFormatter.formatKey("apps_hashcode"); } @Override protected void serializeFields(Object bean, JsonGenerator jgen0, SerializerProvider provider) throws IOException { super.serializeFields(bean, jgen0, provider); Applications applications = (Applications) bean; if (applications.getVersion() != null) { jgen0.writeStringField(versionKey, Long.toString(applications.getVersion())); } if (applications.getAppsHashCode() != null) { jgen0.writeStringField(appsHashCodeKey, applications.getAppsHashCode()); } } }
6,743
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson/serializer/ApplicationsXmlBeanSerializer.java
/* * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery.converters.jackson.serializer; import java.io.IOException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.BeanSerializerBase; import com.fasterxml.jackson.dataformat.xml.ser.XmlBeanSerializer; import com.netflix.discovery.converters.KeyFormatter; import com.netflix.discovery.shared.Applications; /** * Support custom formatting of {@link Applications#appsHashCode} and {@link Applications#versionDelta}. */ public class ApplicationsXmlBeanSerializer extends XmlBeanSerializer { private final String versionKey; private final String appsHashCodeKey; public ApplicationsXmlBeanSerializer(BeanSerializerBase src, KeyFormatter keyFormatter) { super(src); versionKey = keyFormatter.formatKey("versions_delta"); appsHashCodeKey = keyFormatter.formatKey("apps_hashcode"); } @Override protected void serializeFields(Object bean, JsonGenerator jgen0, SerializerProvider provider) throws IOException { super.serializeFields(bean, jgen0, provider); Applications applications = (Applications) bean; if (applications.getVersion() != null) { jgen0.writeStringField(versionKey, Long.toString(applications.getVersion())); } if (applications.getAppsHashCode() != null) { jgen0.writeStringField(appsHashCodeKey, applications.getAppsHashCode()); } } }
6,744
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson/serializer/ApplicationXmlDeserializer.java
/* * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery.converters.jackson.serializer; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.shared.Application; /** * Deserialize {@link Application} from XML directly due to issues with Jackson 2.6.x * (this is not needed for Jackson 2.5.x). */ public class ApplicationXmlDeserializer extends StdDeserializer<Application> { public ApplicationXmlDeserializer() { super(Application.class); } @Override public Application deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { String name = null; List<InstanceInfo> instances = new ArrayList<>(); while (jp.nextToken() == JsonToken.FIELD_NAME) { String fieldName = jp.getCurrentName(); jp.nextToken(); // to point to value if ("name".equals(fieldName)) { name = jp.getValueAsString(); } else if ("instance".equals(fieldName)) { instances.add(jp.readValueAs(InstanceInfo.class)); } else { throw new JsonMappingException("Unexpected field " + fieldName, jp.getCurrentLocation()); } } return new Application(name, instances); } }
6,745
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson/serializer/InstanceInfoXmlBeanSerializer.java
/* * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery.converters.jackson.serializer; import java.io.IOException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.BeanSerializerBase; import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator; import com.fasterxml.jackson.dataformat.xml.ser.XmlBeanSerializer; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.PortType; /** * Custom bean serializer to deal with legacy port layout (check {@link InstanceInfo.PortWrapper} for more information). */ public class InstanceInfoXmlBeanSerializer extends XmlBeanSerializer { public InstanceInfoXmlBeanSerializer(BeanSerializerBase src) { super(src); } @Override protected void serializeFields(Object bean, JsonGenerator jgen0, SerializerProvider provider) throws IOException { super.serializeFields(bean, jgen0, provider); InstanceInfo instanceInfo = (InstanceInfo) bean; ToXmlGenerator xgen = (ToXmlGenerator) jgen0; xgen.writeFieldName("port"); xgen.writeStartObject(); xgen.setNextIsAttribute(true); xgen.writeFieldName("enabled"); xgen.writeBoolean(instanceInfo.isPortEnabled(PortType.UNSECURE)); xgen.setNextIsAttribute(false); xgen.writeFieldName("port"); xgen.setNextIsUnwrapped(true); xgen.writeString(Integer.toString(instanceInfo.getPort())); xgen.writeEndObject(); xgen.writeFieldName("securePort"); xgen.writeStartObject(); xgen.setNextIsAttribute(true); xgen.writeStringField("enabled", Boolean.toString(instanceInfo.isPortEnabled(PortType.SECURE))); xgen.setNextIsAttribute(false); xgen.writeFieldName("securePort"); xgen.setNextIsUnwrapped(true); xgen.writeString(Integer.toString(instanceInfo.getSecurePort())); xgen.writeEndObject(); } }
6,746
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson/mixin/ApplicationsJsonMixIn.java
/* * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery.converters.jackson.mixin; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.netflix.discovery.converters.jackson.builder.ApplicationsJacksonBuilder; /** * Attach custom builder that deals with configurable property name formatting. */ @JsonDeserialize(builder = ApplicationsJacksonBuilder.class) public class ApplicationsJsonMixIn { }
6,747
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson/mixin/ApplicationsXmlMixIn.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.converters.jackson.mixin; import java.util.List; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.netflix.discovery.converters.jackson.builder.ApplicationsXmlJacksonBuilder; import com.netflix.discovery.shared.Application; /** * Attach custom builder that deals with configurable property name formatting. * {@link Application} objects are unwrapped in XML document. The necessary Jackson instrumentation is provided here. */ @JsonDeserialize(builder = ApplicationsXmlJacksonBuilder.class) public interface ApplicationsXmlMixIn { @JacksonXmlElementWrapper(useWrapping = false) List<Application> getRegisteredApplications(); }
6,748
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson/mixin/InstanceInfoJsonMixIn.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.converters.jackson.mixin; import java.util.Map; import com.fasterxml.jackson.annotation.JsonIgnore; import com.netflix.discovery.converters.jackson.serializer.InstanceInfoJsonBeanSerializer; /** * Meta data are handled directly by {@link InstanceInfoJsonBeanSerializer}, for backwards compatibility reasons. */ public interface InstanceInfoJsonMixIn { @JsonIgnore Map<String, String> getMetadata(); }
6,749
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson/mixin/DataCenterInfoXmlMixIn.java
package com.netflix.discovery.converters.jackson.mixin; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeInfo.As; /** * @author Tomasz Bak */ @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = As.PROPERTY, property = "class") public interface DataCenterInfoXmlMixIn { }
6,750
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson/mixin/MiniInstanceInfoMixIn.java
package com.netflix.discovery.converters.jackson.mixin; import java.util.Map; import com.fasterxml.jackson.annotation.JsonIgnore; import com.netflix.appinfo.InstanceInfo.InstanceStatus; import com.netflix.appinfo.LeaseInfo; /** * @author Tomasz Bak */ public interface MiniInstanceInfoMixIn { // define fields are are ignored for mini-InstanceInfo @JsonIgnore String getAppGroupName(); @JsonIgnore InstanceStatus getOverriddenStatus(); @JsonIgnore String getSID(); @JsonIgnore int getCountryId(); @JsonIgnore String getHomePageUrl(); @JsonIgnore String getStatusPageUrl(); @JsonIgnore String getHealthCheckUrl(); @JsonIgnore String getSecureHealthCheckUrl(); @JsonIgnore boolean isCoordinatingDiscoveryServer(); @JsonIgnore Long getLastDirtyTimestamp(); @JsonIgnore LeaseInfo getLeaseInfo(); @JsonIgnore Map<String, String> getMetadata(); }
6,751
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson/mixin/PortWrapperXmlMixIn.java
/* * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery.converters.jackson.mixin; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.netflix.discovery.converters.jackson.serializer.PortWrapperXmlDeserializer; /** * Add custom XML deserializer, due to issue with annotations based mapping in some Jackson versions. */ @JsonDeserialize(using = PortWrapperXmlDeserializer.class) public interface PortWrapperXmlMixIn { }
6,752
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson/mixin/ApplicationXmlMixIn.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.converters.jackson.mixin; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.converters.jackson.serializer.ApplicationXmlDeserializer; /** * {@link InstanceInfo} objects are unwrapped in XML document. The necessary Jackson instrumentation is provided here. */ @JsonDeserialize(using = ApplicationXmlDeserializer.class) public interface ApplicationXmlMixIn { @JacksonXmlElementWrapper(useWrapping = false) @JsonProperty("instance") List<InstanceInfo> getInstances(); }
6,753
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson/builder/ApplicationsXmlJacksonBuilder.java
/* * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery.converters.jackson.builder; import java.util.List; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.netflix.discovery.shared.Application; /** * Add XML specific annotation to {@link ApplicationsJacksonBuilder}. */ public class ApplicationsXmlJacksonBuilder extends ApplicationsJacksonBuilder { @Override @JacksonXmlElementWrapper(useWrapping = false) public void withApplication(List<Application> applications) { super.withApplication(applications); } }
6,754
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson/builder/StringInterningAmazonInfoBuilder.java
/* * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery.converters.jackson.builder; import java.io.IOException; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.netflix.appinfo.AmazonInfo; import com.netflix.appinfo.AmazonInfo.MetaDataKey; import com.netflix.appinfo.DataCenterInfo.Name; import com.netflix.discovery.converters.EnumLookup; import com.netflix.discovery.converters.EurekaJacksonCodec; import com.netflix.discovery.util.DeserializerStringCache; import com.netflix.discovery.util.DeserializerStringCache.CacheScope; import com.netflix.discovery.util.StringCache; /** * Amazon instance info builder that is doing key names interning, together with * value interning for selected keys (see {@link StringInterningAmazonInfoBuilder#VALUE_INTERN_KEYS}). * * The amount of string objects that is interned here is very limited in scope, and is done by calling * {@link String#intern()}, with no custom build string cache. * * @author Tomasz Bak */ public class StringInterningAmazonInfoBuilder extends JsonDeserializer<AmazonInfo>{ private static final Map<String, CacheScope> VALUE_INTERN_KEYS; private static final char[] BUF_METADATA = "metadata".toCharArray(); static { HashMap<String, CacheScope> keys = new HashMap<>(); keys.put(MetaDataKey.accountId.getName(), CacheScope.GLOBAL_SCOPE); keys.put(MetaDataKey.amiId.getName(), CacheScope.GLOBAL_SCOPE); keys.put(MetaDataKey.availabilityZone.getName(), CacheScope.GLOBAL_SCOPE); keys.put(MetaDataKey.instanceType.getName(), CacheScope.GLOBAL_SCOPE); keys.put(MetaDataKey.vpcId.getName(), CacheScope.GLOBAL_SCOPE); keys.put(MetaDataKey.publicIpv4.getName(), CacheScope.APPLICATION_SCOPE); keys.put(MetaDataKey.localHostname.getName(), CacheScope.APPLICATION_SCOPE); VALUE_INTERN_KEYS = keys; } private HashMap<String, String> metadata; public StringInterningAmazonInfoBuilder withName(String name) { return this; } public StringInterningAmazonInfoBuilder withMetadata(HashMap<String, String> metadata) { this.metadata = metadata; if (metadata.isEmpty()) { return this; } for (Map.Entry<String, String> entry : metadata.entrySet()) { String key = entry.getKey().intern(); if (VALUE_INTERN_KEYS.containsKey(key)) { entry.setValue(StringCache.intern(entry.getValue())); } } return this; } public AmazonInfo build() { return new AmazonInfo(Name.Amazon.name(), metadata); } private boolean isEndOfObjectOrInput(JsonToken token) { return token == null || token == JsonToken.END_OBJECT; } private boolean skipToMetadata(JsonParser jp) throws IOException { JsonToken token = jp.getCurrentToken(); while (!isEndOfObjectOrInput(token)) { if (token == JsonToken.FIELD_NAME && EnumLookup.equals(BUF_METADATA, jp.getTextCharacters(), jp.getTextOffset(), jp.getTextLength())) { return true; } token = jp.nextToken(); } return false; } private void skipToEnd(JsonParser jp) throws IOException { JsonToken token = jp.getCurrentToken(); while (!isEndOfObjectOrInput(token)) { token = jp.nextToken(); } } @Override public AmazonInfo deserialize(JsonParser jp, DeserializationContext context) throws IOException { Map<String,String> metadata = EurekaJacksonCodec.METADATA_MAP_SUPPLIER.get(); DeserializerStringCache intern = DeserializerStringCache.from(context); if (skipToMetadata(jp)) { JsonToken jsonToken = jp.nextToken(); while((jsonToken = jp.nextToken()) != JsonToken.END_OBJECT) { String metadataKey = intern.apply(jp, CacheScope.GLOBAL_SCOPE); jp.nextToken(); CacheScope scope = VALUE_INTERN_KEYS.get(metadataKey); String metadataValue = (scope != null) ? intern.apply(jp, scope) : intern.apply(jp, CacheScope.APPLICATION_SCOPE); metadata.put(metadataKey, metadataValue); } skipToEnd(jp); } if (jp.getCurrentToken() == JsonToken.END_OBJECT) { jp.nextToken(); } return new AmazonInfo(Name.Amazon.name(), metadata); } }
6,755
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/converters/jackson/builder/ApplicationsJacksonBuilder.java
/* * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.discovery.converters.jackson.builder; import java.util.List; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonProperty; import com.netflix.discovery.converters.KeyFormatter; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Support custom formatting of {@link Applications#appsHashCode} and {@link Applications#versionDelta}. The * serialized property name is generated by {@link KeyFormatter} according to provided configuration. We can * depend here on fixed prefix to distinguish between property values, and map them correctly. */ public class ApplicationsJacksonBuilder { private static final Logger logger = LoggerFactory.getLogger(ApplicationsJacksonBuilder.class); private List<Application> applications; private long version; private String appsHashCode; @JsonProperty("application") public void withApplication(List<Application> applications) { this.applications = applications; } @JsonAnySetter public void with(String fieldName, Object value) { if (fieldName == null || value == null) { return; } if (fieldName.startsWith("version")) { try { version = value instanceof Number ? ((Number) value).longValue() : Long.parseLong((String) value); } catch (Exception e) { version = -1; logger.warn("Cannot parse version number {}; setting it to default == -1", value); } } else if (fieldName.startsWith("apps")) { if (value instanceof String) { appsHashCode = (String) value; } else { logger.warn("appsHashCode field is not a string, but {}", value.getClass()); } } } public Applications build() { return new Applications(appsHashCode, version, applications); } }
6,756
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/Application.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 javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Random; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicReference; 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.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.InstanceStatus; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.InstanceRegionChecker; import com.netflix.discovery.provider.Serializer; import com.netflix.discovery.util.StringCache; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamImplicit; import com.thoughtworks.xstream.annotations.XStreamOmitField; /** * The application class holds the list of instances for a particular * application. * * @author Karthik Ranganathan * */ @Serializer("com.netflix.discovery.converters.EntityBodyConverter") @XStreamAlias("application") @JsonRootName("application") public class Application { private static Random shuffleRandom = new Random(); @Override public String toString() { return "Application [name=" + name + ", isDirty=" + isDirty + ", instances=" + instances + ", shuffledInstances=" + shuffledInstances + ", instancesMap=" + instancesMap + "]"; } private String name; @XStreamOmitField private volatile boolean isDirty = false; @XStreamImplicit private final Set<InstanceInfo> instances; private final AtomicReference<List<InstanceInfo>> shuffledInstances; private final Map<String, InstanceInfo> instancesMap; public Application() { instances = new LinkedHashSet<InstanceInfo>(); instancesMap = new ConcurrentHashMap<String, InstanceInfo>(); shuffledInstances = new AtomicReference<List<InstanceInfo>>(); } public Application(String name) { this(); this.name = StringCache.intern(name); } @JsonCreator public Application( @JsonProperty("name") String name, @JsonProperty("instance") List<InstanceInfo> instances) { this(name); for (InstanceInfo instanceInfo : instances) { addInstance(instanceInfo); } } /** * Add the given instance info the list. * * @param i * the instance info object to be added. */ public void addInstance(InstanceInfo i) { instancesMap.put(i.getId(), i); synchronized (instances) { instances.remove(i); instances.add(i); isDirty = true; } } /** * Remove the given instance info the list. * * @param i * the instance info object to be removed. */ public void removeInstance(InstanceInfo i) { removeInstance(i, true); } /** * Gets the list of instances associated with this particular application. * <p> * Note that the instances are always returned with random order after * shuffling to avoid traffic to the same instances during startup. The * shuffling always happens once after every fetch cycle as specified in * {@link EurekaClientConfig#getRegistryFetchIntervalSeconds}. * </p> * * @return the list of shuffled instances associated with this application. */ @JsonProperty("instance") public List<InstanceInfo> getInstances() { return Optional.ofNullable(shuffledInstances.get()).orElseGet(this::getInstancesAsIsFromEureka); } /** * Gets the list of non-shuffled and non-filtered instances associated with this particular * application. * * @return list of non-shuffled and non-filtered instances associated with this particular * application. */ @JsonIgnore public List<InstanceInfo> getInstancesAsIsFromEureka() { synchronized (instances) { return new ArrayList<InstanceInfo>(this.instances); } } /** * Get the instance info that matches the given id. * * @param id * the id for which the instance info needs to be returned. * @return the instance info object. */ public InstanceInfo getByInstanceId(String id) { return instancesMap.get(id); } /** * Gets the name of the application. * * @return the name of the application. */ public String getName() { return name; } /** * Sets the name of the application. * * @param name * the name of the application. */ public void setName(String name) { this.name = StringCache.intern(name); } /** * @return the number of instances in this application */ public int size() { return instances.size(); } /** * Shuffles the list of instances in the application and stores it for * future retrievals. * * @param filterUpInstances * indicates whether only the instances with status * {@link InstanceStatus#UP} needs to be stored. */ public void shuffleAndStoreInstances(boolean filterUpInstances) { _shuffleAndStoreInstances(filterUpInstances, false, null, null, null); } public void shuffleAndStoreInstances(Map<String, Applications> remoteRegionsRegistry, EurekaClientConfig clientConfig, InstanceRegionChecker instanceRegionChecker) { _shuffleAndStoreInstances(clientConfig.shouldFilterOnlyUpInstances(), true, remoteRegionsRegistry, clientConfig, instanceRegionChecker); } private void _shuffleAndStoreInstances(boolean filterUpInstances, boolean indexByRemoteRegions, @Nullable Map<String, Applications> remoteRegionsRegistry, @Nullable EurekaClientConfig clientConfig, @Nullable InstanceRegionChecker instanceRegionChecker) { List<InstanceInfo> instanceInfoList; synchronized (instances) { instanceInfoList = new ArrayList<InstanceInfo>(instances); } boolean remoteIndexingActive = indexByRemoteRegions && null != instanceRegionChecker && null != clientConfig && null != remoteRegionsRegistry; if (remoteIndexingActive || filterUpInstances) { Iterator<InstanceInfo> it = instanceInfoList.iterator(); while (it.hasNext()) { InstanceInfo instanceInfo = it.next(); if (filterUpInstances && InstanceStatus.UP != instanceInfo.getStatus()) { it.remove(); } else if (remoteIndexingActive) { String instanceRegion = instanceRegionChecker.getInstanceRegion(instanceInfo); if (!instanceRegionChecker.isLocalRegion(instanceRegion)) { Applications appsForRemoteRegion = remoteRegionsRegistry.get(instanceRegion); if (null == appsForRemoteRegion) { appsForRemoteRegion = new Applications(); remoteRegionsRegistry.put(instanceRegion, appsForRemoteRegion); } Application remoteApp = appsForRemoteRegion.getRegisteredApplications(instanceInfo.getAppName()); if (null == remoteApp) { remoteApp = new Application(instanceInfo.getAppName()); appsForRemoteRegion.addApplication(remoteApp); } remoteApp.addInstance(instanceInfo); this.removeInstance(instanceInfo, false); it.remove(); } } } } Collections.shuffle(instanceInfoList, shuffleRandom); this.shuffledInstances.set(instanceInfoList); } private void removeInstance(InstanceInfo i, boolean markAsDirty) { instancesMap.remove(i.getId()); synchronized (instances) { instances.remove(i); if (markAsDirty) { isDirty = true; } } } }
6,757
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/Applications.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 javax.annotation.Nullable; import java.util.AbstractQueue; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.Random; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; 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.annotation.JsonRootName; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.InstanceStatus; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.InstanceRegionChecker; import com.netflix.discovery.provider.Serializer; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamImplicit; /** * The class that wraps all the registry information returned by eureka server. * * <p> * Note that the registry information is fetched from eureka server as specified * in {@link EurekaClientConfig#getRegistryFetchIntervalSeconds()}. Once the * information is fetched it is shuffled and also filtered for instances with * {@link InstanceStatus#UP} status as specified by the configuration * {@link EurekaClientConfig#shouldFilterOnlyUpInstances()}. * </p> * * @author Karthik Ranganathan * */ @Serializer("com.netflix.discovery.converters.EntityBodyConverter") @XStreamAlias("applications") @JsonRootName("applications") public class Applications { private static class VipIndexSupport { final AbstractQueue<InstanceInfo> instances = new ConcurrentLinkedQueue<>(); final AtomicLong roundRobinIndex = new AtomicLong(0); final AtomicReference<List<InstanceInfo>> vipList = new AtomicReference<>(Collections.emptyList()); public AtomicLong getRoundRobinIndex() { return roundRobinIndex; } public AtomicReference<List<InstanceInfo>> getVipList() { return vipList; } } private static final String STATUS_DELIMITER = "_"; private String appsHashCode; private Long versionDelta; @XStreamImplicit private final AbstractQueue<Application> applications; private final Map<String, Application> appNameApplicationMap; private final Map<String, VipIndexSupport> virtualHostNameAppMap; private final Map<String, VipIndexSupport> secureVirtualHostNameAppMap; /** * Create a new, empty Eureka application list. */ public Applications() { this(null, -1L, Collections.emptyList()); } /** * Note that appsHashCode and versionDelta key names are formatted in a * custom/configurable way. */ @JsonCreator public Applications(@JsonProperty("appsHashCode") String appsHashCode, @JsonProperty("versionDelta") Long versionDelta, @JsonProperty("application") List<Application> registeredApplications) { this.applications = new ConcurrentLinkedQueue<Application>(); this.appNameApplicationMap = new ConcurrentHashMap<String, Application>(); this.virtualHostNameAppMap = new ConcurrentHashMap<String, VipIndexSupport>(); this.secureVirtualHostNameAppMap = new ConcurrentHashMap<String, VipIndexSupport>(); this.appsHashCode = appsHashCode; this.versionDelta = versionDelta; for (Application app : registeredApplications) { this.addApplication(app); } } /** * Add the <em>application</em> to the list. * * @param app * the <em>application</em> to be added. */ public void addApplication(Application app) { appNameApplicationMap.put(app.getName().toUpperCase(Locale.ROOT), app); addInstancesToVIPMaps(app, this.virtualHostNameAppMap, this.secureVirtualHostNameAppMap); applications.add(app); } /** * Gets the list of all registered <em>applications</em> from eureka. * * @return list containing all applications registered with eureka. */ @JsonProperty("application") public List<Application> getRegisteredApplications() { return new ArrayList<Application>(this.applications); } /** * Gets the registered <em>application</em> for the given * application name. * * @param appName * the application name for which the result need to be fetched. * @return the registered application for the given application * name. */ public Application getRegisteredApplications(String appName) { return appNameApplicationMap.get(appName.toUpperCase(Locale.ROOT)); } /** * Gets the list of <em>instances</em> associated to a virtual host name. * * @param virtualHostName * the virtual hostname for which the instances need to be * returned. * @return list of <em>instances</em>. */ public List<InstanceInfo> getInstancesByVirtualHostName(String virtualHostName) { return Optional.ofNullable(this.virtualHostNameAppMap.get(virtualHostName.toUpperCase(Locale.ROOT))) .map(VipIndexSupport::getVipList) .map(AtomicReference::get) .orElseGet(Collections::emptyList); } /** * Gets the list of secure <em>instances</em> associated to a virtual host * name. * * @param secureVirtualHostName * the virtual hostname for which the secure instances need to be * returned. * @return list of <em>instances</em>. */ public List<InstanceInfo> getInstancesBySecureVirtualHostName(String secureVirtualHostName) { return Optional.ofNullable(this.secureVirtualHostNameAppMap.get(secureVirtualHostName.toUpperCase(Locale.ROOT))) .map(VipIndexSupport::getVipList) .map(AtomicReference::get) .orElseGet(Collections::emptyList); } /** * @return a weakly consistent size of the number of instances in all the * applications */ public int size() { return applications.stream().mapToInt(Application::size).sum(); } @Deprecated public void setVersion(Long version) { this.versionDelta = version; } @Deprecated @JsonIgnore // Handled directly due to legacy name formatting public Long getVersion() { return this.versionDelta; } /** * Used by the eureka server. Not for external use. * * @param hashCode * the hash code to assign for this app collection */ public void setAppsHashCode(String hashCode) { this.appsHashCode = hashCode; } /** * Used by the eureka server. Not for external use. * * @return the string indicating the hashcode based on the applications * stored. * */ @JsonIgnore // Handled directly due to legacy name formatting public String getAppsHashCode() { return this.appsHashCode; } /** * Gets the hash code for this <em>applications</em> instance. Used for * comparison of instances between eureka server and eureka client. * * @return the internal hash code representation indicating the information * about the instances. */ @JsonIgnore public String getReconcileHashCode() { TreeMap<String, AtomicInteger> instanceCountMap = new TreeMap<String, AtomicInteger>(); populateInstanceCountMap(instanceCountMap); return getReconcileHashCode(instanceCountMap); } /** * Populates the provided instance count map. The instance count map is used * as part of the general app list synchronization mechanism. * * @param instanceCountMap * the map to populate */ public void populateInstanceCountMap(Map<String, AtomicInteger> instanceCountMap) { for (Application app : this.getRegisteredApplications()) { for (InstanceInfo info : app.getInstancesAsIsFromEureka()) { AtomicInteger instanceCount = instanceCountMap.computeIfAbsent(info.getStatus().name(), k -> new AtomicInteger(0)); instanceCount.incrementAndGet(); } } } /** * Gets the reconciliation hashcode. The hashcode is used to determine * whether the applications list has changed since the last time it was * acquired. * * @param instanceCountMap * the instance count map to use for generating the hash * @return the hash code for this instance */ public static String getReconcileHashCode(Map<String, AtomicInteger> instanceCountMap) { StringBuilder reconcileHashCode = new StringBuilder(75); for (Map.Entry<String, AtomicInteger> mapEntry : instanceCountMap.entrySet()) { reconcileHashCode.append(mapEntry.getKey()).append(STATUS_DELIMITER).append(mapEntry.getValue().get()) .append(STATUS_DELIMITER); } return reconcileHashCode.toString(); } /** * Shuffles the provided instances so that they will not always be returned * in the same order. * * @param filterUpInstances * whether to return only UP instances */ public void shuffleInstances(boolean filterUpInstances) { shuffleInstances(filterUpInstances, false, null, null, null); } /** * Shuffles a whole region so that the instances will not always be returned * in the same order. * * @param remoteRegionsRegistry * the map of remote region names to their registries * @param clientConfig * the {@link EurekaClientConfig}, whose settings will be used to * determine whether to filter to only UP instances * @param instanceRegionChecker * the instance region checker */ public void shuffleAndIndexInstances(Map<String, Applications> remoteRegionsRegistry, EurekaClientConfig clientConfig, InstanceRegionChecker instanceRegionChecker) { shuffleInstances(clientConfig.shouldFilterOnlyUpInstances(), true, remoteRegionsRegistry, clientConfig, instanceRegionChecker); } private void shuffleInstances(boolean filterUpInstances, boolean indexByRemoteRegions, @Nullable Map<String, Applications> remoteRegionsRegistry, @Nullable EurekaClientConfig clientConfig, @Nullable InstanceRegionChecker instanceRegionChecker) { Map<String, VipIndexSupport> secureVirtualHostNameAppMap = new HashMap<>(); Map<String, VipIndexSupport> virtualHostNameAppMap = new HashMap<>(); for (Application application : appNameApplicationMap.values()) { if (indexByRemoteRegions) { application.shuffleAndStoreInstances(remoteRegionsRegistry, clientConfig, instanceRegionChecker); } else { application.shuffleAndStoreInstances(filterUpInstances); } this.addInstancesToVIPMaps(application, virtualHostNameAppMap, secureVirtualHostNameAppMap); } shuffleAndFilterInstances(virtualHostNameAppMap, filterUpInstances); shuffleAndFilterInstances(secureVirtualHostNameAppMap, filterUpInstances); this.virtualHostNameAppMap.putAll(virtualHostNameAppMap); this.virtualHostNameAppMap.keySet().retainAll(virtualHostNameAppMap.keySet()); this.secureVirtualHostNameAppMap.putAll(secureVirtualHostNameAppMap); this.secureVirtualHostNameAppMap.keySet().retainAll(secureVirtualHostNameAppMap.keySet()); } /** * Gets the next round-robin index for the given virtual host name. This * index is reset after every registry fetch cycle. * * @param virtualHostname * the virtual host name. * @param secure * indicates whether it is a secure request or a non-secure * request. * @return AtomicLong value representing the next round-robin index. */ public AtomicLong getNextIndex(String virtualHostname, boolean secure) { Map<String, VipIndexSupport> index = (secure) ? secureVirtualHostNameAppMap : virtualHostNameAppMap; return Optional.ofNullable(index.get(virtualHostname.toUpperCase(Locale.ROOT))) .map(VipIndexSupport::getRoundRobinIndex) .orElse(null); } /** * Shuffle the instances and filter for only {@link InstanceStatus#UP} if * required. * */ private void shuffleAndFilterInstances(Map<String, VipIndexSupport> srcMap, boolean filterUpInstances) { Random shuffleRandom = new Random(); for (Map.Entry<String, VipIndexSupport> entries : srcMap.entrySet()) { VipIndexSupport vipIndexSupport = entries.getValue(); AbstractQueue<InstanceInfo> vipInstances = vipIndexSupport.instances; final List<InstanceInfo> filteredInstances; if (filterUpInstances) { filteredInstances = vipInstances.stream().filter(ii -> ii.getStatus() == InstanceStatus.UP) .collect(Collectors.toCollection(() -> new ArrayList<>(vipInstances.size()))); } else { filteredInstances = new ArrayList<InstanceInfo>(vipInstances); } Collections.shuffle(filteredInstances, shuffleRandom); vipIndexSupport.vipList.set(filteredInstances); vipIndexSupport.roundRobinIndex.set(0); } } /** * Add the instance to the given map based if the vip address matches with * that of the instance. Note that an instance can be mapped to multiple vip * addresses. * */ private void addInstanceToMap(InstanceInfo info, String vipAddresses, Map<String, VipIndexSupport> vipMap) { if (vipAddresses != null) { String[] vipAddressArray = vipAddresses.toUpperCase(Locale.ROOT).split(","); for (String vipAddress : vipAddressArray) { VipIndexSupport vis = vipMap.computeIfAbsent(vipAddress, k -> new VipIndexSupport()); vis.instances.add(info); } } } /** * Adds the instances to the internal vip address map. * * @param app * - the applications for which the instances need to be added. */ private void addInstancesToVIPMaps(Application app, Map<String, VipIndexSupport> virtualHostNameAppMap, Map<String, VipIndexSupport> secureVirtualHostNameAppMap) { // Check and add the instances to the their respective virtual host name // mappings for (InstanceInfo info : app.getInstances()) { String vipAddresses = info.getVIPAddress(); if (vipAddresses != null) { addInstanceToMap(info, vipAddresses, virtualHostNameAppMap); } String secureVipAddresses = info.getSecureVipAddress(); if (secureVipAddresses != null) { addInstanceToMap(info, secureVipAddresses, secureVirtualHostNameAppMap); } } } /** * Remove the <em>application</em> from the list. * * @param app the <em>application</em> */ public void removeApplication(Application app) { this.appNameApplicationMap.remove(app.getName().toUpperCase(Locale.ROOT)); this.applications.remove(app); } }
6,758
0
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery
Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/shared/Pair.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; /** * An utility class for stores any information that needs to exist as a pair. * * @author Karthik Ranganathan * * @param <E1> Generics indicating the type information for the first one in the pair. * @param <E2> Generics indicating the type information for the second one in the pair. */ public class Pair<E1, E2> { public E1 first() { return first; } public void setFirst(E1 first) { this.first = first; } public E2 second() { return second; } public void setSecond(E2 second) { this.second = second; } private E1 first; private E2 second; public Pair(E1 first, E2 second) { this.first = first; this.second = second; } }
6,759
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); } }
6,760
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); } } }
6,761
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); }
6,762
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); } }
6,763
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(); }
6,764
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; } }
6,765
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); } } }
6,766
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(); } } }
6,767
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; } }
6,768
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(); }
6,769
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); } } }
6,770
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(); }
6,771
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(); }
6,772
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(); } }
6,773
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(); } }; } }
6,774
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); }
6,775
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()); } } } }
6,776
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; } }
6,777
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(); }
6,778
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); } } } } } }
6,779
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> { }
6,780
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(); } } } }
6,781
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; } } }
6,782
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); } } }
6,783
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; } } }
6,784
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(); } }
6,785
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; } }
6,786
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; } }); } }
6,787
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; } }
6,788
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); }
6,789
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; } }
6,790
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); } }
6,791
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); }
6,792
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; } }
6,793
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 + '}'; } }
6,794
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(); }
6,795
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 ); } }
6,796
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(); }
6,797
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()) ); } }
6,798
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; } }
6,799