index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared | Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver/ResolverUtilsTest.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery.shared.resolver;
import java.util.List;
import com.netflix.appinfo.AmazonInfo;
import com.netflix.appinfo.DataCenterInfo;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.MyDataCenterInfo;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.discovery.shared.resolver.aws.AwsEndpoint;
import com.netflix.discovery.shared.resolver.aws.SampleCluster;
import com.netflix.discovery.shared.transport.EurekaTransportConfig;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Tomasz Bak
*/
public class ResolverUtilsTest {
@Test
public void testSplitByZone() throws Exception {
List<AwsEndpoint> endpoints = SampleCluster.merge(SampleCluster.UsEast1a, SampleCluster.UsEast1b, SampleCluster.UsEast1c);
List<AwsEndpoint>[] parts = ResolverUtils.splitByZone(endpoints, "us-east-1b");
List<AwsEndpoint> myZoneServers = parts[0];
List<AwsEndpoint> remainingServers = parts[1];
assertThat(myZoneServers, is(equalTo(SampleCluster.UsEast1b.build())));
assertThat(remainingServers, is(equalTo(SampleCluster.merge(SampleCluster.UsEast1a, SampleCluster.UsEast1c))));
}
@Test
public void testExtractZoneFromHostName() throws Exception {
assertThat(ResolverUtils.extractZoneFromHostName("us-east-1c.myservice.net"), is(equalTo("us-east-1c")));
assertThat(ResolverUtils.extractZoneFromHostName("txt.us-east-1c.myservice.net"), is(equalTo("us-east-1c")));
}
@Test
public void testRandomizeProperlyRandomizesList() throws Exception {
boolean success = false;
for (int i = 0; i < 100; i++) {
List<AwsEndpoint> firstList = SampleCluster.UsEast1a.builder().withServerPool(100).build();
List<AwsEndpoint> secondList = ResolverUtils.randomize(firstList);
try {
assertThat(firstList, is(not(equalTo(secondList))));
success = true;
break;
}catch(AssertionError e) {
}
}
if(!success) {
throw new AssertionError("ResolverUtils::randomize returned the same list 100 times, this is more than likely a bug.");
}
}
@Test
public void testRandomizeReturnsACopyOfTheMethodParameter() throws Exception {
List<AwsEndpoint> firstList = SampleCluster.UsEast1a.builder().withServerPool(1).build();
List<AwsEndpoint> secondList = ResolverUtils.randomize(firstList);
assertThat(firstList, is(not(sameInstance(secondList))));
}
@Test
public void testIdentical() throws Exception {
List<AwsEndpoint> firstList = SampleCluster.UsEast1a.builder().withServerPool(10).build();
List<AwsEndpoint> secondList = ResolverUtils.randomize(firstList);
assertThat(ResolverUtils.identical(firstList, secondList), is(true));
secondList.set(0, SampleCluster.UsEast1b.build().get(0));
assertThat(ResolverUtils.identical(firstList, secondList), is(false));
}
@Test
public void testInstanceInfoToEndpoint() throws Exception {
EurekaClientConfig clientConfig = mock(EurekaClientConfig.class);
when(clientConfig.getEurekaServerURLContext()).thenReturn("/eureka");
when(clientConfig.getRegion()).thenReturn("region");
EurekaTransportConfig transportConfig = mock(EurekaTransportConfig.class);
when(transportConfig.applicationsResolverUseIp()).thenReturn(false);
AmazonInfo amazonInfo = AmazonInfo.Builder.newBuilder().addMetadata(AmazonInfo.MetaDataKey.availabilityZone,
"us-east-1c").build();
InstanceInfo instanceWithAWSInfo = InstanceInfo.Builder.newBuilder().setAppName("appName")
.setHostName("hostName").setPort(8080).setDataCenterInfo(amazonInfo).build();
AwsEndpoint awsEndpoint = ResolverUtils.instanceInfoToEndpoint(clientConfig, transportConfig, instanceWithAWSInfo);
assertEquals("zone not equals.", "us-east-1c", awsEndpoint.getZone());
MyDataCenterInfo myDataCenterInfo = new MyDataCenterInfo(DataCenterInfo.Name.MyOwn);
InstanceInfo instanceWithMyDataInfo = InstanceInfo.Builder.newBuilder().setAppName("appName")
.setHostName("hostName").setPort(8080).setDataCenterInfo(myDataCenterInfo)
.add("zone", "us-east-1c").build();
awsEndpoint = ResolverUtils.instanceInfoToEndpoint(clientConfig, transportConfig, instanceWithMyDataInfo);
assertEquals("zone not equals.", "us-east-1c", awsEndpoint.getZone());
}
} | 7,900 |
0 | Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared | Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver/AsyncResolverTest.java | package com.netflix.discovery.shared.resolver;
import com.netflix.discovery.shared.resolver.aws.SampleCluster;
import com.netflix.discovery.shared.transport.EurekaTransportConfig;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author David Liu
*/
public class AsyncResolverTest {
private final EurekaTransportConfig transportConfig = mock(EurekaTransportConfig.class);
private final ClusterResolver delegateResolver = mock(ClosableResolver.class);
private AsyncResolver resolver;
@Before
public void setUp() {
when(transportConfig.getAsyncExecutorThreadPoolSize()).thenReturn(3);
when(transportConfig.getAsyncResolverRefreshIntervalMs()).thenReturn(200);
when(transportConfig.getAsyncResolverWarmUpTimeoutMs()).thenReturn(100);
resolver = spy(new AsyncResolver(
"test",
delegateResolver,
transportConfig.getAsyncExecutorThreadPoolSize(),
transportConfig.getAsyncResolverRefreshIntervalMs(),
transportConfig.getAsyncResolverWarmUpTimeoutMs()
));
}
@After
public void shutDown() {
resolver.shutdown();
}
@Test
public void testHappyCase() {
List delegateReturns1 = new ArrayList(SampleCluster.UsEast1a.builder().withServerPool(2).build());
List delegateReturns2 = new ArrayList(SampleCluster.UsEast1b.builder().withServerPool(3).build());
when(delegateResolver.getClusterEndpoints())
.thenReturn(delegateReturns1)
.thenReturn(delegateReturns2);
List endpoints = resolver.getClusterEndpoints();
assertThat(endpoints.size(), equalTo(delegateReturns1.size()));
verify(delegateResolver, times(1)).getClusterEndpoints();
verify(resolver, times(1)).doWarmUp();
// try again, should be async
endpoints = resolver.getClusterEndpoints();
assertThat(endpoints.size(), equalTo(delegateReturns1.size()));
verify(delegateResolver, times(1)).getClusterEndpoints();
verify(resolver, times(1)).doWarmUp();
// wait for the next async update cycle
verify(delegateResolver, timeout(1000).times(2)).getClusterEndpoints();
endpoints = resolver.getClusterEndpoints();
assertThat(endpoints.size(), equalTo(delegateReturns2.size()));
verify(delegateResolver, times(2)).getClusterEndpoints();
verify(resolver, times(1)).doWarmUp();
}
@Test
public void testDelegateFailureAtWarmUp() {
when(delegateResolver.getClusterEndpoints())
.thenReturn(null);
// override the scheduling which will be triggered immediately if warmUp fails (as is intended).
// do this to avoid thread race conditions for a more predictable test
doNothing().when(resolver).scheduleTask(anyLong());
List endpoints = resolver.getClusterEndpoints();
assertThat(endpoints.isEmpty(), is(true));
verify(delegateResolver, times(1)).getClusterEndpoints();
verify(resolver, times(1)).doWarmUp();
}
}
| 7,901 |
0 | Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared | Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver/ReloadingClusterResolverTest.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery.shared.resolver;
import java.util.List;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import com.netflix.discovery.shared.resolver.aws.AwsEndpoint;
import com.netflix.discovery.shared.resolver.aws.SampleCluster;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
/**
* @author Tomasz Bak
*/
public class ReloadingClusterResolverTest {
private final InjectableFactory factory = new InjectableFactory();
private ReloadingClusterResolver<AwsEndpoint> resolver;
@Test(timeout = 30000)
public void testDataAreReloadedPeriodically() throws Exception {
List<AwsEndpoint> firstEndpointList = SampleCluster.UsEast1a.build();
factory.setEndpoints(firstEndpointList);
// First endpoint list is loaded eagerly
resolver = new ReloadingClusterResolver<>(factory, 1);
assertThat(resolver.getClusterEndpoints(), is(equalTo(firstEndpointList)));
// Swap with a different one
List<AwsEndpoint> secondEndpointList = SampleCluster.UsEast1b.build();
factory.setEndpoints(secondEndpointList);
assertThat(awaitUpdate(resolver, secondEndpointList), is(true));
}
@Test(timeout = 30000)
public void testIdenticalListsDoNotCauseReload() throws Exception {
List<AwsEndpoint> firstEndpointList = SampleCluster.UsEast1a.build();
factory.setEndpoints(firstEndpointList);
// First endpoint list is loaded eagerly
resolver = new ReloadingClusterResolver(factory, 1);
assertThat(resolver.getClusterEndpoints(), is(equalTo(firstEndpointList)));
// Now inject the same one but in the different order
List<AwsEndpoint> snapshot = resolver.getClusterEndpoints();
factory.setEndpoints(ResolverUtils.randomize(firstEndpointList));
Thread.sleep(5);
assertThat(resolver.getClusterEndpoints(), is(equalTo(snapshot)));
// Now inject different list
List<AwsEndpoint> secondEndpointList = SampleCluster.UsEast1b.build();
factory.setEndpoints(secondEndpointList);
assertThat(awaitUpdate(resolver, secondEndpointList), is(true));
}
private static boolean awaitUpdate(ReloadingClusterResolver<AwsEndpoint> resolver, List<AwsEndpoint> expected) throws Exception {
long deadline = System.currentTimeMillis() + 5 * 1000;
do {
List<AwsEndpoint> current = resolver.getClusterEndpoints();
if (ResolverUtils.identical(current, expected)) {
return true;
}
Thread.sleep(1);
} while (System.currentTimeMillis() < deadline);
throw new TimeoutException("Endpoint list not reloaded on time");
}
static class InjectableFactory implements ClusterResolverFactory<AwsEndpoint> {
private final AtomicReference<List<AwsEndpoint>> currentEndpointsRef = new AtomicReference<>();
@Override
public ClusterResolver<AwsEndpoint> createClusterResolver() {
return new StaticClusterResolver<>("regionA", currentEndpointsRef.get());
}
void setEndpoints(List<AwsEndpoint> endpoints) {
currentEndpointsRef.set(endpoints);
}
}
} | 7,902 |
0 | Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver | Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver/aws/ZoneAffinityClusterResolverTest.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery.shared.resolver.aws;
import java.util.List;
import com.netflix.discovery.shared.resolver.ResolverUtils;
import com.netflix.discovery.shared.resolver.StaticClusterResolver;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
/**
* @author Tomasz Bak
*/
public class ZoneAffinityClusterResolverTest {
@Test
public void testApplicationZoneIsFirstOnTheList() throws Exception {
List<AwsEndpoint> endpoints = SampleCluster.merge(SampleCluster.UsEast1a, SampleCluster.UsEast1b, SampleCluster.UsEast1c);
ZoneAffinityClusterResolver resolver = new ZoneAffinityClusterResolver(
new StaticClusterResolver<>("regionA", endpoints),
"us-east-1b",
true,
ResolverUtils::randomize);
List<AwsEndpoint> result = resolver.getClusterEndpoints();
assertThat(result.size(), is(equalTo(endpoints.size())));
assertThat(result.get(0).getZone(), is(equalTo("us-east-1b")));
}
@Test
public void testAntiAffinity() throws Exception {
List<AwsEndpoint> endpoints = SampleCluster.merge(SampleCluster.UsEast1a, SampleCluster.UsEast1b);
ZoneAffinityClusterResolver resolver = new ZoneAffinityClusterResolver(new StaticClusterResolver<>("regionA", endpoints), "us-east-1b", false, ResolverUtils::randomize);
List<AwsEndpoint> result = resolver.getClusterEndpoints();
assertThat(result.size(), is(equalTo(endpoints.size())));
assertThat(result.get(0).getZone(), is(equalTo("us-east-1a")));
}
@Test
public void testUnrecognizedZoneIsIgnored() throws Exception {
List<AwsEndpoint> endpoints = SampleCluster.merge(SampleCluster.UsEast1a, SampleCluster.UsEast1b);
ZoneAffinityClusterResolver resolver = new ZoneAffinityClusterResolver(new StaticClusterResolver<>("regionA", endpoints), "us-east-1c", true, ResolverUtils::randomize);
List<AwsEndpoint> result = resolver.getClusterEndpoints();
assertThat(result.size(), is(equalTo(endpoints.size())));
}
} | 7,903 |
0 | Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver | Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver/aws/ConfigClusterResolverTest.java | package com.netflix.discovery.shared.resolver.aws;
import com.netflix.appinfo.DataCenterInfo;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.MyDataCenterInfo;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.discovery.util.InstanceInfoGenerator;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author David Liu
*/
public class ConfigClusterResolverTest {
private final EurekaClientConfig clientConfig = mock(EurekaClientConfig.class);
private final List<String> endpointsC = Arrays.asList(
"http://1.1.1.1:8000/eureka/v2/",
"http://1.1.1.2:8000/eureka/v2/",
"http://1.1.1.3:8000/eureka/v2/"
);
private final List<String> endpointsD = Arrays.asList(
"http://1.1.2.1:8000/eureka/v2/",
"http://1.1.2.2:8000/eureka/v2/"
);
private final List<String> endpointsWithBasicAuth = Arrays.asList(
"https://myuser:mypassword@1.1.3.1/eureka/v2/"
);
private ConfigClusterResolver resolver;
@Before
public void setUp() {
when(clientConfig.shouldUseDnsForFetchingServiceUrls()).thenReturn(false);
when(clientConfig.getRegion()).thenReturn("us-east-1");
when(clientConfig.getAvailabilityZones("us-east-1")).thenReturn(new String[]{"us-east-1c", "us-east-1d", "us-east-1e"});
when(clientConfig.getEurekaServerServiceUrls("us-east-1c")).thenReturn(endpointsC);
when(clientConfig.getEurekaServerServiceUrls("us-east-1d")).thenReturn(endpointsD);
when(clientConfig.getEurekaServerServiceUrls("us-east-1e")).thenReturn(endpointsWithBasicAuth);
InstanceInfo instanceInfo = new InstanceInfo.Builder(InstanceInfoGenerator.takeOne())
.setDataCenterInfo(new MyDataCenterInfo(DataCenterInfo.Name.MyOwn))
.build();
resolver = new ConfigClusterResolver(clientConfig, instanceInfo);
}
@Test
public void testReadFromConfig() {
List<AwsEndpoint> endpoints = resolver.getClusterEndpoints();
assertThat(endpoints.size(), equalTo(6));
for (AwsEndpoint endpoint : endpoints) {
if (endpoint.getZone().equals("us-east-1e")) {
assertThat("secure was wrong", endpoint.isSecure(), is(true));
assertThat("serviceUrl contains -1", endpoint.getServiceUrl().contains("-1"), is(false));
assertThat("BASIC auth credentials expected", endpoint.getServiceUrl().contains("myuser:mypassword"), is(true));
}
}
}
}
| 7,904 |
0 | Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver | Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver/aws/SampleCluster.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery.shared.resolver.aws;
import java.util.ArrayList;
import java.util.List;
/**
* @author Tomasz Bak
*/
public enum SampleCluster {
UsEast1a() {
@Override
public SampleClusterBuilder builder() {
return new SampleClusterBuilder("us-east-1", "us-east-1a", "10.10.10.");
}
},
UsEast1b() {
@Override
public SampleClusterBuilder builder() {
return new SampleClusterBuilder("us-east-1", "us-east-1b", "10.10.20.");
}
},
UsEast1c() {
@Override
public SampleClusterBuilder builder() {
return new SampleClusterBuilder("us-east-1", "us-east-1c", "10.10.30.");
}
};
public abstract SampleClusterBuilder builder();
public List<AwsEndpoint> build() {
return builder().build();
}
public static List<AwsEndpoint> merge(SampleCluster... sampleClusters) {
List<AwsEndpoint> endpoints = new ArrayList<>();
for (SampleCluster cluster : sampleClusters) {
endpoints.addAll(cluster.build());
}
return endpoints;
}
public static class SampleClusterBuilder {
private final String region;
private final String zone;
private final String networkPrefix;
private int serverPoolSize = 2;
public SampleClusterBuilder(String region, String zone, String networkPrefix) {
this.region = region;
this.zone = zone;
this.networkPrefix = networkPrefix;
}
public SampleClusterBuilder withServerPool(int serverPoolSize) {
this.serverPoolSize = serverPoolSize;
return this;
}
public List<AwsEndpoint> build() {
List<AwsEndpoint> endpoints = new ArrayList<>();
for (int i = 0; i < serverPoolSize; i++) {
String hostName = networkPrefix + i;
endpoints.add(new AwsEndpoint(
hostName,
80,
false,
"/eureka/v2",
region,
zone
));
}
return endpoints;
}
}
}
| 7,905 |
0 | Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver | Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver/aws/EurekaHttpResolverTest.java | package com.netflix.discovery.shared.resolver.aws;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.discovery.shared.Application;
import com.netflix.discovery.shared.Applications;
import com.netflix.discovery.shared.transport.EurekaHttpClient;
import com.netflix.discovery.shared.transport.EurekaHttpClientFactory;
import com.netflix.discovery.shared.transport.EurekaHttpResponse;
import com.netflix.discovery.shared.transport.EurekaTransportConfig;
import com.netflix.discovery.util.InstanceInfoGenerator;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author David Liu
*/
public class EurekaHttpResolverTest {
private final EurekaClientConfig clientConfig = mock(EurekaClientConfig.class);
private final EurekaTransportConfig transportConfig = mock(EurekaTransportConfig.class);
private final EurekaHttpClientFactory clientFactory = mock(EurekaHttpClientFactory.class);
private final EurekaHttpClient httpClient = mock(EurekaHttpClient.class);
private Applications applications;
private String vipAddress;
private EurekaHttpResolver resolver;
@Before
public void setUp() {
when(clientConfig.getEurekaServerURLContext()).thenReturn("context");
when(clientConfig.getRegion()).thenReturn("region");
applications = InstanceInfoGenerator.newBuilder(5, "eurekaRead", "someOther").build().toApplications();
vipAddress = applications.getRegisteredApplications("eurekaRead").getInstances().get(0).getVIPAddress();
when(clientFactory.newClient()).thenReturn(httpClient);
when(httpClient.getVip(vipAddress)).thenReturn(EurekaHttpResponse.anEurekaHttpResponse(200, applications).build());
resolver = new EurekaHttpResolver(clientConfig, transportConfig, clientFactory, vipAddress);
}
@After
public void tearDown() {
}
@Test
public void testHappyCase() {
List<AwsEndpoint> endpoints = resolver.getClusterEndpoints();
assertThat(endpoints.size(), equalTo(applications.getInstancesByVirtualHostName(vipAddress).size()));
verify(httpClient, times(1)).shutdown();
}
@Test
public void testNoValidDataFromRemoteServer() {
Applications newApplications = new Applications();
for (Application application : applications.getRegisteredApplications()) {
if (!application.getInstances().get(0).getVIPAddress().equals(vipAddress)) {
newApplications.addApplication(application);
}
}
when(httpClient.getVip(vipAddress)).thenReturn(EurekaHttpResponse.anEurekaHttpResponse(200, newApplications).build());
List<AwsEndpoint> endpoints = resolver.getClusterEndpoints();
assertThat(endpoints.isEmpty(), is(true));
verify(httpClient, times(1)).shutdown();
}
@Test
public void testErrorResponseFromRemoteServer() {
when(httpClient.getVip(vipAddress)).thenReturn(EurekaHttpResponse.anEurekaHttpResponse(500, (Applications)null).build());
List<AwsEndpoint> endpoints = resolver.getClusterEndpoints();
assertThat(endpoints.isEmpty(), is(true));
verify(httpClient, times(1)).shutdown();
}
}
| 7,906 |
0 | Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver | Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver/aws/ApplicationsResolverTest.java | package com.netflix.discovery.shared.resolver.aws;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.discovery.shared.Applications;
import com.netflix.discovery.shared.resolver.aws.ApplicationsResolver.ApplicationsSource;
import com.netflix.discovery.shared.transport.EurekaTransportConfig;
import com.netflix.discovery.util.InstanceInfoGenerator;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author David Liu
*/
public class ApplicationsResolverTest {
private final EurekaClientConfig clientConfig = mock(EurekaClientConfig.class);
private final EurekaTransportConfig transportConfig = mock(EurekaTransportConfig.class);
private final ApplicationsSource applicationsSource = mock(ApplicationsSource.class);
private Applications applications;
private String vipAddress;
private ApplicationsResolver resolver;
@Before
public void setUp() {
when(clientConfig.getEurekaServerURLContext()).thenReturn("context");
when(clientConfig.getRegion()).thenReturn("region");
when(transportConfig.getApplicationsResolverDataStalenessThresholdSeconds()).thenReturn(1);
applications = InstanceInfoGenerator.newBuilder(5, "eurekaRead", "someOther").build().toApplications();
vipAddress = applications.getRegisteredApplications("eurekaRead").getInstances().get(0).getVIPAddress();
when(transportConfig.getReadClusterVip()).thenReturn(vipAddress);
resolver = new ApplicationsResolver(
clientConfig,
transportConfig,
applicationsSource,
transportConfig.getReadClusterVip()
);
}
@Test
public void testHappyCase() {
when(applicationsSource.getApplications(anyInt(), eq(TimeUnit.SECONDS))).thenReturn(applications);
List<AwsEndpoint> endpoints = resolver.getClusterEndpoints();
assertThat(endpoints.size(), equalTo(applications.getInstancesByVirtualHostName(vipAddress).size()));
}
@Test
public void testVipDoesNotExist() {
vipAddress = "doNotExist";
when(transportConfig.getReadClusterVip()).thenReturn(vipAddress);
resolver = new ApplicationsResolver( // recreate the resolver as desired config behaviour has changed
clientConfig,
transportConfig,
applicationsSource,
transportConfig.getReadClusterVip()
);
when(applicationsSource.getApplications(anyInt(), eq(TimeUnit.SECONDS))).thenReturn(applications);
List<AwsEndpoint> endpoints = resolver.getClusterEndpoints();
assertThat(endpoints.isEmpty(), is(true));
}
@Test
public void testStaleData() {
when(applicationsSource.getApplications(anyInt(), eq(TimeUnit.SECONDS))).thenReturn(null); // stale contract
List<AwsEndpoint> endpoints = resolver.getClusterEndpoints();
assertThat(endpoints.isEmpty(), is(true));
}
}
| 7,907 |
0 | Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver | Create_ds/eureka/eureka-client/src/test/java/com/netflix/discovery/shared/resolver/aws/TestEurekaHttpResolver.java | package com.netflix.discovery.shared.resolver.aws;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.discovery.shared.transport.EurekaHttpClientFactory;
import com.netflix.discovery.shared.transport.EurekaTransportConfig;
/**
* Used to expose test constructor to other packages
*
* @author David Liu
*/
public class TestEurekaHttpResolver extends EurekaHttpResolver {
public TestEurekaHttpResolver(EurekaClientConfig clientConfig, EurekaTransportConfig transportConfig, EurekaHttpClientFactory clientFactory, String vipAddress) {
super(clientConfig, transportConfig, clientFactory, vipAddress);
}
}
| 7,908 |
0 | Create_ds/eureka/eureka-client/src/test/java/com/netflix | Create_ds/eureka/eureka-client/src/test/java/com/netflix/appinfo/ApplicationInfoManagerTest.java | package com.netflix.appinfo;
import com.netflix.discovery.CommonConstants;
import com.netflix.discovery.util.InstanceInfoGenerator;
import org.junit.Before;
import org.junit.Test;
import static com.netflix.appinfo.AmazonInfo.MetaDataKey.localIpv4;
import static com.netflix.appinfo.AmazonInfo.MetaDataKey.publicHostname;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
/**
* @author David Liu
*/
public class ApplicationInfoManagerTest {
private CloudInstanceConfig config;
private String dummyDefault = "dummyDefault";
private InstanceInfo instanceInfo;
private ApplicationInfoManager applicationInfoManager;
@Before
public void setUp() {
AmazonInfo initialAmazonInfo = AmazonInfo.Builder.newBuilder().build();
config = spy(new CloudInstanceConfig(initialAmazonInfo));
instanceInfo = InstanceInfoGenerator.takeOne();
this.applicationInfoManager = new ApplicationInfoManager(config, instanceInfo, null);
when(config.getDefaultAddressResolutionOrder()).thenReturn(new String[]{
publicHostname.name(),
localIpv4.name()
});
when(config.getHostName(anyBoolean())).thenReturn(dummyDefault);
}
@Test
public void testRefreshDataCenterInfoWithAmazonInfo() {
String newPublicHostname = "newValue";
assertThat(instanceInfo.getHostName(), is(not(newPublicHostname)));
((AmazonInfo)config.getDataCenterInfo()).getMetadata().put(publicHostname.getName(), newPublicHostname);
applicationInfoManager.refreshDataCenterInfoIfRequired();
assertThat(instanceInfo.getHostName(), is(newPublicHostname));
}
@Test
public void testSpotInstanceTermination() {
AmazonInfo initialAmazonInfo = AmazonInfo.Builder.newBuilder().build();
RefreshableAmazonInfoProvider refreshableAmazonInfoProvider = spy(new RefreshableAmazonInfoProvider(initialAmazonInfo, new Archaius1AmazonInfoConfig(CommonConstants.DEFAULT_CONFIG_NAMESPACE)));
config = spy(new CloudInstanceConfig(CommonConstants.DEFAULT_CONFIG_NAMESPACE, refreshableAmazonInfoProvider));
this.applicationInfoManager = new ApplicationInfoManager(config, instanceInfo, null);
String terminationTime = "2015-01-05T18:02:00Z";
String spotInstanceAction = "{\"action\": \"terminate\", \"time\": \"2017-09-18T08:22:00Z\"}";
AmazonInfo newAmazonInfo = AmazonInfo.Builder.newBuilder()
.addMetadata(AmazonInfo.MetaDataKey.spotTerminationTime, terminationTime) // new property on refresh
.addMetadata(AmazonInfo.MetaDataKey.spotInstanceAction, spotInstanceAction) // new property refresh
.addMetadata(AmazonInfo.MetaDataKey.publicHostname, instanceInfo.getHostName()) // unchanged
.addMetadata(AmazonInfo.MetaDataKey.instanceId, instanceInfo.getInstanceId()) // unchanged
.addMetadata(AmazonInfo.MetaDataKey.localIpv4, instanceInfo.getIPAddr()) // unchanged
.build();
when(refreshableAmazonInfoProvider.getNewAmazonInfo()).thenReturn(newAmazonInfo);
applicationInfoManager.refreshDataCenterInfoIfRequired();
assertThat(((AmazonInfo)instanceInfo.getDataCenterInfo()).getMetadata().get(AmazonInfo.MetaDataKey.spotTerminationTime.getName()), is(terminationTime));
assertThat(((AmazonInfo)instanceInfo.getDataCenterInfo()).getMetadata().get(AmazonInfo.MetaDataKey.spotInstanceAction.getName()), is(spotInstanceAction));
}
@Test
public void testCustomInstanceStatusMapper() {
ApplicationInfoManager.OptionalArgs optionalArgs = new ApplicationInfoManager.OptionalArgs();
optionalArgs.setInstanceStatusMapper(new ApplicationInfoManager.InstanceStatusMapper() {
@Override
public InstanceInfo.InstanceStatus map(InstanceInfo.InstanceStatus prev) {
return InstanceInfo.InstanceStatus.UNKNOWN;
}
});
applicationInfoManager = new ApplicationInfoManager(config, instanceInfo, optionalArgs);
InstanceInfo.InstanceStatus existingStatus = applicationInfoManager.getInfo().getStatus();
assertNotEquals(existingStatus, InstanceInfo.InstanceStatus.UNKNOWN);
applicationInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.UNKNOWN);
existingStatus = applicationInfoManager.getInfo().getStatus();
assertEquals(existingStatus, InstanceInfo.InstanceStatus.UNKNOWN);
}
@Test
public void testNullResultInstanceStatusMapper() {
ApplicationInfoManager.OptionalArgs optionalArgs = new ApplicationInfoManager.OptionalArgs();
optionalArgs.setInstanceStatusMapper(new ApplicationInfoManager.InstanceStatusMapper() {
@Override
public InstanceInfo.InstanceStatus map(InstanceInfo.InstanceStatus prev) {
return null;
}
});
applicationInfoManager = new ApplicationInfoManager(config, instanceInfo, optionalArgs);
InstanceInfo.InstanceStatus existingStatus1 = applicationInfoManager.getInfo().getStatus();
assertNotEquals(existingStatus1, InstanceInfo.InstanceStatus.UNKNOWN);
applicationInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.UNKNOWN);
InstanceInfo.InstanceStatus existingStatus2 = applicationInfoManager.getInfo().getStatus();
assertEquals(existingStatus2, existingStatus1);
}
}
| 7,909 |
0 | Create_ds/eureka/eureka-client/src/test/java/com/netflix | Create_ds/eureka/eureka-client/src/test/java/com/netflix/appinfo/RefreshableAmazonInfoProviderTest.java | package com.netflix.appinfo;
import com.netflix.discovery.util.InstanceInfoGenerator;
import org.junit.Before;
import org.junit.Test;
import static com.netflix.appinfo.AmazonInfo.MetaDataKey.amiId;
import static com.netflix.appinfo.AmazonInfo.MetaDataKey.instanceId;
import static com.netflix.appinfo.AmazonInfo.MetaDataKey.localIpv4;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
/**
* @author David Liu
*/
public class RefreshableAmazonInfoProviderTest {
private InstanceInfo instanceInfo;
@Before
public void setUp() {
instanceInfo = InstanceInfoGenerator.takeOne();
}
@Test
public void testAmazonInfoNoUpdateIfEqual() {
AmazonInfo oldInfo = (AmazonInfo) instanceInfo.getDataCenterInfo();
AmazonInfo newInfo = copyAmazonInfo(instanceInfo);
assertThat(RefreshableAmazonInfoProvider.shouldUpdate(newInfo, oldInfo), is(false));
}
@Test
public void testAmazonInfoNoUpdateIfEmpty() {
AmazonInfo oldInfo = (AmazonInfo) instanceInfo.getDataCenterInfo();
AmazonInfo newInfo = new AmazonInfo();
assertThat(RefreshableAmazonInfoProvider.shouldUpdate(newInfo, oldInfo), is(false));
}
@Test
public void testAmazonInfoNoUpdateIfNoInstanceId() {
AmazonInfo oldInfo = (AmazonInfo) instanceInfo.getDataCenterInfo();
AmazonInfo newInfo = copyAmazonInfo(instanceInfo);
newInfo.getMetadata().remove(instanceId.getName());
assertThat(newInfo.getId(), is(nullValue()));
assertThat(newInfo.get(instanceId), is(nullValue()));
assertThat(CloudInstanceConfig.shouldUpdate(newInfo, oldInfo), is(false));
newInfo.getMetadata().put(instanceId.getName(), "");
assertThat(newInfo.getId(), is(""));
assertThat(newInfo.get(instanceId), is(""));
assertThat(RefreshableAmazonInfoProvider.shouldUpdate(newInfo, oldInfo), is(false));
}
@Test
public void testAmazonInfoNoUpdateIfNoLocalIpv4() {
AmazonInfo oldInfo = (AmazonInfo) instanceInfo.getDataCenterInfo();
AmazonInfo newInfo = copyAmazonInfo(instanceInfo);
newInfo.getMetadata().remove(localIpv4.getName());
assertThat(newInfo.get(localIpv4), is(nullValue()));
assertThat(CloudInstanceConfig.shouldUpdate(newInfo, oldInfo), is(false));
newInfo.getMetadata().put(localIpv4.getName(), "");
assertThat(newInfo.get(localIpv4), is(""));
assertThat(RefreshableAmazonInfoProvider.shouldUpdate(newInfo, oldInfo), is(false));
}
@Test
public void testAmazonInfoUpdatePositiveCase() {
AmazonInfo oldInfo = (AmazonInfo) instanceInfo.getDataCenterInfo();
AmazonInfo newInfo = copyAmazonInfo(instanceInfo);
newInfo.getMetadata().remove(amiId.getName());
assertThat(newInfo.getMetadata().size(), is(oldInfo.getMetadata().size() - 1));
assertThat(RefreshableAmazonInfoProvider.shouldUpdate(newInfo, oldInfo), is(true));
String newKey = "someNewKey";
newInfo.getMetadata().put(newKey, "bar");
assertThat(newInfo.getMetadata().size(), is(oldInfo.getMetadata().size()));
assertThat(RefreshableAmazonInfoProvider.shouldUpdate(newInfo, oldInfo), is(true));
}
private static AmazonInfo copyAmazonInfo(InstanceInfo instanceInfo) {
AmazonInfo currInfo = (AmazonInfo) instanceInfo.getDataCenterInfo();
AmazonInfo copyInfo = new AmazonInfo();
for (String key : currInfo.getMetadata().keySet()) {
copyInfo.getMetadata().put(key, currInfo.getMetadata().get(key));
}
return copyInfo;
}
}
| 7,910 |
0 | Create_ds/eureka/eureka-client/src/test/java/com/netflix | Create_ds/eureka/eureka-client/src/test/java/com/netflix/appinfo/InstanceInfoTest.java | package com.netflix.appinfo;
import com.netflix.appinfo.InstanceInfo.Builder;
import com.netflix.appinfo.InstanceInfo.PortType;
import com.netflix.config.ConcurrentCompositeConfiguration;
import com.netflix.config.ConfigurationManager;
import com.netflix.discovery.util.InstanceInfoGenerator;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import static com.netflix.appinfo.InstanceInfo.Builder.newBuilder;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertThat;
/**
* Created by jzarfoss on 2/12/14.
*/
public class InstanceInfoTest {
@After
public void tearDown() throws Exception {
((ConcurrentCompositeConfiguration) ConfigurationManager.getConfigInstance()).clearOverrideProperty("NETFLIX_APP_GROUP");
((ConcurrentCompositeConfiguration) ConfigurationManager.getConfigInstance()).clearOverrideProperty("eureka.appGroup");
}
// contrived test to check copy constructor and verify behavior of builder for InstanceInfo
@Test
public void testCopyConstructor() {
DataCenterInfo myDCI = new DataCenterInfo() {
public DataCenterInfo.Name getName() {
return DataCenterInfo.Name.MyOwn;
}
};
InstanceInfo smallII1 = newBuilder().setAppName("test").setDataCenterInfo(myDCI).build();
InstanceInfo smallII2 = new InstanceInfo(smallII1);
assertNotSame(smallII1, smallII2);
Assert.assertEquals(smallII1, smallII2);
InstanceInfo fullII1 = newBuilder().setMetadata(null)
.setOverriddenStatus(InstanceInfo.InstanceStatus.UNKNOWN)
.setHostName("localhost")
.setSecureVIPAddress("testSecureVIP:22")
.setStatus(InstanceInfo.InstanceStatus.UNKNOWN)
.setStatusPageUrl("relative", "explicit/relative")
.setVIPAddress("testVIP:21")
.setAppName("test").setASGName("testASG").setDataCenterInfo(myDCI)
.setHealthCheckUrls("relative", "explicit/relative", "secureExplicit/relative")
.setHomePageUrl("relativeHP", "explicitHP/relativeHP")
.setIPAddr("127.0.0.1")
.setPort(21).setSecurePort(22).build();
InstanceInfo fullII2 = new InstanceInfo(fullII1);
assertNotSame(fullII1, fullII2);
Assert.assertEquals(fullII1, fullII2);
}
@Test
public void testAppGroupNameSystemProp() throws Exception {
String appGroup = "testAppGroupSystemProp";
((ConcurrentCompositeConfiguration) ConfigurationManager.getConfigInstance()).setOverrideProperty("NETFLIX_APP_GROUP",
appGroup);
MyDataCenterInstanceConfig config = new MyDataCenterInstanceConfig();
Assert.assertEquals("Unexpected app group name", appGroup, config.getAppGroupName());
}
@Test
public void testAppGroupName() throws Exception {
String appGroup = "testAppGroup";
((ConcurrentCompositeConfiguration) ConfigurationManager.getConfigInstance()).setOverrideProperty("eureka.appGroup",
appGroup);
MyDataCenterInstanceConfig config = new MyDataCenterInstanceConfig();
Assert.assertEquals("Unexpected app group name", appGroup, config.getAppGroupName());
}
@Test
public void testHealthCheckSetContainsValidUrlEntries() throws Exception {
Builder builder = newBuilder()
.setAppName("test")
.setNamespace("eureka.")
.setHostName("localhost")
.setPort(80)
.setSecurePort(443)
.enablePort(PortType.SECURE, true);
// No health check URLs
InstanceInfo noHealtcheckInstanceInfo = builder.build();
assertThat(noHealtcheckInstanceInfo.getHealthCheckUrls().size(), is(equalTo(0)));
// Now when health check is defined
InstanceInfo instanceInfo = builder
.setHealthCheckUrls("/healthcheck", "http://${eureka.hostname}/healthcheck", "https://${eureka.hostname}/healthcheck")
.build();
assertThat(instanceInfo.getHealthCheckUrls().size(), is(equalTo(2)));
}
@Test
public void testNullUrlEntries() throws Exception {
Builder builder = newBuilder()
.setAppName("test")
.setNamespace("eureka.")
.setHostName("localhost")
.setPort(80)
.setSecurePort(443)
.setHealthCheckUrls(null, null, null)
.setStatusPageUrl(null, null)
.setHomePageUrl(null, null)
.enablePort(PortType.SECURE, true);
// No URLs for healthcheck , status , homepage
InstanceInfo noHealtcheckInstanceInfo = builder.build();
assertThat(noHealtcheckInstanceInfo.getHealthCheckUrls().size(), is(equalTo(0)));
assertThat(noHealtcheckInstanceInfo.getStatusPageUrl(), nullValue());
assertThat(noHealtcheckInstanceInfo.getHomePageUrl(), nullValue());
}
@Test
public void testGetIdWithInstanceIdUsed() {
InstanceInfo baseline = InstanceInfoGenerator.takeOne();
String dataCenterInfoId = ((UniqueIdentifier) baseline.getDataCenterInfo()).getId();
assertThat(baseline.getInstanceId(), is(baseline.getId()));
assertThat(dataCenterInfoId, is(baseline.getId()));
String customInstanceId = "someId";
InstanceInfo instanceInfo = new InstanceInfo.Builder(baseline).setInstanceId(customInstanceId).build();
dataCenterInfoId = ((UniqueIdentifier) instanceInfo.getDataCenterInfo()).getId();
assertThat(instanceInfo.getInstanceId(), is(instanceInfo.getId()));
assertThat(customInstanceId, is(instanceInfo.getId()));
assertThat(dataCenterInfoId, is(not(baseline.getId())));
}
// test case for backwards compatibility
@Test
public void testGetIdWithInstanceIdNotUsed() {
InstanceInfo baseline = InstanceInfoGenerator.takeOne();
// override the sid with ""
InstanceInfo instanceInfo1 = new InstanceInfo.Builder(baseline).setInstanceId("").build();
String dataCenterInfoId = ((UniqueIdentifier) baseline.getDataCenterInfo()).getId();
assertThat(instanceInfo1.getInstanceId().isEmpty(), is(true));
assertThat(instanceInfo1.getInstanceId(), is(not(instanceInfo1.getId())));
assertThat(dataCenterInfoId, is(instanceInfo1.getId()));
// override the sid with null
InstanceInfo instanceInfo2 = new InstanceInfo.Builder(baseline).setInstanceId(null).build();
dataCenterInfoId = ((UniqueIdentifier) baseline.getDataCenterInfo()).getId();
assertThat(instanceInfo2.getInstanceId(), is(nullValue()));
assertThat(instanceInfo2.getInstanceId(), is(not(instanceInfo2.getId())));
assertThat(dataCenterInfoId, is(instanceInfo2.getId()));
}
}
| 7,911 |
0 | Create_ds/eureka/eureka-client/src/test/java/com/netflix | Create_ds/eureka/eureka-client/src/test/java/com/netflix/appinfo/CloudInstanceConfigTest.java | package com.netflix.appinfo;
import com.netflix.discovery.util.InstanceInfoGenerator;
import org.junit.Before;
import org.junit.Test;
import static com.netflix.appinfo.AmazonInfo.MetaDataKey.ipv6;
import static com.netflix.appinfo.AmazonInfo.MetaDataKey.localIpv4;
import static com.netflix.appinfo.AmazonInfo.MetaDataKey.publicHostname;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertEquals;
/**
* @author David Liu
*/
public class CloudInstanceConfigTest {
private CloudInstanceConfig config;
private String dummyDefault = "dummyDefault";
private InstanceInfo instanceInfo;
@Before
public void setUp() {
instanceInfo = InstanceInfoGenerator.takeOne();
}
@Test
public void testResolveDefaultAddress() {
AmazonInfo info = (AmazonInfo) instanceInfo.getDataCenterInfo();
config = createConfig(info);
assertThat(config.resolveDefaultAddress(false), is(info.get(publicHostname)));
info.getMetadata().remove(publicHostname.getName());
config = createConfig(info);
assertThat(config.resolveDefaultAddress(false), is(info.get(localIpv4)));
info.getMetadata().remove(localIpv4.getName());
config = createConfig(info);
assertThat(config.resolveDefaultAddress(false), is(info.get(ipv6)));
info.getMetadata().remove(ipv6.getName());
config = createConfig(info);
assertThat(config.resolveDefaultAddress(false), is(dummyDefault));
}
@Test
public void testBroadcastPublicIpv4Address() {
AmazonInfo info = (AmazonInfo) instanceInfo.getDataCenterInfo();
config = createConfig(info);
// this should work because the test utils class sets the ipAddr to the public IP of the instance
assertEquals(instanceInfo.getIPAddr(), config.getIpAddress());
}
@Test
public void testBroadcastPublicIpv4Address_usingPublicIpv4s() {
AmazonInfo info = (AmazonInfo) instanceInfo.getDataCenterInfo();
info.getMetadata().remove(AmazonInfo.MetaDataKey.publicIpv4.getName());
info.getMetadata().put(AmazonInfo.MetaDataKey.publicIpv4s.getName(), "10.0.0.1");
config = createConfig(info);
assertEquals("10.0.0.1", config.getIpAddress());
}
private CloudInstanceConfig createConfig(AmazonInfo info) {
return new CloudInstanceConfig(info) {
@Override
public String[] getDefaultAddressResolutionOrder() {
return new String[] {
publicHostname.name(),
localIpv4.name(),
ipv6.name()
};
}
@Override
public String getHostName(boolean refresh) {
return dummyDefault;
}
@Override
public boolean shouldBroadcastPublicIpv4Addr() { return true; }
};
}
}
| 7,912 |
0 | Create_ds/eureka/eureka-client/src/test/java/com/netflix | Create_ds/eureka/eureka-client/src/test/java/com/netflix/appinfo/AmazonInfoTest.java | package com.netflix.appinfo;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
import com.netflix.discovery.internal.util.AmazonInfoUtils;
import org.junit.Test;
import org.mockito.MockedStatic;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.mockStatic;
import static org.junit.Assert.assertEquals;
/**
* @author David Liu
*/
public class AmazonInfoTest {
@Test
public void testExtractAccountId() throws Exception {
String json = "{\n" +
" \"imageId\" : \"ami-someId\",\n" +
" \"instanceType\" : \"m1.small\",\n" +
" \"version\" : \"2000-00-00\",\n" +
" \"architecture\" : \"x86_64\",\n" +
" \"accountId\" : \"1111111111\",\n" +
" \"instanceId\" : \"i-someId\",\n" +
" \"billingProducts\" : null,\n" +
" \"pendingTime\" : \"2000-00-00T00:00:00Z\",\n" +
" \"availabilityZone\" : \"us-east-1c\",\n" +
" \"region\" : \"us-east-1\",\n" +
" \"kernelId\" : \"aki-someId\",\n" +
" \"ramdiskId\" : null,\n" +
" \"privateIp\" : \"1.1.1.1\"\n" +
"}";
InputStream inputStream = new ByteArrayInputStream(json.getBytes());
String accountId = AmazonInfo.MetaDataKey.accountId.read(inputStream);
assertEquals("1111111111", accountId);
}
@Test
public void testExtractMacs_SingleMac() throws Exception {
String body = "0d:c2:9a:3c:18:2b";
InputStream inputStream = new ByteArrayInputStream(body.getBytes());
String macs = AmazonInfo.MetaDataKey.macs.read(inputStream);
assertEquals("0d:c2:9a:3c:18:2b", macs);
}
@Test
public void testExtractMacs_MultipleMacs() throws Exception {
String body = "0d:c2:9a:3c:18:2b\n4c:31:99:7e:26:d6";
InputStream inputStream = new ByteArrayInputStream(body.getBytes());
String macs = AmazonInfo.MetaDataKey.macs.read(inputStream);
assertEquals("0d:c2:9a:3c:18:2b\n4c:31:99:7e:26:d6", macs);
}
@Test
public void testExtractPublicIPv4s_SingleAddress() throws Exception {
String body = "10.0.0.1";
InputStream inputStream = new ByteArrayInputStream(body.getBytes());
String publicIPv4s = AmazonInfo.MetaDataKey.publicIpv4s.read(inputStream);
assertEquals("10.0.0.1", publicIPv4s);
}
@Test
public void testExtractPublicIPv4s_MultipleAddresses() throws Exception {
String body = "10.0.0.1\n10.0.0.2";
InputStream inputStream = new ByteArrayInputStream(body.getBytes());
String publicIPv4s = AmazonInfo.MetaDataKey.publicIpv4s.read(inputStream);
assertEquals("10.0.0.1", publicIPv4s);
}
@Test
public void testAutoBuild() throws Exception {
try (MockedStatic<AmazonInfoUtils> mockUtils = mockStatic(AmazonInfoUtils.class)) {
mockUtils.when(
() -> AmazonInfoUtils.readEc2MetadataUrl(any(AmazonInfo.MetaDataKey.class), any(URL.class), anyInt(), anyInt())
).thenReturn(null);
mockUtils.when(
() -> AmazonInfoUtils.readEc2MetadataUrl(any(AmazonInfo.MetaDataKey.class), any(URL.class), anyInt(), anyInt())
).thenReturn(null);
URL macsUrl = AmazonInfo.MetaDataKey.macs.getURL(null, null);
mockUtils.when(
() -> AmazonInfoUtils.readEc2MetadataUrl(eq(AmazonInfo.MetaDataKey.macs), eq(macsUrl), anyInt(), anyInt())
).thenReturn("0d:c2:9a:3c:18:2b\n4c:31:99:7e:26:d6");
URL firstMacPublicIPv4sUrl = AmazonInfo.MetaDataKey.publicIpv4s.getURL(null, "0d:c2:9a:3c:18:2b");
mockUtils.when(
() -> AmazonInfoUtils.readEc2MetadataUrl(eq(AmazonInfo.MetaDataKey.publicIpv4s), eq(firstMacPublicIPv4sUrl), anyInt(), anyInt())
).thenReturn(null);
URL secondMacPublicIPv4sUrl = AmazonInfo.MetaDataKey.publicIpv4s.getURL(null, "4c:31:99:7e:26:d6");
mockUtils.when(
() -> AmazonInfoUtils.readEc2MetadataUrl(eq(AmazonInfo.MetaDataKey.publicIpv4s), eq(secondMacPublicIPv4sUrl), anyInt(), anyInt())
).thenReturn("10.0.0.1");
AmazonInfoConfig config = mock(AmazonInfoConfig.class);
when(config.getNamespace()).thenReturn("test_namespace");
when(config.getConnectTimeout()).thenReturn(10);
when(config.getNumRetries()).thenReturn(1);
when(config.getReadTimeout()).thenReturn(10);
when(config.shouldLogAmazonMetadataErrors()).thenReturn(false);
when(config.shouldValidateInstanceId()).thenReturn(false);
when(config.shouldFailFastOnFirstLoad()).thenReturn(false);
AmazonInfo info = AmazonInfo.Builder.newBuilder().withAmazonInfoConfig(config).autoBuild("test_namespace");
assertEquals("10.0.0.1", info.get(AmazonInfo.MetaDataKey.publicIpv4s));
}
}
}
| 7,913 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/DNSBasedAzToRegionMapper.java | package com.netflix.discovery;
import com.netflix.discovery.endpoint.EndpointUtils;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* DNS-based region mapper that discovers regions via DNS TXT records.
* @author Nitesh Kant
*/
public class DNSBasedAzToRegionMapper extends AbstractAzToRegionMapper {
public DNSBasedAzToRegionMapper(EurekaClientConfig clientConfig) {
super(clientConfig);
}
@Override
protected Set<String> getZonesForARegion(String region) {
Map<String, List<String>> zoneBasedDiscoveryUrlsFromRegion = EndpointUtils
.getZoneBasedDiscoveryUrlsFromRegion(clientConfig, region);
if (null != zoneBasedDiscoveryUrlsFromRegion) {
return zoneBasedDiscoveryUrlsFromRegion.keySet();
}
return Collections.emptySet();
}
}
| 7,914 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/EurekaUpStatusResolver.java | package com.netflix.discovery;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Singleton;
import java.util.concurrent.atomic.AtomicLong;
import com.google.inject.Inject;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.eventbus.spi.EventBus;
import com.netflix.eventbus.spi.InvalidSubscriberException;
import com.netflix.eventbus.spi.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Singleton that manages the state of @UpStatus/@DownStatus Supplier<Boolean>
* and emits status changes to @UpStatus Observable<Boolean>.
*
* @author elandau
*
*/
@Singleton
public class EurekaUpStatusResolver {
private static Logger LOG = LoggerFactory.getLogger(EurekaUpStatusResolver.class);
private volatile InstanceInfo.InstanceStatus currentStatus = InstanceInfo.InstanceStatus.UNKNOWN;
private final EventBus eventBus;
private final EurekaClient client;
private final AtomicLong counter = new AtomicLong();
/**
* @param client the eurekaClient
* @param eventBus the eventBus to publish eureka status change events
*/
@Inject
public EurekaUpStatusResolver(EurekaClient client, EventBus eventBus) {
this.eventBus = eventBus;
this.client = client;
}
@Subscribe
public void onStatusChange(StatusChangeEvent event) {
LOG.info("Eureka status changed from {} to {}", event.getPreviousStatus(), event.getStatus());
currentStatus = event.getStatus();
counter.incrementAndGet();
}
@PostConstruct
public void init() {
try {
// Must set the initial status
currentStatus = client.getInstanceRemoteStatus();
LOG.info("Initial status set to {}", currentStatus);
eventBus.registerSubscriber(this);
} catch (InvalidSubscriberException e) {
LOG.error("Error registring for discovery status change events.", e);
}
}
@PreDestroy
public void shutdown() {
eventBus.unregisterSubscriber(this);
}
/**
* @return Get the current instance status
*/
public InstanceInfo.InstanceStatus getStatus() {
return currentStatus;
}
public long getChangeCount() {
return counter.get();
}
}
| 7,915 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/DiscoveryEvent.java | /**
*
*/
package com.netflix.discovery;
/**
* Class to be extended by all discovery events. Abstract as it
* doesn't make sense for generic events to be published directly.
*/
public abstract class DiscoveryEvent implements EurekaEvent {
// System time when the event happened
private final long timestamp;
protected DiscoveryEvent() {
this.timestamp = System.currentTimeMillis();
}
/**
* @return Return the system time in milliseconds when the event happened.
*/
public final long getTimestamp() {
return this.timestamp;
}
}
| 7,916 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/InstanceInfoReplicator.java | package com.netflix.discovery;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.util.RateLimiter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
/**
* A task for updating and replicating the local instanceinfo to the remote server. Properties of this task are:
* - configured with a single update thread to guarantee sequential update to the remote server
* - update tasks can be scheduled on-demand via onDemandUpdate()
* - task processing is rate limited by burstSize
* - a new update task is always scheduled automatically after an earlier update task. However if an on-demand task
* is started, the scheduled automatic update task is discarded (and a new one will be scheduled after the new
* on-demand update).
*
* @author dliu
*/
class InstanceInfoReplicator implements Runnable {
private static final Logger logger = LoggerFactory.getLogger(InstanceInfoReplicator.class);
private final DiscoveryClient discoveryClient;
private final InstanceInfo instanceInfo;
private final int replicationIntervalSeconds;
private final ScheduledExecutorService scheduler;
private final AtomicReference<Future> scheduledPeriodicRef;
private final AtomicBoolean started;
private final RateLimiter rateLimiter;
private final int burstSize;
private final int allowedRatePerMinute;
InstanceInfoReplicator(DiscoveryClient discoveryClient, InstanceInfo instanceInfo, int replicationIntervalSeconds, int burstSize) {
this.discoveryClient = discoveryClient;
this.instanceInfo = instanceInfo;
this.scheduler = Executors.newScheduledThreadPool(1,
new ThreadFactoryBuilder()
.setNameFormat("DiscoveryClient-InstanceInfoReplicator-%d")
.setDaemon(true)
.build());
this.scheduledPeriodicRef = new AtomicReference<Future>();
this.started = new AtomicBoolean(false);
this.rateLimiter = new RateLimiter(TimeUnit.MINUTES);
this.replicationIntervalSeconds = replicationIntervalSeconds;
this.burstSize = burstSize;
this.allowedRatePerMinute = 60 * this.burstSize / this.replicationIntervalSeconds;
logger.info("InstanceInfoReplicator onDemand update allowed rate per min is {}", allowedRatePerMinute);
}
public void start(int initialDelayMs) {
if (started.compareAndSet(false, true)) {
instanceInfo.setIsDirty(); // for initial register
Future next = scheduler.schedule(this, initialDelayMs, TimeUnit.SECONDS);
scheduledPeriodicRef.set(next);
}
}
public void stop() {
shutdownAndAwaitTermination(scheduler);
started.set(false);
}
private void shutdownAndAwaitTermination(ExecutorService pool) {
pool.shutdown();
try {
if (!pool.awaitTermination(3, TimeUnit.SECONDS)) {
pool.shutdownNow();
}
} catch (InterruptedException e) {
logger.warn("InstanceInfoReplicator stop interrupted");
}
}
public boolean onDemandUpdate() {
if (rateLimiter.acquire(burstSize, allowedRatePerMinute)) {
if (!scheduler.isShutdown()) {
scheduler.submit(new Runnable() {
@Override
public void run() {
logger.debug("Executing on-demand update of local InstanceInfo");
Future latestPeriodic = scheduledPeriodicRef.get();
if (latestPeriodic != null && !latestPeriodic.isDone()) {
logger.debug("Canceling the latest scheduled update, it will be rescheduled at the end of on demand update");
latestPeriodic.cancel(false);
}
InstanceInfoReplicator.this.run();
}
});
return true;
} else {
logger.warn("Ignoring onDemand update due to stopped scheduler");
return false;
}
} else {
logger.warn("Ignoring onDemand update due to rate limiter");
return false;
}
}
public void run() {
try {
discoveryClient.refreshInstanceInfo();
Long dirtyTimestamp = instanceInfo.isDirtyWithTime();
if (dirtyTimestamp != null) {
discoveryClient.register();
instanceInfo.unsetIsDirty(dirtyTimestamp);
}
} catch (Throwable t) {
logger.warn("There was a problem with the instance info replicator", t);
} finally {
Future next = scheduler.schedule(this, replicationIntervalSeconds, TimeUnit.SECONDS);
scheduledPeriodicRef.set(next);
}
}
}
| 7,917 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/InternalEurekaStatusModule.java | package com.netflix.discovery;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
import com.google.common.base.Supplier;
import com.google.inject.AbstractModule;
import com.google.inject.TypeLiteral;
import com.netflix.appinfo.InstanceInfo;
/**
* @deprecated 2016-09-06 this class will be deleted soon. This is also an internal class.
*
* Specific bindings for eureka status checker.
*
* Note that this is an internal modules and ASSUMES that a binding for
* DiscoveryClient was already set.
*
* Exposed bindings,
*
* @UpStatus Supplier<Boolean>
* @DownStatus Supplier<Boolean>
* @UpStatus Observable<Boolean>
*
* @author elandau
*
*/
@Deprecated
@Singleton
public class InternalEurekaStatusModule extends AbstractModule {
@Singleton
public static class UpStatusProvider implements Provider<Supplier<Boolean>> {
@Inject
private Provider<EurekaUpStatusResolver> upStatus;
@Override
public Supplier<Boolean> get() {
final EurekaUpStatusResolver resolver = upStatus.get();
return new Supplier<Boolean>() {
@Override
public Boolean get() {
return resolver.getStatus().equals(InstanceInfo.InstanceStatus.UP);
}
};
}
}
@Singleton
public static class DownStatusProvider implements Provider<Supplier<Boolean>> {
@Inject
private Provider<EurekaUpStatusResolver> upStatus;
@Override
public Supplier<Boolean> get() {
final EurekaUpStatusResolver resolver = upStatus.get();
return new Supplier<Boolean>() {
@Override
public Boolean get() {
return !resolver.getStatus().equals(InstanceInfo.InstanceStatus.UP);
}
};
}
}
@Override
protected void configure() {
bind(new TypeLiteral<Supplier<Boolean>>() {
})
.toProvider(UpStatusProvider.class);
bind(new TypeLiteral<Supplier<Boolean>>() {
})
.toProvider(DownStatusProvider.class);
}
}
| 7,918 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/DefaultEurekaClientConfig.java | /*
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery;
import javax.annotation.Nullable;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.inject.ProvidedBy;
import com.netflix.appinfo.EurekaAccept;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.config.DynamicStringProperty;
import com.netflix.discovery.internal.util.Archaius1Utils;
import com.netflix.discovery.providers.DefaultEurekaClientConfigProvider;
import com.netflix.discovery.shared.transport.DefaultEurekaTransportConfig;
import com.netflix.discovery.shared.transport.EurekaTransportConfig;
import static com.netflix.discovery.PropertyBasedClientConfigConstants.*;
/**
*
* A default implementation of eureka client configuration as required by
* {@link EurekaClientConfig}.
*
* <p>
* The information required for configuring eureka client is provided in a
* configuration file.The configuration file is searched for in the classpath
* with the name specified by the property <em>eureka.client.props</em> and with
* the suffix <em>.properties</em>. If the property is not specified,
* <em>eureka-client.properties</em> is assumed as the default.The properties
* that are looked up uses the <em>namespace</em> passed on to this class.
* </p>
*
* <p>
* If the <em>eureka.environment</em> property is specified, additionally
* <em>eureka-client-<eureka.environment>.properties</em> is loaded in addition
* to <em>eureka-client.properties</em>.
* </p>
*
* @author Karthik Ranganathan
*
*/
@Singleton
@ProvidedBy(DefaultEurekaClientConfigProvider.class)
public class DefaultEurekaClientConfig implements EurekaClientConfig {
/**
* @deprecated 2016-08-29 use {@link com.netflix.discovery.CommonConstants#DEFAULT_CONFIG_NAMESPACE}
*/
@Deprecated
public static final String DEFAULT_NAMESPACE = CommonConstants.DEFAULT_CONFIG_NAMESPACE + ".";
public static final String DEFAULT_ZONE = "defaultZone";
public static final String URL_SEPARATOR = "\\s*,\\s*";
private final String namespace;
private final DynamicPropertyFactory configInstance;
private final EurekaTransportConfig transportConfig;
public DefaultEurekaClientConfig() {
this(CommonConstants.DEFAULT_CONFIG_NAMESPACE);
}
public DefaultEurekaClientConfig(String namespace) {
this.namespace = namespace.endsWith(".")
? namespace
: namespace + ".";
this.configInstance = Archaius1Utils.initConfig(CommonConstants.CONFIG_FILE_NAME);
this.transportConfig = new DefaultEurekaTransportConfig(namespace, configInstance);
}
/*
* (non-Javadoc)
*
* @see
* com.netflix.discovery.EurekaClientConfig#getRegistryFetchIntervalSeconds
* ()
*/
@Override
public int getRegistryFetchIntervalSeconds() {
return configInstance.getIntProperty(
namespace + REGISTRY_REFRESH_INTERVAL_KEY, 30).get();
}
/*
* (non-Javadoc)
*
* @see com.netflix.discovery.EurekaClientConfig#
* getInstanceInfoReplicationIntervalSeconds()
*/
@Override
public int getInstanceInfoReplicationIntervalSeconds() {
return configInstance.getIntProperty(
namespace + REGISTRATION_REPLICATION_INTERVAL_KEY, 30).get();
}
@Override
public int getInitialInstanceInfoReplicationIntervalSeconds() {
return configInstance.getIntProperty(
namespace + INITIAL_REGISTRATION_REPLICATION_DELAY_KEY, 40).get();
}
/*
* (non-Javadoc)
*
* @see com.netflix.discovery.EurekaClientConfig#getDnsPollIntervalSeconds()
*/
@Override
public int getEurekaServiceUrlPollIntervalSeconds() {
return configInstance.getIntProperty(
namespace + EUREKA_SERVER_URL_POLL_INTERVAL_KEY, 5 * 60 * 1000).get() / 1000;
}
/*
* (non-Javadoc)
*
* @see com.netflix.discovery.EurekaClientConfig#getProxyHost()
*/
@Override
public String getProxyHost() {
return configInstance.getStringProperty(
namespace + EUREKA_SERVER_PROXY_HOST_KEY, null).get();
}
/*
* (non-Javadoc)
*
* @see com.netflix.discovery.EurekaClientConfig#getProxyPort()
*/
@Override
public String getProxyPort() {
return configInstance.getStringProperty(
namespace + EUREKA_SERVER_PROXY_PORT_KEY, null).get();
}
@Override
public String getProxyUserName() {
return configInstance.getStringProperty(
namespace + EUREKA_SERVER_PROXY_USERNAME_KEY, null).get();
}
@Override
public String getProxyPassword() {
return configInstance.getStringProperty(
namespace + EUREKA_SERVER_PROXY_PASSWORD_KEY, null).get();
}
/*
* (non-Javadoc)
*
* @see com.netflix.discovery.EurekaClientConfig#shouldGZipContent()
*/
@Override
public boolean shouldGZipContent() {
return configInstance.getBooleanProperty(
namespace + EUREKA_SERVER_GZIP_CONTENT_KEY, true).get();
}
/*
* (non-Javadoc)
*
* @see com.netflix.discovery.EurekaClientConfig#getDSServerReadTimeout()
*/
@Override
public int getEurekaServerReadTimeoutSeconds() {
return configInstance.getIntProperty(
namespace + EUREKA_SERVER_READ_TIMEOUT_KEY, 8).get();
}
/*
* (non-Javadoc)
*
* @see com.netflix.discovery.EurekaClientConfig#getDSServerConnectTimeout()
*/
@Override
public int getEurekaServerConnectTimeoutSeconds() {
return configInstance.getIntProperty(
namespace + EUREKA_SERVER_CONNECT_TIMEOUT_KEY, 5).get();
}
/*
* (non-Javadoc)
*
* @see com.netflix.discovery.EurekaClientConfig#getBackupRegistryImpl()
*/
@Override
public String getBackupRegistryImpl() {
return configInstance.getStringProperty(namespace + BACKUP_REGISTRY_CLASSNAME_KEY,
null).get();
}
/*
* (non-Javadoc)
*
* @see
* com.netflix.discovery.EurekaClientConfig#getDSServerTotalMaxConnections()
*/
@Override
public int getEurekaServerTotalConnections() {
return configInstance.getIntProperty(
namespace + EUREKA_SERVER_MAX_CONNECTIONS_KEY, 200).get();
}
/*
* (non-Javadoc)
*
* @see
* com.netflix.discovery.EurekaClientConfig#getDSServerConnectionsPerHost()
*/
@Override
public int getEurekaServerTotalConnectionsPerHost() {
return configInstance.getIntProperty(
namespace + EUREKA_SERVER_MAX_CONNECTIONS_PER_HOST_KEY, 50).get();
}
/*
* (non-Javadoc)
*
* @see com.netflix.discovery.EurekaClientConfig#getDSServerURLContext()
*/
@Override
public String getEurekaServerURLContext() {
return configInstance.getStringProperty(
namespace + EUREKA_SERVER_URL_CONTEXT_KEY,
configInstance.getStringProperty(namespace + EUREKA_SERVER_FALLBACK_URL_CONTEXT_KEY, null)
.get()).get();
}
/*
* (non-Javadoc)
*
* @see com.netflix.discovery.EurekaClientConfig#getDSServerPort()
*/
@Override
public String getEurekaServerPort() {
return configInstance.getStringProperty(
namespace + EUREKA_SERVER_PORT_KEY,
configInstance.getStringProperty(namespace + EUREKA_SERVER_FALLBACK_PORT_KEY, null)
.get()).get();
}
/*
* (non-Javadoc)
*
* @see com.netflix.discovery.EurekaClientConfig#getDSServerDomain()
*/
@Override
public String getEurekaServerDNSName() {
return configInstance.getStringProperty(
namespace + EUREKA_SERVER_DNS_NAME_KEY,
configInstance
.getStringProperty(namespace + EUREKA_SERVER_FALLBACK_DNS_NAME_KEY, null)
.get()).get();
}
/*
* (non-Javadoc)
*
* @see com.netflix.discovery.EurekaClientConfig#shouldUseDns()
*/
@Override
public boolean shouldUseDnsForFetchingServiceUrls() {
return configInstance.getBooleanProperty(namespace + SHOULD_USE_DNS_KEY,
false).get();
}
/*
* (non-Javadoc)
*
* @see
* com.netflix.discovery.EurekaClientConfig#getDiscoveryRegistrationEnabled()
*/
@Override
public boolean shouldRegisterWithEureka() {
return configInstance.getBooleanProperty(
namespace + REGISTRATION_ENABLED_KEY, true).get();
}
/*
* (non-Javadoc)
*
* @see
* com.netflix.discovery.EurekaClientConfig#shouldUnregisterOnShutdown()
*/
@Override
public boolean shouldUnregisterOnShutdown() {
return configInstance.getBooleanProperty(
namespace + SHOULD_UNREGISTER_ON_SHUTDOWN_KEY, true).get();
}
/*
* (non-Javadoc)
*
* @see com.netflix.discovery.EurekaClientConfig#shouldPreferSameZoneDS()
*/
@Override
public boolean shouldPreferSameZoneEureka() {
return configInstance.getBooleanProperty(namespace + SHOULD_PREFER_SAME_ZONE_SERVER_KEY,
true).get();
}
@Override
public boolean allowRedirects() {
return configInstance.getBooleanProperty(namespace + SHOULD_ALLOW_REDIRECTS_KEY, false).get();
}
/*
* (non-Javadoc)
*
* @see com.netflix.discovery.EurekaClientConfig#shouldLogDeltaDiff()
*/
@Override
public boolean shouldLogDeltaDiff() {
return configInstance.getBooleanProperty(
namespace + SHOULD_LOG_DELTA_DIFF_KEY, false).get();
}
/*
* (non-Javadoc)
*
* @see com.netflix.discovery.EurekaClientConfig#shouldDisableDelta()
*/
@Override
public boolean shouldDisableDelta() {
return configInstance.getBooleanProperty(namespace + SHOULD_DISABLE_DELTA_KEY,
false).get();
}
@Nullable
@Override
public String fetchRegistryForRemoteRegions() {
return configInstance.getStringProperty(namespace + SHOULD_FETCH_REMOTE_REGION_KEY, null).get();
}
/*
* (non-Javadoc)
*
* @see com.netflix.discovery.EurekaClientConfig#getRegion()
*/
@Override
public String getRegion() {
DynamicStringProperty defaultEurekaRegion = configInstance.getStringProperty(CLIENT_REGION_FALLBACK_KEY, Values.DEFAULT_CLIENT_REGION);
return configInstance.getStringProperty(namespace + CLIENT_REGION_KEY, defaultEurekaRegion.get()).get();
}
/*
* (non-Javadoc)
*
* @see com.netflix.discovery.EurekaClientConfig#getAvailabilityZones()
*/
@Override
public String[] getAvailabilityZones(String region) {
return configInstance
.getStringProperty(
namespace + region + "." + CONFIG_AVAILABILITY_ZONE_PREFIX,
DEFAULT_ZONE).get().split(URL_SEPARATOR);
}
/*
* (non-Javadoc)
*
* @see
* com.netflix.discovery.EurekaClientConfig#getEurekaServerServiceUrls()
*/
@Override
public List<String> getEurekaServerServiceUrls(String myZone) {
String serviceUrls = configInstance.getStringProperty(
namespace + CONFIG_EUREKA_SERVER_SERVICE_URL_PREFIX + "." + myZone, null).get();
if (serviceUrls == null || serviceUrls.isEmpty()) {
serviceUrls = configInstance.getStringProperty(
namespace + CONFIG_EUREKA_SERVER_SERVICE_URL_PREFIX + ".default", null).get();
}
if (serviceUrls != null) {
return Arrays.asList(serviceUrls.split(URL_SEPARATOR));
}
return new ArrayList<String>();
}
/*
* (non-Javadoc)
*
* @see
* com.netflix.discovery.EurekaClientConfig#shouldFilterOnlyUpInstances()
*/
@Override
public boolean shouldFilterOnlyUpInstances() {
return configInstance.getBooleanProperty(
namespace + SHOULD_FILTER_ONLY_UP_INSTANCES_KEY, true).get();
}
/*
* (non-Javadoc)
*
* @see
* com.netflix.discovery.EurekaClientConfig#getEurekaConnectionIdleTimeout()
*/
@Override
public int getEurekaConnectionIdleTimeoutSeconds() {
return configInstance.getIntProperty(
namespace + EUREKA_SERVER_CONNECTION_IDLE_TIMEOUT_KEY, 45)
.get();
}
@Override
public boolean shouldFetchRegistry() {
return configInstance.getBooleanProperty(
namespace + FETCH_REGISTRY_ENABLED_KEY, true).get();
}
@Override
public boolean shouldEnforceFetchRegistryAtInit() {
return configInstance.getBooleanProperty(
namespace + SHOULD_ENFORCE_FETCH_REGISTRY_AT_INIT_KEY, false).get();
}
/*
* (non-Javadoc)
*
* @see com.netflix.discovery.EurekaClientConfig#getRegistryRefreshSingleVipAddress()
*/
@Override
public String getRegistryRefreshSingleVipAddress() {
return configInstance.getStringProperty(
namespace + FETCH_SINGLE_VIP_ONLY_KEY, null).get();
}
/**
* (non-Javadoc)
*
* @see com.netflix.discovery.EurekaClientConfig#getHeartbeatExecutorThreadPoolSize()
*/
@Override
public int getHeartbeatExecutorThreadPoolSize() {
return configInstance.getIntProperty(
namespace + HEARTBEAT_THREADPOOL_SIZE_KEY, Values.DEFAULT_EXECUTOR_THREAD_POOL_SIZE).get();
}
@Override
public int getHeartbeatExecutorExponentialBackOffBound() {
return configInstance.getIntProperty(
namespace + HEARTBEAT_BACKOFF_BOUND_KEY, Values.DEFAULT_EXECUTOR_THREAD_POOL_BACKOFF_BOUND).get();
}
/**
* (non-Javadoc)
*
* @see com.netflix.discovery.EurekaClientConfig#getCacheRefreshExecutorThreadPoolSize()
*/
@Override
public int getCacheRefreshExecutorThreadPoolSize() {
return configInstance.getIntProperty(
namespace + CACHEREFRESH_THREADPOOL_SIZE_KEY, Values.DEFAULT_EXECUTOR_THREAD_POOL_SIZE).get();
}
@Override
public int getCacheRefreshExecutorExponentialBackOffBound() {
return configInstance.getIntProperty(
namespace + CACHEREFRESH_BACKOFF_BOUND_KEY, Values.DEFAULT_EXECUTOR_THREAD_POOL_BACKOFF_BOUND).get();
}
@Override
public String getDollarReplacement() {
return configInstance.getStringProperty(
namespace + CONFIG_DOLLAR_REPLACEMENT_KEY, Values.CONFIG_DOLLAR_REPLACEMENT).get();
}
@Override
public String getEscapeCharReplacement() {
return configInstance.getStringProperty(
namespace + CONFIG_ESCAPE_CHAR_REPLACEMENT_KEY, Values.CONFIG_ESCAPE_CHAR_REPLACEMENT).get();
}
@Override
public boolean shouldOnDemandUpdateStatusChange() {
return configInstance.getBooleanProperty(
namespace + SHOULD_ONDEMAND_UPDATE_STATUS_KEY, true).get();
}
@Override
public boolean shouldEnforceRegistrationAtInit() {
return configInstance.getBooleanProperty(
namespace + SHOULD_ENFORCE_REGISTRATION_AT_INIT, false).get();
}
@Override
public String getEncoderName() {
return configInstance.getStringProperty(
namespace + CLIENT_ENCODER_NAME_KEY, null).get();
}
@Override
public String getDecoderName() {
return configInstance.getStringProperty(
namespace + CLIENT_DECODER_NAME_KEY, null).get();
}
@Override
public String getClientDataAccept() {
return configInstance.getStringProperty(
namespace + CLIENT_DATA_ACCEPT_KEY, EurekaAccept.full.name()).get();
}
@Override
public String getExperimental(String name) {
return configInstance.getStringProperty(namespace + CONFIG_EXPERIMENTAL_PREFIX + "." + name, null).get();
}
@Override
public EurekaTransportConfig getTransportConfig() {
return transportConfig;
}
}
| 7,919 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/StatusChangeEvent.java | package com.netflix.discovery;
import com.netflix.appinfo.InstanceInfo;
/**
* Event containing the latest instance status information. This event
* is sent to the {@link com.netflix.eventbus.spi.EventBus} by {@link EurekaClient) whenever
* a status change is identified from the remote Eureka server response.
*/
public class StatusChangeEvent extends DiscoveryEvent {
private final InstanceInfo.InstanceStatus current;
private final InstanceInfo.InstanceStatus previous;
public StatusChangeEvent(InstanceInfo.InstanceStatus previous, InstanceInfo.InstanceStatus current) {
super();
this.current = current;
this.previous = previous;
}
/**
* Return the up current when the event was generated.
* @return true if current is up or false for ALL other current values
*/
public boolean isUp() {
return this.current.equals(InstanceInfo.InstanceStatus.UP);
}
/**
* @return The current at the time the event is generated.
*/
public InstanceInfo.InstanceStatus getStatus() {
return current;
}
/**
* @return Return the client status immediately before the change
*/
public InstanceInfo.InstanceStatus getPreviousStatus() {
return previous;
}
@Override
public String toString() {
return "StatusChangeEvent [timestamp=" + getTimestamp() + ", current=" + current + ", previous="
+ previous + "]";
}
}
| 7,920 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/DiscoveryManager.java | /*
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.EurekaInstanceConfig;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.shared.LookupService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @deprecated use EurekaModule and DI.
*
* <tt>Discovery Manager</tt> configures <tt>Discovery Client</tt> based on the
* properties specified.
*
* <p>
* The configuration file is searched for in the classpath with the name
* specified by the property <em>eureka.client.props</em> and with the suffix
* <em>.properties</em>. If the property is not specified,
* <em>eureka-client.properties</em> is assumed as the default.
*
* @author Karthik Ranganathan
*
*/
@Deprecated
public class DiscoveryManager {
private static final Logger logger = LoggerFactory.getLogger(DiscoveryManager.class);
private DiscoveryClient discoveryClient;
private EurekaClient clientOverride;
private EurekaInstanceConfig eurekaInstanceConfig;
private EurekaClientConfig eurekaClientConfig;
private static final DiscoveryManager s_instance = new DiscoveryManager();
private DiscoveryManager() {
}
public static DiscoveryManager getInstance() {
return s_instance;
}
public void setDiscoveryClient(DiscoveryClient discoveryClient) {
this.discoveryClient = discoveryClient;
}
public void setClientOverride(EurekaClient eurekaClient) {
this.clientOverride = eurekaClient;
}
public void setEurekaClientConfig(EurekaClientConfig eurekaClientConfig) {
this.eurekaClientConfig = eurekaClientConfig;
}
public void setEurekaInstanceConfig(EurekaInstanceConfig eurekaInstanceConfig) {
this.eurekaInstanceConfig = eurekaInstanceConfig;
}
/**
* Initializes the <tt>Discovery Client</tt> with the given configuration.
*
* @param config
* the instance info configuration that will be used for
* registration with Eureka.
* @param eurekaConfig the eureka client configuration of the instance.
*/
public void initComponent(EurekaInstanceConfig config,
EurekaClientConfig eurekaConfig, AbstractDiscoveryClientOptionalArgs args) {
this.eurekaInstanceConfig = config;
this.eurekaClientConfig = eurekaConfig;
if (ApplicationInfoManager.getInstance().getInfo() == null) {
// Initialize application info
ApplicationInfoManager.getInstance().initComponent(config);
}
InstanceInfo info = ApplicationInfoManager.getInstance().getInfo();
discoveryClient = new DiscoveryClient(info, eurekaConfig, args);
}
public void initComponent(EurekaInstanceConfig config,
EurekaClientConfig eurekaConfig) {
initComponent(config, eurekaConfig, null);
}
/**
* Shuts down the <tt>Discovery Client</tt> which unregisters the
* information about this instance from the <tt>Discovery Server</tt>.
*/
public void shutdownComponent() {
if (discoveryClient != null) {
try {
discoveryClient.shutdown();
discoveryClient = null;
} catch (Throwable th) {
logger.error("Error in shutting down client", th);
}
}
}
public LookupService getLookupService() {
return getEurekaClient();
}
/**
* @deprecated use {@link #getEurekaClient()}
*
* Get the {@link DiscoveryClient}.
* @return the client that is used to talk to eureka.
*/
@Deprecated
public DiscoveryClient getDiscoveryClient() {
return discoveryClient;
}
/**
*
* Get the {@link EurekaClient} implementation.
* @return the client that is used to talk to eureka.
*/
public EurekaClient getEurekaClient() {
if (clientOverride != null) {
return clientOverride;
}
return discoveryClient;
}
/**
* Get the instance of {@link EurekaClientConfig} this instance was initialized with.
* @return the instance of {@link EurekaClientConfig} this instance was initialized with.
*/
public EurekaClientConfig getEurekaClientConfig() {
return eurekaClientConfig;
}
/**
* Get the instance of {@link EurekaInstanceConfig} this instance was initialized with.
* @return the instance of {@link EurekaInstanceConfig} this instance was initialized with.
*/
public EurekaInstanceConfig getEurekaInstanceConfig() {
return eurekaInstanceConfig;
}
} | 7,921 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/AbstractDiscoveryClientOptionalArgs.java | package com.netflix.discovery;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import javax.inject.Provider;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import com.google.inject.Inject;
import com.netflix.appinfo.HealthCheckCallback;
import com.netflix.appinfo.HealthCheckHandler;
import com.netflix.discovery.shared.transport.TransportClientFactory;
import com.netflix.discovery.shared.transport.jersey.EurekaJerseyClient;
import com.netflix.discovery.shared.transport.jersey.TransportClientFactories;
import com.netflix.eventbus.spi.EventBus;
/**
* <T> The type for client supplied filters (supports jersey1 and jersey2)
*/
public abstract class AbstractDiscoveryClientOptionalArgs<T> {
Provider<HealthCheckCallback> healthCheckCallbackProvider;
Provider<HealthCheckHandler> healthCheckHandlerProvider;
PreRegistrationHandler preRegistrationHandler;
Collection<T> additionalFilters;
EurekaJerseyClient eurekaJerseyClient;
TransportClientFactory transportClientFactory;
TransportClientFactories transportClientFactories;
private Set<EurekaEventListener> eventListeners;
private Optional<SSLContext> sslContext = Optional.empty();
private Optional<HostnameVerifier> hostnameVerifier = Optional.empty();
@Inject(optional = true)
public void setEventListeners(Set<EurekaEventListener> listeners) {
if (eventListeners == null) {
eventListeners = new HashSet<>();
}
eventListeners.addAll(listeners);
}
@Inject(optional = true)
public void setEventBus(final EventBus eventBus) {
if (eventListeners == null) {
eventListeners = new HashSet<>();
}
eventListeners.add(new EurekaEventListener() {
@Override
public void onEvent(EurekaEvent event) {
eventBus.publish(event);
}
});
}
@Inject(optional = true)
public void setHealthCheckCallbackProvider(Provider<HealthCheckCallback> healthCheckCallbackProvider) {
this.healthCheckCallbackProvider = healthCheckCallbackProvider;
}
@Inject(optional = true)
public void setHealthCheckHandlerProvider(Provider<HealthCheckHandler> healthCheckHandlerProvider) {
this.healthCheckHandlerProvider = healthCheckHandlerProvider;
}
@Inject(optional = true)
public void setPreRegistrationHandler(PreRegistrationHandler preRegistrationHandler) {
this.preRegistrationHandler = preRegistrationHandler;
}
@Inject(optional = true)
public void setAdditionalFilters(Collection<T> additionalFilters) {
this.additionalFilters = additionalFilters;
}
@Inject(optional = true)
public void setEurekaJerseyClient(EurekaJerseyClient eurekaJerseyClient) {
this.eurekaJerseyClient = eurekaJerseyClient;
}
Set<EurekaEventListener> getEventListeners() {
return eventListeners == null ? Collections.<EurekaEventListener>emptySet() : eventListeners;
}
public TransportClientFactories getTransportClientFactories() {
return transportClientFactories;
}
@Inject(optional = true)
public void setTransportClientFactories(TransportClientFactories transportClientFactories) {
this.transportClientFactories = transportClientFactories;
}
public Optional<SSLContext> getSSLContext() {
return sslContext;
}
@Inject(optional = true)
public void setSSLContext(SSLContext sslContext) {
this.sslContext = Optional.of(sslContext);
}
public Optional<HostnameVerifier> getHostnameVerifier() {
return hostnameVerifier;
}
@Inject(optional = true)
public void setHostnameVerifier(HostnameVerifier hostnameVerifier) {
this.hostnameVerifier = Optional.of(hostnameVerifier);
}
} | 7,922 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/EurekaIdentityHeaderFilter.java | package com.netflix.discovery;
import com.netflix.appinfo.AbstractEurekaIdentity;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientRequest;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.filter.ClientFilter;
public class EurekaIdentityHeaderFilter extends ClientFilter {
private final AbstractEurekaIdentity authInfo;
public EurekaIdentityHeaderFilter(AbstractEurekaIdentity authInfo) {
this.authInfo = authInfo;
}
@Override
public ClientResponse handle(ClientRequest cr) throws ClientHandlerException {
if (authInfo != null) {
cr.getHeaders().putSingle(AbstractEurekaIdentity.AUTH_NAME_HEADER_KEY, authInfo.getName());
cr.getHeaders().putSingle(AbstractEurekaIdentity.AUTH_VERSION_HEADER_KEY, authInfo.getVersion());
if (authInfo.getId() != null) {
cr.getHeaders().putSingle(AbstractEurekaIdentity.AUTH_ID_HEADER_KEY, authInfo.getId());
}
}
return getNext().handle(cr);
}
}
| 7,923 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/EurekaClientConfig.java | /*
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery;
import java.util.List;
import javax.annotation.Nullable;
import com.google.inject.ImplementedBy;
import com.netflix.discovery.shared.transport.EurekaTransportConfig;
/**
* Configuration information required by the eureka clients to register an
* instance with <em>Eureka</em> server.
*
* <p>
* Most of the required information is provided by the default configuration
* {@link DefaultEurekaClientConfig}. The users just need to provide the eureka
* server service urls. The Eureka server service urls can be configured by 2
* mechanisms
*
* 1) By registering the information in the DNS. 2) By specifying it in the
* configuration.
* </p>
*
*
* Once the client is registered, users can look up information from
* {@link EurekaClient} based on <em>virtual hostname</em> (also called
* VIPAddress), the most common way of doing it or by other means to get the
* information necessary to talk to other instances registered with
* <em>Eureka</em>.
*
* <p>
* Note that all configurations are not effective at runtime unless and
* otherwise specified.
* </p>
*
* @author Karthik Ranganathan
*
*/
@ImplementedBy(DefaultEurekaClientConfig.class)
public interface EurekaClientConfig {
/**
* Indicates how often(in seconds) to fetch the registry information from
* the eureka server.
*
* @return the fetch interval in seconds.
*/
int getRegistryFetchIntervalSeconds();
/**
* Indicates how often(in seconds) to replicate instance changes to be
* replicated to the eureka server.
*
* @return the instance replication interval in seconds.
*/
int getInstanceInfoReplicationIntervalSeconds();
/**
* Indicates how long initially (in seconds) to replicate instance info
* to the eureka server
*/
int getInitialInstanceInfoReplicationIntervalSeconds();
/**
* Indicates how often(in seconds) to poll for changes to eureka server
* information.
*
* <p>
* Eureka servers could be added or removed and this setting controls how
* soon the eureka clients should know about it.
* </p>
*
* @return the interval to poll for eureka service url changes.
*/
int getEurekaServiceUrlPollIntervalSeconds();
/**
* Gets the proxy host to eureka server if any.
*
* @return the proxy host.
*/
String getProxyHost();
/**
* Gets the proxy port to eureka server if any.
*
* @return the proxy port.
*/
String getProxyPort();
/**
* Gets the proxy user name if any.
*
* @return the proxy user name.
*/
String getProxyUserName();
/**
* Gets the proxy password if any.
*
* @return the proxy password.
*/
String getProxyPassword();
/**
* Indicates whether the content fetched from eureka server has to be
* compressed whenever it is supported by the server. The registry
* information from the eureka server is compressed for optimum network
* traffic.
*
* @return true, if the content need to be compressed, false otherwise.
* @deprecated gzip content encoding will be always enforced in the next minor Eureka release (see com.netflix.eureka.GzipEncodingEnforcingFilter).
*/
boolean shouldGZipContent();
/**
* Indicates how long to wait (in seconds) before a read from eureka server
* needs to timeout.
*
* @return time in seconds before the read should timeout.
*/
int getEurekaServerReadTimeoutSeconds();
/**
* Indicates how long to wait (in seconds) before a connection to eureka
* server needs to timeout.
*
* <p>
* Note that the connections in the client are pooled by
* {@link org.apache.http.client.HttpClient} and this setting affects the actual
* connection creation and also the wait time to get the connection from the
* pool.
* </p>
*
* @return time in seconds before the connections should timeout.
*/
int getEurekaServerConnectTimeoutSeconds();
/**
* Gets the name of the implementation which implements
* {@link BackupRegistry} to fetch the registry information as a fall back
* option for only the first time when the eureka client starts.
*
* <p>
* This may be needed for applications which needs additional resiliency for
* registry information without which it cannot operate.
* </p>
*
* @return the class name which implements {@link BackupRegistry}.
*/
String getBackupRegistryImpl();
/**
* Gets the total number of connections that is allowed from eureka client
* to all eureka servers.
*
* @return total number of allowed connections from eureka client to all
* eureka servers.
*/
int getEurekaServerTotalConnections();
/**
* Gets the total number of connections that is allowed from eureka client
* to a eureka server host.
*
* @return total number of allowed connections from eureka client to a
* eureka server.
*/
int getEurekaServerTotalConnectionsPerHost();
/**
* Gets the URL context to be used to construct the <em>service url</em> to
* contact eureka server when the list of eureka servers come from the
* DNS.This information is not required if the contract returns the service
* urls by implementing {@link #getEurekaServerServiceUrls(String)}.
*
* <p>
* The DNS mechanism is used when
* {@link #shouldUseDnsForFetchingServiceUrls()} is set to <em>true</em> and
* the eureka client expects the DNS to configured a certain way so that it
* can fetch changing eureka servers dynamically.
* </p>
*
* <p>
* <em>The changes are effective at runtime.</em>
* </p>
*
* @return the string indicating the context {@link java.net.URI} of the eureka
* server.
*/
String getEurekaServerURLContext();
/**
* Gets the port to be used to construct the <em>service url</em> to contact
* eureka server when the list of eureka servers come from the DNS.This
* information is not required if the contract returns the service urls by
* implementing {@link #getEurekaServerServiceUrls(String)}.
*
* <p>
* The DNS mechanism is used when
* {@link #shouldUseDnsForFetchingServiceUrls()} is set to <em>true</em> and
* the eureka client expects the DNS to configured a certain way so that it
* can fetch changing eureka servers dynamically.
* </p>
*
* <p>
* <em>The changes are effective at runtime.</em>
* </p>
*
* @return the string indicating the port where the eureka server is
* listening.
*/
String getEurekaServerPort();
/**
* Gets the DNS name to be queried to get the list of eureka servers.This
* information is not required if the contract returns the service urls by
* implementing {@link #getEurekaServerServiceUrls(String)}.
*
* <p>
* The DNS mechanism is used when
* {@link #shouldUseDnsForFetchingServiceUrls()} is set to <em>true</em> and
* the eureka client expects the DNS to configured a certain way so that it
* can fetch changing eureka servers dynamically.
* </p>
*
* <p>
* <em>The changes are effective at runtime.</em>
* </p>
*
* @return the string indicating the DNS name to be queried for eureka
* servers.
*/
String getEurekaServerDNSName();
/**
* Indicates whether the eureka client should use the DNS mechanism to fetch
* a list of eureka servers to talk to. When the DNS name is updated to have
* additional servers, that information is used immediately after the eureka
* client polls for that information as specified in
* {@link #getEurekaServiceUrlPollIntervalSeconds()}.
*
* <p>
* Alternatively, the service urls can be returned
* {@link #getEurekaServerServiceUrls(String)}, but the users should implement
* their own mechanism to return the updated list in case of changes.
* </p>
*
* <p>
* <em>The changes are effective at runtime.</em>
* </p>
*
* @return true if the DNS mechanism should be used for fetching urls, false otherwise.
*/
boolean shouldUseDnsForFetchingServiceUrls();
/**
* Indicates whether or not this instance should register its information
* with eureka server for discovery by others.
*
* <p>
* In some cases, you do not want your instances to be discovered whereas
* you just want do discover other instances.
* </p>
*
* @return true if this instance should register with eureka, false
* otherwise
*/
boolean shouldRegisterWithEureka();
/**
* Indicates whether the client should explicitly unregister itself from the remote server
* on client shutdown.
*
* @return true if this instance should unregister with eureka on client shutdown, false otherwise
*/
default boolean shouldUnregisterOnShutdown() {
return true;
}
/**
* Indicates whether or not this instance should try to use the eureka
* server in the same zone for latency and/or other reason.
*
* <p>
* Ideally eureka clients are configured to talk to servers in the same zone
* </p>
*
* <p>
* <em>The changes are effective at runtime at the next registry fetch cycle as specified by
* {@link #getRegistryFetchIntervalSeconds()}</em>
* </p>
*
* @return true if the eureka client should prefer the server in the same
* zone, false otherwise.
*/
boolean shouldPreferSameZoneEureka();
/**
* Indicates whether server can redirect a client request to a backup server/cluster.
* If set to false, the server will handle the request directly, If set to true, it may
* send HTTP redirect to the client, with a new server location.
*
* @return true if HTTP redirects are allowed
*/
boolean allowRedirects();
/**
* Indicates whether to log differences between the eureka server and the
* eureka client in terms of registry information.
*
* <p>
* Eureka client tries to retrieve only delta changes from eureka server to
* minimize network traffic. After receiving the deltas, eureka client
* reconciles the information from the server to verify it has not missed
* out some information. Reconciliation failures could happen when the
* client has had network issues communicating to server.If the
* reconciliation fails, eureka client gets the full registry information.
* </p>
*
* <p>
* While getting the full registry information, the eureka client can log
* the differences between the client and the server and this setting
* controls that.
* </p>
* <p>
* <em>The changes are effective at runtime at the next registry fetch cycle as specified by
* {@link #getRegistryFetchIntervalSeconds()}</em>
* </p>
*
* @return true if the eureka client should log delta differences in the
* case of reconciliation failure.
*/
boolean shouldLogDeltaDiff();
/**
* Indicates whether the eureka client should disable fetching of delta and
* should rather resort to getting the full registry information.
*
* <p>
* Note that the delta fetches can reduce the traffic tremendously, because
* the rate of change with the eureka server is normally much lower than the
* rate of fetches.
* </p>
* <p>
* <em>The changes are effective at runtime at the next registry fetch cycle as specified by
* {@link #getRegistryFetchIntervalSeconds()}</em>
* </p>
*
* @return true to enable fetching delta information for registry, false to
* get the full registry.
*/
boolean shouldDisableDelta();
/**
* Comma separated list of regions for which the eureka registry information will be fetched. It is mandatory to
* define the availability zones for each of these regions as returned by {@link #getAvailabilityZones(String)}.
* Failing to do so, will result in failure of discovery client startup.
*
* @return Comma separated list of regions for which the eureka registry information will be fetched.
* <code>null</code> if no remote region has to be fetched.
*/
@Nullable
String fetchRegistryForRemoteRegions();
/**
* Gets the region (used in AWS datacenters) where this instance resides.
*
* @return AWS region where this instance resides.
*/
String getRegion();
/**
* Gets the list of availability zones (used in AWS data centers) for the
* region in which this instance resides.
*
* <p>
* <em>The changes are effective at runtime at the next registry fetch cycle as specified by
* {@link #getRegistryFetchIntervalSeconds()}</em>
* </p>
* @param region the region where this instance is deployed.
*
* @return the list of available zones accessible by this instance.
*/
String[] getAvailabilityZones(String region);
/**
* Gets the list of fully qualified {@link java.net.URL}s to communicate with eureka
* server.
*
* <p>
* Typically the eureka server {@link java.net.URL}s carry protocol,host,port,context
* and version information if any.
* <code>Example: http://ec2-256-156-243-129.compute-1.amazonaws.com:7001/eureka/v2/</code>
* <p>
*
* <p>
* <em>The changes are effective at runtime at the next service url refresh cycle as specified by
* {@link #getEurekaServiceUrlPollIntervalSeconds()}</em>
* </p>
* @param myZone the zone in which the instance is deployed.
*
* @return the list of eureka server service urls for eureka clients to talk
* to.
*/
List<String> getEurekaServerServiceUrls(String myZone);
/**
* Indicates whether to get the <em>applications</em> after filtering the
* applications for instances with only {@link com.netflix.appinfo.InstanceInfo.InstanceStatus#UP} states.
*
* <p>
* <em>The changes are effective at runtime at the next registry fetch cycle as specified by
* {@link #getRegistryFetchIntervalSeconds()}</em>
* </p>
*
* @return true to filter, false otherwise.
*/
boolean shouldFilterOnlyUpInstances();
/**
* Indicates how much time (in seconds) that the HTTP connections to eureka
* server can stay idle before it can be closed.
*
* <p>
* In the AWS environment, it is recommended that the values is 30 seconds
* or less, since the firewall cleans up the connection information after a
* few mins leaving the connection hanging in limbo
* </p>
*
* @return time in seconds the connections to eureka can stay idle before it
* can be closed.
*/
int getEurekaConnectionIdleTimeoutSeconds();
/**
* Indicates whether this client should fetch eureka registry information from eureka server.
*
* @return {@code true} if registry information has to be fetched, {@code false} otherwise.
*/
boolean shouldFetchRegistry();
/**
* If set to true, the {@link EurekaClient} initialization should throw an exception at constructor time
* if the initial fetch of eureka registry information from the remote servers is unsuccessful.
*
* Note that if {@link #shouldFetchRegistry()} is set to false, then this config is a no-op.
*
* @return true or false for whether the client initialization should enforce an initial fetch.
*/
default boolean shouldEnforceFetchRegistryAtInit() {
return false;
}
/**
* Indicates whether the client is only interested in the registry information for a single VIP.
*
* @return the address of the VIP (name:port).
* <code>null</code> if single VIP interest is not present.
*/
@Nullable
String getRegistryRefreshSingleVipAddress();
/**
* The thread pool size for the heartbeatExecutor to initialise with
*
* @return the heartbeatExecutor thread pool size
*/
int getHeartbeatExecutorThreadPoolSize();
/**
* Heartbeat executor exponential back off related property.
* It is a maximum multiplier value for retry delay, in case where a sequence of timeouts
* occurred.
*
* @return maximum multiplier value for retry delay
*/
int getHeartbeatExecutorExponentialBackOffBound();
/**
* The thread pool size for the cacheRefreshExecutor to initialise with
*
* @return the cacheRefreshExecutor thread pool size
*/
int getCacheRefreshExecutorThreadPoolSize();
/**
* Cache refresh executor exponential back off related property.
* It is a maximum multiplier value for retry delay, in case where a sequence of timeouts
* occurred.
*
* @return maximum multiplier value for retry delay
*/
int getCacheRefreshExecutorExponentialBackOffBound();
/**
* Get a replacement string for Dollar sign <code>$</code> during serializing/deserializing information in eureka server.
*
* @return Replacement string for Dollar sign <code>$</code>.
*/
String getDollarReplacement();
/**
* Get a replacement string for underscore sign <code>_</code> during serializing/deserializing information in eureka server.
*
* @return Replacement string for underscore sign <code>_</code>.
*/
String getEscapeCharReplacement();
/**
* If set to true, local status updates via
* {@link com.netflix.appinfo.ApplicationInfoManager#setInstanceStatus(com.netflix.appinfo.InstanceInfo.InstanceStatus)}
* will trigger on-demand (but rate limited) register/updates to remote eureka servers
*
* @return true or false for whether local status updates should be updated to remote servers on-demand
*/
boolean shouldOnDemandUpdateStatusChange();
/**
* If set to true, the {@link EurekaClient} initialization should throw an exception at constructor time
* if an initial registration to the remote servers is unsuccessful.
*
* Note that if {@link #shouldRegisterWithEureka()} is set to false, then this config is a no-op
*
* @return true or false for whether the client initialization should enforce an initial registration
*/
default boolean shouldEnforceRegistrationAtInit() {
return false;
}
/**
* This is a transient config and once the latest codecs are stable, can be removed (as there will only be one)
*
* @return the class name of the encoding codec to use for the client. If none set a default codec will be used
*/
String getEncoderName();
/**
* This is a transient config and once the latest codecs are stable, can be removed (as there will only be one)
*
* @return the class name of the decoding codec to use for the client. If none set a default codec will be used
*/
String getDecoderName();
/**
* @return {@link com.netflix.appinfo.EurekaAccept#name()} for client data accept
*/
String getClientDataAccept();
/**
* To avoid configuration API pollution when trying new/experimental or features or for the migration process,
* the corresponding configuration can be put into experimental configuration section. Config format is:
* eureka.experimental.freeFormConfigString
*
* @return a property of experimental feature
*/
String getExperimental(String name);
/**
* For compatibility, return the transport layer config class
*
* @return an instance of {@link EurekaTransportConfig}
*/
EurekaTransportConfig getTransportConfig();
}
| 7,924 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/EurekaNamespace.java | package com.netflix.discovery;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.google.inject.BindingAnnotation;
@BindingAnnotation
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface EurekaNamespace {
}
| 7,925 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/CacheRefreshedEvent.java | package com.netflix.discovery;
/**
* This event is sent by {@link EurekaClient) whenever it has refreshed its local
* local cache with information received from the Eureka server.
*
* @author brenuart
*/
public class CacheRefreshedEvent extends DiscoveryEvent {
@Override
public String toString() {
return "CacheRefreshedEvent[timestamp=" + getTimestamp() + "]";
}
}
| 7,926 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/CommonConstants.java | package com.netflix.discovery;
/**
* @author David Liu
*/
public final class CommonConstants {
public static final String CONFIG_FILE_NAME = "eureka-client";
public static final String DEFAULT_CONFIG_NAMESPACE = "eureka";
public static final String INSTANCE_CONFIG_NAMESPACE_KEY = "eureka.instance.config.namespace";
public static final String CLIENT_CONFIG_NAMESPACE_KEY = "eureka.client.config.namespace";
}
| 7,927 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/TimedSupervisorTask.java | package com.netflix.discovery;
import java.util.TimerTask;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicLong;
import com.netflix.servo.monitor.Counter;
import com.netflix.servo.monitor.LongGauge;
import com.netflix.servo.monitor.MonitorConfig;
import com.netflix.servo.monitor.Monitors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A supervisor task that schedules subtasks while enforce a timeout.
* Wrapped subtasks must be thread safe.
*
* @author David Qiang Liu
*/
public class TimedSupervisorTask extends TimerTask {
private static final Logger logger = LoggerFactory.getLogger(TimedSupervisorTask.class);
private final Counter successCounter;
private final Counter timeoutCounter;
private final Counter rejectedCounter;
private final Counter throwableCounter;
private final LongGauge threadPoolLevelGauge;
private final String name;
private final ScheduledExecutorService scheduler;
private final ThreadPoolExecutor executor;
private final long timeoutMillis;
private final Runnable task;
private final AtomicLong delay;
private final long maxDelay;
public TimedSupervisorTask(String name, ScheduledExecutorService scheduler, ThreadPoolExecutor executor,
int timeout, TimeUnit timeUnit, int expBackOffBound, Runnable task) {
this.name = name;
this.scheduler = scheduler;
this.executor = executor;
this.timeoutMillis = timeUnit.toMillis(timeout);
this.task = task;
this.delay = new AtomicLong(timeoutMillis);
this.maxDelay = timeoutMillis * expBackOffBound;
// Initialize the counters and register.
successCounter = Monitors.newCounter("success");
timeoutCounter = Monitors.newCounter("timeouts");
rejectedCounter = Monitors.newCounter("rejectedExecutions");
throwableCounter = Monitors.newCounter("throwables");
threadPoolLevelGauge = new LongGauge(MonitorConfig.builder("threadPoolUsed").build());
Monitors.registerObject(name, this);
}
@Override
public void run() {
Future<?> future = null;
try {
future = executor.submit(task);
threadPoolLevelGauge.set((long) executor.getActiveCount());
future.get(timeoutMillis, TimeUnit.MILLISECONDS); // block until done or timeout
delay.set(timeoutMillis);
threadPoolLevelGauge.set((long) executor.getActiveCount());
successCounter.increment();
} catch (TimeoutException e) {
logger.warn("task supervisor timed out", e);
timeoutCounter.increment();
long currentDelay = delay.get();
long newDelay = Math.min(maxDelay, currentDelay * 2);
delay.compareAndSet(currentDelay, newDelay);
} catch (RejectedExecutionException e) {
if (executor.isShutdown() || scheduler.isShutdown()) {
logger.warn("task supervisor shutting down, reject the task", e);
} else {
logger.warn("task supervisor rejected the task", e);
}
rejectedCounter.increment();
} catch (Throwable e) {
if (executor.isShutdown() || scheduler.isShutdown()) {
logger.warn("task supervisor shutting down, can't accept the task");
} else {
logger.warn("task supervisor threw an exception", e);
}
throwableCounter.increment();
} finally {
if (future != null) {
future.cancel(true);
}
if (!scheduler.isShutdown()) {
scheduler.schedule(this, delay.get(), TimeUnit.MILLISECONDS);
}
}
}
@Override
public boolean cancel() {
Monitors.unregisterObject(name, this);
return super.cancel();
}
} | 7,928 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/PropertyBasedClientConfigConstants.java | package com.netflix.discovery;
/**
* constants pertaining to property based client configs
*
* @author David Liu
*/
final class PropertyBasedClientConfigConstants {
static final String CLIENT_REGION_FALLBACK_KEY = "eureka.region";
// NOTE: all keys are before any prefixes are applied
static final String CLIENT_REGION_KEY = "region";
static final String REGISTRATION_ENABLED_KEY = "registration.enabled";
static final String FETCH_REGISTRY_ENABLED_KEY = "shouldFetchRegistry";
static final String SHOULD_ENFORCE_FETCH_REGISTRY_AT_INIT_KEY = "shouldEnforceFetchRegistryAtInit";
static final String REGISTRY_REFRESH_INTERVAL_KEY = "client.refresh.interval";
static final String REGISTRATION_REPLICATION_INTERVAL_KEY = "appinfo.replicate.interval";
static final String INITIAL_REGISTRATION_REPLICATION_DELAY_KEY = "appinfo.initial.replicate.time";
static final String HEARTBEAT_THREADPOOL_SIZE_KEY = "client.heartbeat.threadPoolSize";
static final String HEARTBEAT_BACKOFF_BOUND_KEY = "client.heartbeat.exponentialBackOffBound";
static final String CACHEREFRESH_THREADPOOL_SIZE_KEY = "client.cacheRefresh.threadPoolSize";
static final String CACHEREFRESH_BACKOFF_BOUND_KEY = "client.cacheRefresh.exponentialBackOffBound";
static final String SHOULD_UNREGISTER_ON_SHUTDOWN_KEY = "shouldUnregisterOnShutdown";
static final String SHOULD_ONDEMAND_UPDATE_STATUS_KEY = "shouldOnDemandUpdateStatusChange";
static final String SHOULD_ENFORCE_REGISTRATION_AT_INIT = "shouldEnforceRegistrationAtInit";
static final String SHOULD_DISABLE_DELTA_KEY = "disableDelta";
static final String SHOULD_FETCH_REMOTE_REGION_KEY = "fetchRemoteRegionsRegistry";
static final String SHOULD_FILTER_ONLY_UP_INSTANCES_KEY = "shouldFilterOnlyUpInstances";
static final String FETCH_SINGLE_VIP_ONLY_KEY = "registryRefreshSingleVipAddress";
static final String CLIENT_ENCODER_NAME_KEY = "encoderName";
static final String CLIENT_DECODER_NAME_KEY = "decoderName";
static final String CLIENT_DATA_ACCEPT_KEY = "clientDataAccept";
static final String BACKUP_REGISTRY_CLASSNAME_KEY = "backupregistry";
static final String SHOULD_PREFER_SAME_ZONE_SERVER_KEY = "preferSameZone";
static final String SHOULD_ALLOW_REDIRECTS_KEY = "allowRedirects";
static final String SHOULD_USE_DNS_KEY = "shouldUseDns";
static final String EUREKA_SERVER_URL_POLL_INTERVAL_KEY = "serviceUrlPollIntervalMs";
static final String EUREKA_SERVER_URL_CONTEXT_KEY = "eurekaServer.context";
static final String EUREKA_SERVER_FALLBACK_URL_CONTEXT_KEY = "context";
static final String EUREKA_SERVER_PORT_KEY = "eurekaServer.port";
static final String EUREKA_SERVER_FALLBACK_PORT_KEY = "port";
static final String EUREKA_SERVER_DNS_NAME_KEY = "eurekaServer.domainName";
static final String EUREKA_SERVER_FALLBACK_DNS_NAME_KEY = "domainName";
static final String EUREKA_SERVER_PROXY_HOST_KEY = "eurekaServer.proxyHost";
static final String EUREKA_SERVER_PROXY_PORT_KEY = "eurekaServer.proxyPort";
static final String EUREKA_SERVER_PROXY_USERNAME_KEY = "eurekaServer.proxyUserName";
static final String EUREKA_SERVER_PROXY_PASSWORD_KEY = "eurekaServer.proxyPassword";
static final String EUREKA_SERVER_GZIP_CONTENT_KEY = "eurekaServer.gzipContent";
static final String EUREKA_SERVER_READ_TIMEOUT_KEY = "eurekaServer.readTimeout";
static final String EUREKA_SERVER_CONNECT_TIMEOUT_KEY = "eurekaServer.connectTimeout";
static final String EUREKA_SERVER_MAX_CONNECTIONS_KEY = "eurekaServer.maxTotalConnections";
static final String EUREKA_SERVER_MAX_CONNECTIONS_PER_HOST_KEY = "eurekaServer.maxConnectionsPerHost";
// yeah the case on eurekaserver is different, backwards compatibility requirements :(
static final String EUREKA_SERVER_CONNECTION_IDLE_TIMEOUT_KEY = "eurekaserver.connectionIdleTimeoutInSeconds";
static final String SHOULD_LOG_DELTA_DIFF_KEY = "printDeltaFullDiff";
static final String CONFIG_DOLLAR_REPLACEMENT_KEY = "dollarReplacement";
static final String CONFIG_ESCAPE_CHAR_REPLACEMENT_KEY = "escapeCharReplacement";
// additional namespaces
static final String CONFIG_EXPERIMENTAL_PREFIX = "experimental";
static final String CONFIG_AVAILABILITY_ZONE_PREFIX = "availabilityZones";
static final String CONFIG_EUREKA_SERVER_SERVICE_URL_PREFIX = "serviceUrl";
static class Values {
static final String CONFIG_DOLLAR_REPLACEMENT = "_-";
static final String CONFIG_ESCAPE_CHAR_REPLACEMENT = "__";
static final String DEFAULT_CLIENT_REGION = "us-east-1";
static final int DEFAULT_EXECUTOR_THREAD_POOL_SIZE = 5;
static final int DEFAULT_EXECUTOR_THREAD_POOL_BACKOFF_BOUND = 10;
}
}
| 7,929 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/EurekaClientNames.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery;
/**
* @author Tomasz Bak
*/
public final class EurekaClientNames {
/**
* Eureka metric names consist of three parts [source].[component].[detailed name]:
* <ul>
* <li>source - fixed to eurekaClient (and eurekaServer on the server side)</li>
* <li>component - Eureka component, like registry cache</li>
* <li>detailed name - a detailed metric name explaining its purpose</li>
* </ul>
*/
public static final String METRIC_PREFIX = "eurekaClient.";
public static final String METRIC_REGISTRATION_PREFIX = METRIC_PREFIX + "registration.";
public static final String METRIC_REGISTRY_PREFIX = METRIC_PREFIX + "registry.";
public static final String METRIC_RESOLVER_PREFIX = METRIC_PREFIX + "resolver.";
public static final String METRIC_TRANSPORT_PREFIX = METRIC_PREFIX + "transport.";
public static final String RESOLVER = "resolver";
public static final String BOOTSTRAP = "bootstrap";
public static final String QUERY = "query";
public static final String REGISTRATION = "registration";
private EurekaClientNames() {
}
}
| 7,930 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/EurekaEventListener.java | package com.netflix.discovery;
/**
* Listener for receiving {@link EurekaClient} events such as {@link StatusChangeEvent}. Register
* a listener by calling {@link EurekaClient#registerEventListener(EurekaEventListener)}
*/
public interface EurekaEventListener {
/**
* Notification of an event within the {@link EurekaClient}.
*
* {@link EurekaEventListener#onEvent} is called from the context of an internal eureka thread
* and must therefore return as quickly as possible without blocking.
*
* @param event
*/
public void onEvent(EurekaEvent event);
}
| 7,931 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/InstanceRegionChecker.java | package com.netflix.discovery;
import javax.annotation.Nullable;
import java.util.Map;
import com.netflix.appinfo.AmazonInfo;
import com.netflix.appinfo.DataCenterInfo;
import com.netflix.appinfo.InstanceInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Nitesh Kant
*/
public class InstanceRegionChecker {
private static Logger logger = LoggerFactory.getLogger(InstanceRegionChecker.class);
private final AzToRegionMapper azToRegionMapper;
private final String localRegion;
InstanceRegionChecker(AzToRegionMapper azToRegionMapper, String localRegion) {
this.azToRegionMapper = azToRegionMapper;
this.localRegion = localRegion;
}
@Nullable
public String getInstanceRegion(InstanceInfo instanceInfo) {
if (instanceInfo.getDataCenterInfo() == null || instanceInfo.getDataCenterInfo().getName() == null) {
logger.warn("Cannot get region for instance id:{}, app:{} as dataCenterInfo is null. Returning local:{} by default",
instanceInfo.getId(), instanceInfo.getAppName(), localRegion);
return localRegion;
}
if (DataCenterInfo.Name.Amazon.equals(instanceInfo.getDataCenterInfo().getName())) {
AmazonInfo amazonInfo = (AmazonInfo) instanceInfo.getDataCenterInfo();
Map<String, String> metadata = amazonInfo.getMetadata();
String availabilityZone = metadata.get(AmazonInfo.MetaDataKey.availabilityZone.getName());
if (null != availabilityZone) {
return azToRegionMapper.getRegionForAvailabilityZone(availabilityZone);
}
}
return null;
}
public boolean isLocalRegion(@Nullable String instanceRegion) {
return null == instanceRegion || instanceRegion.equals(localRegion); // no region == local
}
public String getLocalRegion() {
return localRegion;
}
public AzToRegionMapper getAzToRegionMapper() {
return azToRegionMapper;
}
}
| 7,932 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/PreRegistrationHandler.java | package com.netflix.discovery;
import com.netflix.appinfo.ApplicationInfoManager;
/**
* A handler that can be registered with an {@link EurekaClient} at creation time to execute
* pre registration logic. The pre registration logic need to be synchronous to be guaranteed
* to execute before registration.
*/
public interface PreRegistrationHandler {
void beforeRegistration();
}
| 7,933 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/EurekaEvent.java | package com.netflix.discovery;
/**
* Marker interface for Eureka events
*
* @see {@link EurekaEventListener}
*/
public interface EurekaEvent {
}
| 7,934 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/EurekaClient.java | package com.netflix.discovery;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;
import com.google.inject.ImplementedBy;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.HealthCheckCallback;
import com.netflix.appinfo.HealthCheckHandler;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.shared.Applications;
import com.netflix.discovery.shared.LookupService;
/**
* Define a simple interface over the current DiscoveryClient implementation.
*
* This interface does NOT try to clean up the current client interface for eureka 1.x. Rather it tries
* to provide an easier transition path from eureka 1.x to eureka 2.x.
*
* EurekaClient API contracts are:
* - provide the ability to get InstanceInfo(s) (in various different ways)
* - provide the ability to get data about the local Client (known regions, own AZ etc)
* - provide the ability to register and access the healthcheck handler for the client
*
* @author David Liu
*/
@ImplementedBy(DiscoveryClient.class)
public interface EurekaClient extends LookupService {
// ========================
// getters for InstanceInfo
// ========================
/**
* @param region the region that the Applications reside in
* @return an {@link com.netflix.discovery.shared.Applications} for the matching region. a Null value
* is treated as the local region.
*/
public Applications getApplicationsForARegion(@Nullable String region);
/**
* Get all applications registered with a specific eureka service.
*
* @param serviceUrl The string representation of the service url.
* @return The registry information containing all applications.
*/
public Applications getApplications(String serviceUrl);
/**
* Gets the list of instances matching the given VIP Address.
*
* @param vipAddress The VIP address to match the instances for.
* @param secure true if it is a secure vip address, false otherwise
* @return - The list of {@link InstanceInfo} objects matching the criteria
*/
public List<InstanceInfo> getInstancesByVipAddress(String vipAddress, boolean secure);
/**
* Gets the list of instances matching the given VIP Address in the passed region.
*
* @param vipAddress The VIP address to match the instances for.
* @param secure true if it is a secure vip address, false otherwise
* @param region region from which the instances are to be fetched. If <code>null</code> then local region is
* assumed.
*
* @return - The list of {@link InstanceInfo} objects matching the criteria, empty list if not instances found.
*/
public List<InstanceInfo> getInstancesByVipAddress(String vipAddress, boolean secure, @Nullable String region);
/**
* Gets the list of instances matching the given VIP Address and the given
* application name if both of them are not null. If one of them is null,
* then that criterion is completely ignored for matching instances.
*
* @param vipAddress The VIP address to match the instances for.
* @param appName The applicationName to match the instances for.
* @param secure true if it is a secure vip address, false otherwise.
* @return - The list of {@link InstanceInfo} objects matching the criteria.
*/
public List<InstanceInfo> getInstancesByVipAddressAndAppName(String vipAddress, String appName, boolean secure);
// ==========================
// getters for local metadata
// ==========================
/**
* @return in String form all regions (local + remote) that can be accessed by this client
*/
public Set<String> getAllKnownRegions();
/**
* @return the current self instance status as seen on the Eureka server.
*/
public InstanceInfo.InstanceStatus getInstanceRemoteStatus();
/**
* @deprecated see {@link com.netflix.discovery.endpoint.EndpointUtils} for replacement
*
* Get the list of all eureka service urls for the eureka client to talk to.
*
* @param zone the zone in which the client resides
* @return The list of all eureka service urls for the eureka client to talk to.
*/
@Deprecated
public List<String> getDiscoveryServiceUrls(String zone);
/**
* @deprecated see {@link com.netflix.discovery.endpoint.EndpointUtils} for replacement
*
* Get the list of all eureka service urls from properties file for the eureka client to talk to.
*
* @param instanceZone The zone in which the client resides
* @param preferSameZone true if we have to prefer the same zone as the client, false otherwise
* @return The list of all eureka service urls for the eureka client to talk to
*/
@Deprecated
public List<String> getServiceUrlsFromConfig(String instanceZone, boolean preferSameZone);
/**
* @deprecated see {@link com.netflix.discovery.endpoint.EndpointUtils} for replacement
*
* Get the list of all eureka service urls from DNS for the eureka client to
* talk to. The client picks up the service url from its zone and then fails over to
* other zones randomly. If there are multiple servers in the same zone, the client once
* again picks one randomly. This way the traffic will be distributed in the case of failures.
*
* @param instanceZone The zone in which the client resides.
* @param preferSameZone true if we have to prefer the same zone as the client, false otherwise.
* @return The list of all eureka service urls for the eureka client to talk to.
*/
@Deprecated
public List<String> getServiceUrlsFromDNS(String instanceZone, boolean preferSameZone);
// ===========================
// healthcheck related methods
// ===========================
/**
* @deprecated Use {@link #registerHealthCheck(com.netflix.appinfo.HealthCheckHandler)} instead.
*
* Register {@link HealthCheckCallback} with the eureka client.
*
* Once registered, the eureka client will invoke the
* {@link HealthCheckCallback} in intervals specified by
* {@link EurekaClientConfig#getInstanceInfoReplicationIntervalSeconds()}.
*
* @param callback app specific healthcheck.
*/
@Deprecated
public void registerHealthCheckCallback(HealthCheckCallback callback);
/**
* Register {@link HealthCheckHandler} with the eureka client.
*
* Once registered, the eureka client will first make an onDemand update of the
* registering instanceInfo by calling the newly registered healthcheck handler,
* and subsequently invoke the {@link HealthCheckHandler} in intervals specified
* by {@link EurekaClientConfig#getInstanceInfoReplicationIntervalSeconds()}.
*
* @param healthCheckHandler app specific healthcheck handler.
*/
public void registerHealthCheck(HealthCheckHandler healthCheckHandler);
/**
* Register {@link EurekaEventListener} with the eureka client.
*
* Once registered, the eureka client will invoke {@link EurekaEventListener#onEvent}
* whenever there is a change in eureka client's internal state. Use this instead of
* polling the client for changes.
*
* {@link EurekaEventListener#onEvent} is called from the context of an internal thread
* and must therefore return as quickly as possible without blocking.
*
* @param eventListener
*/
public void registerEventListener(EurekaEventListener eventListener);
/**
* Unregister a {@link EurekaEventListener} previous registered with {@link EurekaClient#registerEventListener}
* or injected into the constructor of {@link DiscoveryClient}
*
* @param eventListener
* @return True if removed otherwise false if the listener was never registered.
*/
public boolean unregisterEventListener(EurekaEventListener eventListener);
/**
* @return the current registered healthcheck handler
*/
public HealthCheckHandler getHealthCheckHandler();
// =============
// other methods
// =============
/**
* Shuts down Eureka Client. Also sends a deregistration request to the eureka server.
*/
public void shutdown();
/**
* @return the configuration of this eureka client
*/
public EurekaClientConfig getEurekaClientConfig();
/**
* @return the application info manager of this eureka client
*/
public ApplicationInfoManager getApplicationInfoManager();
}
| 7,935 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/NotImplementedRegistryImpl.java | package com.netflix.discovery;
import javax.inject.Singleton;
import com.netflix.discovery.shared.Applications;
/**
* @author Nitesh Kant
*/
@Singleton
public class NotImplementedRegistryImpl implements BackupRegistry {
@Override
public Applications fetchRegistry() {
return null;
}
@Override
public Applications fetchRegistry(String[] includeRemoteRegions) {
return null;
}
}
| 7,936 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/DiscoveryClient.java | /*
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery;
import static com.netflix.discovery.EurekaClientNames.METRIC_REGISTRATION_PREFIX;
import static com.netflix.discovery.EurekaClientNames.METRIC_REGISTRY_PREFIX;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.annotation.Nullable;
import javax.annotation.PreDestroy;
import javax.inject.Provider;
import javax.inject.Singleton;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.ws.rs.core.Response.Status;
import com.netflix.discovery.shared.resolver.EndpointRandomizer;
import com.netflix.discovery.shared.resolver.ResolverUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.google.inject.Inject;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.HealthCheckCallback;
import com.netflix.appinfo.HealthCheckCallbackToHandlerBridge;
import com.netflix.appinfo.HealthCheckHandler;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.InstanceInfo.ActionType;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import com.netflix.discovery.endpoint.EndpointUtils;
import com.netflix.discovery.shared.Application;
import com.netflix.discovery.shared.Applications;
import com.netflix.discovery.shared.resolver.ClosableResolver;
import com.netflix.discovery.shared.resolver.aws.ApplicationsResolver;
import com.netflix.discovery.shared.transport.EurekaHttpClient;
import com.netflix.discovery.shared.transport.EurekaHttpClientFactory;
import com.netflix.discovery.shared.transport.EurekaHttpClients;
import com.netflix.discovery.shared.transport.EurekaHttpResponse;
import com.netflix.discovery.shared.transport.EurekaTransportConfig;
import com.netflix.discovery.shared.transport.TransportClientFactory;
import com.netflix.discovery.shared.transport.jersey.EurekaJerseyClient;
import com.netflix.discovery.shared.transport.jersey.Jersey1DiscoveryClientOptionalArgs;
import com.netflix.discovery.shared.transport.jersey.Jersey1TransportClientFactories;
import com.netflix.discovery.shared.transport.jersey.TransportClientFactories;
import com.netflix.discovery.util.ThresholdLevelsMetric;
import com.netflix.servo.annotations.DataSourceType;
import com.netflix.servo.monitor.Counter;
import com.netflix.servo.monitor.Monitors;
import com.netflix.servo.monitor.Stopwatch;
/**
* The class that is instrumental for interactions with <tt>Eureka Server</tt>.
*
* <p>
* <tt>Eureka Client</tt> is responsible for a) <em>Registering</em> the
* instance with <tt>Eureka Server</tt> b) <em>Renewal</em>of the lease with
* <tt>Eureka Server</tt> c) <em>Cancellation</em> of the lease from
* <tt>Eureka Server</tt> during shutdown
* <p>
* d) <em>Querying</em> the list of services/instances registered with
* <tt>Eureka Server</tt>
* <p>
*
* <p>
* <tt>Eureka Client</tt> needs a configured list of <tt>Eureka Server</tt>
* {@link java.net.URL}s to talk to.These {@link java.net.URL}s are typically amazon elastic eips
* which do not change. All of the functions defined above fail-over to other
* {@link java.net.URL}s specified in the list in the case of failure.
* </p>
*
* @author Karthik Ranganathan, Greg Kim
* @author Spencer Gibb
*
*/
@Singleton
public class DiscoveryClient implements EurekaClient {
private static final Logger logger = LoggerFactory.getLogger(DiscoveryClient.class);
// Constants
public static final String HTTP_X_DISCOVERY_ALLOW_REDIRECT = "X-Discovery-AllowRedirect";
private static final String VALUE_DELIMITER = ",";
private static final String COMMA_STRING = VALUE_DELIMITER;
/**
* @deprecated here for legacy support as the client config has moved to be an instance variable
*/
@Deprecated
private static EurekaClientConfig staticClientConfig;
// Timers
private static final String PREFIX = "DiscoveryClient_";
private final Counter RECONCILE_HASH_CODES_MISMATCH = Monitors.newCounter(PREFIX + "ReconcileHashCodeMismatch");
private final com.netflix.servo.monitor.Timer FETCH_REGISTRY_TIMER = Monitors
.newTimer(PREFIX + "FetchRegistry");
private final Counter REREGISTER_COUNTER = Monitors.newCounter(PREFIX
+ "Reregister");
// instance variables
/**
* A scheduler to be used for the following 3 tasks:
* - updating service urls
* - scheduling a TimedSuperVisorTask
*/
private final ScheduledExecutorService scheduler;
// additional executors for supervised subtasks
private final ThreadPoolExecutor heartbeatExecutor;
private final ThreadPoolExecutor cacheRefreshExecutor;
private TimedSupervisorTask cacheRefreshTask;
private TimedSupervisorTask heartbeatTask;
private final Provider<HealthCheckHandler> healthCheckHandlerProvider;
private final Provider<HealthCheckCallback> healthCheckCallbackProvider;
private final PreRegistrationHandler preRegistrationHandler;
private final AtomicReference<Applications> localRegionApps = new AtomicReference<>();
private final Lock fetchRegistryUpdateLock = new ReentrantLock();
// monotonically increasing generation counter to ensure stale threads do not reset registry to an older version
private final AtomicLong fetchRegistryGeneration;
private final ApplicationInfoManager applicationInfoManager;
private final InstanceInfo instanceInfo;
private final AtomicReference<String> remoteRegionsToFetch;
private final AtomicReference<String[]> remoteRegionsRef;
private final InstanceRegionChecker instanceRegionChecker;
private final EndpointUtils.ServiceUrlRandomizer urlRandomizer;
private final EndpointRandomizer endpointRandomizer;
private final Provider<BackupRegistry> backupRegistryProvider;
private final EurekaTransport eurekaTransport;
private final AtomicReference<HealthCheckHandler> healthCheckHandlerRef = new AtomicReference<>();
private volatile Map<String, Applications> remoteRegionVsApps = new ConcurrentHashMap<>();
private volatile InstanceInfo.InstanceStatus lastRemoteInstanceStatus = InstanceInfo.InstanceStatus.UNKNOWN;
private final CopyOnWriteArraySet<EurekaEventListener> eventListeners = new CopyOnWriteArraySet<>();
private String appPathIdentifier;
private ApplicationInfoManager.StatusChangeListener statusChangeListener;
private InstanceInfoReplicator instanceInfoReplicator;
private volatile int registrySize = 0;
private volatile long lastSuccessfulRegistryFetchTimestamp = -1;
private volatile long lastSuccessfulHeartbeatTimestamp = -1;
private final ThresholdLevelsMetric heartbeatStalenessMonitor;
private final ThresholdLevelsMetric registryStalenessMonitor;
private final AtomicBoolean isShutdown = new AtomicBoolean(false);
protected final EurekaClientConfig clientConfig;
protected final EurekaTransportConfig transportConfig;
private final long initTimestampMs;
private final int initRegistrySize;
private final Stats stats = new Stats();
private static final class EurekaTransport {
private ClosableResolver bootstrapResolver;
private TransportClientFactory transportClientFactory;
private EurekaHttpClient registrationClient;
private EurekaHttpClientFactory registrationClientFactory;
private EurekaHttpClient queryClient;
private EurekaHttpClientFactory queryClientFactory;
void shutdown() {
if (registrationClientFactory != null) {
registrationClientFactory.shutdown();
}
if (queryClientFactory != null) {
queryClientFactory.shutdown();
}
if (registrationClient != null) {
registrationClient.shutdown();
}
if (queryClient != null) {
queryClient.shutdown();
}
if (transportClientFactory != null) {
transportClientFactory.shutdown();
}
if (bootstrapResolver != null) {
bootstrapResolver.shutdown();
}
}
}
public static class DiscoveryClientOptionalArgs extends Jersey1DiscoveryClientOptionalArgs {
}
/**
* Assumes applicationInfoManager is already initialized
*
* @deprecated use constructor that takes ApplicationInfoManager instead of InstanceInfo directly
*/
@Deprecated
public DiscoveryClient(InstanceInfo myInfo, EurekaClientConfig config) {
this(myInfo, config, null);
}
/**
* Assumes applicationInfoManager is already initialized
*
* @deprecated use constructor that takes ApplicationInfoManager instead of InstanceInfo directly
*/
@Deprecated
public DiscoveryClient(InstanceInfo myInfo, EurekaClientConfig config, DiscoveryClientOptionalArgs args) {
this(ApplicationInfoManager.getInstance(), config, args);
}
/**
* @deprecated use constructor that takes ApplicationInfoManager instead of InstanceInfo directly
*/
@Deprecated
public DiscoveryClient(InstanceInfo myInfo, EurekaClientConfig config, AbstractDiscoveryClientOptionalArgs args) {
this(ApplicationInfoManager.getInstance(), config, args);
}
public DiscoveryClient(ApplicationInfoManager applicationInfoManager, EurekaClientConfig config) {
this(applicationInfoManager, config, null);
}
/**
* @deprecated use the version that take {@link com.netflix.discovery.AbstractDiscoveryClientOptionalArgs} instead
*/
@Deprecated
public DiscoveryClient(ApplicationInfoManager applicationInfoManager, final EurekaClientConfig config, DiscoveryClientOptionalArgs args) {
this(applicationInfoManager, config, (AbstractDiscoveryClientOptionalArgs) args);
}
public DiscoveryClient(ApplicationInfoManager applicationInfoManager, final EurekaClientConfig config, AbstractDiscoveryClientOptionalArgs args) {
this(applicationInfoManager, config, args, ResolverUtils::randomize);
}
public DiscoveryClient(ApplicationInfoManager applicationInfoManager, final EurekaClientConfig config, AbstractDiscoveryClientOptionalArgs args, EndpointRandomizer randomizer) {
this(applicationInfoManager, config, args, new Provider<BackupRegistry>() {
private volatile BackupRegistry backupRegistryInstance;
@Override
public synchronized BackupRegistry get() {
if (backupRegistryInstance == null) {
String backupRegistryClassName = config.getBackupRegistryImpl();
if (null != backupRegistryClassName) {
try {
backupRegistryInstance = (BackupRegistry) Class.forName(backupRegistryClassName).newInstance();
logger.info("Enabled backup registry of type {}", backupRegistryInstance.getClass());
} catch (InstantiationException e) {
logger.error("Error instantiating BackupRegistry.", e);
} catch (IllegalAccessException e) {
logger.error("Error instantiating BackupRegistry.", e);
} catch (ClassNotFoundException e) {
logger.error("Error instantiating BackupRegistry.", e);
}
}
if (backupRegistryInstance == null) {
logger.warn("Using default backup registry implementation which does not do anything.");
backupRegistryInstance = new NotImplementedRegistryImpl();
}
}
return backupRegistryInstance;
}
}, randomizer);
}
/**
* @deprecated Use {@link #DiscoveryClient(ApplicationInfoManager, EurekaClientConfig, AbstractDiscoveryClientOptionalArgs, Provider<BackupRegistry>, EndpointRandomizer)}
*/
@Deprecated
DiscoveryClient(ApplicationInfoManager applicationInfoManager, EurekaClientConfig config, AbstractDiscoveryClientOptionalArgs args,
Provider<BackupRegistry> backupRegistryProvider) {
this(applicationInfoManager, config, args, backupRegistryProvider, ResolverUtils::randomize);
}
@Inject
DiscoveryClient(ApplicationInfoManager applicationInfoManager, EurekaClientConfig config, AbstractDiscoveryClientOptionalArgs args,
Provider<BackupRegistry> backupRegistryProvider, EndpointRandomizer endpointRandomizer) {
if (args != null) {
this.healthCheckHandlerProvider = args.healthCheckHandlerProvider;
this.healthCheckCallbackProvider = args.healthCheckCallbackProvider;
this.eventListeners.addAll(args.getEventListeners());
this.preRegistrationHandler = args.preRegistrationHandler;
} else {
this.healthCheckCallbackProvider = null;
this.healthCheckHandlerProvider = null;
this.preRegistrationHandler = null;
}
this.applicationInfoManager = applicationInfoManager;
InstanceInfo myInfo = applicationInfoManager.getInfo();
clientConfig = config;
staticClientConfig = clientConfig;
transportConfig = config.getTransportConfig();
instanceInfo = myInfo;
if (myInfo != null) {
appPathIdentifier = instanceInfo.getAppName() + "/" + instanceInfo.getId();
} else {
logger.warn("Setting instanceInfo to a passed in null value");
}
this.backupRegistryProvider = backupRegistryProvider;
this.endpointRandomizer = endpointRandomizer;
this.urlRandomizer = new EndpointUtils.InstanceInfoBasedUrlRandomizer(instanceInfo);
localRegionApps.set(new Applications());
fetchRegistryGeneration = new AtomicLong(0);
remoteRegionsToFetch = new AtomicReference<String>(clientConfig.fetchRegistryForRemoteRegions());
remoteRegionsRef = new AtomicReference<>(remoteRegionsToFetch.get() == null ? null : remoteRegionsToFetch.get().split(","));
if (config.shouldFetchRegistry()) {
this.registryStalenessMonitor = new ThresholdLevelsMetric(this, METRIC_REGISTRY_PREFIX + "lastUpdateSec_", new long[]{15L, 30L, 60L, 120L, 240L, 480L});
} else {
this.registryStalenessMonitor = ThresholdLevelsMetric.NO_OP_METRIC;
}
if (config.shouldRegisterWithEureka()) {
this.heartbeatStalenessMonitor = new ThresholdLevelsMetric(this, METRIC_REGISTRATION_PREFIX + "lastHeartbeatSec_", new long[]{15L, 30L, 60L, 120L, 240L, 480L});
} else {
this.heartbeatStalenessMonitor = ThresholdLevelsMetric.NO_OP_METRIC;
}
logger.info("Initializing Eureka in region {}", clientConfig.getRegion());
if (!config.shouldRegisterWithEureka() && !config.shouldFetchRegistry()) {
logger.info("Client configured to neither register nor query for data.");
scheduler = null;
heartbeatExecutor = null;
cacheRefreshExecutor = null;
eurekaTransport = null;
instanceRegionChecker = new InstanceRegionChecker(new PropertyBasedAzToRegionMapper(config), clientConfig.getRegion());
// This is a bit of hack to allow for existing code using DiscoveryManager.getInstance()
// to work with DI'd DiscoveryClient
DiscoveryManager.getInstance().setDiscoveryClient(this);
DiscoveryManager.getInstance().setEurekaClientConfig(config);
initTimestampMs = System.currentTimeMillis();
initRegistrySize = this.getApplications().size();
registrySize = initRegistrySize;
logger.info("Discovery Client initialized at timestamp {} with initial instances count: {}",
initTimestampMs, initRegistrySize);
return; // no need to setup up an network tasks and we are done
}
try {
// default size of 2 - 1 each for heartbeat and cacheRefresh
scheduler = Executors.newScheduledThreadPool(2,
new ThreadFactoryBuilder()
.setNameFormat("DiscoveryClient-%d")
.setDaemon(true)
.build());
heartbeatExecutor = new ThreadPoolExecutor(
1, clientConfig.getHeartbeatExecutorThreadPoolSize(), 0, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
new ThreadFactoryBuilder()
.setNameFormat("DiscoveryClient-HeartbeatExecutor-%d")
.setDaemon(true)
.build()
); // use direct handoff
cacheRefreshExecutor = new ThreadPoolExecutor(
1, clientConfig.getCacheRefreshExecutorThreadPoolSize(), 0, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
new ThreadFactoryBuilder()
.setNameFormat("DiscoveryClient-CacheRefreshExecutor-%d")
.setDaemon(true)
.build()
); // use direct handoff
eurekaTransport = new EurekaTransport();
scheduleServerEndpointTask(eurekaTransport, args);
AzToRegionMapper azToRegionMapper;
if (clientConfig.shouldUseDnsForFetchingServiceUrls()) {
azToRegionMapper = new DNSBasedAzToRegionMapper(clientConfig);
} else {
azToRegionMapper = new PropertyBasedAzToRegionMapper(clientConfig);
}
if (null != remoteRegionsToFetch.get()) {
azToRegionMapper.setRegionsToFetch(remoteRegionsToFetch.get().split(","));
}
instanceRegionChecker = new InstanceRegionChecker(azToRegionMapper, clientConfig.getRegion());
} catch (Throwable e) {
throw new RuntimeException("Failed to initialize DiscoveryClient!", e);
}
if (clientConfig.shouldFetchRegistry()) {
try {
boolean primaryFetchRegistryResult = fetchRegistry(false);
if (!primaryFetchRegistryResult) {
logger.info("Initial registry fetch from primary servers failed");
}
boolean backupFetchRegistryResult = true;
if (!primaryFetchRegistryResult && !fetchRegistryFromBackup()) {
backupFetchRegistryResult = false;
logger.info("Initial registry fetch from backup servers failed");
}
if (!primaryFetchRegistryResult && !backupFetchRegistryResult && clientConfig.shouldEnforceFetchRegistryAtInit()) {
throw new IllegalStateException("Fetch registry error at startup. Initial fetch failed.");
}
} catch (Throwable th) {
logger.error("Fetch registry error at startup: {}", th.getMessage());
throw new IllegalStateException(th);
}
}
// call and execute the pre registration handler before all background tasks (inc registration) is started
if (this.preRegistrationHandler != null) {
this.preRegistrationHandler.beforeRegistration();
}
if (clientConfig.shouldRegisterWithEureka() && clientConfig.shouldEnforceRegistrationAtInit()) {
try {
if (!register() ) {
throw new IllegalStateException("Registration error at startup. Invalid server response.");
}
} catch (Throwable th) {
logger.error("Registration error at startup: {}", th.getMessage());
throw new IllegalStateException(th);
}
}
// finally, init the schedule tasks (e.g. cluster resolvers, heartbeat, instanceInfo replicator, fetch
initScheduledTasks();
try {
Monitors.registerObject(this);
} catch (Throwable e) {
logger.warn("Cannot register timers", e);
}
// This is a bit of hack to allow for existing code using DiscoveryManager.getInstance()
// to work with DI'd DiscoveryClient
DiscoveryManager.getInstance().setDiscoveryClient(this);
DiscoveryManager.getInstance().setEurekaClientConfig(config);
initTimestampMs = System.currentTimeMillis();
initRegistrySize = this.getApplications().size();
registrySize = initRegistrySize;
logger.info("Discovery Client initialized at timestamp {} with initial instances count: {}",
initTimestampMs, initRegistrySize);
}
private void scheduleServerEndpointTask(EurekaTransport eurekaTransport,
AbstractDiscoveryClientOptionalArgs args) {
Collection<?> additionalFilters = args == null
? Collections.emptyList()
: args.additionalFilters;
EurekaJerseyClient providedJerseyClient = args == null
? null
: args.eurekaJerseyClient;
TransportClientFactories argsTransportClientFactories = null;
if (args != null && args.getTransportClientFactories() != null) {
argsTransportClientFactories = args.getTransportClientFactories();
}
// Ignore the raw types warnings since the client filter interface changed between jersey 1/2
@SuppressWarnings("rawtypes")
TransportClientFactories transportClientFactories = argsTransportClientFactories == null
? new Jersey1TransportClientFactories()
: argsTransportClientFactories;
Optional<SSLContext> sslContext = args == null
? Optional.empty()
: args.getSSLContext();
Optional<HostnameVerifier> hostnameVerifier = args == null
? Optional.empty()
: args.getHostnameVerifier();
// If the transport factory was not supplied with args, assume they are using jersey 1 for passivity
eurekaTransport.transportClientFactory = providedJerseyClient == null
? transportClientFactories.newTransportClientFactory(clientConfig, additionalFilters, applicationInfoManager.getInfo(), sslContext, hostnameVerifier)
: transportClientFactories.newTransportClientFactory(additionalFilters, providedJerseyClient);
ApplicationsResolver.ApplicationsSource applicationsSource = new ApplicationsResolver.ApplicationsSource() {
@Override
public Applications getApplications(int stalenessThreshold, TimeUnit timeUnit) {
long thresholdInMs = TimeUnit.MILLISECONDS.convert(stalenessThreshold, timeUnit);
long delay = getLastSuccessfulRegistryFetchTimePeriod();
if (delay > thresholdInMs) {
logger.info("Local registry is too stale for local lookup. Threshold:{}, actual:{}",
thresholdInMs, delay);
return null;
} else {
return localRegionApps.get();
}
}
};
eurekaTransport.bootstrapResolver = EurekaHttpClients.newBootstrapResolver(
clientConfig,
transportConfig,
eurekaTransport.transportClientFactory,
applicationInfoManager.getInfo(),
applicationsSource,
endpointRandomizer
);
if (clientConfig.shouldRegisterWithEureka()) {
EurekaHttpClientFactory newRegistrationClientFactory = null;
EurekaHttpClient newRegistrationClient = null;
try {
newRegistrationClientFactory = EurekaHttpClients.registrationClientFactory(
eurekaTransport.bootstrapResolver,
eurekaTransport.transportClientFactory,
transportConfig
);
newRegistrationClient = newRegistrationClientFactory.newClient();
} catch (Exception e) {
logger.warn("Transport initialization failure", e);
}
eurekaTransport.registrationClientFactory = newRegistrationClientFactory;
eurekaTransport.registrationClient = newRegistrationClient;
}
// new method (resolve from primary servers for read)
// Configure new transport layer (candidate for injecting in the future)
if (clientConfig.shouldFetchRegistry()) {
EurekaHttpClientFactory newQueryClientFactory = null;
EurekaHttpClient newQueryClient = null;
try {
newQueryClientFactory = EurekaHttpClients.queryClientFactory(
eurekaTransport.bootstrapResolver,
eurekaTransport.transportClientFactory,
clientConfig,
transportConfig,
applicationInfoManager.getInfo(),
applicationsSource,
endpointRandomizer
);
newQueryClient = newQueryClientFactory.newClient();
} catch (Exception e) {
logger.warn("Transport initialization failure", e);
}
eurekaTransport.queryClientFactory = newQueryClientFactory;
eurekaTransport.queryClient = newQueryClient;
}
}
@Override
public EurekaClientConfig getEurekaClientConfig() {
return clientConfig;
}
@Override
public ApplicationInfoManager getApplicationInfoManager() {
return applicationInfoManager;
}
/*
* (non-Javadoc)
* @see com.netflix.discovery.shared.LookupService#getApplication(java.lang.String)
*/
@Override
public Application getApplication(String appName) {
return getApplications().getRegisteredApplications(appName);
}
/*
* (non-Javadoc)
*
* @see com.netflix.discovery.shared.LookupService#getApplications()
*/
@Override
public Applications getApplications() {
return localRegionApps.get();
}
@Override
public Applications getApplicationsForARegion(@Nullable String region) {
if (instanceRegionChecker.isLocalRegion(region)) {
return localRegionApps.get();
} else {
return remoteRegionVsApps.get(region);
}
}
public Set<String> getAllKnownRegions() {
String localRegion = instanceRegionChecker.getLocalRegion();
if (!remoteRegionVsApps.isEmpty()) {
Set<String> regions = remoteRegionVsApps.keySet();
Set<String> toReturn = new HashSet<>(regions);
toReturn.add(localRegion);
return toReturn;
} else {
return Collections.singleton(localRegion);
}
}
/*
* (non-Javadoc)
* @see com.netflix.discovery.shared.LookupService#getInstancesById(java.lang.String)
*/
@Override
public List<InstanceInfo> getInstancesById(String id) {
List<InstanceInfo> instancesList = new ArrayList<>();
for (Application app : this.getApplications()
.getRegisteredApplications()) {
InstanceInfo instanceInfo = app.getByInstanceId(id);
if (instanceInfo != null) {
instancesList.add(instanceInfo);
}
}
return instancesList;
}
/**
* Register {@link HealthCheckCallback} with the eureka client.
*
* Once registered, the eureka client will invoke the
* {@link HealthCheckCallback} in intervals specified by
* {@link EurekaClientConfig#getInstanceInfoReplicationIntervalSeconds()}.
*
* @param callback app specific healthcheck.
*
* @deprecated Use
*/
@Deprecated
@Override
public void registerHealthCheckCallback(HealthCheckCallback callback) {
if (instanceInfo == null) {
logger.error("Cannot register a listener for instance info since it is null!");
}
if (callback != null) {
healthCheckHandlerRef.set(new HealthCheckCallbackToHandlerBridge(callback));
}
}
@Override
public void registerHealthCheck(HealthCheckHandler healthCheckHandler) {
if (instanceInfo == null) {
logger.error("Cannot register a healthcheck handler when instance info is null!");
}
if (healthCheckHandler != null) {
this.healthCheckHandlerRef.set(healthCheckHandler);
// schedule an onDemand update of the instanceInfo when a new healthcheck handler is registered
if (instanceInfoReplicator != null) {
instanceInfoReplicator.onDemandUpdate();
}
}
}
@Override
public void registerEventListener(EurekaEventListener eventListener) {
this.eventListeners.add(eventListener);
}
@Override
public boolean unregisterEventListener(EurekaEventListener eventListener) {
return this.eventListeners.remove(eventListener);
}
/**
* Gets the list of instances matching the given VIP Address.
*
* @param vipAddress
* - The VIP address to match the instances for.
* @param secure
* - true if it is a secure vip address, false otherwise
* @return - The list of {@link InstanceInfo} objects matching the criteria
*/
@Override
public List<InstanceInfo> getInstancesByVipAddress(String vipAddress, boolean secure) {
return getInstancesByVipAddress(vipAddress, secure, instanceRegionChecker.getLocalRegion());
}
/**
* Gets the list of instances matching the given VIP Address in the passed region.
*
* @param vipAddress - The VIP address to match the instances for.
* @param secure - true if it is a secure vip address, false otherwise
* @param region - region from which the instances are to be fetched. If <code>null</code> then local region is
* assumed.
*
* @return - The list of {@link InstanceInfo} objects matching the criteria, empty list if not instances found.
*/
@Override
public List<InstanceInfo> getInstancesByVipAddress(String vipAddress, boolean secure,
@Nullable String region) {
if (vipAddress == null) {
throw new IllegalArgumentException(
"Supplied VIP Address cannot be null");
}
Applications applications;
if (instanceRegionChecker.isLocalRegion(region)) {
applications = this.localRegionApps.get();
} else {
applications = remoteRegionVsApps.get(region);
if (null == applications) {
logger.debug("No applications are defined for region {}, so returning an empty instance list for vip "
+ "address {}.", region, vipAddress);
return Collections.emptyList();
}
}
if (!secure) {
return applications.getInstancesByVirtualHostName(vipAddress);
} else {
return applications.getInstancesBySecureVirtualHostName(vipAddress);
}
}
/**
* Gets the list of instances matching the given VIP Address and the given
* application name if both of them are not null. If one of them is null,
* then that criterion is completely ignored for matching instances.
*
* @param vipAddress
* - The VIP address to match the instances for.
* @param appName
* - The applicationName to match the instances for.
* @param secure
* - true if it is a secure vip address, false otherwise.
* @return - The list of {@link InstanceInfo} objects matching the criteria.
*/
@Override
public List<InstanceInfo> getInstancesByVipAddressAndAppName(
String vipAddress, String appName, boolean secure) {
List<InstanceInfo> result = new ArrayList<>();
if (vipAddress == null && appName == null) {
throw new IllegalArgumentException(
"Supplied VIP Address and application name cannot both be null");
} else if (vipAddress != null && appName == null) {
return getInstancesByVipAddress(vipAddress, secure);
} else if (vipAddress == null && appName != null) {
Application application = getApplication(appName);
if (application != null) {
result = application.getInstances();
}
return result;
}
String instanceVipAddress;
for (Application app : getApplications().getRegisteredApplications()) {
for (InstanceInfo instance : app.getInstances()) {
if (secure) {
instanceVipAddress = instance.getSecureVipAddress();
} else {
instanceVipAddress = instance.getVIPAddress();
}
if (instanceVipAddress == null) {
continue;
}
String[] instanceVipAddresses = instanceVipAddress
.split(COMMA_STRING);
// If the VIP Address is delimited by a comma, then consider to
// be a list of VIP Addresses.
// Try to match at least one in the list, if it matches then
// return the instance info for the same
for (String vipAddressFromList : instanceVipAddresses) {
if (vipAddress.equalsIgnoreCase(vipAddressFromList.trim())
&& appName.equalsIgnoreCase(instance.getAppName())) {
result.add(instance);
break;
}
}
}
}
return result;
}
/*
* (non-Javadoc)
*
* @see
* com.netflix.discovery.shared.LookupService#getNextServerFromEureka(java
* .lang.String, boolean)
*/
@Override
public InstanceInfo getNextServerFromEureka(String virtualHostname, boolean secure) {
List<InstanceInfo> instanceInfoList = this.getInstancesByVipAddress(
virtualHostname, secure);
if (instanceInfoList == null || instanceInfoList.isEmpty()) {
throw new RuntimeException("No matches for the virtual host name :"
+ virtualHostname);
}
Applications apps = this.localRegionApps.get();
int index = (int) (apps.getNextIndex(virtualHostname,
secure).incrementAndGet() % instanceInfoList.size());
return instanceInfoList.get(index);
}
/**
* Get all applications registered with a specific eureka service.
*
* @param serviceUrl
* - The string representation of the service url.
* @return - The registry information containing all applications.
*/
@Override
public Applications getApplications(String serviceUrl) {
try {
EurekaHttpResponse<Applications> response = clientConfig.getRegistryRefreshSingleVipAddress() == null
? eurekaTransport.queryClient.getApplications()
: eurekaTransport.queryClient.getVip(clientConfig.getRegistryRefreshSingleVipAddress());
if (response.getStatusCode() == Status.OK.getStatusCode()) {
logger.debug(PREFIX + "{} - refresh status: {}", appPathIdentifier, response.getStatusCode());
return response.getEntity();
}
logger.info(PREFIX + "{} - was unable to refresh its cache! This periodic background refresh will be retried in {} seconds. status = {}",
appPathIdentifier, clientConfig.getRegistryFetchIntervalSeconds(), response.getStatusCode());
} catch (Throwable th) {
logger.info(PREFIX + "{} - was unable to refresh its cache! This periodic background refresh will be retried in {} seconds. status = {} stacktrace = {}",
appPathIdentifier, clientConfig.getRegistryFetchIntervalSeconds(), th.getMessage(), ExceptionUtils.getStackTrace(th));
}
return null;
}
/**
* Register with the eureka service by making the appropriate REST call.
*/
boolean register() throws Throwable {
logger.info(PREFIX + "{}: registering service...", appPathIdentifier);
EurekaHttpResponse<Void> httpResponse;
try {
httpResponse = eurekaTransport.registrationClient.register(instanceInfo);
} catch (Exception e) {
logger.warn(PREFIX + "{} - registration failed {}", appPathIdentifier, e.getMessage(), e);
throw e;
}
if (logger.isInfoEnabled()) {
logger.info(PREFIX + "{} - registration status: {}", appPathIdentifier, httpResponse.getStatusCode());
}
return httpResponse.getStatusCode() == Status.NO_CONTENT.getStatusCode();
}
/**
* Renew with the eureka service by making the appropriate REST call
*/
boolean renew() {
EurekaHttpResponse<InstanceInfo> httpResponse;
try {
httpResponse = eurekaTransport.registrationClient.sendHeartBeat(instanceInfo.getAppName(), instanceInfo.getId(), instanceInfo, null);
logger.debug(PREFIX + "{} - Heartbeat status: {}", appPathIdentifier, httpResponse.getStatusCode());
if (httpResponse.getStatusCode() == Status.NOT_FOUND.getStatusCode()) {
REREGISTER_COUNTER.increment();
logger.info(PREFIX + "{} - Re-registering apps/{}", appPathIdentifier, instanceInfo.getAppName());
long timestamp = instanceInfo.setIsDirtyWithTime();
boolean success = register();
if (success) {
instanceInfo.unsetIsDirty(timestamp);
}
return success;
}
return httpResponse.getStatusCode() == Status.OK.getStatusCode();
} catch (Throwable e) {
logger.error(PREFIX + "{} - was unable to send heartbeat!", appPathIdentifier, e);
return false;
}
}
/**
* @deprecated see replacement in {@link com.netflix.discovery.endpoint.EndpointUtils}
*
* Get the list of all eureka service urls from properties file for the eureka client to talk to.
*
* @param instanceZone The zone in which the client resides
* @param preferSameZone true if we have to prefer the same zone as the client, false otherwise
* @return The list of all eureka service urls for the eureka client to talk to
*/
@Deprecated
@Override
public List<String> getServiceUrlsFromConfig(String instanceZone, boolean preferSameZone) {
return EndpointUtils.getServiceUrlsFromConfig(clientConfig, instanceZone, preferSameZone);
}
/**
* Shuts down Eureka Client. Also sends a deregistration request to the
* eureka server.
*/
@PreDestroy
@Override
public synchronized void shutdown() {
if (isShutdown.compareAndSet(false, true)) {
logger.info("Shutting down DiscoveryClient ...");
if (statusChangeListener != null && applicationInfoManager != null) {
applicationInfoManager.unregisterStatusChangeListener(statusChangeListener.getId());
}
cancelScheduledTasks();
// If APPINFO was registered
if (applicationInfoManager != null
&& clientConfig.shouldRegisterWithEureka()
&& clientConfig.shouldUnregisterOnShutdown()) {
applicationInfoManager.setInstanceStatus(InstanceStatus.DOWN);
unregister();
}
if (eurekaTransport != null) {
eurekaTransport.shutdown();
}
heartbeatStalenessMonitor.shutdown();
registryStalenessMonitor.shutdown();
Monitors.unregisterObject(this);
logger.info("Completed shut down of DiscoveryClient");
}
}
/**
* unregister w/ the eureka service.
*/
void unregister() {
// It can be null if shouldRegisterWithEureka == false
if(eurekaTransport != null && eurekaTransport.registrationClient != null) {
try {
logger.info("Unregistering ...");
EurekaHttpResponse<Void> httpResponse = eurekaTransport.registrationClient.cancel(instanceInfo.getAppName(), instanceInfo.getId());
logger.info(PREFIX + "{} - deregister status: {}", appPathIdentifier, httpResponse.getStatusCode());
} catch (Exception e) {
logger.error(PREFIX + "{} - de-registration failed{}", appPathIdentifier, e.getMessage(), e);
}
}
}
/**
* Fetches the registry information.
*
* <p>
* This method tries to get only deltas after the first fetch unless there
* is an issue in reconciling eureka server and client registry information.
* </p>
*
* @param forceFullRegistryFetch Forces a full registry fetch.
*
* @return true if the registry was fetched
*/
private boolean fetchRegistry(boolean forceFullRegistryFetch) {
Stopwatch tracer = FETCH_REGISTRY_TIMER.start();
try {
// If the delta is disabled or if it is the first time, get all
// applications
Applications applications = getApplications();
if (clientConfig.shouldDisableDelta()
|| (!Strings.isNullOrEmpty(clientConfig.getRegistryRefreshSingleVipAddress()))
|| forceFullRegistryFetch
|| (applications == null)
|| (applications.getRegisteredApplications().size() == 0)
|| (applications.getVersion() == -1)) //Client application does not have latest library supporting delta
{
logger.info("Disable delta property : {}", clientConfig.shouldDisableDelta());
logger.info("Single vip registry refresh property : {}", clientConfig.getRegistryRefreshSingleVipAddress());
logger.info("Force full registry fetch : {}", forceFullRegistryFetch);
logger.info("Application is null : {}", (applications == null));
logger.info("Registered Applications size is zero : {}",
(applications.getRegisteredApplications().size() == 0));
logger.info("Application version is -1: {}", (applications.getVersion() == -1));
getAndStoreFullRegistry();
} else {
getAndUpdateDelta(applications);
}
applications.setAppsHashCode(applications.getReconcileHashCode());
logTotalInstances();
} catch (Throwable e) {
logger.info(PREFIX + "{} - was unable to refresh its cache! This periodic background refresh will be retried in {} seconds. status = {} stacktrace = {}",
appPathIdentifier, clientConfig.getRegistryFetchIntervalSeconds(), e.getMessage(), ExceptionUtils.getStackTrace(e));
return false;
} finally {
if (tracer != null) {
tracer.stop();
}
}
// Notify about cache refresh before updating the instance remote status
onCacheRefreshed();
// Update remote status based on refreshed data held in the cache
updateInstanceRemoteStatus();
// registry was fetched successfully, so return true
return true;
}
private synchronized void updateInstanceRemoteStatus() {
// Determine this instance's status for this app and set to UNKNOWN if not found
InstanceInfo.InstanceStatus currentRemoteInstanceStatus = null;
if (instanceInfo.getAppName() != null) {
Application app = getApplication(instanceInfo.getAppName());
if (app != null) {
InstanceInfo remoteInstanceInfo = app.getByInstanceId(instanceInfo.getId());
if (remoteInstanceInfo != null) {
currentRemoteInstanceStatus = remoteInstanceInfo.getStatus();
}
}
}
if (currentRemoteInstanceStatus == null) {
currentRemoteInstanceStatus = InstanceInfo.InstanceStatus.UNKNOWN;
}
// Notify if status changed
if (lastRemoteInstanceStatus != currentRemoteInstanceStatus) {
onRemoteStatusChanged(lastRemoteInstanceStatus, currentRemoteInstanceStatus);
lastRemoteInstanceStatus = currentRemoteInstanceStatus;
}
}
/**
* @return Return he current instance status as seen on the Eureka server.
*/
@Override
public InstanceInfo.InstanceStatus getInstanceRemoteStatus() {
return lastRemoteInstanceStatus;
}
private String getReconcileHashCode(Applications applications) {
TreeMap<String, AtomicInteger> instanceCountMap = new TreeMap<String, AtomicInteger>();
if (isFetchingRemoteRegionRegistries()) {
for (Applications remoteApp : remoteRegionVsApps.values()) {
remoteApp.populateInstanceCountMap(instanceCountMap);
}
}
applications.populateInstanceCountMap(instanceCountMap);
return Applications.getReconcileHashCode(instanceCountMap);
}
/**
* Gets the full registry information from the eureka server and stores it locally.
* When applying the full registry, the following flow is observed:
*
* if (update generation have not advanced (due to another thread))
* atomically set the registry to the new registry
* fi
*
* @return the full registry information.
* @throws Throwable
* on error.
*/
private void getAndStoreFullRegistry() throws Throwable {
long currentUpdateGeneration = fetchRegistryGeneration.get();
logger.info("Getting all instance registry info from the eureka server");
Applications apps = null;
EurekaHttpResponse<Applications> httpResponse = clientConfig.getRegistryRefreshSingleVipAddress() == null
? eurekaTransport.queryClient.getApplications(remoteRegionsRef.get())
: eurekaTransport.queryClient.getVip(clientConfig.getRegistryRefreshSingleVipAddress(), remoteRegionsRef.get());
if (httpResponse.getStatusCode() == Status.OK.getStatusCode()) {
apps = httpResponse.getEntity();
}
logger.info("The response status is {}", httpResponse.getStatusCode());
if (apps == null) {
logger.error("The application is null for some reason. Not storing this information");
} else if (fetchRegistryGeneration.compareAndSet(currentUpdateGeneration, currentUpdateGeneration + 1)) {
localRegionApps.set(this.filterAndShuffle(apps));
logger.debug("Got full registry with apps hashcode {}", apps.getAppsHashCode());
} else {
logger.warn("Not updating applications as another thread is updating it already");
}
}
/**
* Get the delta registry information from the eureka server and update it locally.
* When applying the delta, the following flow is observed:
*
* if (update generation have not advanced (due to another thread))
* atomically try to: update application with the delta and get reconcileHashCode
* abort entire processing otherwise
* do reconciliation if reconcileHashCode clash
* fi
*
* @return the client response
* @throws Throwable on error
*/
private void getAndUpdateDelta(Applications applications) throws Throwable {
long currentUpdateGeneration = fetchRegistryGeneration.get();
Applications delta = null;
EurekaHttpResponse<Applications> httpResponse = eurekaTransport.queryClient.getDelta(remoteRegionsRef.get());
if (httpResponse.getStatusCode() == Status.OK.getStatusCode()) {
delta = httpResponse.getEntity();
}
if (delta == null) {
logger.warn("The server does not allow the delta revision to be applied because it is not safe. "
+ "Hence got the full registry.");
getAndStoreFullRegistry();
} else if (fetchRegistryGeneration.compareAndSet(currentUpdateGeneration, currentUpdateGeneration + 1)) {
logger.debug("Got delta update with apps hashcode {}", delta.getAppsHashCode());
String reconcileHashCode = "";
if (fetchRegistryUpdateLock.tryLock()) {
try {
updateDelta(delta);
reconcileHashCode = getReconcileHashCode(applications);
} finally {
fetchRegistryUpdateLock.unlock();
}
} else {
logger.warn("Cannot acquire update lock, aborting getAndUpdateDelta");
}
// There is a diff in number of instances for some reason
if (!reconcileHashCode.equals(delta.getAppsHashCode()) || clientConfig.shouldLogDeltaDiff()) {
reconcileAndLogDifference(delta, reconcileHashCode); // this makes a remoteCall
}
} else {
logger.warn("Not updating application delta as another thread is updating it already");
logger.debug("Ignoring delta update with apps hashcode {}, as another thread is updating it already", delta.getAppsHashCode());
}
}
/**
* Logs the total number of non-filtered instances stored locally.
*/
private void logTotalInstances() {
if (logger.isDebugEnabled()) {
int totInstances = 0;
for (Application application : getApplications().getRegisteredApplications()) {
totInstances += application.getInstancesAsIsFromEureka().size();
}
logger.debug("The total number of all instances in the client now is {}", totInstances);
}
}
/**
* Reconcile the eureka server and client registry information and logs the differences if any.
* When reconciling, the following flow is observed:
*
* make a remote call to the server for the full registry
* calculate and log differences
* if (update generation have not advanced (due to another thread))
* atomically set the registry to the new registry
* fi
*
* @param delta
* the last delta registry information received from the eureka
* server.
* @param reconcileHashCode
* the hashcode generated by the server for reconciliation.
* @return ClientResponse the HTTP response object.
* @throws Throwable
* on any error.
*/
private void reconcileAndLogDifference(Applications delta, String reconcileHashCode) throws Throwable {
logger.debug("The Reconcile hashcodes do not match, client : {}, server : {}. Getting the full registry",
reconcileHashCode, delta.getAppsHashCode());
RECONCILE_HASH_CODES_MISMATCH.increment();
long currentUpdateGeneration = fetchRegistryGeneration.get();
EurekaHttpResponse<Applications> httpResponse = clientConfig.getRegistryRefreshSingleVipAddress() == null
? eurekaTransport.queryClient.getApplications(remoteRegionsRef.get())
: eurekaTransport.queryClient.getVip(clientConfig.getRegistryRefreshSingleVipAddress(), remoteRegionsRef.get());
Applications serverApps = httpResponse.getEntity();
if (serverApps == null) {
logger.warn("Cannot fetch full registry from the server; reconciliation failure");
return;
}
if (fetchRegistryGeneration.compareAndSet(currentUpdateGeneration, currentUpdateGeneration + 1)) {
localRegionApps.set(this.filterAndShuffle(serverApps));
getApplications().setVersion(delta.getVersion());
logger.debug(
"The Reconcile hashcodes after complete sync up, client : {}, server : {}.",
getApplications().getReconcileHashCode(),
delta.getAppsHashCode());
} else {
logger.warn("Not setting the applications map as another thread has advanced the update generation");
}
}
/**
* Updates the delta information fetches from the eureka server into the
* local cache.
*
* @param delta
* the delta information received from eureka server in the last
* poll cycle.
*/
private void updateDelta(Applications delta) {
int deltaCount = 0;
for (Application app : delta.getRegisteredApplications()) {
for (InstanceInfo instance : app.getInstances()) {
Applications applications = getApplications();
String instanceRegion = instanceRegionChecker.getInstanceRegion(instance);
if (!instanceRegionChecker.isLocalRegion(instanceRegion)) {
Applications remoteApps = remoteRegionVsApps.get(instanceRegion);
if (null == remoteApps) {
remoteApps = new Applications();
remoteRegionVsApps.put(instanceRegion, remoteApps);
}
applications = remoteApps;
}
++deltaCount;
if (ActionType.ADDED.equals(instance.getActionType())) {
Application existingApp = applications.getRegisteredApplications(instance.getAppName());
if (existingApp == null) {
applications.addApplication(app);
}
logger.debug("Added instance {} to the existing apps in region {}", instance.getId(), instanceRegion);
applications.getRegisteredApplications(instance.getAppName()).addInstance(instance);
} else if (ActionType.MODIFIED.equals(instance.getActionType())) {
Application existingApp = applications.getRegisteredApplications(instance.getAppName());
if (existingApp == null) {
applications.addApplication(app);
}
logger.debug("Modified instance {} to the existing apps ", instance.getId());
applications.getRegisteredApplications(instance.getAppName()).addInstance(instance);
} else if (ActionType.DELETED.equals(instance.getActionType())) {
Application existingApp = applications.getRegisteredApplications(instance.getAppName());
if (existingApp != null) {
logger.debug("Deleted instance {} to the existing apps ", instance.getId());
existingApp.removeInstance(instance);
/*
* We find all instance list from application(The status of instance status is not only the status is UP but also other status)
* if instance list is empty, we remove the application.
*/
if (existingApp.getInstancesAsIsFromEureka().isEmpty()) {
applications.removeApplication(existingApp);
}
}
}
}
}
logger.debug("The total number of instances fetched by the delta processor : {}", deltaCount);
getApplications().setVersion(delta.getVersion());
getApplications().shuffleInstances(clientConfig.shouldFilterOnlyUpInstances());
for (Applications applications : remoteRegionVsApps.values()) {
applications.setVersion(delta.getVersion());
applications.shuffleInstances(clientConfig.shouldFilterOnlyUpInstances());
}
}
/**
* Initializes all scheduled tasks.
*/
private void initScheduledTasks() {
if (clientConfig.shouldFetchRegistry()) {
// registry cache refresh timer
int registryFetchIntervalSeconds = clientConfig.getRegistryFetchIntervalSeconds();
int expBackOffBound = clientConfig.getCacheRefreshExecutorExponentialBackOffBound();
cacheRefreshTask = new TimedSupervisorTask(
"cacheRefresh",
scheduler,
cacheRefreshExecutor,
registryFetchIntervalSeconds,
TimeUnit.SECONDS,
expBackOffBound,
new CacheRefreshThread()
);
scheduler.schedule(
cacheRefreshTask,
registryFetchIntervalSeconds, TimeUnit.SECONDS);
}
if (clientConfig.shouldRegisterWithEureka()) {
int renewalIntervalInSecs = instanceInfo.getLeaseInfo().getRenewalIntervalInSecs();
int expBackOffBound = clientConfig.getHeartbeatExecutorExponentialBackOffBound();
logger.info("Starting heartbeat executor: " + "renew interval is: {}", renewalIntervalInSecs);
// Heartbeat timer
heartbeatTask = new TimedSupervisorTask(
"heartbeat",
scheduler,
heartbeatExecutor,
renewalIntervalInSecs,
TimeUnit.SECONDS,
expBackOffBound,
new HeartbeatThread()
);
scheduler.schedule(
heartbeatTask,
renewalIntervalInSecs, TimeUnit.SECONDS);
// InstanceInfo replicator
instanceInfoReplicator = new InstanceInfoReplicator(
this,
instanceInfo,
clientConfig.getInstanceInfoReplicationIntervalSeconds(),
2); // burstSize
statusChangeListener = new ApplicationInfoManager.StatusChangeListener() {
@Override
public String getId() {
return "statusChangeListener";
}
@Override
public void notify(StatusChangeEvent statusChangeEvent) {
logger.info("Saw local status change event {}", statusChangeEvent);
instanceInfoReplicator.onDemandUpdate();
}
};
if (clientConfig.shouldOnDemandUpdateStatusChange()) {
applicationInfoManager.registerStatusChangeListener(statusChangeListener);
}
instanceInfoReplicator.start(clientConfig.getInitialInstanceInfoReplicationIntervalSeconds());
} else {
logger.info("Not registering with Eureka server per configuration");
}
}
private void cancelScheduledTasks() {
if (instanceInfoReplicator != null) {
instanceInfoReplicator.stop();
}
if (heartbeatExecutor != null) {
heartbeatExecutor.shutdownNow();
}
if (cacheRefreshExecutor != null) {
cacheRefreshExecutor.shutdownNow();
}
if (scheduler != null) {
scheduler.shutdownNow();
}
if (cacheRefreshTask != null) {
cacheRefreshTask.cancel();
}
if (heartbeatTask != null) {
heartbeatTask.cancel();
}
}
/**
* @deprecated see replacement in {@link com.netflix.discovery.endpoint.EndpointUtils}
*
* Get the list of all eureka service urls from DNS for the eureka client to
* talk to. The client picks up the service url from its zone and then fails over to
* other zones randomly. If there are multiple servers in the same zone, the client once
* again picks one randomly. This way the traffic will be distributed in the case of failures.
*
* @param instanceZone The zone in which the client resides.
* @param preferSameZone true if we have to prefer the same zone as the client, false otherwise.
* @return The list of all eureka service urls for the eureka client to talk to.
*/
@Deprecated
@Override
public List<String> getServiceUrlsFromDNS(String instanceZone, boolean preferSameZone) {
return EndpointUtils.getServiceUrlsFromDNS(clientConfig, instanceZone, preferSameZone, urlRandomizer);
}
/**
* @deprecated see replacement in {@link com.netflix.discovery.endpoint.EndpointUtils}
*/
@Deprecated
@Override
public List<String> getDiscoveryServiceUrls(String zone) {
return EndpointUtils.getDiscoveryServiceUrls(clientConfig, zone, urlRandomizer);
}
/**
* @deprecated see replacement in {@link com.netflix.discovery.endpoint.EndpointUtils}
*
* Get the list of EC2 URLs given the zone name.
*
* @param dnsName The dns name of the zone-specific CNAME
* @param type CNAME or EIP that needs to be retrieved
* @return The list of EC2 URLs associated with the dns name
*/
@Deprecated
public static Set<String> getEC2DiscoveryUrlsFromZone(String dnsName,
EndpointUtils.DiscoveryUrlType type) {
return EndpointUtils.getEC2DiscoveryUrlsFromZone(dnsName, type);
}
/**
* Refresh the current local instanceInfo. Note that after a valid refresh where changes are observed, the
* isDirty flag on the instanceInfo is set to true
*/
void refreshInstanceInfo() {
applicationInfoManager.refreshDataCenterInfoIfRequired();
applicationInfoManager.refreshLeaseInfoIfRequired();
InstanceStatus status;
try {
status = getHealthCheckHandler().getStatus(instanceInfo.getStatus());
} catch (Exception e) {
logger.warn("Exception from healthcheckHandler.getStatus, setting status to DOWN", e);
status = InstanceStatus.DOWN;
}
if (null != status) {
applicationInfoManager.setInstanceStatus(status);
}
}
/**
* The heartbeat task that renews the lease in the given intervals.
*/
private class HeartbeatThread implements Runnable {
public void run() {
if (renew()) {
lastSuccessfulHeartbeatTimestamp = System.currentTimeMillis();
}
}
}
@VisibleForTesting
InstanceInfoReplicator getInstanceInfoReplicator() {
return instanceInfoReplicator;
}
@VisibleForTesting
InstanceInfo getInstanceInfo() {
return instanceInfo;
}
@Override
public HealthCheckHandler getHealthCheckHandler() {
HealthCheckHandler healthCheckHandler = this.healthCheckHandlerRef.get();
if (healthCheckHandler == null) {
if (null != healthCheckHandlerProvider) {
healthCheckHandler = healthCheckHandlerProvider.get();
} else if (null != healthCheckCallbackProvider) {
healthCheckHandler = new HealthCheckCallbackToHandlerBridge(healthCheckCallbackProvider.get());
}
if (null == healthCheckHandler) {
healthCheckHandler = new HealthCheckCallbackToHandlerBridge(null);
}
this.healthCheckHandlerRef.compareAndSet(null, healthCheckHandler);
}
return this.healthCheckHandlerRef.get();
}
/**
* The task that fetches the registry information at specified intervals.
*
*/
class CacheRefreshThread implements Runnable {
public void run() {
refreshRegistry();
}
}
@VisibleForTesting
void refreshRegistry() {
try {
boolean isFetchingRemoteRegionRegistries = isFetchingRemoteRegionRegistries();
boolean remoteRegionsModified = false;
// This makes sure that a dynamic change to remote regions to fetch is honored.
String latestRemoteRegions = clientConfig.fetchRegistryForRemoteRegions();
if (null != latestRemoteRegions) {
String currentRemoteRegions = remoteRegionsToFetch.get();
if (!latestRemoteRegions.equals(currentRemoteRegions)) {
// Both remoteRegionsToFetch and AzToRegionMapper.regionsToFetch need to be in sync
synchronized (instanceRegionChecker.getAzToRegionMapper()) {
if (remoteRegionsToFetch.compareAndSet(currentRemoteRegions, latestRemoteRegions)) {
String[] remoteRegions = latestRemoteRegions.split(",");
remoteRegionsRef.set(remoteRegions);
instanceRegionChecker.getAzToRegionMapper().setRegionsToFetch(remoteRegions);
remoteRegionsModified = true;
} else {
logger.info("Remote regions to fetch modified concurrently," +
" ignoring change from {} to {}", currentRemoteRegions, latestRemoteRegions);
}
}
} else {
// Just refresh mapping to reflect any DNS/Property change
instanceRegionChecker.getAzToRegionMapper().refreshMapping();
}
}
boolean success = fetchRegistry(remoteRegionsModified);
if (success) {
registrySize = localRegionApps.get().size();
lastSuccessfulRegistryFetchTimestamp = System.currentTimeMillis();
}
if (logger.isDebugEnabled()) {
StringBuilder allAppsHashCodes = new StringBuilder();
allAppsHashCodes.append("Local region apps hashcode: ");
allAppsHashCodes.append(localRegionApps.get().getAppsHashCode());
allAppsHashCodes.append(", is fetching remote regions? ");
allAppsHashCodes.append(isFetchingRemoteRegionRegistries);
for (Map.Entry<String, Applications> entry : remoteRegionVsApps.entrySet()) {
allAppsHashCodes.append(", Remote region: ");
allAppsHashCodes.append(entry.getKey());
allAppsHashCodes.append(" , apps hashcode: ");
allAppsHashCodes.append(entry.getValue().getAppsHashCode());
}
logger.debug("Completed cache refresh task for discovery. All Apps hash code is {} ",
allAppsHashCodes);
}
} catch (Throwable e) {
logger.error("Cannot fetch registry from server", e);
}
}
/**
* Fetch the registry information from back up registry if all eureka server
* urls are unreachable.
*
* @return true if the registry was fetched
*/
private boolean fetchRegistryFromBackup() {
try {
@SuppressWarnings("deprecation")
BackupRegistry backupRegistryInstance = newBackupRegistryInstance();
if (null == backupRegistryInstance) { // backward compatibility with the old protected method, in case it is being used.
backupRegistryInstance = backupRegistryProvider.get();
}
if (null != backupRegistryInstance) {
Applications apps = null;
if (isFetchingRemoteRegionRegistries()) {
String remoteRegionsStr = remoteRegionsToFetch.get();
if (null != remoteRegionsStr) {
apps = backupRegistryInstance.fetchRegistry(remoteRegionsStr.split(","));
}
} else {
apps = backupRegistryInstance.fetchRegistry();
}
if (apps != null) {
final Applications applications = this.filterAndShuffle(apps);
applications.setAppsHashCode(applications.getReconcileHashCode());
localRegionApps.set(applications);
logTotalInstances();
logger.info("Fetched registry successfully from the backup");
return true;
}
} else {
logger.warn("No backup registry instance defined & unable to find any discovery servers.");
}
} catch (Throwable e) {
logger.warn("Cannot fetch applications from apps although backup registry was specified", e);
}
return false;
}
/**
* @deprecated Use injection to provide {@link BackupRegistry} implementation.
*/
@Deprecated
@Nullable
protected BackupRegistry newBackupRegistryInstance()
throws ClassNotFoundException, IllegalAccessException, InstantiationException {
return null;
}
/**
* Gets the <em>applications</em> after filtering the applications for
* instances with only UP states and shuffling them.
*
* <p>
* The filtering depends on the option specified by the configuration
* {@link EurekaClientConfig#shouldFilterOnlyUpInstances()}. Shuffling helps
* in randomizing the applications list there by avoiding the same instances
* receiving traffic during start ups.
* </p>
*
* @param apps
* The applications that needs to be filtered and shuffled.
* @return The applications after the filter and the shuffle.
*/
private Applications filterAndShuffle(Applications apps) {
if (apps != null) {
if (isFetchingRemoteRegionRegistries()) {
Map<String, Applications> remoteRegionVsApps = new ConcurrentHashMap<String, Applications>();
apps.shuffleAndIndexInstances(remoteRegionVsApps, clientConfig, instanceRegionChecker);
for (Applications applications : remoteRegionVsApps.values()) {
applications.shuffleInstances(clientConfig.shouldFilterOnlyUpInstances());
}
this.remoteRegionVsApps = remoteRegionVsApps;
} else {
apps.shuffleInstances(clientConfig.shouldFilterOnlyUpInstances());
}
}
return apps;
}
private boolean isFetchingRemoteRegionRegistries() {
return null != remoteRegionsToFetch.get();
}
/**
* Invoked when the remote status of this client has changed.
* Subclasses may override this method to implement custom behavior if needed.
*
* @param oldStatus the previous remote {@link InstanceStatus}
* @param newStatus the new remote {@link InstanceStatus}
*/
protected void onRemoteStatusChanged(InstanceInfo.InstanceStatus oldStatus, InstanceInfo.InstanceStatus newStatus) {
fireEvent(new StatusChangeEvent(oldStatus, newStatus));
}
/**
* Invoked every time the local registry cache is refreshed (whether changes have
* been detected or not).
*
* Subclasses may override this method to implement custom behavior if needed.
*/
protected void onCacheRefreshed() {
fireEvent(new CacheRefreshedEvent());
}
/**
* Send the given event on the EventBus if one is available
*
* @param event the event to send on the eventBus
*/
protected void fireEvent(final EurekaEvent event) {
for (EurekaEventListener listener : eventListeners) {
try {
listener.onEvent(event);
} catch (Exception e) {
logger.info("Event {} throw an exception for listener {}", event, listener, e.getMessage());
}
}
}
/**
* @deprecated see {@link com.netflix.appinfo.InstanceInfo#getZone(String[], com.netflix.appinfo.InstanceInfo)}
*
* Get the zone that a particular instance is in.
*
* @param myInfo
* - The InstanceInfo object of the instance.
* @return - The zone in which the particular instance belongs to.
*/
@Deprecated
public static String getZone(InstanceInfo myInfo) {
String[] availZones = staticClientConfig.getAvailabilityZones(staticClientConfig.getRegion());
return InstanceInfo.getZone(availZones, myInfo);
}
/**
* @deprecated see replacement in {@link com.netflix.discovery.endpoint.EndpointUtils}
*
* Get the region that this particular instance is in.
*
* @return - The region in which the particular instance belongs to.
*/
@Deprecated
public static String getRegion() {
String region = staticClientConfig.getRegion();
if (region == null) {
region = "default";
}
region = region.trim().toLowerCase();
return region;
}
/**
* @deprecated use {@link #getServiceUrlsFromConfig(String, boolean)} instead.
*/
@Deprecated
public static List<String> getEurekaServiceUrlsFromConfig(String instanceZone, boolean preferSameZone) {
return EndpointUtils.getServiceUrlsFromConfig(staticClientConfig, instanceZone, preferSameZone);
}
public long getLastSuccessfulHeartbeatTimePeriod() {
return lastSuccessfulHeartbeatTimestamp < 0
? lastSuccessfulHeartbeatTimestamp
: System.currentTimeMillis() - lastSuccessfulHeartbeatTimestamp;
}
public long getLastSuccessfulRegistryFetchTimePeriod() {
return lastSuccessfulRegistryFetchTimestamp < 0
? lastSuccessfulRegistryFetchTimestamp
: System.currentTimeMillis() - lastSuccessfulRegistryFetchTimestamp;
}
@com.netflix.servo.annotations.Monitor(name = METRIC_REGISTRATION_PREFIX + "lastSuccessfulHeartbeatTimePeriod",
description = "How much time has passed from last successful heartbeat", type = DataSourceType.GAUGE)
private long getLastSuccessfulHeartbeatTimePeriodInternal() {
final long delay = (!clientConfig.shouldRegisterWithEureka() || isShutdown.get())
? 0
: getLastSuccessfulHeartbeatTimePeriod();
heartbeatStalenessMonitor.update(computeStalenessMonitorDelay(delay));
return delay;
}
// for metrics only
@com.netflix.servo.annotations.Monitor(name = METRIC_REGISTRY_PREFIX + "lastSuccessfulRegistryFetchTimePeriod",
description = "How much time has passed from last successful local registry update", type = DataSourceType.GAUGE)
private long getLastSuccessfulRegistryFetchTimePeriodInternal() {
final long delay = (!clientConfig.shouldFetchRegistry() || isShutdown.get())
? 0
: getLastSuccessfulRegistryFetchTimePeriod();
registryStalenessMonitor.update(computeStalenessMonitorDelay(delay));
return delay;
}
@com.netflix.servo.annotations.Monitor(name = METRIC_REGISTRY_PREFIX + "localRegistrySize",
description = "Count of instances in the local registry", type = DataSourceType.GAUGE)
public int localRegistrySize() {
return registrySize;
}
private long computeStalenessMonitorDelay(long delay) {
if (delay < 0) {
return System.currentTimeMillis() - initTimestampMs;
} else {
return delay;
}
}
/**
* Gets stats for the DiscoveryClient.
*
* @return The DiscoveryClientStats instance.
*/
public Stats getStats() {
return stats;
}
/**
* Stats is used to track useful attributes of the DiscoveryClient. It includes helpers that can aid
* debugging and log analysis.
*/
public class Stats {
private Stats() {}
public int initLocalRegistrySize() {
return initRegistrySize;
}
public long initTimestampMs() {
return initTimestampMs;
}
public int localRegistrySize() {
return registrySize;
}
public long lastSuccessfulRegistryFetchTimestampMs() {
return lastSuccessfulRegistryFetchTimestamp;
}
public long lastSuccessfulHeartbeatTimestampMs() {
return lastSuccessfulHeartbeatTimestamp;
}
/**
* Used to determine if the Discovery client's first attempt to fetch from the service registry succeeded with
* non-empty results.
*
* @return true if succeeded, failed otherwise
*/
public boolean initSucceeded() {
return initLocalRegistrySize() > 0 && initTimestampMs() > 0;
}
}
}
| 7,937 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/PropertyBasedAzToRegionMapper.java | package com.netflix.discovery;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* @author Nitesh Kant
*/
public class PropertyBasedAzToRegionMapper extends AbstractAzToRegionMapper {
public PropertyBasedAzToRegionMapper(EurekaClientConfig clientConfig) {
super(clientConfig);
}
@Override
protected Set<String> getZonesForARegion(String region) {
return new HashSet<String>(Arrays.asList(clientConfig.getAvailabilityZones(region)));
}
}
| 7,938 |
0 | Create_ds/eureka/eureka-client/src/main/java/com/netflix | Create_ds/eureka/eureka-client/src/main/java/com/netflix/discovery/BackupRegistry.java | /*
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.discovery;
import com.google.inject.ImplementedBy;
import com.netflix.discovery.shared.Applications;
/**
* A simple contract for <em>eureka</em> clients to fallback for getting
* registry information in case eureka clients are unable to retrieve this
* information from any of the <em>eureka</em> servers.
*
* <p>
* This is normally not required, but for applications that cannot exist without
* the registry information it can provide some additional reslience.
* </p>
*
* @author Karthik Ranganathan
*
*/
@ImplementedBy(NotImplementedRegistryImpl.class)
public interface BackupRegistry {
Applications fetchRegistry();
Applications fetchRegistry(String[] includeRemoteRegions);
}
| 7,939 |
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();
}
| 7,940 |
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");
}
}
| 7,941 |
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);
}
}
| 7,942 |
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);
}
}
}
| 7,943 |
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() {
}
}
}
| 7,944 |
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();
}
}
| 7,945 |
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);
}
}
| 7,946 |
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());
}
}
| 7,947 |
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);
}
}
| 7,948 |
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();
}
}
| 7,949 |
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;
}
};
}
| 7,950 |
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();
}
| 7,951 |
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;
}
}
| 7,952 |
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;
}
}
}
}
| 7,953 |
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;
}
}
}
| 7,954 |
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;
}
}
| 7,955 |
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();
}
}
| 7,956 |
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;
}
}
| 7,957 |
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;
}
}
| 7,958 |
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);
}
}
}
}
| 7,959 |
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;
}
| 7,960 |
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 "";
}
| 7,961 |
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());
}
}
| 7,962 |
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);
}
}
}
| 7,963 |
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 {
}
| 7,964 |
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;
}
}
}
| 7,965 |
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;
}
}
| 7,966 |
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;
}
} | 7,967 |
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;
}
}
| 7,968 |
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());
}
}
| 7,969 |
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;
}
| 7,970 |
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;
}
| 7,971 |
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);
}
| 7,972 |
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 {
}
| 7,973 |
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);
}
}
}
| 7,974 |
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;
}
}
| 7,975 |
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;
}
}
| 7,976 |
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;
}
};
}
}
| 7,977 |
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;
}
};
}
}
| 7,978 |
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;
}
}
| 7,979 |
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;
}
}
| 7,980 |
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);
}
}
| 7,981 |
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());
}
}
}
}
| 7,982 |
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());
}
}
}
| 7,983 |
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());
}
}
}
| 7,984 |
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);
}
}
| 7,985 |
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();
}
}
| 7,986 |
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 {
}
| 7,987 |
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();
}
| 7,988 |
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();
}
| 7,989 |
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 {
}
| 7,990 |
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();
}
| 7,991 |
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 {
}
| 7,992 |
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();
}
| 7,993 |
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);
}
}
| 7,994 |
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);
}
}
| 7,995 |
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);
}
}
| 7,996 |
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;
}
}
}
}
| 7,997 |
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);
}
}
| 7,998 |
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;
}
}
| 7,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.