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-archaius2/src/main/java/com/netflix/appinfo | Create_ds/eureka/eureka-client-archaius2/src/main/java/com/netflix/appinfo/providers/AmazonInfoProviderFactory.java | package com.netflix.appinfo.providers;
import com.netflix.appinfo.AmazonInfo;
import javax.inject.Provider;
public interface AmazonInfoProviderFactory {
Provider<AmazonInfo> get();
}
| 8,100 |
0 | Create_ds/eureka/eureka-client-archaius2/src/main/java/com/netflix/appinfo | Create_ds/eureka/eureka-client-archaius2/src/main/java/com/netflix/appinfo/providers/EurekaInstanceConfigFactory.java | package com.netflix.appinfo.providers;
import com.netflix.appinfo.EurekaInstanceConfig;
/**
* An equivalent {@link javax.inject.Provider} interface for {@link com.netflix.appinfo.EurekaInstanceConfig}.
*
* Why define this {@link com.netflix.appinfo.providers.EurekaInstanceConfigFactory} instead
* of using {@link javax.inject.Provider} instead? Provider does not work due to the fact that
* Guice treats Providers specially.
*
* @author David Liu
*/
public interface EurekaInstanceConfigFactory {
EurekaInstanceConfig get();
}
| 8,101 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/RemoteRegionSoftDependencyTest.java | package com.netflix.eureka;
import com.netflix.eureka.mock.MockRemoteEurekaServer;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Mockito.doReturn;
/**
* @author Nitesh Kant
*/
public class RemoteRegionSoftDependencyTest extends AbstractTester {
@Override
@Before
public void setUp() throws Exception {
super.setUp();
doReturn(10).when(serverConfig).getWaitTimeInMsWhenSyncEmpty();
doReturn(1).when(serverConfig).getRegistrySyncRetries();
doReturn(1l).when(serverConfig).getRegistrySyncRetryWaitMs();
registry.syncUp();
}
@Test
public void testSoftDepRemoteDown() throws Exception {
Assert.assertTrue("Registry access disallowed when remote region is down.", registry.shouldAllowAccess(false));
Assert.assertFalse("Registry access allowed when remote region is down.", registry.shouldAllowAccess(true));
}
@Override
protected MockRemoteEurekaServer newMockRemoteServer() {
MockRemoteEurekaServer server = super.newMockRemoteServer();
server.simulateNotReady(true);
return server;
}
}
| 8,102 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/RateLimitingFilterTest.java | /*
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.eureka;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.netflix.appinfo.AbstractEurekaIdentity;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.EurekaClientIdentity;
import com.netflix.appinfo.MyDataCenterInstanceConfig;
import com.netflix.config.ConfigurationManager;
import com.netflix.eureka.util.EurekaMonitors;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Tomasz Bak
*/
@RunWith(MockitoJUnitRunner.class)
public class RateLimitingFilterTest {
private static final String FULL_FETCH = "base/apps";
private static final String DELTA_FETCH = "base/apps/delta";
private static final String APP_FETCH = "base/apps/myAppId";
private static final String CUSTOM_CLIENT = "CustomClient";
private static final String PYTHON_CLIENT = "PythonClient";
@Mock
private HttpServletRequest request;
@Mock
private HttpServletResponse response;
@Mock
private FilterChain filterChain;
private RateLimitingFilter filter;
@Before
public void setUp() throws Exception {
RateLimitingFilter.reset();
ConfigurationManager.getConfigInstance().setProperty("eureka.rateLimiter.privilegedClients", PYTHON_CLIENT);
ConfigurationManager.getConfigInstance().setProperty("eureka.rateLimiter.enabled", true);
ConfigurationManager.getConfigInstance().setProperty("eureka.rateLimiter.burstSize", 2);
ConfigurationManager.getConfigInstance().setProperty("eureka.rateLimiter.registryFetchAverageRate", 1);
ConfigurationManager.getConfigInstance().setProperty("eureka.rateLimiter.fullFetchAverageRate", 1);
ConfigurationManager.getConfigInstance().setProperty("eureka.rateLimiter.throttleStandardClients", false);
ApplicationInfoManager applicationInfoManager = new ApplicationInfoManager(new MyDataCenterInstanceConfig());
DefaultEurekaServerConfig config = new DefaultEurekaServerConfig();
EurekaServerContext mockServer = mock(EurekaServerContext.class);
when(mockServer.getServerConfig()).thenReturn(config);
filter = new RateLimitingFilter(mockServer);
}
@Test
public void testPrivilegedClientAlwaysServed() throws Exception {
whenRequest(FULL_FETCH, PYTHON_CLIENT);
filter.doFilter(request, response, filterChain);
whenRequest(DELTA_FETCH, EurekaClientIdentity.DEFAULT_CLIENT_NAME);
filter.doFilter(request, response, filterChain);
whenRequest(APP_FETCH, EurekaServerIdentity.DEFAULT_SERVER_NAME);
filter.doFilter(request, response, filterChain);
verify(filterChain, times(3)).doFilter(request, response);
verify(response, never()).setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
}
@Test
public void testStandardClientsThrottlingEnforceable() throws Exception {
ConfigurationManager.getConfigInstance().setProperty("eureka.rateLimiter.throttleStandardClients", true);
// Custom clients will go up to the window limit
whenRequest(FULL_FETCH, EurekaClientIdentity.DEFAULT_CLIENT_NAME);
filter.doFilter(request, response, filterChain);
filter.doFilter(request, response, filterChain);
verify(filterChain, times(2)).doFilter(request, response);
// Now we hit the limit
long rateLimiterCounter = EurekaMonitors.RATE_LIMITED.getCount();
filter.doFilter(request, response, filterChain);
assertEquals("Expected rate limiter counter increase", rateLimiterCounter + 1, EurekaMonitors.RATE_LIMITED.getCount());
verify(response, times(1)).setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
}
@Test
public void testCustomClientShedding() throws Exception {
// Custom clients will go up to the window limit
whenRequest(FULL_FETCH, CUSTOM_CLIENT);
filter.doFilter(request, response, filterChain);
filter.doFilter(request, response, filterChain);
verify(filterChain, times(2)).doFilter(request, response);
// Now we hit the limit
long rateLimiterCounter = EurekaMonitors.RATE_LIMITED.getCount();
filter.doFilter(request, response, filterChain);
assertEquals("Expected rate limiter counter increase", rateLimiterCounter + 1, EurekaMonitors.RATE_LIMITED.getCount());
verify(response, times(1)).setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
}
@Test
public void testCustomClientThrottlingCandidatesCounter() throws Exception {
ConfigurationManager.getConfigInstance().setProperty("eureka.rateLimiter.enabled", false);
// Custom clients will go up to the window limit
whenRequest(FULL_FETCH, CUSTOM_CLIENT);
filter.doFilter(request, response, filterChain);
filter.doFilter(request, response, filterChain);
verify(filterChain, times(2)).doFilter(request, response);
// Now we hit the limit
long rateLimiterCounter = EurekaMonitors.RATE_LIMITED_CANDIDATES.getCount();
filter.doFilter(request, response, filterChain);
assertEquals("Expected rate limiter counter increase", rateLimiterCounter + 1, EurekaMonitors.RATE_LIMITED_CANDIDATES.getCount());
// We just test the counter
verify(response, times(0)).setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
}
private void whenRequest(String path, String client) {
when(request.getMethod()).thenReturn("GET");
when(request.getRequestURI()).thenReturn(path);
when(request.getHeader(AbstractEurekaIdentity.AUTH_NAME_HEADER_KEY)).thenReturn(client);
}
} | 8,103 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/GzipEncodingEnforcingFilterTest.java | /*
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.eureka;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
/**
* @author Kebe Liu
*/
@RunWith(MockitoJUnitRunner.class)
public class GzipEncodingEnforcingFilterTest {
private static final String ACCEPT_ENCODING_HEADER = "Accept-Encoding";
@Mock
private HttpServletRequest request;
private HttpServletRequest filteredRequest;
@Mock
private HttpServletResponse response;
@Mock
private FilterChain filterChain;
private GzipEncodingEnforcingFilter filter;
@Before
public void setUp() throws Exception {
filter = new GzipEncodingEnforcingFilter();
filterChain = new FilterChain() {
@Override
public void doFilter(ServletRequest req, ServletResponse response) throws IOException, ServletException {
filteredRequest = (HttpServletRequest) req;
}
};
}
@Test
public void testAlreadyGzip() throws Exception {
gzipRequest();
filter.doFilter(request, response, filterChain);
Enumeration values = filteredRequest.getHeaders(ACCEPT_ENCODING_HEADER);
assertEquals("Expected Accept-Encoding null", null, values);
}
@Test
public void testForceGzip() throws Exception {
noneGzipRequest();
filter.doFilter(request, response, filterChain);
String res = "";
Enumeration values = filteredRequest.getHeaders(ACCEPT_ENCODING_HEADER);
while (values.hasMoreElements()) {
res = res + values.nextElement() + "\n";
}
assertEquals("Expected Accept-Encoding gzip", "gzip\n", res);
}
@Test
public void testForceGzipOtherHeader() throws Exception {
noneGzipRequest();
when(request.getHeaders("Test")).thenReturn(new Enumeration() {
private int c = 0;
@Override
public boolean hasMoreElements() {
return c == 0;
}
@Override
public Object nextElement() {
c++;
return "ok";
}
});
filter.doFilter(request, response, filterChain);
String res = "";
Enumeration values = filteredRequest.getHeaders("Test");
while (values.hasMoreElements()) {
res = res + values.nextElement() + "\n";
}
assertEquals("Expected Test ok", "ok\n", res);
}
private void gzipRequest() {
when(request.getMethod()).thenReturn("GET");
when(request.getHeader(ACCEPT_ENCODING_HEADER)).thenReturn("gzip");
}
private void noneGzipRequest() {
when(request.getMethod()).thenReturn("GET");
when(request.getHeader(ACCEPT_ENCODING_HEADER)).thenReturn(null);
}
} | 8,104 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/DefaultEurekaServerConfigTest.java | package com.netflix.eureka;
import java.util.Map;
import java.util.Set;
import com.netflix.config.ConfigurationManager;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Nitesh Kant
*/
public class DefaultEurekaServerConfigTest {
@Test
public void testRemoteRegionUrlsWithName2Regions() throws Exception {
String region1 = "myregion1";
String region1url = "http://local:888/eee";
String region2 = "myregion2";
String region2url = "http://local:888/eee";
ConfigurationManager.getConfigInstance().setProperty("eureka.remoteRegionUrlsWithName", region1
+ ';' + region1url
+ ',' + region2
+ ';' + region2url);
DefaultEurekaServerConfig config = new DefaultEurekaServerConfig();
Map<String, String> remoteRegionUrlsWithName = config.getRemoteRegionUrlsWithName();
Assert.assertEquals("Unexpected remote region url count.", 2, remoteRegionUrlsWithName.size());
Assert.assertTrue("Remote region 1 not found.", remoteRegionUrlsWithName.containsKey(region1));
Assert.assertTrue("Remote region 2 not found.", remoteRegionUrlsWithName.containsKey(region2));
Assert.assertEquals("Unexpected remote region 1 url.", region1url, remoteRegionUrlsWithName.get(region1));
Assert.assertEquals("Unexpected remote region 2 url.", region2url, remoteRegionUrlsWithName.get(region2));
}
@Test
public void testRemoteRegionUrlsWithName1Region() throws Exception {
String region1 = "myregion1";
String region1url = "http://local:888/eee";
ConfigurationManager.getConfigInstance().setProperty("eureka.remoteRegionUrlsWithName", region1
+ ';' + region1url);
DefaultEurekaServerConfig config = new DefaultEurekaServerConfig();
Map<String, String> remoteRegionUrlsWithName = config.getRemoteRegionUrlsWithName();
Assert.assertEquals("Unexpected remote region url count.", 1, remoteRegionUrlsWithName.size());
Assert.assertTrue("Remote region 1 not found.", remoteRegionUrlsWithName.containsKey(region1));
Assert.assertEquals("Unexpected remote region 1 url.", region1url, remoteRegionUrlsWithName.get(region1));
}
@Test
public void testGetGlobalAppWhiteList() throws Exception {
String whitelistApp = "myapp";
ConfigurationManager.getConfigInstance().setProperty("eureka.remoteRegion.global.appWhiteList", whitelistApp);
DefaultEurekaServerConfig config = new DefaultEurekaServerConfig();
Set<String> globalList = config.getRemoteRegionAppWhitelist(null);
Assert.assertNotNull("Global whitelist is null.", globalList);
Assert.assertEquals("Global whitelist not as expected.", 1, globalList.size());
Assert.assertEquals("Global whitelist not as expected.", whitelistApp, globalList.iterator().next());
}
@Test
public void testGetRegionAppWhiteList() throws Exception {
String globalWhiteListApp = "myapp";
String regionWhiteListApp = "myapp";
ConfigurationManager.getConfigInstance().setProperty("eureka.remoteRegion.global.appWhiteList", globalWhiteListApp);
ConfigurationManager.getConfigInstance().setProperty("eureka.remoteRegion.region1.appWhiteList", regionWhiteListApp);
DefaultEurekaServerConfig config = new DefaultEurekaServerConfig();
Set<String> regionList = config.getRemoteRegionAppWhitelist(null);
Assert.assertNotNull("Region whitelist is null.", regionList);
Assert.assertEquals("Region whitelist not as expected.", 1, regionList.size());
Assert.assertEquals("Region whitelist not as expected.", regionWhiteListApp, regionList.iterator().next());
}
}
| 8,105 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/AbstractTester.java | package com.netflix.eureka;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.google.common.collect.Lists;
import com.netflix.appinfo.AmazonInfo;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.DataCenterInfo;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.LeaseInfo;
import com.netflix.appinfo.MyDataCenterInstanceConfig;
import com.netflix.config.ConfigurationManager;
import com.netflix.discovery.DefaultEurekaClientConfig;
import com.netflix.discovery.DiscoveryClient;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.discovery.shared.Application;
import com.netflix.discovery.shared.Pair;
import com.netflix.eureka.cluster.PeerEurekaNodes;
import com.netflix.eureka.mock.MockRemoteEurekaServer;
import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl;
import com.netflix.eureka.resources.DefaultServerCodecs;
import com.netflix.eureka.resources.ServerCodecs;
import com.netflix.eureka.test.async.executor.SingleEvent;
import org.junit.After;
import org.junit.Before;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
/**
* @author Nitesh Kant
*/
public class AbstractTester {
public static final String REMOTE_REGION_NAME = "us-east-1";
public static final String REMOTE_REGION_APP_NAME = "MYAPP";
public static final String REMOTE_REGION_INSTANCE_1_HOSTNAME = "blah";
public static final String REMOTE_REGION_INSTANCE_2_HOSTNAME = "blah2";
public static final String LOCAL_REGION_APP_NAME = "MYLOCAPP";
public static final String LOCAL_REGION_INSTANCE_1_HOSTNAME = "blahloc";
public static final String LOCAL_REGION_INSTANCE_2_HOSTNAME = "blahloc2";
public static final String REMOTE_ZONE = "us-east-1c";
protected final List<Pair<String, String>> registeredApps = new ArrayList<>();
protected final Map<String, Application> remoteRegionApps = new HashMap<>();
protected final Map<String, Application> remoteRegionAppsDelta = new HashMap<>();
protected MockRemoteEurekaServer mockRemoteEurekaServer;
protected EurekaServerConfig serverConfig;
protected EurekaServerContext serverContext;
protected EurekaClient client;
protected PeerAwareInstanceRegistryImpl registry;
@Before
public void setUp() throws Exception {
ConfigurationManager.getConfigInstance().clearProperty("eureka.remoteRegion.global.appWhiteList");
ConfigurationManager.getConfigInstance().setProperty("eureka.responseCacheAutoExpirationInSeconds", "10");
ConfigurationManager.getConfigInstance().clearProperty("eureka.remoteRegion." + REMOTE_REGION_NAME + ".appWhiteList");
ConfigurationManager.getConfigInstance().setProperty("eureka.deltaRetentionTimerIntervalInMs", "600000");
ConfigurationManager.getConfigInstance().setProperty("eureka.remoteRegion.registryFetchIntervalInSeconds", "5");
ConfigurationManager.getConfigInstance().setProperty("eureka.renewalThresholdUpdateIntervalMs", "5000");
ConfigurationManager.getConfigInstance().setProperty("eureka.evictionIntervalTimerInMs", "10000");
populateRemoteRegistryAtStartup();
mockRemoteEurekaServer = newMockRemoteServer();
mockRemoteEurekaServer.start();
ConfigurationManager.getConfigInstance().setProperty("eureka.remoteRegionUrlsWithName",
REMOTE_REGION_NAME + ";http://localhost:" + mockRemoteEurekaServer.getPort() + MockRemoteEurekaServer.EUREKA_API_BASE_PATH);
serverConfig = spy(new DefaultEurekaServerConfig());
InstanceInfo.Builder builder = InstanceInfo.Builder.newBuilder();
builder.setIPAddr("10.10.101.00");
builder.setHostName("Hosttt");
builder.setAppName("EurekaTestApp-" + UUID.randomUUID());
builder.setLeaseInfo(LeaseInfo.Builder.newBuilder().build());
builder.setDataCenterInfo(getDataCenterInfo());
ConfigurationManager.getConfigInstance().setProperty("eureka.serviceUrl.default",
"http://localhost:" + mockRemoteEurekaServer.getPort() + MockRemoteEurekaServer.EUREKA_API_BASE_PATH);
DefaultEurekaClientConfig clientConfig = new DefaultEurekaClientConfig();
// setup config in advance, used in initialize converter
ApplicationInfoManager applicationInfoManager = new ApplicationInfoManager(new MyDataCenterInstanceConfig(), builder.build());
client = new DiscoveryClient(applicationInfoManager, clientConfig);
ServerCodecs serverCodecs = new DefaultServerCodecs(serverConfig);
registry = makePeerAwareInstanceRegistry(serverConfig, clientConfig, serverCodecs, client);
serverContext = new DefaultEurekaServerContext(
serverConfig,
serverCodecs,
registry,
mock(PeerEurekaNodes.class),
applicationInfoManager
);
serverContext.initialize();
registry.openForTraffic(applicationInfoManager, 1);
}
protected DataCenterInfo getDataCenterInfo() {
return new DataCenterInfo() {
@Override
public Name getName() {
return Name.MyOwn;
}
};
}
protected PeerAwareInstanceRegistryImpl makePeerAwareInstanceRegistry(EurekaServerConfig serverConfig,
EurekaClientConfig clientConfig,
ServerCodecs serverCodecs,
EurekaClient eurekaClient) {
return new TestPeerAwareInstanceRegistry(serverConfig, clientConfig, serverCodecs, eurekaClient);
}
protected MockRemoteEurekaServer newMockRemoteServer() {
return new MockRemoteEurekaServer(0 /* use ephemeral */, remoteRegionApps, remoteRegionAppsDelta);
}
@After
public void tearDown() throws Exception {
for (Pair<String, String> registeredApp : registeredApps) {
System.out.println("Canceling application: " + registeredApp.first() + " from local registry.");
registry.cancel(registeredApp.first(), registeredApp.second(), false);
}
serverContext.shutdown();
mockRemoteEurekaServer.stop();
remoteRegionApps.clear();
remoteRegionAppsDelta.clear();
ConfigurationManager.getConfigInstance().clearProperty("eureka.remoteRegionUrls");
ConfigurationManager.getConfigInstance().clearProperty("eureka.deltaRetentionTimerIntervalInMs");
}
private static Application createRemoteApps() {
Application myapp = new Application(REMOTE_REGION_APP_NAME);
InstanceInfo instanceInfo = createRemoteInstance(REMOTE_REGION_INSTANCE_1_HOSTNAME);
//instanceInfo.setActionType(InstanceInfo.ActionType.MODIFIED);
myapp.addInstance(instanceInfo);
return myapp;
}
private static Application createRemoteAppsDelta() {
Application myapp = new Application(REMOTE_REGION_APP_NAME);
InstanceInfo instanceInfo = createRemoteInstance(REMOTE_REGION_INSTANCE_1_HOSTNAME);
myapp.addInstance(instanceInfo);
return myapp;
}
protected static InstanceInfo createRemoteInstance(String instanceHostName) {
InstanceInfo.Builder instanceBuilder = InstanceInfo.Builder.newBuilder();
instanceBuilder.setAppName(REMOTE_REGION_APP_NAME);
instanceBuilder.setHostName(instanceHostName);
instanceBuilder.setIPAddr("10.10.101.1");
instanceBuilder.setDataCenterInfo(getAmazonInfo(REMOTE_ZONE, instanceHostName));
instanceBuilder.setLeaseInfo(LeaseInfo.Builder.newBuilder().build());
return instanceBuilder.build();
}
protected static InstanceInfo createLocalInstance(String hostname) {
return createLocalInstanceWithStatus(hostname, InstanceInfo.InstanceStatus.UP);
}
protected static InstanceInfo createLocalStartingInstance(String hostname) {
return createLocalInstanceWithStatus(hostname, InstanceInfo.InstanceStatus.STARTING);
}
protected static InstanceInfo createLocalOutOfServiceInstance(String hostname) {
return createLocalInstanceWithStatus(hostname, InstanceInfo.InstanceStatus.OUT_OF_SERVICE);
}
protected static InstanceInfo createLocalInstanceWithIdAndStatus(String hostname, String id, InstanceInfo.InstanceStatus status) {
InstanceInfo.Builder instanceBuilder = InstanceInfo.Builder.newBuilder();
instanceBuilder.setInstanceId(id);
instanceBuilder.setAppName(LOCAL_REGION_APP_NAME);
instanceBuilder.setHostName(hostname);
instanceBuilder.setIPAddr("10.10.101.1");
instanceBuilder.setDataCenterInfo(getAmazonInfo(null, hostname));
instanceBuilder.setLeaseInfo(LeaseInfo.Builder.newBuilder().build());
instanceBuilder.setStatus(status);
return instanceBuilder.build();
}
private static InstanceInfo createLocalInstanceWithStatus(String hostname, InstanceInfo.InstanceStatus status) {
InstanceInfo.Builder instanceBuilder = InstanceInfo.Builder.newBuilder();
instanceBuilder.setInstanceId("foo");
instanceBuilder.setAppName(LOCAL_REGION_APP_NAME);
instanceBuilder.setHostName(hostname);
instanceBuilder.setIPAddr("10.10.101.1");
instanceBuilder.setDataCenterInfo(getAmazonInfo(null, hostname));
instanceBuilder.setLeaseInfo(LeaseInfo.Builder.newBuilder().build());
instanceBuilder.setStatus(status);
return instanceBuilder.build();
}
private static AmazonInfo getAmazonInfo(@Nullable String availabilityZone, String instanceHostName) {
AmazonInfo.Builder azBuilder = AmazonInfo.Builder.newBuilder();
azBuilder.addMetadata(AmazonInfo.MetaDataKey.availabilityZone, null == availabilityZone ? "us-east-1a" : availabilityZone);
azBuilder.addMetadata(AmazonInfo.MetaDataKey.instanceId, instanceHostName);
azBuilder.addMetadata(AmazonInfo.MetaDataKey.amiId, "XXX");
azBuilder.addMetadata(AmazonInfo.MetaDataKey.instanceType, "XXX");
azBuilder.addMetadata(AmazonInfo.MetaDataKey.localIpv4, "XXX");
azBuilder.addMetadata(AmazonInfo.MetaDataKey.publicIpv4, "XXX");
azBuilder.addMetadata(AmazonInfo.MetaDataKey.publicHostname, instanceHostName);
return azBuilder.build();
}
private void populateRemoteRegistryAtStartup() {
Application myapp = createRemoteApps();
Application myappDelta = createRemoteAppsDelta();
remoteRegionApps.put(REMOTE_REGION_APP_NAME, myapp);
remoteRegionAppsDelta.put(REMOTE_REGION_APP_NAME, myappDelta);
}
private static class TestPeerAwareInstanceRegistry extends PeerAwareInstanceRegistryImpl {
public TestPeerAwareInstanceRegistry(EurekaServerConfig serverConfig,
EurekaClientConfig clientConfig,
ServerCodecs serverCodecs,
EurekaClient eurekaClient) {
super(serverConfig, clientConfig, serverCodecs, eurekaClient);
}
@Override
public InstanceInfo getNextServerFromEureka(String virtualHostname, boolean secure) {
return null;
}
}
protected void verifyLocalInstanceStatus(String id, InstanceInfo.InstanceStatus status) {
InstanceInfo instanceInfo = registry.getApplication(LOCAL_REGION_APP_NAME).getByInstanceId(id);
assertThat("InstanceInfo with id " + id + " not found", instanceInfo, is(notNullValue()));
assertThat("Invalid InstanceInfo state", instanceInfo.getStatus(), is(equalTo(status)));
}
protected void registerInstanceLocally(InstanceInfo remoteInstance) {
registry.register(remoteInstance, 10000000, false);
registeredApps.add(new Pair<String, String>(LOCAL_REGION_APP_NAME, remoteInstance.getId()));
}
protected void registerInstanceLocallyWithLeaseDurationInSecs(InstanceInfo remoteInstance, int leaseDurationInSecs) {
registry.register(remoteInstance, leaseDurationInSecs, false);
registeredApps.add(new Pair<String, String>(LOCAL_REGION_APP_NAME, remoteInstance.getId()));
}
/**
* Send renewal request to Eureka server to renew lease for 45 instances.
*
* @return action.
*/
protected SingleEvent.Action renewPartOfTheWholeInstancesAction() {
return new SingleEvent.Action() {
@Override
public void execute() {
for (int j = 0; j < 45; j++) {
registry.renew(LOCAL_REGION_APP_NAME,
LOCAL_REGION_INSTANCE_1_HOSTNAME + j, false);
}
}
};
}
/**
* Build one single event.
*
* @param intervalTimeInSecs the interval time from previous event.
* @param action action to take.
* @return single event.
*/
protected SingleEvent buildEvent(int intervalTimeInSecs, SingleEvent.Action action) {
return SingleEvent.Builder.newBuilder()
.withIntervalTimeInMs(intervalTimeInSecs * 1000)
.withAction(action).build();
}
/**
* Build multiple {@link SingleEvent}.
*
* @param intervalTimeInSecs the interval time between those events.
* @param eventCount total event count.
* @param action action to take for every event.
* @return list consisting of multiple single events.
*/
protected List<SingleEvent> buildEvents(int intervalTimeInSecs, int eventCount, SingleEvent.Action action) {
List<SingleEvent> result = Lists.newArrayListWithCapacity(eventCount);
for (int i = 0; i < eventCount; i++) {
result.add(SingleEvent.Builder.newBuilder()
.withIntervalTimeInMs(intervalTimeInSecs * 1000)
.withAction(action).build());
}
return result;
}
}
| 8,106 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/cluster/PeerEurekaNodeTest.java | package com.netflix.eureka.cluster;
import java.util.List;
import java.util.concurrent.TimeUnit;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import com.netflix.discovery.shared.transport.ClusterSampleData;
import com.netflix.eureka.EurekaServerConfig;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl.Action;
import com.netflix.eureka.cluster.TestableHttpReplicationClient.HandledRequest;
import com.netflix.eureka.cluster.TestableHttpReplicationClient.RequestType;
import com.netflix.eureka.cluster.protocol.ReplicationInstance;
import com.netflix.eureka.cluster.protocol.ReplicationList;
import com.netflix.eureka.resources.ASGResource.ASGStatus;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
/**
* @author Tomasz Bak
*/
public class PeerEurekaNodeTest {
private static final int BATCH_SIZE = 10;
private static final long MAX_BATCHING_DELAY_MS = 10;
private final PeerAwareInstanceRegistry registry = mock(PeerAwareInstanceRegistry.class);
private final TestableHttpReplicationClient httpReplicationClient = new TestableHttpReplicationClient();
private final InstanceInfo instanceInfo = ClusterSampleData.newInstanceInfo(1);
private PeerEurekaNode peerEurekaNode;
@Before
public void setUp() throws Exception {
httpReplicationClient.withNetworkStatusCode(200);
httpReplicationClient.withBatchReply(200);
}
@After
public void tearDown() throws Exception {
if (peerEurekaNode != null) {
peerEurekaNode.shutDown();
}
}
@Test
public void testRegistrationBatchReplication() throws Exception {
createPeerEurekaNode().register(instanceInfo);
ReplicationInstance replicationInstance = expectSingleBatchRequest();
assertThat(replicationInstance.getAction(), is(equalTo(Action.Register)));
}
@Test
public void testCancelBatchReplication() throws Exception {
createPeerEurekaNode().cancel(instanceInfo.getAppName(), instanceInfo.getId());
ReplicationInstance replicationInstance = expectSingleBatchRequest();
assertThat(replicationInstance.getAction(), is(equalTo(Action.Cancel)));
}
@Test
public void testHeartbeatBatchReplication() throws Throwable {
createPeerEurekaNode().heartbeat(instanceInfo.getAppName(), instanceInfo.getId(), instanceInfo, null, false);
ReplicationInstance replicationInstance = expectSingleBatchRequest();
assertThat(replicationInstance.getAction(), is(equalTo(Action.Heartbeat)));
}
@Test
public void testHeartbeatReplicationFailure() throws Throwable {
httpReplicationClient.withNetworkStatusCode(200, 200);
httpReplicationClient.withBatchReply(404); // Not found, to trigger registration
createPeerEurekaNode().heartbeat(instanceInfo.getAppName(), instanceInfo.getId(), instanceInfo, null, false);
// Heartbeat replied with an error
ReplicationInstance replicationInstance = expectSingleBatchRequest();
assertThat(replicationInstance.getAction(), is(equalTo(Action.Heartbeat)));
// Second, registration task is scheduled
replicationInstance = expectSingleBatchRequest();
assertThat(replicationInstance.getAction(), is(equalTo(Action.Register)));
}
@Test
public void testHeartbeatWithInstanceInfoFromPeer() throws Throwable {
InstanceInfo instanceInfoFromPeer = ClusterSampleData.newInstanceInfo(2);
httpReplicationClient.withNetworkStatusCode(200);
httpReplicationClient.withBatchReply(400);
httpReplicationClient.withInstanceInfo(instanceInfoFromPeer);
// InstanceInfo in response from peer will trigger local registry call
createPeerEurekaNode().heartbeat(instanceInfo.getAppName(), instanceInfo.getId(), instanceInfo, null, false);
expectRequestType(RequestType.Batch);
// Check that registry has instanceInfo from peer
verify(registry, timeout(1000).times(1)).register(instanceInfoFromPeer, true);
}
@Test
public void testAsgStatusUpdate() throws Throwable {
createPeerEurekaNode().statusUpdate(instanceInfo.getASGName(), ASGStatus.DISABLED);
Object newAsgStatus = expectRequestType(RequestType.AsgStatusUpdate);
assertThat(newAsgStatus, is(equalTo((Object) ASGStatus.DISABLED)));
}
@Test
public void testStatusUpdateBatchReplication() throws Throwable {
createPeerEurekaNode().statusUpdate(instanceInfo.getAppName(), instanceInfo.getId(), InstanceStatus.DOWN, instanceInfo);
ReplicationInstance replicationInstance = expectSingleBatchRequest();
assertThat(replicationInstance.getAction(), is(equalTo(Action.StatusUpdate)));
}
@Test
public void testDeleteStatusOverrideBatchReplication() throws Throwable {
createPeerEurekaNode().deleteStatusOverride(instanceInfo.getAppName(), instanceInfo.getId(), instanceInfo);
ReplicationInstance replicationInstance = expectSingleBatchRequest();
assertThat(replicationInstance.getAction(), is(equalTo(Action.DeleteStatusOverride)));
}
private PeerEurekaNode createPeerEurekaNode() {
EurekaServerConfig config = ClusterSampleData.newEurekaServerConfig();
peerEurekaNode = new PeerEurekaNode(
registry, "test", "http://test.host.com",
httpReplicationClient,
config,
BATCH_SIZE,
MAX_BATCHING_DELAY_MS,
ClusterSampleData.RETRY_SLEEP_TIME_MS,
ClusterSampleData.SERVER_UNAVAILABLE_SLEEP_TIME_MS
);
return peerEurekaNode;
}
private Object expectRequestType(RequestType requestType) throws InterruptedException {
HandledRequest handledRequest = httpReplicationClient.nextHandledRequest(60, TimeUnit.SECONDS);
assertThat(handledRequest, is(notNullValue()));
assertThat(handledRequest.getRequestType(), is(equalTo(requestType)));
return handledRequest.getData();
}
private ReplicationInstance expectSingleBatchRequest() throws InterruptedException {
HandledRequest handledRequest = httpReplicationClient.nextHandledRequest(30, TimeUnit.SECONDS);
assertThat(handledRequest, is(notNullValue()));
assertThat(handledRequest.getRequestType(), is(equalTo(RequestType.Batch)));
Object data = handledRequest.getData();
assertThat(data, is(instanceOf(ReplicationList.class)));
List<ReplicationInstance> replications = ((ReplicationList) data).getReplicationList();
assertThat(replications.size(), is(equalTo(1)));
return replications.get(0);
}
} | 8,107 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/cluster/ReplicationTaskProcessorTest.java | package com.netflix.eureka.cluster;
import java.util.Collections;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.util.InstanceInfoGenerator;
import com.netflix.eureka.cluster.TestableInstanceReplicationTask.ProcessingState;
import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl.Action;
import com.netflix.eureka.util.batcher.TaskProcessor.ProcessingResult;
import org.junit.Before;
import org.junit.Test;
import static com.netflix.eureka.cluster.TestableInstanceReplicationTask.aReplicationTask;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
/**
* @author Tomasz Bak
*/
public class ReplicationTaskProcessorTest {
private final TestableHttpReplicationClient replicationClient = new TestableHttpReplicationClient();
private ReplicationTaskProcessor replicationTaskProcessor;
@Before
public void setUp() throws Exception {
replicationTaskProcessor = new ReplicationTaskProcessor("peerId#test", replicationClient);
}
@Test
public void testNonBatchableTaskExecution() throws Exception {
TestableInstanceReplicationTask task = aReplicationTask().withAction(Action.Heartbeat).withReplyStatusCode(200).build();
ProcessingResult status = replicationTaskProcessor.process(task);
assertThat(status, is(ProcessingResult.Success));
}
@Test
public void testNonBatchableTaskCongestionFailureHandling() throws Exception {
TestableInstanceReplicationTask task = aReplicationTask().withAction(Action.Heartbeat).withReplyStatusCode(503).build();
ProcessingResult status = replicationTaskProcessor.process(task);
assertThat(status, is(ProcessingResult.Congestion));
assertThat(task.getProcessingState(), is(ProcessingState.Pending));
}
@Test
public void testNonBatchableTaskNetworkFailureHandling() throws Exception {
TestableInstanceReplicationTask task = aReplicationTask().withAction(Action.Heartbeat).withNetworkFailures(1).build();
ProcessingResult status = replicationTaskProcessor.process(task);
assertThat(status, is(ProcessingResult.TransientError));
assertThat(task.getProcessingState(), is(ProcessingState.Pending));
}
@Test
public void testNonBatchableTaskPermanentFailureHandling() throws Exception {
TestableInstanceReplicationTask task = aReplicationTask().withAction(Action.Heartbeat).withReplyStatusCode(406).build();
ProcessingResult status = replicationTaskProcessor.process(task);
assertThat(status, is(ProcessingResult.PermanentError));
assertThat(task.getProcessingState(), is(ProcessingState.Failed));
}
@Test
public void testBatchableTaskListExecution() throws Exception {
TestableInstanceReplicationTask task = aReplicationTask().build();
replicationClient.withBatchReply(200);
replicationClient.withNetworkStatusCode(200);
ProcessingResult status = replicationTaskProcessor.process(Collections.<ReplicationTask>singletonList(task));
assertThat(status, is(ProcessingResult.Success));
assertThat(task.getProcessingState(), is(ProcessingState.Finished));
}
@Test
public void testBatchableTaskCongestionFailureHandling() throws Exception {
TestableInstanceReplicationTask task = aReplicationTask().build();
replicationClient.withNetworkStatusCode(503);
ProcessingResult status = replicationTaskProcessor.process(Collections.<ReplicationTask>singletonList(task));
assertThat(status, is(ProcessingResult.Congestion));
assertThat(task.getProcessingState(), is(ProcessingState.Pending));
}
@Test
public void testBatchableTaskNetworkReadTimeOutHandling() throws Exception {
TestableInstanceReplicationTask task = aReplicationTask().build();
replicationClient.withReadtimeOut(1);
ProcessingResult status = replicationTaskProcessor.process(Collections.<ReplicationTask>singletonList(task));
assertThat(status, is(ProcessingResult.Congestion));
assertThat(task.getProcessingState(), is(ProcessingState.Pending));
}
@Test
public void testBatchableTaskNetworkFailureHandling() throws Exception {
TestableInstanceReplicationTask task = aReplicationTask().build();
replicationClient.withNetworkError(1);
ProcessingResult status = replicationTaskProcessor.process(Collections.<ReplicationTask>singletonList(task));
assertThat(status, is(ProcessingResult.TransientError));
assertThat(task.getProcessingState(), is(ProcessingState.Pending));
}
@Test
public void testBatchableTaskPermanentFailureHandling() throws Exception {
TestableInstanceReplicationTask task = aReplicationTask().build();
InstanceInfo instanceInfoFromPeer = InstanceInfoGenerator.takeOne();
replicationClient.withNetworkStatusCode(200);
replicationClient.withBatchReply(400);
replicationClient.withInstanceInfo(instanceInfoFromPeer);
ProcessingResult status = replicationTaskProcessor.process(Collections.<ReplicationTask>singletonList(task));
assertThat(status, is(ProcessingResult.Success));
assertThat(task.getProcessingState(), is(ProcessingState.Failed));
}
} | 8,108 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/cluster/JerseyReplicationClientTest.java | package com.netflix.eureka.cluster;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import com.netflix.discovery.converters.EurekaJacksonCodec;
import com.netflix.discovery.shared.transport.ClusterSampleData;
import com.netflix.discovery.shared.transport.EurekaHttpResponse;
import com.netflix.eureka.DefaultEurekaServerConfig;
import com.netflix.eureka.EurekaServerConfig;
import com.netflix.eureka.resources.ASGResource.ASGStatus;
import com.netflix.eureka.resources.DefaultServerCodecs;
import com.netflix.eureka.resources.ServerCodecs;
import com.netflix.eureka.transport.JerseyReplicationClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockserver.client.server.MockServerClient;
import org.mockserver.junit.MockServerRule;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockserver.model.Header.header;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;
/**
* Ideally we would test client/server REST layer together as an integration test, where server side has mocked
* service layer. Right now server side REST has to much logic, so this test would be equal to testing everything.
* Here we test only client side REST communication.
*
* @author Tomasz Bak
*/
public class JerseyReplicationClientTest {
@Rule
public MockServerRule serverMockRule = new MockServerRule(this);
private MockServerClient serverMockClient;
private JerseyReplicationClient replicationClient;
private final EurekaServerConfig config = new DefaultEurekaServerConfig();
private final ServerCodecs serverCodecs = new DefaultServerCodecs(config);
private final InstanceInfo instanceInfo = ClusterSampleData.newInstanceInfo(1);
@Before
public void setUp() throws Exception {
replicationClient = JerseyReplicationClient.createReplicationClient(
config, serverCodecs, "http://localhost:" + serverMockRule.getHttpPort() + "/eureka/v2"
);
}
@After
public void tearDown() {
if (serverMockClient != null) {
serverMockClient.reset();
}
}
@Test
public void testRegistrationReplication() throws Exception {
serverMockClient.when(
request()
.withMethod("POST")
.withHeader(header(PeerEurekaNode.HEADER_REPLICATION, "true"))
.withPath("/eureka/v2/apps/" + instanceInfo.getAppName())
).respond(
response().withStatusCode(200)
);
EurekaHttpResponse<Void> response = replicationClient.register(instanceInfo);
assertThat(response.getStatusCode(), is(equalTo(200)));
}
@Test
public void testCancelReplication() throws Exception {
serverMockClient.when(
request()
.withMethod("DELETE")
.withHeader(header(PeerEurekaNode.HEADER_REPLICATION, "true"))
.withPath("/eureka/v2/apps/" + instanceInfo.getAppName() + '/' + instanceInfo.getId())
).respond(
response().withStatusCode(204)
);
EurekaHttpResponse<Void> response = replicationClient.cancel(instanceInfo.getAppName(), instanceInfo.getId());
assertThat(response.getStatusCode(), is(equalTo(204)));
}
@Test
public void testHeartbeatReplicationWithNoResponseBody() throws Exception {
serverMockClient.when(
request()
.withMethod("PUT")
.withHeader(header(PeerEurekaNode.HEADER_REPLICATION, "true"))
.withPath("/eureka/v2/apps/" + instanceInfo.getAppName() + '/' + instanceInfo.getId())
).respond(
response().withStatusCode(200)
);
EurekaHttpResponse<InstanceInfo> response = replicationClient.sendHeartBeat(instanceInfo.getAppName(), instanceInfo.getId(), instanceInfo, InstanceStatus.DOWN);
assertThat(response.getStatusCode(), is(equalTo(200)));
assertThat(response.getEntity(), is(nullValue()));
}
@Test
public void testHeartbeatReplicationWithResponseBody() throws Exception {
InstanceInfo remoteInfo = new InstanceInfo(this.instanceInfo);
remoteInfo.setStatus(InstanceStatus.DOWN);
byte[] responseBody = toGzippedJson(remoteInfo);
serverMockClient.when(
request()
.withMethod("PUT")
.withHeader(header(PeerEurekaNode.HEADER_REPLICATION, "true"))
.withPath("/eureka/v2/apps/" + this.instanceInfo.getAppName() + '/' + this.instanceInfo.getId())
).respond(
response()
.withStatusCode(Status.CONFLICT.getStatusCode())
.withHeader(header("Content-Type", MediaType.APPLICATION_JSON))
.withHeader(header("Content-Encoding", "gzip"))
.withBody(responseBody)
);
EurekaHttpResponse<InstanceInfo> response = replicationClient.sendHeartBeat(this.instanceInfo.getAppName(), this.instanceInfo.getId(), this.instanceInfo, null);
assertThat(response.getStatusCode(), is(equalTo(Status.CONFLICT.getStatusCode())));
assertThat(response.getEntity(), is(notNullValue()));
}
@Test
public void testAsgStatusUpdateReplication() throws Exception {
serverMockClient.when(
request()
.withMethod("PUT")
.withHeader(header(PeerEurekaNode.HEADER_REPLICATION, "true"))
.withPath("/eureka/v2/asg/" + instanceInfo.getASGName() + "/status")
).respond(
response().withStatusCode(200)
);
EurekaHttpResponse<Void> response = replicationClient.statusUpdate(instanceInfo.getASGName(), ASGStatus.ENABLED);
assertThat(response.getStatusCode(), is(equalTo(200)));
}
@Test
public void testStatusUpdateReplication() throws Exception {
serverMockClient.when(
request()
.withMethod("PUT")
.withHeader(header(PeerEurekaNode.HEADER_REPLICATION, "true"))
.withPath("/eureka/v2/apps/" + instanceInfo.getAppName() + '/' + instanceInfo.getId() + "/status")
).respond(
response().withStatusCode(200)
);
EurekaHttpResponse<Void> response = replicationClient.statusUpdate(instanceInfo.getAppName(), instanceInfo.getId(), InstanceStatus.DOWN, instanceInfo);
assertThat(response.getStatusCode(), is(equalTo(200)));
}
@Test
public void testDeleteStatusOverrideReplication() throws Exception {
serverMockClient.when(
request()
.withMethod("DELETE")
.withHeader(header(PeerEurekaNode.HEADER_REPLICATION, "true"))
.withPath("/eureka/v2/apps/" + instanceInfo.getAppName() + '/' + instanceInfo.getId() + "/status")
).respond(
response().withStatusCode(204)
);
EurekaHttpResponse<Void> response = replicationClient.deleteStatusOverride(instanceInfo.getAppName(), instanceInfo.getId(), instanceInfo);
assertThat(response.getStatusCode(), is(equalTo(204)));
}
private static byte[] toGzippedJson(InstanceInfo remoteInfo) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
GZIPOutputStream gos = new GZIPOutputStream(bos);
EurekaJacksonCodec.getInstance().writeTo(remoteInfo, gos);
gos.flush();
return bos.toByteArray();
}
} | 8,109 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/cluster/TestableHttpReplicationClient.java | package com.netflix.eureka.cluster;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import com.netflix.discovery.shared.Application;
import com.netflix.discovery.shared.Applications;
import com.netflix.discovery.shared.transport.EurekaHttpResponse;
import com.netflix.eureka.cluster.protocol.ReplicationInstanceResponse;
import com.netflix.eureka.cluster.protocol.ReplicationList;
import com.netflix.eureka.cluster.protocol.ReplicationListResponse;
import com.netflix.eureka.resources.ASGResource.ASGStatus;
import static com.netflix.discovery.shared.transport.EurekaHttpResponse.anEurekaHttpResponse;
/**
* This stub implementation is primarily useful for batch updates, and complex failure scenarios.
* Using mock would results in too convoluted code.
*
* @author Tomasz Bak
*/
public class TestableHttpReplicationClient implements HttpReplicationClient {
private int[] networkStatusCodes;
private InstanceInfo instanceInfoFromPeer;
private int networkFailuresRepeatCount;
private int readtimeOutRepeatCount;
private int batchStatusCode;
private final AtomicInteger callCounter = new AtomicInteger();
private final AtomicInteger networkFailureCounter = new AtomicInteger();
private final AtomicInteger readTimeOutCounter = new AtomicInteger();
private long processingDelayMs;
private final BlockingQueue<HandledRequest> handledRequests = new LinkedBlockingQueue<>();
public void withNetworkStatusCode(int... networkStatusCodes) {
this.networkStatusCodes = networkStatusCodes;
}
public void withInstanceInfo(InstanceInfo instanceInfoFromPeer) {
this.instanceInfoFromPeer = instanceInfoFromPeer;
}
public void withBatchReply(int batchStatusCode) {
this.batchStatusCode = batchStatusCode;
}
public void withNetworkError(int networkFailuresRepeatCount) {
this.networkFailuresRepeatCount = networkFailuresRepeatCount;
}
public void withReadtimeOut(int readtimeOutRepeatCount) {
this.readtimeOutRepeatCount = readtimeOutRepeatCount;
}
public void withProcessingDelay(long processingDelay, TimeUnit timeUnit) {
this.processingDelayMs = timeUnit.toMillis(processingDelay);
}
public HandledRequest nextHandledRequest(long timeout, TimeUnit timeUnit) throws InterruptedException {
return handledRequests.poll(timeout, timeUnit);
}
@Override
public EurekaHttpResponse<Void> register(InstanceInfo info) {
handledRequests.add(new HandledRequest(RequestType.Register, info));
return EurekaHttpResponse.status(networkStatusCodes[callCounter.getAndIncrement()]);
}
@Override
public EurekaHttpResponse<Void> cancel(String appName, String id) {
handledRequests.add(new HandledRequest(RequestType.Cancel, id));
return EurekaHttpResponse.status(networkStatusCodes[callCounter.getAndIncrement()]);
}
@Override
public EurekaHttpResponse<InstanceInfo> sendHeartBeat(String appName, String id, InstanceInfo info, InstanceStatus overriddenStatus) {
handledRequests.add(new HandledRequest(RequestType.Heartbeat, instanceInfoFromPeer));
int statusCode = networkStatusCodes[callCounter.getAndIncrement()];
return anEurekaHttpResponse(statusCode, instanceInfoFromPeer).type(MediaType.APPLICATION_JSON_TYPE).build();
}
@Override
public EurekaHttpResponse<Void> statusUpdate(String asgName, ASGStatus newStatus) {
handledRequests.add(new HandledRequest(RequestType.AsgStatusUpdate, newStatus));
return EurekaHttpResponse.status(networkStatusCodes[callCounter.getAndIncrement()]);
}
@Override
public EurekaHttpResponse<Void> statusUpdate(String appName, String id, InstanceStatus newStatus, InstanceInfo info) {
handledRequests.add(new HandledRequest(RequestType.StatusUpdate, newStatus));
return EurekaHttpResponse.status(networkStatusCodes[callCounter.getAndIncrement()]);
}
@Override
public EurekaHttpResponse<Void> deleteStatusOverride(String appName, String id, InstanceInfo info) {
handledRequests.add(new HandledRequest(RequestType.DeleteStatusOverride, null));
return EurekaHttpResponse.status(networkStatusCodes[callCounter.getAndIncrement()]);
}
@Override
public EurekaHttpResponse<Applications> getApplications(String... regions) {
throw new IllegalStateException("method not supported");
}
@Override
public EurekaHttpResponse<Applications> getDelta(String... regions) {
throw new IllegalStateException("method not supported");
}
@Override
public EurekaHttpResponse<Applications> getVip(String vipAddress, String... regions) {
throw new IllegalStateException("method not supported");
}
@Override
public EurekaHttpResponse<Applications> getSecureVip(String secureVipAddress, String... regions) {
throw new IllegalStateException("method not supported");
}
@Override
public EurekaHttpResponse<Application> getApplication(String appName) {
throw new IllegalStateException("method not supported");
}
@Override
public EurekaHttpResponse<InstanceInfo> getInstance(String id) {
throw new IllegalStateException("method not supported");
}
@Override
public EurekaHttpResponse<InstanceInfo> getInstance(String appName, String id) {
throw new IllegalStateException("method not supported");
}
@Override
public EurekaHttpResponse<ReplicationListResponse> submitBatchUpdates(ReplicationList replicationList) {
if (readTimeOutCounter.get() < readtimeOutRepeatCount) {
readTimeOutCounter.incrementAndGet();
throw new RuntimeException(new SocketTimeoutException("Read timed out"));
}
if (networkFailureCounter.get() < networkFailuresRepeatCount) {
networkFailureCounter.incrementAndGet();
throw new RuntimeException(new IOException("simulated network failure"));
}
if (processingDelayMs > 0) {
try {
Thread.sleep(processingDelayMs);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
List<ReplicationInstanceResponse> responseList = new ArrayList<>();
responseList.add(new ReplicationInstanceResponse(batchStatusCode, instanceInfoFromPeer));
ReplicationListResponse replicationListResponse = new ReplicationListResponse(responseList);
handledRequests.add(new HandledRequest(RequestType.Batch, replicationList));
int statusCode = networkStatusCodes[callCounter.getAndIncrement()];
return anEurekaHttpResponse(statusCode, replicationListResponse).type(MediaType.APPLICATION_JSON_TYPE).build();
}
@Override
public void shutdown() {
}
public enum RequestType {Heartbeat, Register, Cancel, StatusUpdate, DeleteStatusOverride, AsgStatusUpdate, Batch}
public static class HandledRequest {
private final RequestType requestType;
private final Object data;
public HandledRequest(RequestType requestType, Object data) {
this.requestType = requestType;
this.data = data;
}
public RequestType getRequestType() {
return requestType;
}
public Object getData() {
return data;
}
}
}
| 8,110 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/cluster/PeerEurekaNodesTest.java | package com.netflix.eureka.cluster;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.discovery.DefaultEurekaClientConfig;
import com.netflix.discovery.shared.transport.ClusterSampleData;
import com.netflix.eureka.EurekaServerConfig;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
import com.netflix.eureka.resources.DefaultServerCodecs;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Tomasz Bak
*/
public class PeerEurekaNodesTest {
private static final String PEER_EUREKA_URL_A = "http://a.eureka.test";
private static final String PEER_EUREKA_URL_B = "http://b.eureka.test";
private static final String PEER_EUREKA_URL_C = "http://c.eureka.test";
private final PeerAwareInstanceRegistry registry = mock(PeerAwareInstanceRegistry.class);
private final TestablePeerEurekaNodes peerEurekaNodes = new TestablePeerEurekaNodes(registry, ClusterSampleData.newEurekaServerConfig());
@Test
public void testInitialStartupShutdown() throws Exception {
peerEurekaNodes.withPeerUrls(PEER_EUREKA_URL_A);
// Start
peerEurekaNodes.start();
PeerEurekaNode peerNode = getPeerNode(PEER_EUREKA_URL_A);
assertThat(peerNode, is(notNullValue()));
// Shutdown
peerEurekaNodes.shutdown();
verify(peerNode, times(1)).shutDown();
}
@Test
public void testReloadWithNoPeerChange() throws Exception {
// Start
peerEurekaNodes.withPeerUrls(PEER_EUREKA_URL_A);
peerEurekaNodes.start();
PeerEurekaNode peerNode = getPeerNode(PEER_EUREKA_URL_A);
assertThat(peerEurekaNodes.awaitNextReload(60, TimeUnit.SECONDS), is(true));
assertThat(getPeerNode(PEER_EUREKA_URL_A), is(equalTo(peerNode)));
}
@Test
public void testReloadWithPeerUpdates() throws Exception {
// Start
peerEurekaNodes.withPeerUrls(PEER_EUREKA_URL_A);
peerEurekaNodes.start();
PeerEurekaNode peerNodeA = getPeerNode(PEER_EUREKA_URL_A);
// Add one more peer
peerEurekaNodes.withPeerUrls(PEER_EUREKA_URL_A, PEER_EUREKA_URL_B);
assertThat(peerEurekaNodes.awaitNextReload(60, TimeUnit.SECONDS), is(true));
assertThat(getPeerNode(PEER_EUREKA_URL_A), is(notNullValue()));
assertThat(getPeerNode(PEER_EUREKA_URL_B), is(notNullValue()));
// Remove first peer, and add yet another one
peerEurekaNodes.withPeerUrls(PEER_EUREKA_URL_B, PEER_EUREKA_URL_C);
assertThat(peerEurekaNodes.awaitNextReload(60, TimeUnit.SECONDS), is(true));
assertThat(getPeerNode(PEER_EUREKA_URL_A), is(nullValue()));
assertThat(getPeerNode(PEER_EUREKA_URL_B), is(notNullValue()));
assertThat(getPeerNode(PEER_EUREKA_URL_C), is(notNullValue()));
verify(peerNodeA, times(1)).shutDown();
}
private PeerEurekaNode getPeerNode(String peerEurekaUrl) {
for (PeerEurekaNode node : peerEurekaNodes.getPeerEurekaNodes()) {
if (node.getServiceUrl().equals(peerEurekaUrl)) {
return node;
}
}
return null;
}
static class TestablePeerEurekaNodes extends PeerEurekaNodes {
private AtomicReference<List<String>> peerUrlsRef = new AtomicReference<>(Collections.<String>emptyList());
private final ConcurrentHashMap<String, PeerEurekaNode> peerEurekaNodeByUrl = new ConcurrentHashMap<>();
private final AtomicInteger reloadCounter = new AtomicInteger();
TestablePeerEurekaNodes(PeerAwareInstanceRegistry registry, EurekaServerConfig serverConfig) {
super(registry,
serverConfig,
new DefaultEurekaClientConfig(),
new DefaultServerCodecs(serverConfig),
mock(ApplicationInfoManager.class)
);
}
void withPeerUrls(String... peerUrls) {
this.peerUrlsRef.set(Arrays.asList(peerUrls));
}
boolean awaitNextReload(long timeout, TimeUnit timeUnit) throws InterruptedException {
int lastReloadCounter = reloadCounter.get();
long endTime = System.currentTimeMillis() + timeUnit.toMillis(timeout);
while (endTime > System.currentTimeMillis() && lastReloadCounter == reloadCounter.get()) {
Thread.sleep(10);
}
return lastReloadCounter != reloadCounter.get();
}
@Override
protected void updatePeerEurekaNodes(List<String> newPeerUrls) {
super.updatePeerEurekaNodes(newPeerUrls);
reloadCounter.incrementAndGet();
}
@Override
protected List<String> resolvePeerUrls() {
return peerUrlsRef.get();
}
@Override
protected PeerEurekaNode createPeerEurekaNode(String peerEurekaNodeUrl) {
if (peerEurekaNodeByUrl.containsKey(peerEurekaNodeUrl)) {
throw new IllegalStateException("PeerEurekaNode for URL " + peerEurekaNodeUrl + " is already created");
}
PeerEurekaNode peerEurekaNode = mock(PeerEurekaNode.class);
when(peerEurekaNode.getServiceUrl()).thenReturn(peerEurekaNodeUrl);
return peerEurekaNode;
}
}
} | 8,111 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/cluster/TestableInstanceReplicationTask.java | package com.netflix.eureka.cluster;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicReference;
import com.netflix.discovery.shared.transport.EurekaHttpResponse;
import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl.Action;
/**
* @author Tomasz Bak
*/
class TestableInstanceReplicationTask extends InstanceReplicationTask {
public static final String APP_NAME = "testableReplicationTaskApp";
public enum ProcessingState {Pending, Finished, Failed}
private final int replyStatusCode;
private final int networkFailuresRepeatCount;
private final AtomicReference<ProcessingState> processingState = new AtomicReference<>(ProcessingState.Pending);
private volatile int triggeredNetworkFailures;
TestableInstanceReplicationTask(String peerNodeName,
String appName,
String id,
Action action,
int replyStatusCode,
int networkFailuresRepeatCount) {
super(peerNodeName, action, appName, id);
this.replyStatusCode = replyStatusCode;
this.networkFailuresRepeatCount = networkFailuresRepeatCount;
}
@Override
public EurekaHttpResponse<Void> execute() throws Throwable {
if (triggeredNetworkFailures < networkFailuresRepeatCount) {
triggeredNetworkFailures++;
throw new IOException("simulated network failure");
}
return EurekaHttpResponse.status(replyStatusCode);
}
@Override
public void handleSuccess() {
processingState.compareAndSet(ProcessingState.Pending, ProcessingState.Finished);
}
@Override
public void handleFailure(int statusCode, Object responseEntity) throws Throwable {
processingState.compareAndSet(ProcessingState.Pending, ProcessingState.Failed);
}
public ProcessingState getProcessingState() {
return processingState.get();
}
public static TestableReplicationTaskBuilder aReplicationTask() {
return new TestableReplicationTaskBuilder();
}
static class TestableReplicationTaskBuilder {
private int autoId;
private int replyStatusCode = 200;
private Action action = Action.Heartbeat;
private int networkFailuresRepeatCount;
public TestableReplicationTaskBuilder withReplyStatusCode(int replyStatusCode) {
this.replyStatusCode = replyStatusCode;
return this;
}
public TestableReplicationTaskBuilder withAction(Action action) {
this.action = action;
return this;
}
public TestableReplicationTaskBuilder withNetworkFailures(int networkFailuresRepeatCount) {
this.networkFailuresRepeatCount = networkFailuresRepeatCount;
return this;
}
public TestableInstanceReplicationTask build() {
return new TestableInstanceReplicationTask(
"peerNodeName#test",
APP_NAME,
"id#" + autoId++,
action,
replyStatusCode,
networkFailuresRepeatCount
);
}
}
}
| 8,112 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/cluster | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/cluster/protocol/JacksonEncodingTest.java | package com.netflix.eureka.cluster.protocol;
import com.netflix.discovery.converters.EurekaJacksonCodec;
import com.netflix.discovery.shared.transport.ClusterSampleData;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
/**
* @author Tomasz Bak
*/
public class JacksonEncodingTest {
private final EurekaJacksonCodec jacksonCodec = new EurekaJacksonCodec();
@Test
public void testReplicationInstanceEncoding() throws Exception {
ReplicationInstance replicationInstance = ClusterSampleData.newReplicationInstance();
// Encode / decode
String jsonText = jacksonCodec.writeToString(replicationInstance);
ReplicationInstance decodedValue = jacksonCodec.readValue(ReplicationInstance.class, jsonText);
assertThat(decodedValue, is(equalTo(replicationInstance)));
}
@Test
public void testReplicationInstanceResponseEncoding() throws Exception {
ReplicationInstanceResponse replicationInstanceResponse = ClusterSampleData.newReplicationInstanceResponse(true);
// Encode / decode
String jsonText = jacksonCodec.writeToString(replicationInstanceResponse);
ReplicationInstanceResponse decodedValue = jacksonCodec.readValue(ReplicationInstanceResponse.class, jsonText);
assertThat(decodedValue, is(equalTo(replicationInstanceResponse)));
}
@Test
public void testReplicationListEncoding() throws Exception {
ReplicationList replicationList = new ReplicationList();
replicationList.addReplicationInstance(ClusterSampleData.newReplicationInstance());
// Encode / decode
String jsonText = jacksonCodec.writeToString(replicationList);
ReplicationList decodedValue = jacksonCodec.readValue(ReplicationList.class, jsonText);
assertThat(decodedValue, is(equalTo(replicationList)));
}
@Test
public void testReplicationListResponseEncoding() throws Exception {
ReplicationListResponse replicationListResponse = new ReplicationListResponse();
replicationListResponse.addResponse(ClusterSampleData.newReplicationInstanceResponse(false));
// Encode / decode
String jsonText = jacksonCodec.writeToString(replicationListResponse);
ReplicationListResponse decodedValue = jacksonCodec.readValue(ReplicationListResponse.class, jsonText);
assertThat(decodedValue, is(equalTo(replicationListResponse)));
}
} | 8,113 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/test/async | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/test/async/executor/AsyncResult.java | package com.netflix.eureka.test.async.executor;
import java.util.concurrent.Future;
/**
* Async result which extends {@link Future}.
*
* @param <T> The result type.
*/
public interface AsyncResult<T> extends Future<T> {
/**
* Handle result normally.
*
* @param result result.
*/
void handleResult(T result);
/**
* Handle error.
*
* @param error error during execution.
*/
void handleError(Throwable error);
/**
* Get result which will be blocked until the result is available or an error occurs.
*/
T getResult() throws AsyncExecutorException;
/**
* Get error if possible.
*
* @return error.
*/
Throwable getError();
}
| 8,114 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/test/async | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/test/async/executor/Backoff.java | package com.netflix.eureka.test.async.executor;
/**
* Backoff for pausing for a duration
*/
public class Backoff {
/**
* Pause time in milliseconds
*/
private final int pauseTimeInMs;
/**
* Prepare to pause for one duration.
*
* @param pauseTimeInMs pause time in milliseconds
*/
public Backoff(int pauseTimeInMs) {
this.pauseTimeInMs = pauseTimeInMs;
}
/**
* Backoff for one duration.
*/
public void backoff() throws InterruptedException {
Thread.sleep(pauseTimeInMs);
}
}
| 8,115 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/test/async | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/test/async/executor/AsyncExecutorException.java | package com.netflix.eureka.test.async.executor;
/**
* Async executor exception for {@link ConcreteAsyncResult}.
*/
public class AsyncExecutorException extends RuntimeException {
public AsyncExecutorException() {
}
public AsyncExecutorException(String message) {
super(message);
}
public AsyncExecutorException(String message, Throwable cause) {
super(message, cause);
}
public AsyncExecutorException(Throwable cause) {
super(cause);
}
public AsyncExecutorException(String message,
Throwable cause,
boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
| 8,116 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/test/async | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/test/async/executor/AsyncSequentialExecutor.java | package com.netflix.eureka.test.async.executor;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;
import com.amazonaws.util.CollectionUtils;
import com.google.common.base.Optional;
/**
* Run a sequential events in asynchronous way.
*/
public class AsyncSequentialExecutor {
/**
* Index for thread naming
*/
private static final AtomicInteger INDEX = new AtomicInteger(0);
/**
* Result status, if events are executed successfully in sequential manner, then return this by default
*/
public enum ResultStatus {
DONE
}
/**
* Run a sequential events in asynchronous way. An result holder will be returned to the caller.
* If calling is successful, then will return {@link ResultStatus#DONE}, or else exception will
* be thrown and {@link AsyncResult} will be filled with the error.
*
* @param events sequential events.
* @return result holder.
*/
public AsyncResult<ResultStatus> run(SequentialEvents events) {
return run(new Callable<ResultStatus>() {
@Override
public ResultStatus call() throws Exception {
if (events == null || CollectionUtils.isNullOrEmpty(events.getEventList())) {
throw new IllegalArgumentException("SequentialEvents does not contain any event to run");
}
for (SingleEvent singleEvent : events.getEventList()) {
new Backoff(singleEvent.getIntervalTimeInMs()).backoff();
singleEvent.getAction().execute();
}
return ResultStatus.DONE;
}
});
}
/**
* Run task in a thread.
*
* @param task task to run.
*/
protected <T> AsyncResult<T> run(Callable<T> task) {
final AsyncResult<T> result = new ConcreteAsyncResult<>();
new Thread(new Runnable() {
@Override
public void run() {
T value = null;
Optional<Exception> e = Optional.absent();
try {
value = task.call();
result.handleResult(value);
} catch (Exception e1) {
e = Optional.of(e1);
result.handleError(e1);
}
}
}, "AsyncSequentialExecutor-" + INDEX.incrementAndGet()).start();
return result;
}
}
| 8,117 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/test/async | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/test/async/executor/ConcreteAsyncResult.java | package com.netflix.eureka.test.async.executor;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Async result which is usually hold be caller to retrieve result or error.
*/
public class ConcreteAsyncResult<T> implements AsyncResult<T> {
private final CountDownLatch latch = new CountDownLatch(1);
private T result = null;
private Throwable error = null;
public ConcreteAsyncResult() {
}
/**
* Sets the result and unblocks all threads waiting on {@link #get()} or {@link #get(long, TimeUnit)}.
*
* @param result the result to set.
*/
@Override
public void handleResult(T result) {
this.result = result;
latch.countDown();
}
/**
* Sets an error thrown during execution, and unblocks all threads waiting on {@link #get()} or
* {@link #get(long, TimeUnit)}.
*
* @param error the RPC error to set.
*/
public void handleError(Throwable error) {
this.error = error;
latch.countDown();
}
/**
* Gets the value of the result in blocking way. Using {@link #get()} or {@link #get(long, TimeUnit)} is
* usually preferred because these methods block until the result is available or an error occurs.
*
* @return the value of the response, or null if no result was returned or the RPC has not yet completed.
*/
public T getResult() throws AsyncExecutorException {
return get();
}
/**
* Gets the error that was thrown during execution. Does not block. Either {@link #get()} or
* {@link #get(long, TimeUnit)} should be called first because these methods block until execution has completed.
*
* @return the error that was thrown, or null if no error has occurred or if the execution has not yet completed.
*/
public Throwable getError() {
return error;
}
public boolean cancel(boolean mayInterruptIfRunning) {
latch.countDown();
return false;
}
public boolean isCancelled() {
return false;
}
public T get() throws AsyncExecutorException {
try {
latch.await();
} catch (InterruptedException e) {
throw new AsyncExecutorException("Interrupted", error);
}
if (error != null) {
if (error instanceof AsyncExecutorException) {
throw (AsyncExecutorException) error;
} else {
throw new AsyncExecutorException("Execution exception", error);
}
}
return result;
}
public T get(long timeout, TimeUnit unit) throws AsyncExecutorException {
try {
if (latch.await(timeout, unit)) {
if (error != null) {
if (error instanceof AsyncExecutorException) {
throw (AsyncExecutorException) error;
} else {
throw new RuntimeException("call future get exception", error);
}
}
return result;
} else {
throw new AsyncExecutorException("async get time out");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new AsyncExecutorException("call future is interuptted", e);
}
}
/**
* Waits for the CallFuture to complete without returning the result.
*
* @throws InterruptedException if interrupted.
*/
public void await() throws InterruptedException {
latch.await();
}
/**
* Waits for the CallFuture to complete without returning the result.
*
* @param timeout the maximum time to wait.
* @param unit the time unit of the timeout argument.
* @throws InterruptedException if interrupted.
* @throws TimeoutException if the wait timed out.
*/
public void await(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException {
if (!latch.await(timeout, unit)) {
throw new TimeoutException();
}
}
public boolean isDone() {
return latch.getCount() <= 0;
}
}
| 8,118 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/test/async | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/test/async/executor/SingleEvent.java | package com.netflix.eureka.test.async.executor;
import com.google.common.base.Preconditions;
/**
* Single event which represents the action that will be executed in a time line.
*/
public class SingleEvent {
/**
* Interval time between the previous event.
*/
private int intervalTimeInMs;
/**
* Action to take.
*/
private Action action;
/**
* Constructor.
*/
public SingleEvent(int intervalTimeInMs, Action action) {
this.intervalTimeInMs = intervalTimeInMs;
this.action = action;
}
public int getIntervalTimeInMs() {
return intervalTimeInMs;
}
public Action getAction() {
return action;
}
/**
* SingleEvent builder.
*/
public static final class Builder {
/**
* Interval time between the previous event.
*/
private int intervalTimeInMs;
/**
* Action to take.
*/
private Action action;
private Builder() {
}
public static Builder newBuilder() {
return new Builder();
}
public Builder withIntervalTimeInMs(int intervalTimeInMs) {
this.intervalTimeInMs = intervalTimeInMs;
return this;
}
public Builder withAction(Action action) {
this.action = action;
return this;
}
public SingleEvent build() {
Preconditions.checkNotNull(intervalTimeInMs, "IntervalTimeInMs is not set for SingleEvent");
Preconditions.checkNotNull(action, "Action is not set for SingleEvent");
return new SingleEvent(intervalTimeInMs, action);
}
}
@Override
public String toString() {
return "SingleEvent{" +
"intervalTimeInMs=" + intervalTimeInMs +
", action=" + action +
'}';
}
/**
* Action to perform.
*/
public interface Action {
void execute();
}
}
| 8,119 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/test/async | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/test/async/executor/SequentialEvents.java | package com.netflix.eureka.test.async.executor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.common.base.Preconditions;
/**
* SequentialEvents represents multiple events which should be executed in a
* sequential manner.
*/
public class SequentialEvents {
/**
* Multiple single events.
*/
private List<SingleEvent> eventList;
/**
* Default constructor.
*
* @param eventList event list.
*/
private SequentialEvents(List<SingleEvent> eventList) {
this.eventList = eventList;
}
/**
* Instance creator.
*
* @return SequentialEvents.
*/
public static SequentialEvents newInstance() {
return new SequentialEvents(new ArrayList<>());
}
/**
* Instance creator with expected event list size.
*
* @param expectedEventListSize expected event list size.
* @return SequentialEvents.
*/
public static SequentialEvents newInstance(int expectedEventListSize) {
return new SequentialEvents(new ArrayList<>(expectedEventListSize));
}
/**
* Build sequential events from multiple single events.
*
* @param event a bunch of single events.
* @return SequentialEvents.
*/
public static SequentialEvents of(SingleEvent... events) {
return new SequentialEvents(Arrays.asList(events));
}
/**
* Build sequential events from multiple single events.
*
* @param eventList a bunch of single events.
* @return SequentialEvents.
*/
public static SequentialEvents of(List<SingleEvent> eventList) {
return new SequentialEvents(eventList);
}
/**
* Add one more single event to sequential events.
*
* @param event one event.
* @return SequentialEvents.
*/
public SequentialEvents with(SingleEvent event) {
Preconditions.checkNotNull(eventList, "eventList should not be null");
this.eventList.add(event);
return this;
}
/**
* Get event lists.
*
* @return event lists.
*/
public List<SingleEvent> getEventList() {
return eventList;
}
@Override
public String toString() {
return "SequentialEvents{" +
"eventList=" + eventList +
'}';
}
}
| 8,120 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/util/StatusUtilTest.java | package com.netflix.eureka.util;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.discovery.shared.Application;
import com.netflix.discovery.shared.transport.EurekaTransportConfig;
import com.netflix.eureka.EurekaServerConfig;
import com.netflix.eureka.EurekaServerContext;
import com.netflix.eureka.cluster.PeerEurekaNode;
import com.netflix.eureka.cluster.PeerEurekaNodes;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
public class StatusUtilTest {
@Test
public void testGetStatusInfoHealthy() {
StatusUtil statusUtil = getStatusUtil(3, 3, 2);
assertTrue(statusUtil.getStatusInfo().isHealthy());
}
@Test
public void testGetStatusInfoUnhealthy() {
StatusUtil statusUtil = getStatusUtil(5, 3, 4);
assertFalse(statusUtil.getStatusInfo().isHealthy());
}
@Test
public void testGetStatusInfoUnsetHealth() {
StatusUtil statusUtil = getStatusUtil(5, 3, -1);
StatusInfo statusInfo = statusUtil.getStatusInfo();
try {
statusInfo.isHealthy();
} catch (NullPointerException e) {
// Expected that the healthy flag is not set when the minimum value is -1
return;
}
fail("Excpected NPE to be thrown when healthy threshold is not set");
}
/**
* @param replicas the number of replicas to mock
* @param instances the number of instances to mock
* @param minimum the minimum number of peers
* @return the status utility with the mocked replicas/instances
*/
private StatusUtil getStatusUtil(int replicas, int instances, int minimum) {
EurekaServerContext mockEurekaServerContext = mock(EurekaServerContext.class);
List<InstanceInfo> mockInstanceInfos = getMockInstanceInfos(instances);
Application mockApplication = mock(Application.class);
when(mockApplication.getInstances()).thenReturn(mockInstanceInfos);
ApplicationInfoManager mockAppInfoManager = mock(ApplicationInfoManager.class);
when(mockAppInfoManager.getInfo()).thenReturn(mockInstanceInfos.get(0));
when(mockEurekaServerContext.getApplicationInfoManager()).thenReturn(mockAppInfoManager);
PeerAwareInstanceRegistry mockRegistry = mock(PeerAwareInstanceRegistry.class);
when(mockRegistry.getApplication("stuff", false)).thenReturn(mockApplication);
when(mockEurekaServerContext.getRegistry()).thenReturn(mockRegistry);
List<PeerEurekaNode> mockNodes = getMockNodes(replicas);
EurekaTransportConfig mockTransportConfig = mock(EurekaTransportConfig.class);
when(mockTransportConfig.applicationsResolverUseIp()).thenReturn(false);
EurekaClientConfig mockClientConfig = mock(EurekaClientConfig.class);
when(mockClientConfig.getTransportConfig()).thenReturn(mockTransportConfig);
EurekaServerConfig mockServerConfig = mock(EurekaServerConfig.class);
when(mockServerConfig.getHealthStatusMinNumberOfAvailablePeers()).thenReturn(minimum);
PeerEurekaNodes peerEurekaNodes = new PeerEurekaNodes(mockRegistry, mockServerConfig, mockClientConfig, null, mockAppInfoManager);
PeerEurekaNodes spyPeerEurekaNodes = spy(peerEurekaNodes);
when(spyPeerEurekaNodes.getPeerEurekaNodes()).thenReturn(mockNodes);
when(mockEurekaServerContext.getPeerEurekaNodes()).thenReturn(spyPeerEurekaNodes);
return new StatusUtil(mockEurekaServerContext);
}
List<InstanceInfo> getMockInstanceInfos(int size) {
List<InstanceInfo> instances = new ArrayList<>();
for (int i = 0; i < size; i++) {
InstanceInfo mockInstance = mock(InstanceInfo.class);
when(mockInstance.getHostName()).thenReturn(String.valueOf(i));
when(mockInstance.getIPAddr()).thenReturn(String.valueOf(i));
when(mockInstance.getAppName()).thenReturn("stuff");
instances.add(mockInstance);
}
return instances;
}
List<PeerEurekaNode> getMockNodes(int size) {
List<PeerEurekaNode> nodes = new ArrayList<>();
for (int i = 0; i < size; i++) {
PeerEurekaNode mockNode = mock(PeerEurekaNode.class);
when(mockNode.getServiceUrl()).thenReturn(String.format("http://%d:8080/v2", i));
nodes.add(mockNode);
}
return nodes;
}
}
| 8,121 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/util/AwsAsgUtilTest.java | package com.netflix.eureka.util;
import com.netflix.appinfo.AmazonInfo;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.LeaseInfo;
import com.netflix.appinfo.MyDataCenterInstanceConfig;
import com.netflix.config.ConfigurationManager;
import com.netflix.discovery.DefaultEurekaClientConfig;
import com.netflix.discovery.DiscoveryClient;
import com.netflix.eureka.DefaultEurekaServerConfig;
import com.netflix.eureka.EurekaServerConfig;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
import com.netflix.eureka.aws.AwsAsgUtil;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.UUID;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
/**
* @author David Liu
*/
public class AwsAsgUtilTest {
private ApplicationInfoManager applicationInfoManager;
private PeerAwareInstanceRegistry registry;
private DiscoveryClient client;
private AwsAsgUtil awsAsgUtil;
private InstanceInfo instanceInfo;
@Before
public void setUp() throws Exception {
ConfigurationManager.getConfigInstance().setProperty("eureka.awsAccessId", "fakeId");
ConfigurationManager.getConfigInstance().setProperty("eureka.awsSecretKey", "fakeKey");
AmazonInfo dataCenterInfo = mock(AmazonInfo.class);
EurekaServerConfig serverConfig = new DefaultEurekaServerConfig();
InstanceInfo.Builder builder = InstanceInfo.Builder.newBuilder();
builder.setIPAddr("10.10.101.00");
builder.setHostName("fakeHost");
builder.setAppName("fake-" + UUID.randomUUID());
builder.setLeaseInfo(LeaseInfo.Builder.newBuilder().build());
builder.setDataCenterInfo(dataCenterInfo);
instanceInfo = builder.build();
applicationInfoManager = new ApplicationInfoManager(new MyDataCenterInstanceConfig(), instanceInfo);
DefaultEurekaClientConfig clientConfig = new DefaultEurekaClientConfig();
// setup config in advance, used in initialize converter
client = mock(DiscoveryClient.class);
registry = mock(PeerAwareInstanceRegistry.class);
awsAsgUtil = spy(new AwsAsgUtil(serverConfig, clientConfig, registry));
}
@After
public void tearDown() throws Exception {
ConfigurationManager.getConfigInstance().clear();
}
@Test
public void testDefaultAsgStatus() {
Assert.assertEquals(true, awsAsgUtil.isASGEnabled(instanceInfo));
}
@Test
public void testAsyncLoadingFromCache() {
// TODO
}
}
| 8,122 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/util | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/util/batcher/TaskDispatchersTest.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.eureka.util.batcher;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import com.netflix.eureka.util.batcher.TaskProcessor.ProcessingResult;
import org.junit.After;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
/**
* @author Tomasz Bak
*/
public class TaskDispatchersTest {
private static final long SERVER_UNAVAILABLE_SLEEP_TIME_MS = 1000;
private static final long RETRY_SLEEP_TIME_MS = 100;
private static final long MAX_BATCHING_DELAY_MS = 10;
private static final int MAX_BUFFER_SIZE = 1000000;
private static final int WORK_LOAD_SIZE = 2;
private final RecordingProcessor processor = new RecordingProcessor();
private TaskDispatcher<Integer, ProcessingResult> dispatcher;
@After
public void tearDown() throws Exception {
if (dispatcher != null) {
dispatcher.shutdown();
}
}
@Test
public void testSingleTaskDispatcher() throws Exception {
dispatcher = TaskDispatchers.createNonBatchingTaskDispatcher(
"TEST",
MAX_BUFFER_SIZE,
1,
MAX_BATCHING_DELAY_MS,
SERVER_UNAVAILABLE_SLEEP_TIME_MS,
RETRY_SLEEP_TIME_MS,
processor
);
dispatcher.process(1, ProcessingResult.Success, System.currentTimeMillis() + 60 * 1000);
ProcessingResult result = processor.completedTasks.poll(5, TimeUnit.SECONDS);
assertThat(result, is(equalTo(ProcessingResult.Success)));
}
@Test
public void testBatchingDispatcher() throws Exception {
dispatcher = TaskDispatchers.createBatchingTaskDispatcher(
"TEST",
MAX_BUFFER_SIZE,
WORK_LOAD_SIZE,
1,
MAX_BATCHING_DELAY_MS,
SERVER_UNAVAILABLE_SLEEP_TIME_MS,
RETRY_SLEEP_TIME_MS,
processor
);
dispatcher.process(1, ProcessingResult.Success, System.currentTimeMillis() + 60 * 1000);
dispatcher.process(2, ProcessingResult.Success, System.currentTimeMillis() + 60 * 1000);
processor.expectSuccesses(2);
}
@Test
public void testTasksAreDistributedAcrossAllWorkerThreads() throws Exception {
int threadCount = 3;
CountingTaskProcessor countingProcessor = new CountingTaskProcessor();
TaskDispatcher<Integer, Boolean> dispatcher = TaskDispatchers.createBatchingTaskDispatcher(
"TEST",
MAX_BUFFER_SIZE,
WORK_LOAD_SIZE,
threadCount,
MAX_BATCHING_DELAY_MS,
SERVER_UNAVAILABLE_SLEEP_TIME_MS,
RETRY_SLEEP_TIME_MS,
countingProcessor
);
try {
int loops = 1000;
while (true) {
countingProcessor.resetTo(loops);
for (int i = 0; i < loops; i++) {
dispatcher.process(i, true, System.currentTimeMillis() + 60 * 1000);
}
countingProcessor.awaitCompletion();
int minHitPerThread = (int) (loops / threadCount * 0.9);
if (countingProcessor.lowestHit() < minHitPerThread) {
loops *= 2;
} else {
break;
}
if (loops > MAX_BUFFER_SIZE) {
fail("Uneven load distribution");
}
}
} finally {
dispatcher.shutdown();
}
}
static class CountingTaskProcessor implements TaskProcessor<Boolean> {
final ConcurrentMap<Thread, Integer> threadHits = new ConcurrentHashMap<>();
volatile Semaphore completionGuard;
@Override
public ProcessingResult process(Boolean task) {
throw new IllegalStateException("unexpected");
}
@Override
public ProcessingResult process(List<Boolean> tasks) {
Thread currentThread = Thread.currentThread();
Integer current = threadHits.get(currentThread);
if (current == null) {
threadHits.put(currentThread, tasks.size());
} else {
threadHits.put(currentThread, tasks.size() + current);
}
completionGuard.release(tasks.size());
return ProcessingResult.Success;
}
void resetTo(int expectedTasks) {
completionGuard = new Semaphore(-expectedTasks + 1);
}
void awaitCompletion() throws InterruptedException {
assertThat(completionGuard.tryAcquire(5, TimeUnit.SECONDS), is(true));
}
int lowestHit() {
return Collections.min(threadHits.values());
}
}
} | 8,123 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/util | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/util/batcher/AcceptorExecutorTest.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.eureka.util.batcher;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import com.netflix.eureka.util.batcher.TaskProcessor.ProcessingResult;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
/**
* @author Tomasz Bak
*/
public class AcceptorExecutorTest {
private static final long SERVER_UNAVAILABLE_SLEEP_TIME_MS = 1000;
private static final long RETRY_SLEEP_TIME_MS = 100;
private static final long MAX_BATCHING_DELAY_MS = 10;
private static final int MAX_BUFFER_SIZE = 3;
private static final int WORK_LOAD_SIZE = 2;
private AcceptorExecutor<Integer, String> acceptorExecutor;
@Before
public void setUp() throws Exception {
acceptorExecutor = new AcceptorExecutor<>(
"TEST", MAX_BUFFER_SIZE, WORK_LOAD_SIZE, MAX_BATCHING_DELAY_MS,
SERVER_UNAVAILABLE_SLEEP_TIME_MS, RETRY_SLEEP_TIME_MS
);
}
@After
public void tearDown() throws Exception {
acceptorExecutor.shutdown();
}
@Test
public void testTasksAreDispatchedToWorkers() throws Exception {
acceptorExecutor.process(1, "Task1", System.currentTimeMillis() + 60 * 1000);
TaskHolder<Integer, String> taskHolder = acceptorExecutor.requestWorkItem().poll(5, TimeUnit.SECONDS);
verifyTaskHolder(taskHolder, 1, "Task1");
acceptorExecutor.process(2, "Task2", System.currentTimeMillis() + 60 * 1000);
List<TaskHolder<Integer, String>> taskHolders = acceptorExecutor.requestWorkItems().poll(5, TimeUnit.SECONDS);
assertThat(taskHolders.size(), is(equalTo(1)));
verifyTaskHolder(taskHolders.get(0), 2, "Task2");
}
@Test
public void testBatchSizeIsConstrainedByConfiguredMaxSize() throws Exception {
for (int i = 0; i <= MAX_BUFFER_SIZE; i++) {
acceptorExecutor.process(i, "Task" + i, System.currentTimeMillis() + 60 * 1000);
}
List<TaskHolder<Integer, String>> taskHolders = acceptorExecutor.requestWorkItems().poll(5, TimeUnit.SECONDS);
assertThat(taskHolders.size(), is(equalTo(WORK_LOAD_SIZE)));
}
@Test
public void testNewTaskOverridesOldOne() throws Exception {
acceptorExecutor.process(1, "Task1", System.currentTimeMillis() + 60 * 1000);
acceptorExecutor.process(1, "Task1.1", System.currentTimeMillis() + 60 * 1000);
TaskHolder<Integer, String> taskHolder = acceptorExecutor.requestWorkItem().poll(5, TimeUnit.SECONDS);
verifyTaskHolder(taskHolder, 1, "Task1.1");
}
@Test
public void testRepublishedTaskIsHandledFirst() throws Exception {
acceptorExecutor.process(1, "Task1", System.currentTimeMillis() + 60 * 1000);
acceptorExecutor.process(2, "Task2", System.currentTimeMillis() + 60 * 1000);
TaskHolder<Integer, String> firstTaskHolder = acceptorExecutor.requestWorkItem().poll(5, TimeUnit.SECONDS);
verifyTaskHolder(firstTaskHolder, 1, "Task1");
acceptorExecutor.reprocess(firstTaskHolder, ProcessingResult.TransientError);
TaskHolder<Integer, String> secondTaskHolder = acceptorExecutor.requestWorkItem().poll(5, TimeUnit.SECONDS);
verifyTaskHolder(secondTaskHolder, 1, "Task1");
TaskHolder<Integer, String> thirdTaskHolder = acceptorExecutor.requestWorkItem().poll(5, TimeUnit.SECONDS);
verifyTaskHolder(thirdTaskHolder, 2, "Task2");
}
@Test
public void testWhenBufferOverflowsOldestTasksAreRemoved() throws Exception {
for (int i = 0; i <= MAX_BUFFER_SIZE; i++) {
acceptorExecutor.process(i, "Task" + i, System.currentTimeMillis() + 60 * 1000);
}
// Task 0 should be dropped out
TaskHolder<Integer, String> firstTaskHolder = acceptorExecutor.requestWorkItem().poll(5, TimeUnit.SECONDS);
verifyTaskHolder(firstTaskHolder, 1, "Task1");
}
@Test
public void testTasksAreDelayToMaximizeBatchSize() throws Exception {
BlockingQueue<List<TaskHolder<Integer, String>>> taskQueue = acceptorExecutor.requestWorkItems();
acceptorExecutor.process(1, "Task1", System.currentTimeMillis() + 60 * 1000);
Thread.sleep(MAX_BATCHING_DELAY_MS / 2);
acceptorExecutor.process(2, "Task2", System.currentTimeMillis() + 60 * 1000);
List<TaskHolder<Integer, String>> taskHolders = taskQueue.poll(5, TimeUnit.SECONDS);
assertThat(taskHolders.size(), is(equalTo(2)));
}
private static void verifyTaskHolder(TaskHolder<Integer, String> taskHolder, int id, String task) {
assertThat(taskHolder, is(notNullValue()));
assertThat(taskHolder.getId(), is(equalTo(id)));
assertThat(taskHolder.getTask(), is(equalTo(task)));
}
} | 8,124 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/util | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/util/batcher/RecordingProcessor.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.eureka.util.batcher;
import java.util.List;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
import com.netflix.eureka.util.batcher.TaskProcessor.ProcessingResult;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
/**
* @author Tomasz Bak
*/
class RecordingProcessor implements TaskProcessor<ProcessingResult> {
final BlockingDeque<ProcessingResult> completedTasks = new LinkedBlockingDeque<>();
final BlockingDeque<ProcessingResult> transientErrorTasks = new LinkedBlockingDeque<>();
final BlockingDeque<ProcessingResult> permanentErrorTasks = new LinkedBlockingDeque<>();
@Override
public ProcessingResult process(ProcessingResult task) {
switch (task) {
case Success:
completedTasks.add(task);
break;
case PermanentError:
permanentErrorTasks.add(task);
break;
case TransientError:
transientErrorTasks.add(task);
break;
}
return task;
}
@Override
public ProcessingResult process(List<ProcessingResult> tasks) {
for (ProcessingResult task : tasks) {
process(task);
}
return tasks.get(0);
}
public static TaskHolder<Integer, ProcessingResult> successfulTaskHolder(int id) {
return new TaskHolder<>(id, ProcessingResult.Success, System.currentTimeMillis() + 60 * 1000);
}
public static TaskHolder<Integer, ProcessingResult> transientErrorTaskHolder(int id) {
return new TaskHolder<>(id, ProcessingResult.TransientError, System.currentTimeMillis() + 60 * 1000);
}
public static TaskHolder<Integer, ProcessingResult> permanentErrorTaskHolder(int id) {
return new TaskHolder<>(id, ProcessingResult.PermanentError, System.currentTimeMillis() + 60 * 1000);
}
public void expectSuccesses(int count) throws InterruptedException {
for (int i = 0; i < count; i++) {
ProcessingResult task = completedTasks.poll(5, TimeUnit.SECONDS);
assertThat(task, is(notNullValue()));
}
}
public void expectTransientErrors(int count) throws InterruptedException {
for (int i = 0; i < count; i++) {
ProcessingResult task = transientErrorTasks.poll(5, TimeUnit.SECONDS);
assertThat(task, is(notNullValue()));
}
}
public void expectPermanentErrors(int count) throws InterruptedException {
for (int i = 0; i < count; i++) {
ProcessingResult task = permanentErrorTasks.poll(5, TimeUnit.SECONDS);
assertThat(task, is(notNullValue()));
}
}
}
| 8,125 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/util | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/util/batcher/TaskExecutorsTest.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.eureka.util.batcher;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import com.netflix.eureka.util.batcher.TaskProcessor.ProcessingResult;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static com.netflix.eureka.util.batcher.RecordingProcessor.permanentErrorTaskHolder;
import static com.netflix.eureka.util.batcher.RecordingProcessor.successfulTaskHolder;
import static com.netflix.eureka.util.batcher.RecordingProcessor.transientErrorTaskHolder;
import static java.util.Arrays.asList;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Tomasz Bak
*/
public class TaskExecutorsTest {
@SuppressWarnings("unchecked")
private final AcceptorExecutor<Integer, ProcessingResult> acceptorExecutor = mock(AcceptorExecutor.class);
private final RecordingProcessor processor = new RecordingProcessor();
private final BlockingQueue<TaskHolder<Integer, ProcessingResult>> taskQueue = new LinkedBlockingDeque<>();
private final BlockingQueue<List<TaskHolder<Integer, ProcessingResult>>> taskBatchQueue = new LinkedBlockingDeque<>();
private TaskExecutors<Integer, ProcessingResult> taskExecutors;
@Before
public void setUp() throws Exception {
when(acceptorExecutor.requestWorkItem()).thenReturn(taskQueue);
when(acceptorExecutor.requestWorkItems()).thenReturn(taskBatchQueue);
}
@After
public void tearDown() throws Exception {
taskExecutors.shutdown();
}
@Test
public void testSingleItemSuccessfulProcessing() throws Exception {
taskExecutors = TaskExecutors.singleItemExecutors("TEST", 1, processor, acceptorExecutor);
taskQueue.add(successfulTaskHolder(1));
processor.expectSuccesses(1);
}
@Test
public void testBatchSuccessfulProcessing() throws Exception {
taskExecutors = TaskExecutors.batchExecutors("TEST", 1, processor, acceptorExecutor);
taskBatchQueue.add(asList(successfulTaskHolder(1), successfulTaskHolder(2)));
processor.expectSuccesses(2);
}
@Test
public void testSingleItemProcessingWithTransientError() throws Exception {
taskExecutors = TaskExecutors.singleItemExecutors("TEST", 1, processor, acceptorExecutor);
TaskHolder<Integer, ProcessingResult> taskHolder = transientErrorTaskHolder(1);
taskQueue.add(taskHolder);
// Verify that transient task is be re-scheduled
processor.expectTransientErrors(1);
verify(acceptorExecutor, timeout(500).times(1)).reprocess(taskHolder, ProcessingResult.TransientError);
}
@Test
public void testBatchProcessingWithTransientError() throws Exception {
taskExecutors = TaskExecutors.batchExecutors("TEST", 1, processor, acceptorExecutor);
List<TaskHolder<Integer, ProcessingResult>> taskHolderBatch = asList(transientErrorTaskHolder(1), transientErrorTaskHolder(2));
taskBatchQueue.add(taskHolderBatch);
// Verify that transient task is be re-scheduled
processor.expectTransientErrors(2);
verify(acceptorExecutor, timeout(500).times(1)).reprocess(taskHolderBatch, ProcessingResult.TransientError);
}
@Test
public void testSingleItemProcessingWithPermanentError() throws Exception {
taskExecutors = TaskExecutors.singleItemExecutors("TEST", 1, processor, acceptorExecutor);
TaskHolder<Integer, ProcessingResult> taskHolder = permanentErrorTaskHolder(1);
taskQueue.add(taskHolder);
// Verify that transient task is re-scheduled
processor.expectPermanentErrors(1);
verify(acceptorExecutor, never()).reprocess(taskHolder, ProcessingResult.TransientError);
}
@Test
public void testBatchProcessingWithPermanentError() throws Exception {
taskExecutors = TaskExecutors.batchExecutors("TEST", 1, processor, acceptorExecutor);
List<TaskHolder<Integer, ProcessingResult>> taskHolderBatch = asList(permanentErrorTaskHolder(1), permanentErrorTaskHolder(2));
taskBatchQueue.add(taskHolderBatch);
// Verify that transient task is re-scheduled
processor.expectPermanentErrors(2);
verify(acceptorExecutor, never()).reprocess(taskHolderBatch, ProcessingResult.TransientError);
}
} | 8,126 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/mock/MockRemoteEurekaServer.java | package com.netflix.eureka.mock;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import com.netflix.appinfo.AbstractEurekaIdentity;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.converters.jackson.EurekaJsonJacksonCodec;
import com.netflix.discovery.shared.Application;
import com.netflix.discovery.shared.Applications;
import com.netflix.eureka.*;
import org.junit.Assert;
import org.junit.rules.ExternalResource;
import org.mortbay.jetty.Request;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.FilterHolder;
import org.mortbay.jetty.servlet.ServletHandler;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Nitesh Kant
*/
public class MockRemoteEurekaServer extends ExternalResource {
public static final String EUREKA_API_BASE_PATH = "/eureka/v2/";
private final Map<String, Application> applicationMap;
private final Map<String, Application> applicationDeltaMap;
private final Server server;
private boolean sentDelta;
private int port;
private volatile boolean simulateNotReady;
public MockRemoteEurekaServer(int port, Map<String, Application> applicationMap,
Map<String, Application> applicationDeltaMap) {
this.applicationMap = applicationMap;
this.applicationDeltaMap = applicationDeltaMap;
ServletHandler handler = new AppsResourceHandler();
EurekaServerConfig serverConfig = new DefaultEurekaServerConfig();
EurekaServerContext serverContext = mock(EurekaServerContext.class);
when(serverContext.getServerConfig()).thenReturn(serverConfig);
handler.addFilterWithMapping(ServerRequestAuthFilter.class, "/*", 1).setFilter(new ServerRequestAuthFilter(serverContext));
handler.addFilterWithMapping(RateLimitingFilter.class, "/*", 1).setFilter(new RateLimitingFilter(serverContext));
server = new Server(port);
server.addHandler(handler);
System.out.println(String.format(
"Created eureka server mock with applications map %s and applications delta map %s",
stringifyAppMap(applicationMap), stringifyAppMap(applicationDeltaMap)));
}
@Override
protected void before() throws Throwable {
start();
}
@Override
protected void after() {
try {
stop();
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
public void start() throws Exception {
server.start();
port = server.getConnectors()[0].getLocalPort();
}
public void stop() throws Exception {
server.stop();
}
public boolean isSentDelta() {
return sentDelta;
}
public int getPort() {
return port;
}
public void simulateNotReady(boolean simulateNotReady) {
this.simulateNotReady = simulateNotReady;
}
private static String stringifyAppMap(Map<String, Application> applicationMap) {
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, Application> entry : applicationMap.entrySet()) {
String entryAsString = String.format("{ name : %s , instance count: %d }", entry.getKey(),
entry.getValue().getInstances().size());
builder.append(entryAsString);
}
return builder.toString();
}
private class AppsResourceHandler extends ServletHandler {
@Override
public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch)
throws IOException, ServletException {
if (simulateNotReady) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return;
}
String authName = request.getHeader(AbstractEurekaIdentity.AUTH_NAME_HEADER_KEY);
String authVersion = request.getHeader(AbstractEurekaIdentity.AUTH_VERSION_HEADER_KEY);
String authId = request.getHeader(AbstractEurekaIdentity.AUTH_ID_HEADER_KEY);
Assert.assertNotNull(authName);
Assert.assertNotNull(authVersion);
Assert.assertNotNull(authId);
Assert.assertTrue(!authName.equals(ServerRequestAuthFilter.UNKNOWN));
Assert.assertTrue(!authVersion.equals(ServerRequestAuthFilter.UNKNOWN));
Assert.assertTrue(!authId.equals(ServerRequestAuthFilter.UNKNOWN));
for (FilterHolder filterHolder : this.getFilters()) {
filterHolder.getFilter().doFilter(request, response, new FilterChain() {
@Override
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
// do nothing;
}
});
}
String pathInfo = request.getPathInfo();
System.out.println(
"Eureka resource mock, received request on path: " + pathInfo + ". HTTP method: |" + request
.getMethod() + '|');
boolean handled = false;
if (null != pathInfo && pathInfo.startsWith("")) {
pathInfo = pathInfo.substring(EUREKA_API_BASE_PATH.length());
if (pathInfo.startsWith("apps/delta")) {
Applications apps = new Applications();
for (Application application : applicationDeltaMap.values()) {
apps.addApplication(application);
}
apps.setAppsHashCode(apps.getReconcileHashCode());
sendOkResponseWithContent((Request) request, response, toJson(apps));
handled = true;
sentDelta = true;
} else if (request.getMethod().equals("PUT") && pathInfo.startsWith("apps")) {
InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder()
.setAppName("TEST-APP").build();
sendOkResponseWithContent((Request) request, response,
new EurekaJsonJacksonCodec().getObjectMapper(Applications.class).writeValueAsString(instanceInfo));
handled = true;
} else if (pathInfo.startsWith("apps")) {
Applications apps = new Applications();
for (Application application : applicationMap.values()) {
apps.addApplication(application);
}
apps.setAppsHashCode(apps.getReconcileHashCode());
sendOkResponseWithContent((Request) request, response, toJson(apps));
handled = true;
}
}
if (!handled) {
response.sendError(HttpServletResponse.SC_NOT_FOUND,
"Request path: " + pathInfo + " not supported by eureka resource mock.");
}
}
private void sendOkResponseWithContent(Request request, HttpServletResponse response, String content)
throws IOException {
response.setContentType("application/json; charset=UTF-8");
response.setStatus(HttpServletResponse.SC_OK);
response.getOutputStream().write(content.getBytes("UTF-8"));
response.getOutputStream().flush();
request.setHandled(true);
System.out.println("Eureka resource mock, sent response for request path: " + request.getPathInfo() +
" with content" + content);
}
}
private String toJson(Applications apps) throws IOException {
return new EurekaJsonJacksonCodec().getObjectMapper(Applications.class).writeValueAsString(apps);
}
}
| 8,127 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/resources/ApplicationsResourceTest.java | package com.netflix.eureka.resources;
import com.netflix.appinfo.EurekaAccept;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.util.EurekaEntityComparators;
import com.netflix.discovery.converters.wrappers.CodecWrappers;
import com.netflix.discovery.converters.wrappers.DecoderWrapper;
import com.netflix.discovery.shared.Application;
import com.netflix.discovery.shared.Applications;
import com.netflix.discovery.util.InstanceInfoGenerator;
import com.netflix.eureka.AbstractTester;
import com.netflix.eureka.Version;
import org.junit.Before;
import org.junit.Test;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* @author David Liu
*/
public class ApplicationsResourceTest extends AbstractTester {
private ApplicationsResource applicationsResource;
private Applications testApplications;
@Override
@Before
public void setUp() throws Exception {
super.setUp();
InstanceInfoGenerator instanceInfos = InstanceInfoGenerator.newBuilder(20, 6).build();
testApplications = instanceInfos.toApplications();
applicationsResource = new ApplicationsResource(serverContext);
for (Application application : testApplications.getRegisteredApplications()) {
for (InstanceInfo instanceInfo : application.getInstances()) {
registry.register(instanceInfo, false);
}
}
}
@Test
public void testFullAppsGetJson() throws Exception {
Response response = applicationsResource.getContainers(
Version.V2.name(),
MediaType.APPLICATION_JSON,
null, // encoding
EurekaAccept.full.name(),
null, // uriInfo
null // remote regions
);
String json = String.valueOf(response.getEntity());
DecoderWrapper decoder = CodecWrappers.getDecoder(CodecWrappers.LegacyJacksonJson.class);
Applications decoded = decoder.decode(json, Applications.class);
// test per app as the full apps list include the mock server that is not part of the test apps
for (Application application : testApplications.getRegisteredApplications()) {
Application decodedApp = decoded.getRegisteredApplications(application.getName());
assertThat(EurekaEntityComparators.equal(application, decodedApp), is(true));
}
}
@Test
public void testFullAppsGetGzipJsonHeaderType() throws Exception {
Response response = applicationsResource.getContainers(
Version.V2.name(),
MediaType.APPLICATION_JSON,
"gzip", // encoding
EurekaAccept.full.name(),
null, // uriInfo
null // remote regions
);
assertThat(response.getMetadata().getFirst("Content-Encoding").toString(), is("gzip"));
assertThat(response.getMetadata().getFirst("Content-Type").toString(), is(MediaType.APPLICATION_JSON));
}
@Test
public void testFullAppsGetGzipXmlHeaderType() throws Exception {
Response response = applicationsResource.getContainers(
Version.V2.name(),
MediaType.APPLICATION_XML,
"gzip", // encoding
EurekaAccept.full.name(),
null, // uriInfo
null // remote regions
);
assertThat(response.getMetadata().getFirst("Content-Encoding").toString(), is("gzip"));
assertThat(response.getMetadata().getFirst("Content-Type").toString(), is(MediaType.APPLICATION_XML));
}
@Test
public void testMiniAppsGet() throws Exception {
Response response = applicationsResource.getContainers(
Version.V2.name(),
MediaType.APPLICATION_JSON,
null, // encoding
EurekaAccept.compact.name(),
null, // uriInfo
null // remote regions
);
String json = String.valueOf(response.getEntity());
DecoderWrapper decoder = CodecWrappers.getDecoder(CodecWrappers.LegacyJacksonJson.class);
Applications decoded = decoder.decode(json, Applications.class);
// test per app as the full apps list include the mock server that is not part of the test apps
for (Application application : testApplications.getRegisteredApplications()) {
Application decodedApp = decoded.getRegisteredApplications(application.getName());
// assert false as one is mini, so should NOT equal
assertThat(EurekaEntityComparators.equal(application, decodedApp), is(false));
}
for (Application application : testApplications.getRegisteredApplications()) {
Application decodedApp = decoded.getRegisteredApplications(application.getName());
assertThat(application.getName(), is(decodedApp.getName()));
// now do mini equals
for (InstanceInfo instanceInfo : application.getInstances()) {
InstanceInfo decodedInfo = decodedApp.getByInstanceId(instanceInfo.getId());
assertThat(EurekaEntityComparators.equalMini(instanceInfo, decodedInfo), is(true));
}
}
}
}
| 8,128 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/resources/PeerReplicationResourceTest.java | package com.netflix.eureka.resources;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.shared.transport.ClusterSampleData;
import com.netflix.eureka.EurekaServerConfig;
import com.netflix.eureka.EurekaServerContext;
import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl.Action;
import com.netflix.eureka.cluster.protocol.ReplicationInstance;
import com.netflix.eureka.cluster.protocol.ReplicationInstanceResponse;
import com.netflix.eureka.cluster.protocol.ReplicationList;
import com.netflix.eureka.cluster.protocol.ReplicationListResponse;
import org.junit.Before;
import org.junit.Test;
import static com.netflix.discovery.shared.transport.ClusterSampleData.newReplicationInstanceOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Tomasz Bak
*/
public class PeerReplicationResourceTest {
private final ApplicationResource applicationResource = mock(ApplicationResource.class);
private final InstanceResource instanceResource = mock(InstanceResource.class);
private EurekaServerContext serverContext;
private PeerReplicationResource peerReplicationResource;
private final InstanceInfo instanceInfo = ClusterSampleData.newInstanceInfo(0);
@Before
public void setUp() {
serverContext = mock(EurekaServerContext.class);
when(serverContext.getServerConfig()).thenReturn(mock(EurekaServerConfig.class));
peerReplicationResource = new PeerReplicationResource(serverContext) {
@Override
ApplicationResource createApplicationResource(ReplicationInstance instanceInfo) {
return applicationResource;
}
@Override
InstanceResource createInstanceResource(ReplicationInstance instanceInfo, ApplicationResource applicationResource) {
return instanceResource;
}
};
}
@Test
public void testRegisterBatching() throws Exception {
ReplicationList replicationList = new ReplicationList(newReplicationInstanceOf(Action.Register, instanceInfo));
Response response = peerReplicationResource.batchReplication(replicationList);
assertStatusOkReply(response);
verify(applicationResource, times(1)).addInstance(instanceInfo, "true");
}
@Test
public void testCancelBatching() throws Exception {
when(instanceResource.cancelLease(anyString())).thenReturn(Response.ok().build());
ReplicationList replicationList = new ReplicationList(newReplicationInstanceOf(Action.Cancel, instanceInfo));
Response response = peerReplicationResource.batchReplication(replicationList);
assertStatusOkReply(response);
verify(instanceResource, times(1)).cancelLease("true");
}
@Test
public void testHeartbeat() throws Exception {
when(instanceResource.renewLease(anyString(), anyString(), anyString(), anyString())).thenReturn(Response.ok().build());
ReplicationInstance replicationInstance = newReplicationInstanceOf(Action.Heartbeat, instanceInfo);
Response response = peerReplicationResource.batchReplication(new ReplicationList(replicationInstance));
assertStatusOkReply(response);
verify(instanceResource, times(1)).renewLease(
"true",
replicationInstance.getOverriddenStatus(),
instanceInfo.getStatus().name(),
Long.toString(replicationInstance.getLastDirtyTimestamp())
);
}
@Test
public void testConflictResponseReturnsTheInstanceInfoInTheResponseEntity() throws Exception {
when(instanceResource.renewLease(anyString(), anyString(), anyString(), anyString())).thenReturn(Response.status(Status.CONFLICT).entity(instanceInfo).build());
ReplicationInstance replicationInstance = newReplicationInstanceOf(Action.Heartbeat, instanceInfo);
Response response = peerReplicationResource.batchReplication(new ReplicationList(replicationInstance));
assertStatusIsConflict(response);
assertResponseEntityExist(response);
}
@Test
public void testStatusUpdate() throws Exception {
when(instanceResource.statusUpdate(anyString(), anyString(), anyString())).thenReturn(Response.ok().build());
ReplicationInstance replicationInstance = newReplicationInstanceOf(Action.StatusUpdate, instanceInfo);
Response response = peerReplicationResource.batchReplication(new ReplicationList(replicationInstance));
assertStatusOkReply(response);
verify(instanceResource, times(1)).statusUpdate(
replicationInstance.getStatus(),
"true",
Long.toString(replicationInstance.getLastDirtyTimestamp())
);
}
@Test
public void testDeleteStatusOverride() throws Exception {
when(instanceResource.deleteStatusUpdate(anyString(), anyString(), anyString())).thenReturn(Response.ok().build());
ReplicationInstance replicationInstance = newReplicationInstanceOf(Action.DeleteStatusOverride, instanceInfo);
Response response = peerReplicationResource.batchReplication(new ReplicationList(replicationInstance));
assertStatusOkReply(response);
verify(instanceResource, times(1)).deleteStatusUpdate(
"true",
replicationInstance.getStatus(),
Long.toString(replicationInstance.getLastDirtyTimestamp())
);
}
private static void assertStatusOkReply(Response httpResponse) {
assertStatus(httpResponse, 200);
}
private static void assertStatusIsConflict(Response httpResponse) {
assertStatus(httpResponse, 409);
}
private static void assertStatus(Response httpResponse, int expectedStatusCode) {
ReplicationListResponse entity = (ReplicationListResponse) httpResponse.getEntity();
assertThat(entity, is(notNullValue()));
ReplicationInstanceResponse replicationResponse = entity.getResponseList().get(0);
assertThat(replicationResponse.getStatusCode(), is(equalTo(expectedStatusCode)));
}
private static void assertResponseEntityExist(Response httpResponse) {
ReplicationListResponse entity = (ReplicationListResponse) httpResponse.getEntity();
assertThat(entity, is(notNullValue()));
ReplicationInstanceResponse replicationResponse = entity.getResponseList().get(0);
assertThat(replicationResponse.getResponseEntity(), is(notNullValue()));
}
}
| 8,129 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/resources/AbstractVIPResourceTest.java | package com.netflix.eureka.resources;
import com.netflix.appinfo.EurekaAccept;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.converters.wrappers.CodecWrappers;
import com.netflix.discovery.converters.wrappers.DecoderWrapper;
import com.netflix.discovery.shared.Application;
import com.netflix.discovery.shared.Applications;
import com.netflix.discovery.util.EurekaEntityComparators;
import com.netflix.discovery.util.InstanceInfoGenerator;
import com.netflix.eureka.AbstractTester;
import com.netflix.eureka.Version;
import com.netflix.eureka.registry.Key;
import org.junit.Before;
import org.junit.Test;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* @author David Liu
*/
public class AbstractVIPResourceTest extends AbstractTester {
private String vipName;
private AbstractVIPResource resource;
private Application testApplication;
@Override
@Before
public void setUp() throws Exception {
super.setUp();
InstanceInfoGenerator instanceInfos = InstanceInfoGenerator.newBuilder(6, 1).build();
testApplication = instanceInfos.toApplications().getRegisteredApplications().get(0);
resource = new AbstractVIPResource(serverContext) {
@Override
protected Response getVipResponse(String version, String entityName, String acceptHeader, EurekaAccept eurekaAccept, Key.EntityType entityType) {
return super.getVipResponse(version, entityName, acceptHeader, eurekaAccept, entityType);
}
};
vipName = testApplication.getName() + "#VIP";
for (InstanceInfo instanceInfo : testApplication.getInstances()) {
InstanceInfo changed = new InstanceInfo.Builder(instanceInfo)
.setASGName(null) // null asgName to get around AwsAsgUtil check
.setVIPAddress(vipName) // use the same vip address for all the instances in this test
.build();
registry.register(changed, false);
}
}
@Test
public void testFullVipGet() throws Exception {
Response response = resource.getVipResponse(
Version.V2.name(),
vipName,
MediaType.APPLICATION_JSON,
EurekaAccept.full,
Key.EntityType.VIP
);
String json = String.valueOf(response.getEntity());
DecoderWrapper decoder = CodecWrappers.getDecoder(CodecWrappers.LegacyJacksonJson.class);
Applications decodedApps = decoder.decode(json, Applications.class);
Application decodedApp = decodedApps.getRegisteredApplications(testApplication.getName());
assertThat(EurekaEntityComparators.equal(testApplication, decodedApp), is(true));
}
@Test
public void testMiniVipGet() throws Exception {
Response response = resource.getVipResponse(
Version.V2.name(),
vipName,
MediaType.APPLICATION_JSON,
EurekaAccept.compact,
Key.EntityType.VIP
);
String json = String.valueOf(response.getEntity());
DecoderWrapper decoder = CodecWrappers.getDecoder(CodecWrappers.LegacyJacksonJson.class);
Applications decodedApps = decoder.decode(json, Applications.class);
Application decodedApp = decodedApps.getRegisteredApplications(testApplication.getName());
// assert false as one is mini, so should NOT equal
assertThat(EurekaEntityComparators.equal(testApplication, decodedApp), is(false));
for (InstanceInfo instanceInfo : testApplication.getInstances()) {
InstanceInfo decodedInfo = decodedApp.getByInstanceId(instanceInfo.getId());
assertThat(EurekaEntityComparators.equalMini(instanceInfo, decodedInfo), is(true));
}
}
}
| 8,130 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/resources/ReplicationConcurrencyTest.java | package com.netflix.eureka.resources;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.MyDataCenterInstanceConfig;
import com.netflix.discovery.DefaultEurekaClientConfig;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.util.InstanceInfoGenerator;
import com.netflix.eureka.DefaultEurekaServerConfig;
import com.netflix.eureka.EurekaServerContext;
import com.netflix.eureka.cluster.PeerEurekaNode;
import com.netflix.eureka.cluster.PeerEurekaNodes;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import java.util.Collections;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* A pseudo mock test to test concurrent scenarios to do with registration and replication of cluster setups
* with 1+ eureka servers
*
* @author David Liu
*/
public class ReplicationConcurrencyTest {
private String id;
private String appName;
private InstanceInfo instance1;
private InstanceInfo instance2;
private MockServer server1;
private MockServer server2;
private InstanceInfo server1Sees;
private InstanceInfo server2Sees;
@Before
public void setUp() throws Exception {
InstanceInfo seed = InstanceInfoGenerator.takeOne();
id = seed.getId();
appName = seed.getAppName();
// set up test instances
instance1 = InstanceInfo.Builder.newBuilder()
.setInstanceId(id)
.setAppName(appName)
.setHostName(seed.getHostName())
.setIPAddr(seed.getIPAddr())
.setDataCenterInfo(seed.getDataCenterInfo())
.setStatus(InstanceInfo.InstanceStatus.STARTING)
.setLastDirtyTimestamp(11111l)
.build();
instance2 = new InstanceInfo.Builder(seed)
.setInstanceId(id)
.setAppName(appName)
.setHostName(seed.getHostName())
.setIPAddr(seed.getIPAddr())
.setDataCenterInfo(seed.getDataCenterInfo())
.setStatus(InstanceInfo.InstanceStatus.UP)
.setLastDirtyTimestamp(22222l)
.build();
assertThat(instance1.getStatus(), not(equalTo(instance2.getStatus())));
// set up server1 with no replication anywhere
PeerEurekaNodes server1Peers = Mockito.mock(PeerEurekaNodes.class);
Mockito.when(server1Peers.getPeerEurekaNodes()).thenReturn(Collections.<PeerEurekaNode>emptyList());
server1 = new MockServer(appName, server1Peers);
// set up server2
PeerEurekaNodes server2Peers = Mockito.mock(PeerEurekaNodes.class);
Mockito.when(server2Peers.getPeerEurekaNodes()).thenReturn(Collections.<PeerEurekaNode>emptyList());
server2 = new MockServer(appName, server2Peers);
// register with server1
server1.applicationResource.addInstance(instance1, "false"/* isReplication */); // STARTING
server1Sees = server1.registry.getInstanceByAppAndId(appName, id);
assertThat(server1Sees, equalTo(instance1));
// update (via a register) with server2
server2.applicationResource.addInstance(instance2, "false"/* isReplication */); // UP
server2Sees = server2.registry.getInstanceByAppAndId(appName, id);
assertThat(server2Sees, equalTo(instance2));
// make sure data in server 1 is "older"
assertThat(server2Sees.getLastDirtyTimestamp() > server1Sees.getLastDirtyTimestamp(), is(true));
}
/**
* this test tests a scenario where multiple registration and update requests for a single client is sent to
* different eureka servers before replication can occur between them
*/
@Test
public void testReplicationWithRegistrationAndUpdateOnDifferentServers() throws Exception {
// now simulate server1 (delayed) replication to server2.
// without batching this is done by server1 making a REST call to the register endpoint of server2 with
// replication=true
server2.applicationResource.addInstance(instance1, "true");
// verify that server2's "newer" info is (or is not) overridden
// server2 should still see instance2 even though server1 tried to replicate across server1
InstanceInfo newServer2Sees = server2.registry.getInstanceByAppAndId(appName, id);
assertThat(newServer2Sees.getStatus(), equalTo(instance2.getStatus()));
// now let server2 replicate to server1
server1.applicationResource.addInstance(newServer2Sees, "true");
// verify that server1 now have the updated info from server2
InstanceInfo newServer1Sees = server1.registry.getInstanceByAppAndId(appName, id);
assertThat(newServer1Sees.getStatus(), equalTo(instance2.getStatus()));
}
private static class MockServer {
public final ApplicationResource applicationResource;
public final PeerReplicationResource replicationResource;
public final PeerAwareInstanceRegistry registry;
public MockServer(String appName, PeerEurekaNodes peerEurekaNodes) throws Exception {
ApplicationInfoManager infoManager = new ApplicationInfoManager(new MyDataCenterInstanceConfig());
DefaultEurekaServerConfig serverConfig = Mockito.spy(new DefaultEurekaServerConfig());
DefaultEurekaClientConfig clientConfig = new DefaultEurekaClientConfig();
ServerCodecs serverCodecs = new DefaultServerCodecs(serverConfig);
EurekaClient eurekaClient = Mockito.mock(EurekaClient.class);
Mockito.doReturn("true").when(serverConfig).getExperimental("registry.registration.ignoreIfDirtyTimestampIsOlder");
this.registry = new PeerAwareInstanceRegistryImpl(serverConfig, clientConfig, serverCodecs, eurekaClient);
this.registry.init(peerEurekaNodes);
this.applicationResource = new ApplicationResource(appName, serverConfig, registry);
EurekaServerContext serverContext = Mockito.mock(EurekaServerContext.class);
Mockito.when(serverContext.getServerConfig()).thenReturn(serverConfig);
Mockito.when(serverContext.getRegistry()).thenReturn(registry);
this.replicationResource = new PeerReplicationResource(serverContext);
}
}
}
| 8,131 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/resources/ApplicationResourceTest.java | package com.netflix.eureka.resources;
import com.netflix.appinfo.AmazonInfo;
import com.netflix.appinfo.DataCenterInfo;
import com.netflix.appinfo.EurekaAccept;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.UniqueIdentifier;
import com.netflix.config.ConfigurationManager;
import com.netflix.discovery.converters.wrappers.CodecWrappers;
import com.netflix.discovery.converters.wrappers.DecoderWrapper;
import com.netflix.discovery.shared.Application;
import com.netflix.discovery.util.EurekaEntityComparators;
import com.netflix.discovery.util.InstanceInfoGenerator;
import com.netflix.eureka.AbstractTester;
import com.netflix.eureka.Version;
import org.junit.Before;
import org.junit.Test;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
/**
* @author David Liu
*/
public class ApplicationResourceTest extends AbstractTester {
private ApplicationResource applicationResource;
private Application testApplication;
@Override
@Before
public void setUp() throws Exception {
super.setUp();
InstanceInfoGenerator instanceInfos = InstanceInfoGenerator.newBuilder(6, 1).build();
testApplication = instanceInfos.toApplications().getRegisteredApplications().get(0);
applicationResource = new ApplicationResource(testApplication.getName(), serverContext.getServerConfig(), serverContext.getRegistry());
for (InstanceInfo instanceInfo : testApplication.getInstances()) {
registry.register(instanceInfo, false);
}
}
@Test
public void testFullAppGet() throws Exception {
Response response = applicationResource.getApplication(
Version.V2.name(),
MediaType.APPLICATION_JSON,
EurekaAccept.full.name()
);
String json = String.valueOf(response.getEntity());
DecoderWrapper decoder = CodecWrappers.getDecoder(CodecWrappers.LegacyJacksonJson.class);
Application decodedApp = decoder.decode(json, Application.class);
assertThat(EurekaEntityComparators.equal(testApplication, decodedApp), is(true));
}
@Test
public void testMiniAppGet() throws Exception {
Response response = applicationResource.getApplication(
Version.V2.name(),
MediaType.APPLICATION_JSON,
EurekaAccept.compact.name()
);
String json = String.valueOf(response.getEntity());
DecoderWrapper decoder = CodecWrappers.getDecoder(CodecWrappers.LegacyJacksonJson.class);
Application decodedApp = decoder.decode(json, Application.class);
// assert false as one is mini, so should NOT equal
assertThat(EurekaEntityComparators.equal(testApplication, decodedApp), is(false));
for (InstanceInfo instanceInfo : testApplication.getInstances()) {
InstanceInfo decodedInfo = decodedApp.getByInstanceId(instanceInfo.getId());
assertThat(EurekaEntityComparators.equalMini(instanceInfo, decodedInfo), is(true));
}
}
@Test
public void testGoodRegistration() throws Exception {
InstanceInfo noIdInfo = InstanceInfoGenerator.takeOne();
Response response = applicationResource.addInstance(noIdInfo, false+"");
assertThat(response.getStatus(), is(204));
}
@Test
public void testBadRegistration() throws Exception {
InstanceInfo instanceInfo = spy(InstanceInfoGenerator.takeOne());
when(instanceInfo.getId()).thenReturn(null);
Response response = applicationResource.addInstance(instanceInfo, false+"");
assertThat(response.getStatus(), is(400));
instanceInfo = spy(InstanceInfoGenerator.takeOne());
when(instanceInfo.getHostName()).thenReturn(null);
response = applicationResource.addInstance(instanceInfo, false+"");
assertThat(response.getStatus(), is(400));
instanceInfo = spy(InstanceInfoGenerator.takeOne());
when(instanceInfo.getIPAddr()).thenReturn(null);
response = applicationResource.addInstance(instanceInfo, false+"");
assertThat(response.getStatus(), is(400));
instanceInfo = spy(InstanceInfoGenerator.takeOne());
when(instanceInfo.getAppName()).thenReturn("");
response = applicationResource.addInstance(instanceInfo, false+"");
assertThat(response.getStatus(), is(400));
instanceInfo = spy(InstanceInfoGenerator.takeOne());
when(instanceInfo.getAppName()).thenReturn(applicationResource.getName() + "extraExtra");
response = applicationResource.addInstance(instanceInfo, false+"");
assertThat(response.getStatus(), is(400));
instanceInfo = spy(InstanceInfoGenerator.takeOne());
when(instanceInfo.getDataCenterInfo()).thenReturn(null);
response = applicationResource.addInstance(instanceInfo, false+"");
assertThat(response.getStatus(), is(400));
instanceInfo = spy(InstanceInfoGenerator.takeOne());
when(instanceInfo.getDataCenterInfo()).thenReturn(new DataCenterInfo() {
@Override
public Name getName() {
return null;
}
});
response = applicationResource.addInstance(instanceInfo, false+"");
assertThat(response.getStatus(), is(400));
}
@Test
public void testBadRegistrationOfDataCenterInfo() throws Exception {
try {
// test 400 when configured to return client error
ConfigurationManager.getConfigInstance().setProperty("eureka.experimental.registration.validation.dataCenterInfoId", "true");
InstanceInfo instanceInfo = spy(InstanceInfoGenerator.takeOne());
when(instanceInfo.getDataCenterInfo()).thenReturn(new TestDataCenterInfo());
Response response = applicationResource.addInstance(instanceInfo, false + "");
assertThat(response.getStatus(), is(400));
// test backfill of data for AmazonInfo
ConfigurationManager.getConfigInstance().setProperty("eureka.experimental.registration.validation.dataCenterInfoId", "false");
instanceInfo = spy(InstanceInfoGenerator.takeOne());
assertThat(instanceInfo.getDataCenterInfo(), instanceOf(AmazonInfo.class));
((AmazonInfo) instanceInfo.getDataCenterInfo()).getMetadata().remove(AmazonInfo.MetaDataKey.instanceId.getName()); // clear the Id
response = applicationResource.addInstance(instanceInfo, false + "");
assertThat(response.getStatus(), is(204));
} finally {
ConfigurationManager.getConfigInstance().clearProperty("eureka.experimental.registration.validation.dataCenterInfoId");
}
}
private static class TestDataCenterInfo implements DataCenterInfo, UniqueIdentifier {
@Override
public Name getName() {
return Name.MyOwn;
}
@Override
public String getId() {
return null; // return null to test
}
}
}
| 8,132 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/resources/InstanceResourceTest.java | package com.netflix.eureka.resources;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import com.netflix.eureka.AbstractTester;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class InstanceResourceTest extends AbstractTester {
private final InstanceInfo testInstanceInfo = createLocalInstance(LOCAL_REGION_INSTANCE_1_HOSTNAME);
private ApplicationResource applicationResource;
private InstanceResource instanceResource;
@Override
@Before
public void setUp() throws Exception {
super.setUp();
applicationResource = new ApplicationResource(testInstanceInfo.getAppName(), serverContext.getServerConfig(), serverContext.getRegistry());
instanceResource = new InstanceResource(applicationResource, testInstanceInfo.getId(), serverContext.getServerConfig(), serverContext.getRegistry());
}
@Test
public void testStatusOverrideReturnsNotFoundErrorCodeIfInstanceNotRegistered() throws Exception {
Response response = instanceResource.statusUpdate(InstanceStatus.OUT_OF_SERVICE.name(), "false", "0");
assertThat(response.getStatus(), is(equalTo(Status.NOT_FOUND.getStatusCode())));
}
@Test
public void testStatusOverrideDeleteReturnsNotFoundErrorCodeIfInstanceNotRegistered() throws Exception {
Response response = instanceResource.deleteStatusUpdate(InstanceStatus.OUT_OF_SERVICE.name(), "false", "0");
assertThat(response.getStatus(), is(equalTo(Status.NOT_FOUND.getStatusCode())));
}
@Test
public void testStatusOverrideDeleteIsAppliedToRegistry() throws Exception {
// Override instance status
registry.register(testInstanceInfo, false);
registry.statusUpdate(testInstanceInfo.getAppName(), testInstanceInfo.getId(), InstanceStatus.OUT_OF_SERVICE, "0", false);
assertThat(testInstanceInfo.getStatus(), is(equalTo(InstanceStatus.OUT_OF_SERVICE)));
// Remove the override
Response response = instanceResource.deleteStatusUpdate("false", null, "0");
assertThat(response.getStatus(), is(equalTo(200)));
assertThat(testInstanceInfo.getStatus(), is(equalTo(InstanceStatus.UNKNOWN)));
}
@Test
public void testStatusOverrideDeleteIsAppliedToRegistryAndProvidedStatusIsSet() throws Exception {
// Override instance status
registry.register(testInstanceInfo, false);
registry.statusUpdate(testInstanceInfo.getAppName(), testInstanceInfo.getId(), InstanceStatus.OUT_OF_SERVICE, "0", false);
assertThat(testInstanceInfo.getStatus(), is(equalTo(InstanceStatus.OUT_OF_SERVICE)));
// Remove the override
Response response = instanceResource.deleteStatusUpdate("false", "DOWN", "0");
assertThat(response.getStatus(), is(equalTo(200)));
assertThat(testInstanceInfo.getStatus(), is(equalTo(InstanceStatus.DOWN)));
}
} | 8,133 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/registry/AwsInstanceRegistryTest.java | package com.netflix.eureka.registry;
import com.netflix.appinfo.AmazonInfo;
import com.netflix.appinfo.DataCenterInfo;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import com.netflix.appinfo.LeaseInfo;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.eureka.EurekaServerConfig;
import com.netflix.eureka.resources.ServerCodecs;
import org.junit.Test;
/**
* Created by Nikos Michalakis on 7/14/16.
*/
public class AwsInstanceRegistryTest extends InstanceRegistryTest {
@Test
public void testOverridesWithAsgEnabledThenDisabled() {
// Regular registration first
InstanceInfo myInstance = createLocalUpInstanceWithAsg(LOCAL_REGION_INSTANCE_1_HOSTNAME);
registerInstanceLocally(myInstance);
verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.UP);
// Now we disable the ASG and we should expect OUT_OF_SERVICE status.
((AwsInstanceRegistry) registry).getAwsAsgUtil().setStatus(myInstance.getASGName(), false);
myInstance = createLocalUpInstanceWithAsg(LOCAL_REGION_INSTANCE_1_HOSTNAME);
registerInstanceLocally(myInstance);
verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.OUT_OF_SERVICE);
// Now we re-enable the ASG and we should expect UP status.
((AwsInstanceRegistry) registry).getAwsAsgUtil().setStatus(myInstance.getASGName(), true);
myInstance = createLocalUpInstanceWithAsg(LOCAL_REGION_INSTANCE_1_HOSTNAME);
registerInstanceLocally(myInstance);
verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.UP);
}
private static InstanceInfo createLocalUpInstanceWithAsg(String hostname) {
InstanceInfo.Builder instanceBuilder = InstanceInfo.Builder.newBuilder();
instanceBuilder.setAppName(LOCAL_REGION_APP_NAME);
instanceBuilder.setHostName(hostname);
instanceBuilder.setIPAddr("10.10.101.1");
instanceBuilder.setDataCenterInfo(getAmazonInfo(hostname));
instanceBuilder.setLeaseInfo(LeaseInfo.Builder.newBuilder().build());
instanceBuilder.setStatus(InstanceStatus.UP);
instanceBuilder.setASGName("ASG-YO-HO");
return instanceBuilder.build();
}
private static AmazonInfo getAmazonInfo(String instanceHostName) {
AmazonInfo.Builder azBuilder = AmazonInfo.Builder.newBuilder();
azBuilder.addMetadata(AmazonInfo.MetaDataKey.availabilityZone, "us-east-1a");
azBuilder.addMetadata(AmazonInfo.MetaDataKey.instanceId, instanceHostName);
azBuilder.addMetadata(AmazonInfo.MetaDataKey.amiId, "XXX");
azBuilder.addMetadata(AmazonInfo.MetaDataKey.instanceType, "XXX");
azBuilder.addMetadata(AmazonInfo.MetaDataKey.localIpv4, "XXX");
azBuilder.addMetadata(AmazonInfo.MetaDataKey.publicIpv4, "XXX");
azBuilder.addMetadata(AmazonInfo.MetaDataKey.publicHostname, instanceHostName);
return azBuilder.build();
}
@Override
protected DataCenterInfo getDataCenterInfo() {
return getAmazonInfo(LOCAL_REGION_INSTANCE_1_HOSTNAME);
}
@Override
protected PeerAwareInstanceRegistryImpl makePeerAwareInstanceRegistry(EurekaServerConfig serverConfig,
EurekaClientConfig clientConfig,
ServerCodecs serverCodecs,
EurekaClient eurekaClient) {
return new TestAwsInstanceRegistry(serverConfig, clientConfig, serverCodecs, eurekaClient);
}
private static class TestAwsInstanceRegistry extends AwsInstanceRegistry {
public TestAwsInstanceRegistry(EurekaServerConfig serverConfig,
EurekaClientConfig clientConfig,
ServerCodecs serverCodecs,
EurekaClient eurekaClient) {
super(serverConfig, clientConfig, serverCodecs, eurekaClient);
}
@Override
public boolean isLeaseExpirationEnabled() {
return false;
}
@Override
public InstanceInfo getNextServerFromEureka(String virtualHostname, boolean secure) {
return null;
}
}
}
| 8,134 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/registry/InstanceRegistryTest.java | package com.netflix.eureka.registry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import com.netflix.discovery.shared.Application;
import com.netflix.discovery.shared.Applications;
import com.netflix.eureka.AbstractTester;
import com.netflix.eureka.registry.AbstractInstanceRegistry.CircularQueue;
import com.netflix.eureka.registry.AbstractInstanceRegistry.EvictionTask;
import org.junit.Assert;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
/**
* @author Nitesh Kant
*/
public class InstanceRegistryTest extends AbstractTester {
@Test
public void testSoftDepRemoteUp() throws Exception {
Assert.assertTrue("Registry access disallowed when remote region is UP.", registry.shouldAllowAccess(false));
Assert.assertTrue("Registry access disallowed when remote region is UP.", registry.shouldAllowAccess(true));
}
@Test
public void testGetAppsFromAllRemoteRegions() throws Exception {
Applications apps = registry.getApplicationsFromAllRemoteRegions();
List<Application> registeredApplications = apps.getRegisteredApplications();
Assert.assertEquals("Apps size from remote regions do not match", 1, registeredApplications.size());
Application app = registeredApplications.iterator().next();
Assert.assertEquals("Added app did not return from remote registry", REMOTE_REGION_APP_NAME, app.getName());
Assert.assertEquals("Returned app did not have the instance", 1, app.getInstances().size());
}
@Test
public void testGetAppsDeltaFromAllRemoteRegions() throws Exception {
registerInstanceLocally(createLocalInstance(LOCAL_REGION_INSTANCE_2_HOSTNAME)); /// local delta
waitForDeltaToBeRetrieved();
Applications appDelta = registry.getApplicationDeltasFromMultipleRegions(null);
List<Application> registeredApplications = appDelta.getRegisteredApplications();
Assert.assertEquals("Apps size from remote regions do not match", 2, registeredApplications.size());
Application localApplication = null;
Application remApplication = null;
for (Application registeredApplication : registeredApplications) {
if (registeredApplication.getName().equalsIgnoreCase(LOCAL_REGION_APP_NAME)) {
localApplication = registeredApplication;
}
if (registeredApplication.getName().equalsIgnoreCase(REMOTE_REGION_APP_NAME)) {
remApplication = registeredApplication;
}
}
Assert.assertNotNull("Did not find local registry app in delta.", localApplication);
Assert.assertEquals("Local registry app instance count in delta not as expected.", 1,
localApplication.getInstances().size());
Assert.assertNotNull("Did not find remote registry app in delta", remApplication);
Assert.assertEquals("Remote registry app instance count in delta not as expected.", 1,
remApplication.getInstances().size());
}
@Test
public void testAppsHashCodeAfterRefresh() throws InterruptedException {
Assert.assertEquals("UP_1_", registry.getApplicationsFromAllRemoteRegions().getAppsHashCode());
registerInstanceLocally(createLocalInstance(LOCAL_REGION_INSTANCE_2_HOSTNAME));
waitForDeltaToBeRetrieved();
Assert.assertEquals("UP_2_", registry.getApplicationsFromAllRemoteRegions().getAppsHashCode());
}
private void waitForDeltaToBeRetrieved() throws InterruptedException {
int count = 0;
System.out.println("Sleeping up to 35 seconds to let the remote registry fetch delta.");
while (count++ < 35 && !mockRemoteEurekaServer.isSentDelta()) {
Thread.sleep(1000);
}
if (!mockRemoteEurekaServer.isSentDelta()) {
System.out.println("Waited for 35 seconds but remote server did not send delta");
}
// Wait 2 seconds more to be sure the delta was processed
Thread.sleep(2000);
}
@Test
public void testGetAppsFromLocalRegionOnly() throws Exception {
registerInstanceLocally(createLocalInstance(LOCAL_REGION_INSTANCE_1_HOSTNAME));
Applications apps = registry.getApplicationsFromLocalRegionOnly();
List<Application> registeredApplications = apps.getRegisteredApplications();
Assert.assertEquals("Apps size from local region do not match", 1, registeredApplications.size());
Application app = registeredApplications.iterator().next();
Assert.assertEquals("Added app did not return from local registry", LOCAL_REGION_APP_NAME, app.getName());
Assert.assertEquals("Returned app did not have the instance", 1, app.getInstances().size());
}
@Test
public void testGetAppsFromBothRegions() throws Exception {
registerInstanceLocally(createRemoteInstance(LOCAL_REGION_INSTANCE_2_HOSTNAME));
registerInstanceLocally(createLocalInstance(LOCAL_REGION_INSTANCE_1_HOSTNAME));
Applications apps = registry.getApplicationsFromAllRemoteRegions();
List<Application> registeredApplications = apps.getRegisteredApplications();
Assert.assertEquals("Apps size from both regions do not match", 2, registeredApplications.size());
Application locaApplication = null;
Application remApplication = null;
for (Application registeredApplication : registeredApplications) {
if (registeredApplication.getName().equalsIgnoreCase(LOCAL_REGION_APP_NAME)) {
locaApplication = registeredApplication;
}
if (registeredApplication.getName().equalsIgnoreCase(REMOTE_REGION_APP_NAME)) {
remApplication = registeredApplication;
}
}
Assert.assertNotNull("Did not find local registry app", locaApplication);
Assert.assertEquals("Local registry app instance count not as expected.", 1,
locaApplication.getInstances().size());
Assert.assertNotNull("Did not find remote registry app", remApplication);
Assert.assertEquals("Remote registry app instance count not as expected.", 2,
remApplication.getInstances().size());
}
@Test
public void testStatusOverrideSetAndRemoval() throws Exception {
InstanceInfo seed = createLocalInstance(LOCAL_REGION_INSTANCE_1_HOSTNAME);
seed.setLastDirtyTimestamp(100l);
// Regular registration first
InstanceInfo myInstance1 = new InstanceInfo(seed);
registerInstanceLocally(myInstance1);
verifyLocalInstanceStatus(myInstance1.getId(), InstanceStatus.UP);
// Override status
boolean statusResult = registry.statusUpdate(LOCAL_REGION_APP_NAME, seed.getId(), InstanceStatus.OUT_OF_SERVICE, "0", false);
assertThat("Couldn't override instance status", statusResult, is(true));
verifyLocalInstanceStatus(seed.getId(), InstanceStatus.OUT_OF_SERVICE);
// Register again with status UP to verify that the override is still in place even if the dirtytimestamp is higher
InstanceInfo myInstance2 = new InstanceInfo(seed); // clone to avoid object state in this test
myInstance2.setLastDirtyTimestamp(200l); // use a later 'client side' dirty timestamp
registry.register(myInstance2, 10000000, false);
verifyLocalInstanceStatus(seed.getId(), InstanceStatus.OUT_OF_SERVICE);
// Now remove override
statusResult = registry.deleteStatusOverride(LOCAL_REGION_APP_NAME, seed.getId(), InstanceStatus.DOWN, "0", false);
assertThat("Couldn't remove status override", statusResult, is(true));
verifyLocalInstanceStatus(seed.getId(), InstanceStatus.DOWN);
// Register again with status UP after the override deletion, keeping myInstance2's dirtyTimestamp (== no client side change)
InstanceInfo myInstance3 = new InstanceInfo(seed); // clone to avoid object state in this test
myInstance3.setLastDirtyTimestamp(200l); // use a later 'client side' dirty timestamp
registry.register(myInstance3, 10000000, false);
verifyLocalInstanceStatus(seed.getId(), InstanceStatus.UP);
}
@Test
public void testStatusOverrideWithRenewAppliedToAReplica() throws Exception {
InstanceInfo seed = createLocalInstance(LOCAL_REGION_INSTANCE_1_HOSTNAME);
seed.setLastDirtyTimestamp(100l);
// Regular registration first
InstanceInfo myInstance1 = new InstanceInfo(seed);
registerInstanceLocally(myInstance1);
verifyLocalInstanceStatus(myInstance1.getId(), InstanceStatus.UP);
// Override status
boolean statusResult = registry.statusUpdate(LOCAL_REGION_APP_NAME, seed.getId(), InstanceStatus.OUT_OF_SERVICE, "0", false);
assertThat("Couldn't override instance status", statusResult, is(true));
verifyLocalInstanceStatus(seed.getId(), InstanceStatus.OUT_OF_SERVICE);
// Send a renew to ensure timestamps are consistent even with the override in existence.
// To do this, we get hold of the registry local InstanceInfo and reset its status to before an override
// has been applied
// (this is to simulate a case in a replica server where the override has been replicated, but not yet
// applied to the local InstanceInfo)
InstanceInfo registeredInstance = registry.getInstanceByAppAndId(seed.getAppName(), seed.getId());
registeredInstance.setStatusWithoutDirty(InstanceStatus.UP);
verifyLocalInstanceStatus(seed.getId(), InstanceStatus.UP);
registry.renew(seed.getAppName(), seed.getId(), false);
verifyLocalInstanceStatus(seed.getId(), InstanceStatus.OUT_OF_SERVICE);
// Now remove override
statusResult = registry.deleteStatusOverride(LOCAL_REGION_APP_NAME, seed.getId(), InstanceStatus.DOWN, "0", false);
assertThat("Couldn't remove status override", statusResult, is(true));
verifyLocalInstanceStatus(seed.getId(), InstanceStatus.DOWN);
// Register again with status UP after the override deletion, keeping myInstance2's dirtyTimestamp (== no client side change)
InstanceInfo myInstance3 = new InstanceInfo(seed); // clone to avoid object state in this test
myInstance3.setLastDirtyTimestamp(200l); // use a later 'client side' dirty timestamp
registry.register(myInstance3, 10000000, false);
verifyLocalInstanceStatus(seed.getId(), InstanceStatus.UP);
}
@Test
public void testStatusOverrideStartingStatus() throws Exception {
// Regular registration first
InstanceInfo myInstance = createLocalInstance(LOCAL_REGION_INSTANCE_1_HOSTNAME);
registerInstanceLocally(myInstance);
verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.UP);
// Override status
boolean statusResult = registry.statusUpdate(LOCAL_REGION_APP_NAME, myInstance.getId(), InstanceStatus.OUT_OF_SERVICE, "0", false);
assertThat("Couldn't override instance status", statusResult, is(true));
verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.OUT_OF_SERVICE);
// If we are not UP or OUT_OF_SERVICE, the OUT_OF_SERVICE override does not apply. It gets trumped by the current
// status (STARTING or DOWN). Here we test with STARTING.
myInstance = createLocalStartingInstance(LOCAL_REGION_INSTANCE_1_HOSTNAME);
registerInstanceLocally(myInstance);
verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.STARTING);
}
@Test
public void testStatusOverrideWithExistingLeaseUp() throws Exception {
// Without an override we expect to get the existing UP lease when we re-register with OUT_OF_SERVICE.
// First, we are "up".
InstanceInfo myInstance = createLocalInstance(LOCAL_REGION_INSTANCE_1_HOSTNAME);
registerInstanceLocally(myInstance);
verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.UP);
// Then, we re-register with "out of service".
InstanceInfo sameInstance = createLocalOutOfServiceInstance(LOCAL_REGION_INSTANCE_1_HOSTNAME);
registry.register(sameInstance, 10000000, false);
verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.UP);
// Let's try again. We shouldn't see a difference.
sameInstance = createLocalOutOfServiceInstance(LOCAL_REGION_INSTANCE_1_HOSTNAME);
registry.register(sameInstance, 10000000, false);
verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.UP);
}
@Test
public void testStatusOverrideWithExistingLeaseOutOfService() throws Exception {
// Without an override we expect to get the existing OUT_OF_SERVICE lease when we re-register with UP.
// First, we are "out of service".
InstanceInfo myInstance = createLocalOutOfServiceInstance(LOCAL_REGION_INSTANCE_1_HOSTNAME);
registerInstanceLocally(myInstance);
verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.OUT_OF_SERVICE);
// Then, we re-register with "UP".
InstanceInfo sameInstance = createLocalInstance(LOCAL_REGION_INSTANCE_1_HOSTNAME);
registry.register(sameInstance, 10000000, false);
verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.OUT_OF_SERVICE);
// Let's try again. We shouldn't see a difference.
sameInstance = createLocalInstance(LOCAL_REGION_INSTANCE_1_HOSTNAME);
registry.register(sameInstance, 10000000, false);
verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.OUT_OF_SERVICE);
}
@Test
public void testEvictionTaskCompensationTime() throws Exception {
long evictionTaskPeriodNanos = serverConfig.getEvictionIntervalTimerInMs() * 1000000;
AbstractInstanceRegistry.EvictionTask testTask = spy(registry.new EvictionTask());
when(testTask.getCurrentTimeNano())
.thenReturn(1l) // less than the period
.thenReturn(1l + evictionTaskPeriodNanos) // exactly 1 period
.thenReturn(1l + evictionTaskPeriodNanos*2 + 10000000l) // 10ms longer than 1 period
.thenReturn(1l + evictionTaskPeriodNanos*3 - 1l); // less than 1 period
assertThat(testTask.getCompensationTimeMs(), is(0l));
assertThat(testTask.getCompensationTimeMs(), is(0l));
assertThat(testTask.getCompensationTimeMs(), is(10l));
assertThat(testTask.getCompensationTimeMs(), is(0l));
}
@Test
public void testCircularQueue() throws Exception {
CircularQueue<Integer> queue = new CircularQueue<>(5);
Assert.assertEquals(0, queue.size());
Assert.assertNull(queue.peek());
Assert.assertEquals(Collections.emptyList(), new ArrayList<>(queue));
queue.add(1);
queue.add(2);
queue.add(3);
queue.add(4);
Assert.assertEquals(4, queue.size());
Assert.assertEquals(Arrays.asList(1, 2, 3, 4), new ArrayList<>(queue));
queue.offer(5);
Assert.assertEquals(5, queue.size());
Assert.assertEquals(Arrays.asList(1, 2, 3, 4, 5), new ArrayList<>(queue));
queue.offer(6);
Assert.assertEquals(5, queue.size());
Assert.assertEquals(Arrays.asList(2, 3, 4, 5, 6), new ArrayList<>(queue));
Integer poll = queue.poll();
Assert.assertEquals(4, queue.size());
Assert.assertEquals((Object) 2, poll);
Assert.assertEquals(Arrays.asList(3, 4, 5, 6), new ArrayList<>(queue));
queue.add(7);
Assert.assertEquals(5, queue.size());
Assert.assertEquals(Arrays.asList(3, 4, 5, 6, 7), new ArrayList<>(queue));
queue.clear();
Assert.assertEquals(0, queue.size());
Assert.assertEquals(Collections.emptyList(), new ArrayList<>(queue));
}
}
| 8,135 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/registry/TimeConsumingInstanceRegistryTest.java | package com.netflix.eureka.registry;
import com.google.common.base.Preconditions;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import com.netflix.eureka.AbstractTester;
import com.netflix.eureka.EurekaServerConfig;
import com.netflix.eureka.test.async.executor.AsyncResult;
import com.netflix.eureka.test.async.executor.AsyncSequentialExecutor;
import com.netflix.eureka.test.async.executor.SequentialEvents;
import com.netflix.eureka.test.async.executor.SingleEvent;
import org.junit.Assert;
import org.junit.Test;
/**
* Time consuming test case for {@link InstanceRegistry}.
*
* @author neoremind
*/
public class TimeConsumingInstanceRegistryTest extends AbstractTester {
/**
* Verify the following behaviors, the test case will run for 2 minutes.
* <ul>
* <li>1. Registration of new instances.</li>
* <li>2. Lease expiration.</li>
* <li>3. NumOfRenewsPerMinThreshold will be updated. Since this threshold will be updated according to
* {@link EurekaServerConfig#getRenewalThresholdUpdateIntervalMs()}, and discovery client will try to get
* applications count from peer or remote Eureka servers, the count number will be used to update threshold.</li>
* </ul>
* </p>
* Below shows the time line of a bunch of events in 120 seconds. Here the following setting are configured during registry startup:
* <code>eureka.renewalThresholdUpdateIntervalMs=5000</code>,
* <code>eureka.evictionIntervalTimerInMs=10000</code>,
* <code>eureka.renewalPercentThreshold=0.85</code>
* </p>
* <pre>
* TimeInSecs 0 15 30 40 45 60 75 80 90 105 120
* |----------|----------|------|----|----------|---------|----|-------|----------|---------|
* Events (1) (2) (3) (4) (5) (6) (7) (8) (9)
* </pre>
* </p>
* <ul>
* <li>(1). Remote server started on random port, local registry started as well.
* 50 instances will be registered to local registry with application name of {@link #LOCAL_REGION_APP_NAME}
* and lease duration set to 30 seconds.
* At this time isLeaseExpirationEnabled=false, getNumOfRenewsPerMinThreshold=
* (50*2 + 1(initial value))*85%=86</li>
* <li>(2). 45 out of the 50 instances send heartbeats to local registry.</li>
* <li>(3). Check registry status, isLeaseExpirationEnabled=false, getNumOfRenewsInLastMin=0,
* getNumOfRenewsPerMinThreshold=86, registeredInstancesNumberOfMYLOCALAPP=50</li>
* <li>(4). 45 out of the 50 instances send heartbeats to local registry.</li>
* <li>(5). Accumulate one minutes data, and from now on, isLeaseExpirationEnabled=true,
* getNumOfRenewsInLastMin=90. Because lease expiration is enabled, and lease for 5 instance are expired,
* so when eviction thread is working, the 5 instances will be marked as deleted.</li>
* <li>(6). 45 out of the 50 instances send heartbeats to local registry.</li>
* <li>(7). Check registry status, isLeaseExpirationEnabled=true, getNumOfRenewsInLastMin=90,
* getNumOfRenewsPerMinThreshold=86, registeredInstancesNumberOfMYLOCALAPP=45</li>
* Remote region add another 150 instances to application of {@link #LOCAL_REGION_APP_NAME}.
* This will make {@link PeerAwareInstanceRegistryImpl#updateRenewalThreshold()} to refresh
* {@link AbstractInstanceRegistry#numberOfRenewsPerMinThreshold}.</li>
* <li>(8). 45 out of the 50 instances send heartbeats to local registry.</li>
* <li>(9). Check registry status, isLeaseExpirationEnabled=false, getNumOfRenewsInLastMin=90,
* getNumOfRenewsPerMinThreshold=256, registeredInstancesNumberOfMYLOCALAPP=45</li>
* </ul>
* </p>
* Note that there is a thread retrieving and printing out registry status for debugging purpose.
*/
@Test
public void testLeaseExpirationAndUpdateRenewalThreshold() throws InterruptedException {
final int registeredInstanceCount = 50;
final int leaseDurationInSecs = 30;
AsyncSequentialExecutor executor = new AsyncSequentialExecutor();
SequentialEvents registerMyLocalAppAndInstancesEvents = SequentialEvents.of(
buildEvent(0, new SingleEvent.Action() {
@Override
public void execute() {
for (int j = 0; j < registeredInstanceCount; j++) {
registerInstanceLocallyWithLeaseDurationInSecs(createLocalInstanceWithIdAndStatus(LOCAL_REGION_APP_NAME,
LOCAL_REGION_INSTANCE_1_HOSTNAME + j, InstanceStatus.UP), leaseDurationInSecs);
}
}
})
);
SequentialEvents showRegistryStatusEvents = SequentialEvents.of(
buildEvents(5, 24, new SingleEvent.Action() {
@Override
public void execute() {
System.out.println(String.format("isLeaseExpirationEnabled=%s, getNumOfRenewsInLastMin=%d, "
+ "getNumOfRenewsPerMinThreshold=%s, instanceNumberOfMYLOCALAPP=%d", registry.isLeaseExpirationEnabled(),
registry.getNumOfRenewsInLastMin(), registry.getNumOfRenewsPerMinThreshold(),
registry.getApplication(LOCAL_REGION_APP_NAME).getInstances().size()));
}
})
);
SequentialEvents renewEvents = SequentialEvents.of(
buildEvent(15, renewPartOfTheWholeInstancesAction()),
buildEvent(30, renewPartOfTheWholeInstancesAction()),
buildEvent(30, renewPartOfTheWholeInstancesAction()),
buildEvent(30, renewPartOfTheWholeInstancesAction())
);
SequentialEvents remoteRegionAddMoreInstancesEvents = SequentialEvents.of(
buildEvent(90, new SingleEvent.Action() {
@Override
public void execute() {
for (int i = 0; i < 150; i++) {
InstanceInfo newlyCreatedInstance = createLocalInstanceWithIdAndStatus(REMOTE_REGION_APP_NAME,
LOCAL_REGION_INSTANCE_1_HOSTNAME + i, InstanceStatus.UP);
remoteRegionApps.get(REMOTE_REGION_APP_NAME).addInstance(newlyCreatedInstance);
remoteRegionAppsDelta.get(REMOTE_REGION_APP_NAME).addInstance(newlyCreatedInstance);
}
}
})
);
SequentialEvents checkEvents = SequentialEvents.of(
buildEvent(40, new SingleEvent.Action() {
@Override
public void execute() {
System.out.println("checking on 40s");
Preconditions.checkState(Boolean.FALSE.equals(registry.isLeaseExpirationEnabled()), "Lease expiration should be disabled");
Preconditions.checkState(registry.getNumOfRenewsInLastMin() == 0, "Renewals in last min should be 0");
Preconditions.checkState(registry.getApplication(LOCAL_REGION_APP_NAME).getInstances().size() == 50,
"There should be 50 instances in application - MYLOCAPP");
}
}),
buildEvent(40, new SingleEvent.Action() {
@Override
public void execute() {
System.out.println("checking on 80s");
Preconditions.checkState(Boolean.TRUE.equals(registry.isLeaseExpirationEnabled()), "Lease expiration should be enabled");
Preconditions.checkState(registry.getNumOfRenewsInLastMin() == 90, "Renewals in last min should be 90");
Preconditions.checkState(registry.getApplication(LOCAL_REGION_APP_NAME).getInstances().size() == 45,
"There should be 45 instances in application - MYLOCAPP");
}
}),
buildEvent(40, new SingleEvent.Action() {
@Override
public void execute() {
System.out.println("checking on 120s");
System.out.println("getNumOfRenewsPerMinThreshold=" + registry.getNumOfRenewsPerMinThreshold());
Preconditions.checkState(registry.getNumOfRenewsPerMinThreshold() == 256, "NumOfRenewsPerMinThreshold should be updated to 256");
Preconditions.checkState(registry.getApplication(LOCAL_REGION_APP_NAME).getInstances().size() == 45,
"There should be 45 instances in application - MYLOCAPP");
}
})
);
AsyncResult<AsyncSequentialExecutor.ResultStatus> registerMyLocalAppAndInstancesResult = executor.run(registerMyLocalAppAndInstancesEvents);
AsyncResult<AsyncSequentialExecutor.ResultStatus> showRegistryStatusEventResult = executor.run(showRegistryStatusEvents);
AsyncResult<AsyncSequentialExecutor.ResultStatus> renewResult = executor.run(renewEvents);
AsyncResult<AsyncSequentialExecutor.ResultStatus> remoteRegionAddMoreInstancesResult = executor.run(remoteRegionAddMoreInstancesEvents);
AsyncResult<AsyncSequentialExecutor.ResultStatus> checkResult = executor.run(checkEvents);
Assert.assertEquals("Register application and instances failed", AsyncSequentialExecutor.ResultStatus.DONE, registerMyLocalAppAndInstancesResult.getResult());
Assert.assertEquals("Show registry status failed", AsyncSequentialExecutor.ResultStatus.DONE, showRegistryStatusEventResult.getResult());
Assert.assertEquals("Renew lease did not succeed", AsyncSequentialExecutor.ResultStatus.DONE, renewResult.getResult());
Assert.assertEquals("More instances are registered to remote region did not succeed", AsyncSequentialExecutor.ResultStatus.DONE, remoteRegionAddMoreInstancesResult.getResult());
Assert.assertEquals("Check failed", AsyncSequentialExecutor.ResultStatus.DONE, checkResult.getResult());
}
}
| 8,136 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/registry/ResponseCacheTest.java | package com.netflix.eureka.registry;
import com.netflix.appinfo.EurekaAccept;
import com.netflix.discovery.DefaultEurekaClientConfig;
import com.netflix.eureka.AbstractTester;
import com.netflix.eureka.DefaultEurekaServerConfig;
import com.netflix.eureka.EurekaServerConfig;
import com.netflix.eureka.Version;
import com.netflix.eureka.resources.DefaultServerCodecs;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
/**
* @author Nitesh Kant
*/
public class ResponseCacheTest extends AbstractTester {
private static final String REMOTE_REGION = "myremote";
private PeerAwareInstanceRegistry testRegistry;
@Override
@Before
public void setUp() throws Exception {
super.setUp();
// create a new registry that is sync'ed up with the default registry in the AbstractTester,
// but disable transparent fetch to the remote for gets
EurekaServerConfig serverConfig = spy(new DefaultEurekaServerConfig());
doReturn(true).when(serverConfig).disableTransparentFallbackToOtherRegion();
testRegistry = new PeerAwareInstanceRegistryImpl(
serverConfig,
new DefaultEurekaClientConfig(),
new DefaultServerCodecs(serverConfig),
client
);
testRegistry.init(serverContext.getPeerEurekaNodes());
testRegistry.syncUp();
}
@Test
public void testInvalidate() throws Exception {
ResponseCacheImpl cache = (ResponseCacheImpl) testRegistry.getResponseCache();
Key key = new Key(Key.EntityType.Application, REMOTE_REGION_APP_NAME,
Key.KeyType.JSON, Version.V1, EurekaAccept.full);
String response = cache.get(key, false);
Assert.assertNotNull("Cache get returned null.", response);
testRegistry.cancel(REMOTE_REGION_APP_NAME, REMOTE_REGION_INSTANCE_1_HOSTNAME, true);
Assert.assertNull("Cache after invalidate did not return null for write view.", cache.get(key, true));
}
@Test
public void testInvalidateWithRemoteRegion() throws Exception {
ResponseCacheImpl cache = (ResponseCacheImpl) testRegistry.getResponseCache();
Key key = new Key(
Key.EntityType.Application,
REMOTE_REGION_APP_NAME,
Key.KeyType.JSON, Version.V1, EurekaAccept.full, new String[]{REMOTE_REGION}
);
Assert.assertNotNull("Cache get returned null.", cache.get(key, false));
testRegistry.cancel(REMOTE_REGION_APP_NAME, REMOTE_REGION_INSTANCE_1_HOSTNAME, true);
Assert.assertNull("Cache after invalidate did not return null.", cache.get(key));
}
@Test
public void testInvalidateWithMultipleRemoteRegions() throws Exception {
ResponseCacheImpl cache = (ResponseCacheImpl) testRegistry.getResponseCache();
Key key1 = new Key(
Key.EntityType.Application,
REMOTE_REGION_APP_NAME,
Key.KeyType.JSON, Version.V1, EurekaAccept.full, new String[]{REMOTE_REGION, "myregion2"}
);
Key key2 = new Key(
Key.EntityType.Application,
REMOTE_REGION_APP_NAME,
Key.KeyType.JSON, Version.V1, EurekaAccept.full, new String[]{REMOTE_REGION}
);
Assert.assertNotNull("Cache get returned null.", cache.get(key1, false));
Assert.assertNotNull("Cache get returned null.", cache.get(key2, false));
testRegistry.cancel(REMOTE_REGION_APP_NAME, REMOTE_REGION_INSTANCE_1_HOSTNAME, true);
Assert.assertNull("Cache after invalidate did not return null.", cache.get(key1, true));
Assert.assertNull("Cache after invalidate did not return null.", cache.get(key2, true));
}
}
| 8,137 |
0 | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/test/java/com/netflix/eureka/aws/EIPManagerTest.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.eureka.aws;
import com.google.common.collect.Lists;
import com.netflix.discovery.EurekaClientConfig;
import org.junit.Before;
import org.junit.Test;
import java.util.Collection;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Joseph Witthuhn
*/
public class EIPManagerTest {
private EurekaClientConfig config = mock(EurekaClientConfig.class);
private EIPManager eipManager;
@Before
public void setUp() {
when(config.shouldUseDnsForFetchingServiceUrls()).thenReturn(Boolean.FALSE);
eipManager = new EIPManager(null, config, null, null);
}
@Test
public void shouldFilterNonElasticNames() {
when(config.getRegion()).thenReturn("us-east-1");
List<String> hosts = Lists.newArrayList("example.com", "ec2-1-2-3-4.compute.amazonaws.com", "5.6.7.8",
"ec2-101-202-33-44.compute.amazonaws.com");
when(config.getEurekaServerServiceUrls(any(String.class))).thenReturn(hosts);
Collection<String> returnValue = eipManager.getCandidateEIPs("i-123", "us-east-1d");
assertEquals(2, returnValue.size());
assertTrue(returnValue.contains("1.2.3.4"));
assertTrue(returnValue.contains("101.202.33.44"));
}
@Test
public void shouldFilterNonElasticNamesInOtherRegion() {
when(config.getRegion()).thenReturn("eu-west-1");
List<String> hosts = Lists.newArrayList("example.com", "ec2-1-2-3-4.eu-west-1.compute.amazonaws.com",
"5.6.7.8", "ec2-101-202-33-44.eu-west-1.compute.amazonaws.com");
when(config.getEurekaServerServiceUrls(any(String.class))).thenReturn(hosts);
Collection<String> returnValue = eipManager.getCandidateEIPs("i-123", "eu-west-1a");
assertEquals(2, returnValue.size());
assertTrue(returnValue.contains("1.2.3.4"));
assertTrue(returnValue.contains("101.202.33.44"));
}
@Test(expected = RuntimeException.class)
public void shouldThrowExceptionWhenNoElasticNames() {
when(config.getRegion()).thenReturn("eu-west-1");
List<String> hosts = Lists.newArrayList("example.com", "5.6.7.8");
when(config.getEurekaServerServiceUrls(any(String.class))).thenReturn(hosts);
eipManager.getCandidateEIPs("i-123", "eu-west-1a");
}
}
| 8,138 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/EurekaServerContext.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.eureka;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.eureka.cluster.PeerEurekaNodes;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
import com.netflix.eureka.resources.ServerCodecs;
/**
* @author David Liu
*/
public interface EurekaServerContext {
void initialize() throws Exception;
void shutdown() throws Exception;
EurekaServerConfig getServerConfig();
PeerEurekaNodes getPeerEurekaNodes();
ServerCodecs getServerCodecs();
PeerAwareInstanceRegistry getRegistry();
ApplicationInfoManager getApplicationInfoManager();
}
| 8,139 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/RateLimitingFilter.java | /*
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.eureka;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.netflix.appinfo.AbstractEurekaIdentity;
import com.netflix.appinfo.EurekaClientIdentity;
import com.netflix.eureka.util.EurekaMonitors;
import com.netflix.discovery.util.RateLimiter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Rate limiting filter, with configurable threshold above which non-privileged clients
* will be dropped. This feature enables cutting off non-standard and potentially harmful clients
* in case of system overload. Since it is critical to always allow client registrations and heartbeats into
* the system, which at the same time are relatively cheap operations, the rate limiting is applied only to
* full and delta registry fetches. Furthermore, since delta fetches are much smaller than full fetches,
* and if not served my result in following full registry fetch from the client, they have relatively
* higher priority. This is implemented by two parallel rate limiters, one for overall number of
* full/delta fetches (higher threshold) and one for full fetches only (low threshold).
* <p>
* The client is identified by {@link AbstractEurekaIdentity#AUTH_NAME_HEADER_KEY} HTTP header
* value. The privileged group by default contains:
* <ul>
* <li>
* {@link EurekaClientIdentity#DEFAULT_CLIENT_NAME} - standard Java eureka-client. Applications using
* this client automatically belong to the privileged group.
* </li>
* <li>
* {@link com.netflix.eureka.EurekaServerIdentity#DEFAULT_SERVER_NAME} - connections from peer Eureka servers
* (internal only, traffic replication)
* </li>
* </ul>
* It is possible to turn off privileged client filtering via
* {@link EurekaServerConfig#isRateLimiterThrottleStandardClients()} property.
* <p>
* Rate limiting is not enabled by default, but can be turned on via configuration. Even when disabled,
* the throttling statistics are still counted, although on a separate counter, so it is possible to
* measure the impact of this feature before activation.
*
* <p>
* Rate limiter implementation is based on token bucket algorithm. There are two configurable
* 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
* </li>
* </ul>
*
* @author Tomasz Bak
*/
@Singleton
public class RateLimitingFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger(RateLimitingFilter.class);
private static final Set<String> DEFAULT_PRIVILEGED_CLIENTS = new HashSet<>(
Arrays.asList(EurekaClientIdentity.DEFAULT_CLIENT_NAME, EurekaServerIdentity.DEFAULT_SERVER_NAME)
);
private static final Pattern TARGET_RE = Pattern.compile("^.*/apps(/[^/]*)?$");
enum Target {FullFetch, DeltaFetch, Application, Other}
/**
* Includes both full and delta fetches.
*/
private static final RateLimiter registryFetchRateLimiter = new RateLimiter(TimeUnit.SECONDS);
/**
* Only full registry fetches.
*/
private static final RateLimiter registryFullFetchRateLimiter = new RateLimiter(TimeUnit.SECONDS);
private EurekaServerConfig serverConfig;
@Inject
public RateLimitingFilter(EurekaServerContext server) {
this.serverConfig = server.getServerConfig();
}
// for non-DI use
public RateLimitingFilter() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
if (serverConfig == null) {
EurekaServerContext serverContext = (EurekaServerContext) filterConfig.getServletContext()
.getAttribute(EurekaServerContext.class.getName());
serverConfig = serverContext.getServerConfig();
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
Target target = getTarget(request);
if (target == Target.Other) {
chain.doFilter(request, response);
return;
}
HttpServletRequest httpRequest = (HttpServletRequest) request;
if (isRateLimited(httpRequest, target)) {
incrementStats(target);
if (serverConfig.isRateLimiterEnabled()) {
((HttpServletResponse) response).setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
return;
}
}
chain.doFilter(request, response);
}
private static Target getTarget(ServletRequest request) {
Target target = Target.Other;
if (request instanceof HttpServletRequest) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String pathInfo = httpRequest.getRequestURI();
if ("GET".equals(httpRequest.getMethod()) && pathInfo != null) {
Matcher matcher = TARGET_RE.matcher(pathInfo);
if (matcher.matches()) {
if (matcher.groupCount() == 0 || matcher.group(1) == null || "/".equals(matcher.group(1))) {
target = Target.FullFetch;
} else if ("/delta".equals(matcher.group(1))) {
target = Target.DeltaFetch;
} else {
target = Target.Application;
}
}
}
if (target == Target.Other) {
logger.debug("URL path {} not matched by rate limiting filter", pathInfo);
}
}
return target;
}
private boolean isRateLimited(HttpServletRequest request, Target target) {
if (isPrivileged(request)) {
logger.debug("Privileged {} request", target);
return false;
}
if (isOverloaded(target)) {
logger.debug("Overloaded {} request; discarding it", target);
return true;
}
logger.debug("{} request admitted", target);
return false;
}
private boolean isPrivileged(HttpServletRequest request) {
if (serverConfig.isRateLimiterThrottleStandardClients()) {
return false;
}
Set<String> privilegedClients = serverConfig.getRateLimiterPrivilegedClients();
String clientName = request.getHeader(AbstractEurekaIdentity.AUTH_NAME_HEADER_KEY);
return privilegedClients.contains(clientName) || DEFAULT_PRIVILEGED_CLIENTS.contains(clientName);
}
private boolean isOverloaded(Target target) {
int maxInWindow = serverConfig.getRateLimiterBurstSize();
int fetchWindowSize = serverConfig.getRateLimiterRegistryFetchAverageRate();
boolean overloaded = !registryFetchRateLimiter.acquire(maxInWindow, fetchWindowSize);
if (target == Target.FullFetch) {
int fullFetchWindowSize = serverConfig.getRateLimiterFullFetchAverageRate();
overloaded |= !registryFullFetchRateLimiter.acquire(maxInWindow, fullFetchWindowSize);
}
return overloaded;
}
private void incrementStats(Target target) {
if (serverConfig.isRateLimiterEnabled()) {
EurekaMonitors.RATE_LIMITED.increment();
if (target == Target.FullFetch) {
EurekaMonitors.RATE_LIMITED_FULL_FETCH.increment();
}
} else {
EurekaMonitors.RATE_LIMITED_CANDIDATES.increment();
if (target == Target.FullFetch) {
EurekaMonitors.RATE_LIMITED_FULL_FETCH_CANDIDATES.increment();
}
}
}
@Override
public void destroy() {
}
// For testing purposes
static void reset() {
registryFetchRateLimiter.reset();
registryFullFetchRateLimiter.reset();
}
}
| 8,140 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/EurekaBootStrap.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.eureka;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.Date;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.CloudInstanceConfig;
import com.netflix.appinfo.DataCenterInfo;
import com.netflix.appinfo.EurekaInstanceConfig;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.MyDataCenterInstanceConfig;
import com.netflix.appinfo.providers.EurekaConfigBasedInstanceInfoProvider;
import com.netflix.config.ConfigurationManager;
import com.netflix.config.DeploymentContext;
import com.netflix.discovery.DefaultEurekaClientConfig;
import com.netflix.discovery.DiscoveryClient;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.discovery.converters.JsonXStream;
import com.netflix.discovery.converters.XmlXStream;
import com.netflix.eureka.aws.AwsBinder;
import com.netflix.eureka.aws.AwsBinderDelegate;
import com.netflix.eureka.cluster.PeerEurekaNodes;
import com.netflix.eureka.registry.AwsInstanceRegistry;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl;
import com.netflix.eureka.resources.DefaultServerCodecs;
import com.netflix.eureka.resources.ServerCodecs;
import com.netflix.eureka.util.EurekaMonitors;
import com.thoughtworks.xstream.XStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The class that kick starts the eureka server.
*
* <p>
* The eureka server is configured by using the configuration
* {@link EurekaServerConfig} specified by <em>eureka.server.props</em> in the
* classpath. The eureka client component is also initialized by using the
* configuration {@link EurekaInstanceConfig} specified by
* <em>eureka.client.props</em>. If the server runs in the AWS cloud, the eureka
* server binds it to the elastic ip as specified.
* </p>
*
* @author Karthik Ranganathan, Greg Kim, David Liu
*
*/
public class EurekaBootStrap implements ServletContextListener {
private static final Logger logger = LoggerFactory.getLogger(EurekaBootStrap.class);
private static final String TEST = "test";
private static final String ARCHAIUS_DEPLOYMENT_ENVIRONMENT = "archaius.deployment.environment";
private static final String EUREKA_ENVIRONMENT = "eureka.environment";
private static final String CLOUD = "cloud";
private static final String DEFAULT = "default";
private static final String ARCHAIUS_DEPLOYMENT_DATACENTER = "archaius.deployment.datacenter";
private static final String EUREKA_DATACENTER = "eureka.datacenter";
protected volatile EurekaServerContext serverContext;
protected volatile AwsBinder awsBinder;
private EurekaClient eurekaClient;
/**
* Construct a default instance of Eureka boostrap
*/
public EurekaBootStrap() {
this(null);
}
/**
* Construct an instance of eureka bootstrap with the supplied eureka client
*
* @param eurekaClient the eureka client to bootstrap
*/
public EurekaBootStrap(EurekaClient eurekaClient) {
this.eurekaClient = eurekaClient;
}
/**
* Initializes Eureka, including syncing up with other Eureka peers and publishing the registry.
*
* @see
* javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
*/
@Override
public void contextInitialized(ServletContextEvent event) {
try {
initEurekaEnvironment();
initEurekaServerContext();
ServletContext sc = event.getServletContext();
sc.setAttribute(EurekaServerContext.class.getName(), serverContext);
} catch (Throwable e) {
logger.error("Cannot bootstrap eureka server :", e);
throw new RuntimeException("Cannot bootstrap eureka server :", e);
}
}
/**
* Users can override to initialize the environment themselves.
*/
protected void initEurekaEnvironment() throws Exception {
logger.info("Setting the eureka configuration..");
String dataCenter = ConfigurationManager.getConfigInstance().getString(EUREKA_DATACENTER);
if (dataCenter == null) {
logger.info("Eureka data center value eureka.datacenter is not set, defaulting to default");
ConfigurationManager.getConfigInstance().setProperty(ARCHAIUS_DEPLOYMENT_DATACENTER, DEFAULT);
} else {
ConfigurationManager.getConfigInstance().setProperty(ARCHAIUS_DEPLOYMENT_DATACENTER, dataCenter);
}
String environment = ConfigurationManager.getConfigInstance().getString(EUREKA_ENVIRONMENT);
if (environment == null) {
ConfigurationManager.getConfigInstance().setProperty(ARCHAIUS_DEPLOYMENT_ENVIRONMENT, TEST);
logger.info("Eureka environment value eureka.environment is not set, defaulting to test");
}
}
/**
* init hook for server context. Override for custom logic.
*/
protected void initEurekaServerContext() throws Exception {
EurekaServerConfig eurekaServerConfig = new DefaultEurekaServerConfig();
// For backward compatibility
JsonXStream.getInstance().registerConverter(new V1AwareInstanceInfoConverter(), XStream.PRIORITY_VERY_HIGH);
XmlXStream.getInstance().registerConverter(new V1AwareInstanceInfoConverter(), XStream.PRIORITY_VERY_HIGH);
logger.info("Initializing the eureka client...");
logger.info(eurekaServerConfig.getJsonCodecName());
ServerCodecs serverCodecs = new DefaultServerCodecs(eurekaServerConfig);
ApplicationInfoManager applicationInfoManager = null;
if (eurekaClient == null) {
EurekaInstanceConfig instanceConfig = isCloud(ConfigurationManager.getDeploymentContext())
? new CloudInstanceConfig()
: new MyDataCenterInstanceConfig();
applicationInfoManager = new ApplicationInfoManager(
instanceConfig, new EurekaConfigBasedInstanceInfoProvider(instanceConfig).get());
EurekaClientConfig eurekaClientConfig = new DefaultEurekaClientConfig();
eurekaClient = new DiscoveryClient(applicationInfoManager, eurekaClientConfig);
} else {
applicationInfoManager = eurekaClient.getApplicationInfoManager();
}
PeerAwareInstanceRegistry registry;
if (isAws(applicationInfoManager.getInfo())) {
registry = new AwsInstanceRegistry(
eurekaServerConfig,
eurekaClient.getEurekaClientConfig(),
serverCodecs,
eurekaClient
);
awsBinder = new AwsBinderDelegate(eurekaServerConfig, eurekaClient.getEurekaClientConfig(), registry, applicationInfoManager);
awsBinder.start();
} else {
registry = new PeerAwareInstanceRegistryImpl(
eurekaServerConfig,
eurekaClient.getEurekaClientConfig(),
serverCodecs,
eurekaClient
);
}
PeerEurekaNodes peerEurekaNodes = getPeerEurekaNodes(
registry,
eurekaServerConfig,
eurekaClient.getEurekaClientConfig(),
serverCodecs,
applicationInfoManager
);
serverContext = new DefaultEurekaServerContext(
eurekaServerConfig,
serverCodecs,
registry,
peerEurekaNodes,
applicationInfoManager
);
EurekaServerContextHolder.initialize(serverContext);
serverContext.initialize();
logger.info("Initialized server context");
// Copy registry from neighboring eureka node
int registryCount = registry.syncUp();
registry.openForTraffic(applicationInfoManager, registryCount);
// Register all monitoring statistics.
EurekaMonitors.registerAllStats();
}
protected PeerEurekaNodes getPeerEurekaNodes(PeerAwareInstanceRegistry registry, EurekaServerConfig eurekaServerConfig, EurekaClientConfig eurekaClientConfig, ServerCodecs serverCodecs, ApplicationInfoManager applicationInfoManager) {
PeerEurekaNodes peerEurekaNodes = new PeerEurekaNodes(
registry,
eurekaServerConfig,
eurekaClientConfig,
serverCodecs,
applicationInfoManager
);
return peerEurekaNodes;
}
/**
* Handles Eureka cleanup, including shutting down all monitors and yielding all EIPs.
*
* @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
*/
@Override
public void contextDestroyed(ServletContextEvent event) {
try {
logger.info("{} Shutting down Eureka Server..", new Date());
ServletContext sc = event.getServletContext();
sc.removeAttribute(EurekaServerContext.class.getName());
destroyEurekaServerContext();
destroyEurekaEnvironment();
} catch (Throwable e) {
logger.error("Error shutting down eureka", e);
}
logger.info("{} Eureka Service is now shutdown...", new Date());
}
/**
* Server context shutdown hook. Override for custom logic
*/
protected void destroyEurekaServerContext() throws Exception {
EurekaMonitors.shutdown();
if (awsBinder != null) {
awsBinder.shutdown();
}
if (serverContext != null) {
serverContext.shutdown();
}
}
/**
* Users can override to clean up the environment themselves.
*/
protected void destroyEurekaEnvironment() throws Exception {
}
protected boolean isAws(InstanceInfo selfInstanceInfo) {
boolean result = DataCenterInfo.Name.Amazon == selfInstanceInfo.getDataCenterInfo().getName();
logger.info("isAws returned {}", result);
return result;
}
protected boolean isCloud(DeploymentContext deploymentContext) {
logger.info("Deployment datacenter is {}", deploymentContext.getDeploymentDatacenter());
return CLOUD.equals(deploymentContext.getDeploymentDatacenter());
}
}
| 8,141 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/Names.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.eureka;
/**
* @author Tomasz Bak
*/
public class Names {
/**
* Eureka metric names consist of three parts [source].[component].[detailed name]:
* <ul>
* <li>source - fixed to eurekaServer (and eurekaClient on the client side)</li>
* <li>component - Eureka component, like REST layer, replication, etc</li>
* <li>detailed name - a detailed metric name explaining its purpose</li>
* </ul>
*/
public static final String METRIC_PREFIX = "eurekaServer.";
public static final String METRIC_REPLICATION_PREFIX = METRIC_PREFIX + "replication.";
public static final String METRIC_REGISTRY_PREFIX = METRIC_PREFIX + "registry.";
public static final String REMOTE = "remote";
}
| 8,142 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/ServerRequestAuthFilter.java | package com.netflix.eureka;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import com.google.common.base.Strings;
import com.netflix.appinfo.AbstractEurekaIdentity;
import com.netflix.servo.monitor.DynamicCounter;
import com.netflix.servo.monitor.MonitorConfig;
/**
* An auth filter for client requests. For now, it only logs supported client identification data from header info
*/
@Singleton
public class ServerRequestAuthFilter implements Filter {
public static final String UNKNOWN = "unknown";
private static final String NAME_PREFIX = "DiscoveryServerRequestAuth_Name_";
private EurekaServerConfig serverConfig;
@Inject
public ServerRequestAuthFilter(EurekaServerContext server) {
this.serverConfig = server.getServerConfig();
}
// for non-DI use
public ServerRequestAuthFilter() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
if (serverConfig == null) {
EurekaServerContext serverContext = (EurekaServerContext) filterConfig.getServletContext()
.getAttribute(EurekaServerContext.class.getName());
serverConfig = serverContext.getServerConfig();
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
logAuth(request);
chain.doFilter(request, response);
}
@Override
public void destroy() {
// nothing to do here
}
protected void logAuth(ServletRequest request) {
if (serverConfig.shouldLogIdentityHeaders()) {
if (request instanceof HttpServletRequest) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String clientName = getHeader(httpRequest, AbstractEurekaIdentity.AUTH_NAME_HEADER_KEY);
String clientVersion = getHeader(httpRequest, AbstractEurekaIdentity.AUTH_VERSION_HEADER_KEY);
DynamicCounter.increment(MonitorConfig.builder(NAME_PREFIX + clientName + "-" + clientVersion).build());
}
}
}
protected String getHeader(HttpServletRequest request, String headerKey) {
String value = request.getHeader(headerKey);
return Strings.isNullOrEmpty(value) ? UNKNOWN : value;
}
}
| 8,143 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/DefaultEurekaServerContext.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.eureka;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.discovery.DiscoveryManager;
import com.netflix.eureka.cluster.PeerEurekaNodes;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
import com.netflix.eureka.resources.ServerCodecs;
import com.netflix.eureka.util.EurekaMonitors;
import com.netflix.eureka.util.ServoControl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.inject.Singleton;
/**
* Represent the local server context and exposes getters to components of the
* local server such as the registry.
*
* @author David Liu
*/
@Singleton
public class DefaultEurekaServerContext implements EurekaServerContext {
private static final Logger logger = LoggerFactory.getLogger(DefaultEurekaServerContext.class);
private final EurekaServerConfig serverConfig;
private final ServerCodecs serverCodecs;
private final PeerAwareInstanceRegistry registry;
private final PeerEurekaNodes peerEurekaNodes;
private final ApplicationInfoManager applicationInfoManager;
@Inject
public DefaultEurekaServerContext(EurekaServerConfig serverConfig,
ServerCodecs serverCodecs,
PeerAwareInstanceRegistry registry,
PeerEurekaNodes peerEurekaNodes,
ApplicationInfoManager applicationInfoManager) {
this.serverConfig = serverConfig;
this.serverCodecs = serverCodecs;
this.registry = registry;
this.peerEurekaNodes = peerEurekaNodes;
this.applicationInfoManager = applicationInfoManager;
}
@PostConstruct
@Override
public void initialize() {
logger.info("Initializing ...");
peerEurekaNodes.start();
try {
registry.init(peerEurekaNodes);
} catch (Exception e) {
throw new RuntimeException(e);
}
logger.info("Initialized");
}
@PreDestroy
@Override
public void shutdown() {
logger.info("Shutting down ...");
registry.shutdown();
peerEurekaNodes.shutdown();
ServoControl.shutdown();
EurekaMonitors.shutdown();
logger.info("Shut down");
}
@Override
public EurekaServerConfig getServerConfig() {
return serverConfig;
}
@Override
public PeerEurekaNodes getPeerEurekaNodes() {
return peerEurekaNodes;
}
@Override
public ServerCodecs getServerCodecs() {
return serverCodecs;
}
@Override
public PeerAwareInstanceRegistry getRegistry() {
return registry;
}
@Override
public ApplicationInfoManager getApplicationInfoManager() {
return applicationInfoManager;
}
}
| 8,144 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/EurekaServerConfig.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.eureka;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import com.netflix.eureka.aws.AwsBindingStrategy;
/**
* Configuration information required by the eureka server to operate.
*
* <p>
* Most of the required information is provided by the default configuration
* {@link com.netflix.eureka.DefaultEurekaServerConfig}.
*
* Note that all configurations are not effective at runtime unless and
* otherwise specified.
* </p>
*
* @author Karthik Ranganathan
*
*/
public interface EurekaServerConfig {
/**
* Gets the <em>AWS Access Id</em>. This is primarily used for
* <em>Elastic IP Biding</em>. The access id should be provided with
* appropriate AWS permissions to bind the EIP.
*
* @return
*/
String getAWSAccessId();
/**
* Gets the <em>AWS Secret Key</em>. This is primarily used for
* <em>Elastic IP Biding</em>. The access id should be provided with
* appropriate AWS permissions to bind the EIP.
*
* @return
*/
String getAWSSecretKey();
/**
* Gets the number of times the server should try to bind to the candidate
* EIP.
*
* <p>
* <em>The changes are effective at runtime.</em>
* </p>
*
* @return the number of times the server should try to bind to the
* candidate EIP.
*/
int getEIPBindRebindRetries();
/**
* Get the interval with which the server should check if the EIP is bound
* and should try to bind in the case if it is already not bound, iff the EIP
* is not currently bound.
* <p>
* <em>The changes are effective at runtime.</em>
* </p>
*
* @return the time in milliseconds.
*/
int getEIPBindingRetryIntervalMsWhenUnbound();
/**
* Gets the interval with which the server should check if the EIP is bound
* and should try to bind in the case if it is already not bound, iff the EIP
* is already bound. (so this refresh is just for steady state checks)
* <p>
* <em>The changes are effective at runtime.</em>
* </p>
*
* @return the time in milliseconds.
*/
int getEIPBindingRetryIntervalMs();
/**
* Checks to see if the eureka server is enabled for self preservation.
*
* <p>
* When enabled, the server keeps track of the number of <em>renewals</em>
* it should receive from the server. Any time, the number of renewals drops
* below the threshold percentage as defined by
* {@link #getRenewalPercentThreshold()}, the server turns off expirations
* to avert danger.This will help the server in maintaining the registry
* information in case of network problems between client and the server.
* <p>
* <em>The changes are effective at runtime.</em>
* </p>
*
* @return true to enable self preservation, false otherwise.
*/
boolean shouldEnableSelfPreservation();
/**
* The minimum percentage of renewals that is expected from the clients in
* the period specified by {@link #getRenewalThresholdUpdateIntervalMs()}.
* If the renewals drop below the threshold, the expirations are disabled if
* the {@link #shouldEnableSelfPreservation()} is enabled.
*
* <p>
* <em>The changes are effective at runtime.</em>
* </p>
*
* @return value between 0 and 1 indicating the percentage. For example,
* <code>85%</code> will be specified as <code>0.85</code>.
*/
double getRenewalPercentThreshold();
/**
* The interval with which the threshold as specified in
* {@link #getRenewalPercentThreshold()} needs to be updated.
*
* @return time in milliseconds indicating the interval.
*/
int getRenewalThresholdUpdateIntervalMs();
/**
* The interval with which clients are expected to send their heartbeats. Defaults to 30
* seconds. If clients send heartbeats with different frequency, say, every 15 seconds, then
* this parameter should be tuned accordingly, otherwise, self-preservation won't work as
* expected.
*
* @return time in seconds indicating the expected interval
*/
int getExpectedClientRenewalIntervalSeconds();
/**
* The interval with which the information about the changes in peer eureka
* nodes is updated. The user can use the DNS mechanism or dynamic
* configuration provided by <a href="https://github.com/Netflix/archaius">Archaius</a> to
* change the information dynamically.
* <p>
* <em>The changes are effective at runtime.</em>
* </p>
*
* @return timer in milliseconds indicating the interval.
*/
int getPeerEurekaNodesUpdateIntervalMs();
/**
* If set to true, the replicated data send in the request will be always compressed.
* This does not define response path, which is driven by "Accept-Encoding" header.
*/
boolean shouldEnableReplicatedRequestCompression();
/**
* Get the number of times the replication events should be retried with
* peers.
* <p>
* <em>The changes are effective at runtime.</em>
* </p>
*
* @return the number of retries.
*/
int getNumberOfReplicationRetries();
/**
* Gets the interval with which the status information about peer nodes is
* updated.
* <p>
* <em>The changes are effective at runtime.</em>
* </p>
*
* @return time in milliseconds indicating the interval.
*/
int getPeerEurekaStatusRefreshTimeIntervalMs();
/**
* Gets the time to wait when the eureka server starts up unable to get
* instances from peer nodes. It is better not to start serving rightaway
* during these scenarios as the information that is stored in the registry
* may not be complete.
*
* When the instance registry starts up empty, it builds over time when the
* clients start to send heartbeats and the server requests the clients for
* registration information.
*
* @return time in milliseconds.
*/
int getWaitTimeInMsWhenSyncEmpty();
/**
* Gets the timeout value for connecting to peer eureka nodes for
* replication.
*
* @return timeout value in milliseconds.
*/
int getPeerNodeConnectTimeoutMs();
/**
* Gets the timeout value for reading information from peer eureka nodes for
* replication.
*
* @return timeout value in milliseconds.
*/
int getPeerNodeReadTimeoutMs();
/**
* Gets the total number of <em>HTTP</em> connections allowed to peer eureka
* nodes for replication.
*
* @return total number of allowed <em>HTTP</em> connections.
*/
int getPeerNodeTotalConnections();
/**
* Gets the total number of <em>HTTP</em> connections allowed to a
* particular peer eureka node for replication.
*
* @return total number of allowed <em>HTTP</em> connections for a peer
* node.
*/
int getPeerNodeTotalConnectionsPerHost();
/**
* Gets the idle time after which the <em>HTTP</em> connection should be
* cleaned up.
*
* @return idle time in seconds.
*/
int getPeerNodeConnectionIdleTimeoutSeconds();
/**
* Get the time for which the delta information should be cached for the
* clients to retrieve the value without missing it.
*
* @return time in milliseconds
*/
long getRetentionTimeInMSInDeltaQueue();
/**
* Get the time interval with which the clean up task should wake up and
* check for expired delta information.
*
* @return time in milliseconds.
*/
long getDeltaRetentionTimerIntervalInMs();
/**
* Get the time interval with which the task that expires instances should
* wake up and run.
*
* @return time in milliseconds.
*/
long getEvictionIntervalTimerInMs();
/**
* Whether to use AWS API to query ASG statuses.
*
* @return true if AWS API is used, false otherwise.
*/
boolean shouldUseAwsAsgApi();
/**
* Get the timeout value for querying the <em>AWS</em> for <em>ASG</em>
* information.
*
* @return timeout value in milliseconds.
*/
int getASGQueryTimeoutMs();
/**
* Get the time interval with which the <em>ASG</em> information must be
* queried from <em>AWS</em>.
*
* @return time in milliseconds.
*/
long getASGUpdateIntervalMs();
/**
* Get the expiration value for the cached <em>ASG</em> information
*
* @return time in milliseconds.
*/
long getASGCacheExpiryTimeoutMs();
/**
* Gets the time for which the registry payload should be kept in the cache
* if it is not invalidated by change events.
*
* @return time in seconds.
*/
long getResponseCacheAutoExpirationInSeconds();
/**
* Gets the time interval with which the payload cache of the client should
* be updated.
*
* @return time in milliseconds.
*/
long getResponseCacheUpdateIntervalMs();
/**
* The {@link com.netflix.eureka.registry.ResponseCache} currently uses a two level caching
* strategy to responses. A readWrite cache with an expiration policy, and a readonly cache
* that caches without expiry.
*
* @return true if the read only cache is to be used
*/
boolean shouldUseReadOnlyResponseCache();
/**
* Checks to see if the delta information can be served to client or not.
* <p>
* <em>The changes are effective at runtime.</em>
* </p>
*
* @return true if the delta information is allowed to be served, false
* otherwise.
*/
boolean shouldDisableDelta();
/**
* Get the idle time for which the status replication threads can stay
* alive.
*
* @return time in minutes.
*/
long getMaxIdleThreadInMinutesAgeForStatusReplication();
/**
* Get the minimum number of threads to be used for status replication.
*
* @return minimum number of threads to be used for status replication.
*/
int getMinThreadsForStatusReplication();
/**
* Get the maximum number of threads to be used for status replication.
*
* @return maximum number of threads to be used for status replication.
*/
int getMaxThreadsForStatusReplication();
/**
* Get the maximum number of replication events that can be allowed to back
* up in the status replication pool.
* <p>
* Depending on the memory allowed, timeout and the replication traffic,
* this value can vary.
* </p>
*
* @return the maximum number of replication events that can be allowed to
* back up.
*/
int getMaxElementsInStatusReplicationPool();
/**
* Checks whether to synchronize instances when timestamp differs.
* <p>
* <em>The changes are effective at runtime.</em>
* </p>
*
* @return true, to synchronize, false otherwise.
*/
boolean shouldSyncWhenTimestampDiffers();
/**
* Get the number of times that a eureka node would try to get the registry
* information from the peers during startup.
*
* @return the number of retries
*/
int getRegistrySyncRetries();
/**
* Get the wait/sleep time between each retry sync attempts, if the prev retry failed and there are
* more retries to attempt.
*
* @return the wait time in ms between each sync retries
*/
long getRegistrySyncRetryWaitMs();
/**
* Get the maximum number of replication events that can be allowed to back
* up in the replication pool. This replication pool is responsible for all
* events except status updates.
* <p>
* Depending on the memory allowed, timeout and the replication traffic,
* this value can vary.
* </p>
*
* @return the maximum number of replication events that can be allowed to
* back up.
*/
int getMaxElementsInPeerReplicationPool();
/**
* Get the idle time for which the replication threads can stay alive.
*
* @return time in minutes.
*/
long getMaxIdleThreadAgeInMinutesForPeerReplication();
/**
* Get the minimum number of threads to be used for replication.
*
* @return minimum number of threads to be used for replication.
*/
int getMinThreadsForPeerReplication();
/**
* Get the maximum number of threads to be used for replication.
*
* @return maximum number of threads to be used for replication.
*/
int getMaxThreadsForPeerReplication();
/**
* Get the minimum number of available peer replication instances
* for this instance to be considered healthy. The design of eureka allows
* for an instance to continue operating with zero peers, but that would not
* be ideal.
* <p>
* The default value of -1 is interpreted as a marker to not compare
* the number of replicas. This would be done to either disable this check
* or to run eureka in a single node configuration.
*
* @return minimum number of available peer replication instances
* for this instance to be considered healthy.
*/
int getHealthStatusMinNumberOfAvailablePeers();
/**
* Get the time in milliseconds to try to replicate before dropping
* replication events.
*
* @return time in milliseconds
*/
int getMaxTimeForReplication();
/**
* Checks whether the connections to replicas should be primed. In AWS, the
* firewall requires sometime to establish network connection for new nodes.
*
* @return true, if connections should be primed, false otherwise.
*/
boolean shouldPrimeAwsReplicaConnections();
/**
* Checks to see if the delta information can be served to client or not for
* remote regions.
* <p>
* <em>The changes are effective at runtime.</em>
* </p>
*
* @return true if the delta information is allowed to be served, false
* otherwise.
*/
boolean shouldDisableDeltaForRemoteRegions();
/**
* Gets the timeout value for connecting to peer eureka nodes for remote
* regions.
*
* @return timeout value in milliseconds.
*/
int getRemoteRegionConnectTimeoutMs();
/**
* Gets the timeout value for reading information from peer eureka nodes for
* remote regions.
*
* @return timeout value in milliseconds.
*/
int getRemoteRegionReadTimeoutMs();
/**
* Gets the total number of <em>HTTP</em> connections allowed to peer eureka
* nodes for remote regions.
*
* @return total number of allowed <em>HTTP</em> connections.
*/
int getRemoteRegionTotalConnections();
/**
* Gets the total number of <em>HTTP</em> connections allowed to a
* particular peer eureka node for remote regions.
*
* @return total number of allowed <em>HTTP</em> connections for a peer
* node.
*/
int getRemoteRegionTotalConnectionsPerHost();
/**
* Gets the idle time after which the <em>HTTP</em> connection should be
* cleaned up for remote regions.
*
* @return idle time in seconds.
*/
int getRemoteRegionConnectionIdleTimeoutSeconds();
/**
* Indicates whether the content fetched from eureka server has to be
* compressed for remote regions 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.
*/
boolean shouldGZipContentFromRemoteRegion();
/**
* Get a map of region name against remote region discovery url.
*
* @return - An unmodifiable map of remote region name against remote region discovery url. Empty map if no remote
* region url is defined.
*/
Map<String, String> getRemoteRegionUrlsWithName();
/**
* Get the list of remote region urls.
* @return - array of string representing {@link java.net.URL}s.
* @deprecated Use {@link #getRemoteRegionUrlsWithName()}
*/
String[] getRemoteRegionUrls();
/**
* Returns a list of applications that must be retrieved from the passed remote region. <br/>
* This list can be <code>null</code> which means that no filtering should be applied on the applications
* for this region i.e. all applications must be returned. <br/>
* A global whitelist can also be configured which can be used when no setting is available for a region, such a
* whitelist can be obtained by passing <code>null</code> to this method.
*
* @param regionName Name of the region for which the application whitelist is to be retrieved. If null a global
* setting is returned.
*
* @return A set of application names which must be retrieved from the passed region. If <code>null</code> all
* applications must be retrieved.
*/
@Nullable
Set<String> getRemoteRegionAppWhitelist(@Nullable String regionName);
/**
* Get the time interval for which the registry information need to be fetched from the remote region.
* @return time in seconds.
*/
int getRemoteRegionRegistryFetchInterval();
/**
* Size of a thread pool used to execute remote region registry fetch requests. Delegating these requests
* to internal threads is necessary workaround to https://bugs.openjdk.java.net/browse/JDK-8049846 bug.
*/
int getRemoteRegionFetchThreadPoolSize();
/**
* Gets the fully qualified trust store file that will be used for remote region registry fetches.
* @return
*/
String getRemoteRegionTrustStore();
/**
* Get the remote region trust store's password.
*/
String getRemoteRegionTrustStorePassword();
/**
* Old behavior of fallback to applications in the remote region (if configured) if there are no instances of that
* application in the local region, will be disabled.
*
* @return {@code true} if the old behavior is to be disabled.
*/
boolean disableTransparentFallbackToOtherRegion();
/**
* Indicates whether the replication between cluster nodes should be batched for network efficiency.
* @return {@code true} if the replication needs to be batched.
*/
boolean shouldBatchReplication();
/**
* Allows to configure URL which Eureka should treat as its own during replication. In some cases Eureka URLs don't
* match IP address or hostname (for example, when nodes are behind load balancers). Setting this parameter on each
* node to URLs of associated load balancers helps to avoid replication to the same node where event originally came
* to. Important: you need to configure the whole URL including scheme and path, like
* <code>http://eureka-node1.mydomain.com:8010/eureka/v2/</code>
* @return URL Eureka will treat as its own
*/
String getMyUrl();
/**
* Indicates whether the eureka server should log/metric clientAuthHeaders
* @return {@code true} if the clientAuthHeaders should be logged and/or emitted as metrics
*/
boolean shouldLogIdentityHeaders();
/**
* Indicates whether the rate limiter should be enabled or disabled.
*/
boolean isRateLimiterEnabled();
/**
* Indicate if rate limit standard clients. If set to false, only non standard clients
* will be rate limited.
*/
boolean isRateLimiterThrottleStandardClients();
/**
* A list of certified clients. This is in addition to standard eureka Java clients.
*/
Set<String> getRateLimiterPrivilegedClients();
/**
* Rate limiter, token bucket algorithm property. See also {@link #getRateLimiterRegistryFetchAverageRate()}
* and {@link #getRateLimiterFullFetchAverageRate()}.
*/
int getRateLimiterBurstSize();
/**
* Rate limiter, token bucket algorithm property. Specifies the average enforced request rate.
* See also {@link #getRateLimiterBurstSize()}.
*/
int getRateLimiterRegistryFetchAverageRate();
/**
* Rate limiter, token bucket algorithm property. Specifies the average enforced request rate.
* See also {@link #getRateLimiterBurstSize()}.
*/
int getRateLimiterFullFetchAverageRate();
/**
* Name of the Role used to describe auto scaling groups from third AWS accounts.
*/
String getListAutoScalingGroupsRoleName();
/**
* @return the class name of the full json codec to use for the server. If none set a default codec will be used
*/
String getJsonCodecName();
/**
* @return the class name of the full xml codec to use for the server. If none set a default codec will be used
*/
String getXmlCodecName();
/**
* Get the configured binding strategy EIP or Route53.
* @return the configured binding strategy
*/
AwsBindingStrategy getBindingStrategy();
/**
*
* @return the ttl used to set up the route53 domain if new
*/
long getRoute53DomainTTL();
/**
* Gets the number of times the server should try to bind to the candidate
* Route53 domain.
*
* <p>
* <em>The changes are effective at runtime.</em>
* </p>
*
* @return the number of times the server should try to bind to the
* candidate Route53 domain.
*/
int getRoute53BindRebindRetries();
/**
* Gets the interval with which the server should check if the Route53 domain is bound
* and should try to bind in the case if it is already not bound.
* <p>
* <em>The changes are effective at runtime.</em>
* </p>
*
* @return the time in milliseconds.
*/
int getRoute53BindingRetryIntervalMs();
/**
* 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.
*
* @return a property of experimental feature
*/
String getExperimental(String name);
/**
* Get the capacity of responseCache, default value is 1000.
*
* @return the capacity of responseCache.
*/
int getInitialCapacityOfResponseCache();
}
| 8,145 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/DefaultEurekaServerConfig.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.eureka;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import javax.inject.Singleton;
import com.netflix.config.ConfigurationManager;
import com.netflix.config.DynamicBooleanProperty;
import com.netflix.config.DynamicIntProperty;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.config.DynamicStringProperty;
import com.netflix.config.DynamicStringSetProperty;
import com.netflix.eureka.aws.AwsBindingStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* A default implementation of eureka server configuration as required by
* {@link EurekaServerConfig}.
*
* <p>
* The information required for configuring eureka server is provided in a
* configuration file.The configuration file is searched for in the classpath
* with the name specified by the property <em>eureka.server.props</em> and with
* the suffix <em>.properties</em>. If the property is not specified,
* <em>eureka-server.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-server-<eureka.environment>.properties</em> is loaded in addition
* to <em>eureka-server.properties</em>.
* </p>
*
* @author Karthik Ranganathan
*
*/
@Singleton
public class DefaultEurekaServerConfig implements EurekaServerConfig {
private static final String ARCHAIUS_DEPLOYMENT_ENVIRONMENT = "archaius.deployment.environment";
private static final String TEST = "test";
private static final String EUREKA_ENVIRONMENT = "eureka.environment";
private static final Logger logger = LoggerFactory
.getLogger(DefaultEurekaServerConfig.class);
private static final DynamicPropertyFactory configInstance = com.netflix.config.DynamicPropertyFactory
.getInstance();
private static final DynamicStringProperty EUREKA_PROPS_FILE = DynamicPropertyFactory
.getInstance().getStringProperty("eureka.server.props",
"eureka-server");
private static final int TIME_TO_WAIT_FOR_REPLICATION = 30000;
private String namespace = "eureka.";
// These counters are checked for each HTTP request. Instantiating them per request like for the other
// properties would be too costly.
private final DynamicStringSetProperty rateLimiterPrivilegedClients =
new DynamicStringSetProperty(namespace + "rateLimiter.privilegedClients", Collections.<String>emptySet());
private final DynamicBooleanProperty rateLimiterEnabled = configInstance.getBooleanProperty(namespace + "rateLimiter.enabled", false);
private final DynamicBooleanProperty rateLimiterThrottleStandardClients = configInstance.getBooleanProperty(namespace + "rateLimiter.throttleStandardClients", false);
private final DynamicIntProperty rateLimiterBurstSize = configInstance.getIntProperty(namespace + "rateLimiter.burstSize", 10);
private final DynamicIntProperty rateLimiterRegistryFetchAverageRate = configInstance.getIntProperty(namespace + "rateLimiter.registryFetchAverageRate", 500);
private final DynamicIntProperty rateLimiterFullFetchAverageRate = configInstance.getIntProperty(namespace + "rateLimiter.fullFetchAverageRate", 100);
private final DynamicStringProperty listAutoScalingGroupsRoleName =
configInstance.getStringProperty(namespace + "listAutoScalingGroupsRoleName", "ListAutoScalingGroups");
private final DynamicStringProperty myUrl = configInstance.getStringProperty(namespace + "myUrl", null);
public DefaultEurekaServerConfig() {
init();
}
public DefaultEurekaServerConfig(String namespace) {
this.namespace = namespace;
init();
}
private void init() {
String env = ConfigurationManager.getConfigInstance().getString(
EUREKA_ENVIRONMENT, TEST);
ConfigurationManager.getConfigInstance().setProperty(
ARCHAIUS_DEPLOYMENT_ENVIRONMENT, env);
String eurekaPropsFile = EUREKA_PROPS_FILE.get();
try {
// ConfigurationManager
// .loadPropertiesFromResources(eurekaPropsFile);
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);
}
}
/*
* (non-Javadoc)
*
* @see com.netflix.eureka.EurekaServerConfig#getAWSAccessId()
*/
@Override
public String getAWSAccessId() {
String aWSAccessId = configInstance.getStringProperty(
namespace + "awsAccessId", null).get();
if (null != aWSAccessId) {
return aWSAccessId.trim();
} else {
return null;
}
}
/*
* (non-Javadoc)
*
* @see com.netflix.eureka.EurekaServerConfig#getAWSAccessId()
*/
@Override
public String getAWSSecretKey() {
String aWSSecretKey = configInstance.getStringProperty(
namespace + "awsSecretKey", null).get();
if (null != aWSSecretKey) {
return aWSSecretKey.trim();
} else {
return null;
}
}
/*
* (non-Javadoc)
*
* @see com.netflix.eureka.EurekaServerConfig#getEIPBindRebindRetries()
*/
@Override
public int getEIPBindRebindRetries() {
return configInstance.getIntProperty(
namespace + "eipBindRebindRetries", 3).get();
}
/*
* (non-Javadoc)
*
* @see com.netflix.eureka.EurekaServerConfig#getEIPBindingRetryInterval()
*/
@Override
public int getEIPBindingRetryIntervalMsWhenUnbound() {
return configInstance.getIntProperty(
namespace + "eipBindRebindRetryIntervalMsWhenUnbound", (1 * 60 * 1000)).get();
}
/*
* (non-Javadoc)
*
* @see com.netflix.eureka.EurekaServerConfig#getEIPBindingRetryInterval()
*/
@Override
public int getEIPBindingRetryIntervalMs() {
return configInstance.getIntProperty(
namespace + "eipBindRebindRetryIntervalMs", (5 * 60 * 1000)).get();
}
/*
* (non-Javadoc)
*
* @see com.netflix.eureka.EurekaServerConfig#shouldEnableSelfPreservation()
*/
@Override
public boolean shouldEnableSelfPreservation() {
return configInstance.getBooleanProperty(
namespace + "enableSelfPreservation", true).get();
}
/*
* (non-Javadoc)
*
* @see
* com.netflix.eureka.EurekaServerConfig#getPeerEurekaNodesUpdateInterval()
*/
@Override
public int getPeerEurekaNodesUpdateIntervalMs() {
return configInstance
.getIntProperty(namespace + "peerEurekaNodesUpdateIntervalMs",
(10 * 60 * 1000)).get();
}
@Override
public int getRenewalThresholdUpdateIntervalMs() {
return configInstance.getIntProperty(
namespace + "renewalThresholdUpdateIntervalMs",
(15 * 60 * 1000)).get();
}
/*
* (non-Javadoc)
*
* @see
* com.netflix.eureka.EurekaServerConfig#getExpectedClientRenewalIntervalSeconds()
*/
@Override
public int getExpectedClientRenewalIntervalSeconds() {
final int configured = configInstance.getIntProperty(
namespace + "expectedClientRenewalIntervalSeconds",
30).get();
return configured > 0 ? configured : 30;
}
@Override
public double getRenewalPercentThreshold() {
return configInstance.getDoubleProperty(
namespace + "renewalPercentThreshold", 0.85).get();
}
@Override
public boolean shouldEnableReplicatedRequestCompression() {
return configInstance.getBooleanProperty(
namespace + "enableReplicatedRequestCompression", false).get();
}
@Override
public int getNumberOfReplicationRetries() {
return configInstance.getIntProperty(
namespace + "numberOfReplicationRetries", 5).get();
}
@Override
public int getPeerEurekaStatusRefreshTimeIntervalMs() {
return configInstance.getIntProperty(
namespace + "peerEurekaStatusRefreshTimeIntervalMs",
(30 * 1000)).get();
}
@Override
public int getWaitTimeInMsWhenSyncEmpty() {
return configInstance.getIntProperty(
namespace + "waitTimeInMsWhenSyncEmpty", (1000 * 60 * 5)).get();
}
@Override
public int getPeerNodeConnectTimeoutMs() {
return configInstance.getIntProperty(
namespace + "peerNodeConnectTimeoutMs", 1000).get();
}
@Override
public int getPeerNodeReadTimeoutMs() {
return configInstance.getIntProperty(
namespace + "peerNodeReadTimeoutMs", 5000).get();
}
@Override
public int getPeerNodeTotalConnections() {
return configInstance.getIntProperty(
namespace + "peerNodeTotalConnections", 1000).get();
}
@Override
public int getPeerNodeTotalConnectionsPerHost() {
return configInstance.getIntProperty(
namespace + "peerNodeTotalConnectionsPerHost", 500).get();
}
@Override
public int getPeerNodeConnectionIdleTimeoutSeconds() {
return configInstance.getIntProperty(
namespace + "peerNodeConnectionIdleTimeoutSeconds", 30).get();
}
@Override
public long getRetentionTimeInMSInDeltaQueue() {
return configInstance.getLongProperty(
namespace + "retentionTimeInMSInDeltaQueue", (3 * 60 * 1000))
.get();
}
@Override
public long getDeltaRetentionTimerIntervalInMs() {
return configInstance.getLongProperty(
namespace + "deltaRetentionTimerIntervalInMs", (30 * 1000))
.get();
}
@Override
public long getEvictionIntervalTimerInMs() {
return configInstance.getLongProperty(
namespace + "evictionIntervalTimerInMs", (60 * 1000)).get();
}
@Override
public boolean shouldUseAwsAsgApi() {
return configInstance.getBooleanProperty(namespace + "shouldUseAwsAsgApi", true).get();
}
@Override
public int getASGQueryTimeoutMs() {
return configInstance.getIntProperty(namespace + "asgQueryTimeoutMs",
300).get();
}
@Override
public long getASGUpdateIntervalMs() {
return configInstance.getIntProperty(namespace + "asgUpdateIntervalMs",
(5 * 60 * 1000)).get();
}
@Override
public long getASGCacheExpiryTimeoutMs() {
return configInstance.getIntProperty(namespace + "asgCacheExpiryTimeoutMs",
(10 * 60 * 1000)).get(); // defaults to longer than the asg update interval
}
@Override
public long getResponseCacheAutoExpirationInSeconds() {
return configInstance.getIntProperty(
namespace + "responseCacheAutoExpirationInSeconds", 180).get();
}
@Override
public long getResponseCacheUpdateIntervalMs() {
return configInstance.getIntProperty(
namespace + "responseCacheUpdateIntervalMs", (30 * 1000)).get();
}
@Override
public boolean shouldUseReadOnlyResponseCache() {
return configInstance.getBooleanProperty(
namespace + "shouldUseReadOnlyResponseCache", true).get();
}
@Override
public boolean shouldDisableDelta() {
return configInstance.getBooleanProperty(namespace + "disableDelta",
false).get();
}
@Override
public long getMaxIdleThreadInMinutesAgeForStatusReplication() {
return configInstance
.getLongProperty(
namespace + "maxIdleThreadAgeInMinutesForStatusReplication",
10).get();
}
@Override
public int getMinThreadsForStatusReplication() {
return configInstance.getIntProperty(
namespace + "minThreadsForStatusReplication", 1).get();
}
@Override
public int getMaxThreadsForStatusReplication() {
return configInstance.getIntProperty(
namespace + "maxThreadsForStatusReplication", 1).get();
}
@Override
public int getMaxElementsInStatusReplicationPool() {
return configInstance.getIntProperty(
namespace + "maxElementsInStatusReplicationPool", 10000).get();
}
@Override
public boolean shouldSyncWhenTimestampDiffers() {
return configInstance.getBooleanProperty(
namespace + "syncWhenTimestampDiffers", true).get();
}
@Override
public int getRegistrySyncRetries() {
return configInstance.getIntProperty(
namespace + "numberRegistrySyncRetries", 5).get();
}
@Override
public long getRegistrySyncRetryWaitMs() {
return configInstance.getIntProperty(
namespace + "registrySyncRetryWaitMs", 30 * 1000).get();
}
@Override
public int getMaxElementsInPeerReplicationPool() {
return configInstance.getIntProperty(
namespace + "maxElementsInPeerReplicationPool", 10000).get();
}
@Override
public long getMaxIdleThreadAgeInMinutesForPeerReplication() {
return configInstance.getIntProperty(
namespace + "maxIdleThreadAgeInMinutesForPeerReplication", 15)
.get();
}
@Override
public int getMinThreadsForPeerReplication() {
return configInstance.getIntProperty(
namespace + "minThreadsForPeerReplication", 5).get();
}
@Override
public int getMaxThreadsForPeerReplication() {
return configInstance.getIntProperty(
namespace + "maxThreadsForPeerReplication", 20).get();
}
@Override
public int getMaxTimeForReplication() {
return configInstance.getIntProperty(
namespace + "maxTimeForReplication",
TIME_TO_WAIT_FOR_REPLICATION).get();
}
@Override
public boolean shouldPrimeAwsReplicaConnections() {
return configInstance.getBooleanProperty(
namespace + "primeAwsReplicaConnections", true).get();
}
@Override
public boolean shouldDisableDeltaForRemoteRegions() {
return configInstance.getBooleanProperty(
namespace + "disableDeltaForRemoteRegions", false).get();
}
@Override
public int getRemoteRegionConnectTimeoutMs() {
return configInstance.getIntProperty(
namespace + "remoteRegionConnectTimeoutMs", 2000).get();
}
@Override
public int getRemoteRegionReadTimeoutMs() {
return configInstance.getIntProperty(
namespace + "remoteRegionReadTimeoutMs", 5000).get();
}
@Override
public int getRemoteRegionTotalConnections() {
return configInstance.getIntProperty(
namespace + "remoteRegionTotalConnections", 1000).get();
}
@Override
public int getRemoteRegionTotalConnectionsPerHost() {
return configInstance.getIntProperty(
namespace + "remoteRegionTotalConnectionsPerHost", 500).get();
}
@Override
public int getRemoteRegionConnectionIdleTimeoutSeconds() {
return configInstance.getIntProperty(
namespace + "remoteRegionConnectionIdleTimeoutSeconds", 30)
.get();
}
@Override
public boolean shouldGZipContentFromRemoteRegion() {
return configInstance.getBooleanProperty(
namespace + "remoteRegion.gzipContent", true).get();
}
/**
* Expects a property with name: [eureka-namespace].remoteRegionUrlsWithName and a value being a comma separated
* list of region name & remote url pairs, separated with a ";". <br/>
* So, if you wish to specify two regions with name region1 & region2, the property value will be:
<PRE>
eureka.remoteRegionUrlsWithName=region1;http://region1host/eureka/v2,region2;http://region2host/eureka/v2
</PRE>
* The above property will result in the following map:
<PRE>
region1->"http://region1host/eureka/v2"
region2->"http://region2host/eureka/v2"
</PRE>
* @return A map of region name to remote region URL parsed from the property specified above. If there is no
* property available, then an empty map is returned.
*/
@Override
public Map<String, String> getRemoteRegionUrlsWithName() {
String propName = namespace + "remoteRegionUrlsWithName";
String remoteRegionUrlWithNameString = configInstance.getStringProperty(propName, null).get();
if (null == remoteRegionUrlWithNameString) {
return Collections.emptyMap();
}
String[] remoteRegionUrlWithNamePairs = remoteRegionUrlWithNameString.split(",");
Map<String, String> toReturn = new HashMap<String, String>(remoteRegionUrlWithNamePairs.length);
final String pairSplitChar = ";";
for (String remoteRegionUrlWithNamePair : remoteRegionUrlWithNamePairs) {
String[] pairSplit = remoteRegionUrlWithNamePair.split(pairSplitChar);
if (pairSplit.length < 2) {
logger.error("Error reading eureka remote region urls from property {}. "
+ "Invalid entry {} for remote region url. The entry must contain region name and url "
+ "separated by a {}. Ignoring this entry.",
propName, remoteRegionUrlWithNamePair, pairSplitChar);
} else {
String regionName = pairSplit[0];
String regionUrl = pairSplit[1];
if (pairSplit.length > 2) {
StringBuilder regionUrlAssembler = new StringBuilder();
for (int i = 1; i < pairSplit.length; i++) {
if (regionUrlAssembler.length() != 0) {
regionUrlAssembler.append(pairSplitChar);
}
regionUrlAssembler.append(pairSplit[i]);
}
regionUrl = regionUrlAssembler.toString();
}
toReturn.put(regionName, regionUrl);
}
}
return toReturn;
}
@Override
public String[] getRemoteRegionUrls() {
String remoteRegionUrlString = configInstance.getStringProperty(
namespace + "remoteRegionUrls", null).get();
String[] remoteRegionUrl = null;
if (remoteRegionUrlString != null) {
remoteRegionUrl = remoteRegionUrlString.split(",");
}
return remoteRegionUrl;
}
@Nullable
@Override
public Set<String> getRemoteRegionAppWhitelist(@Nullable String regionName) {
if (null == regionName) {
regionName = "global";
} else {
regionName = regionName.trim().toLowerCase();
}
DynamicStringProperty appWhiteListProp =
configInstance.getStringProperty(namespace + "remoteRegion." + regionName + ".appWhiteList", null);
if (null == appWhiteListProp || null == appWhiteListProp.get()) {
return null;
} else {
String appWhiteListStr = appWhiteListProp.get();
String[] whitelistEntries = appWhiteListStr.split(",");
return new HashSet<String>(Arrays.asList(whitelistEntries));
}
}
@Override
public int getRemoteRegionRegistryFetchInterval() {
return configInstance.getIntProperty(
namespace + "remoteRegion.registryFetchIntervalInSeconds", 30)
.get();
}
@Override
public int getRemoteRegionFetchThreadPoolSize() {
return configInstance.getIntProperty(
namespace + "remoteRegion.fetchThreadPoolSize", 20)
.get();
}
@Override
public String getRemoteRegionTrustStore() {
return configInstance.getStringProperty(
namespace + "remoteRegion.trustStoreFileName", "").get();
}
@Override
public String getRemoteRegionTrustStorePassword() {
return configInstance.getStringProperty(
namespace + "remoteRegion.trustStorePassword", "changeit")
.get();
}
@Override
public boolean disableTransparentFallbackToOtherRegion() {
return configInstance.getBooleanProperty(namespace + "remoteRegion.disable.transparent.fallback", false).get();
}
@Override
public boolean shouldBatchReplication() {
return configInstance.getBooleanProperty(namespace + "shouldBatchReplication", false).get();
}
@Override
public String getMyUrl() {
return myUrl.get();
}
@Override
public boolean shouldLogIdentityHeaders() {
return configInstance.getBooleanProperty(namespace + "auth.shouldLogIdentityHeaders", true).get();
}
@Override
public String getJsonCodecName() {
return configInstance.getStringProperty(
namespace + "jsonCodecName", null).get();
}
@Override
public String getXmlCodecName() {
return configInstance.getStringProperty(
namespace + "xmlCodecName", null).get();
}
@Override
public boolean isRateLimiterEnabled() {
return rateLimiterEnabled.get();
}
@Override
public boolean isRateLimiterThrottleStandardClients() {
return rateLimiterThrottleStandardClients.get();
}
@Override
public Set<String> getRateLimiterPrivilegedClients() {
return rateLimiterPrivilegedClients.get();
}
@Override
public int getRateLimiterBurstSize() {
return rateLimiterBurstSize.get();
}
@Override
public int getRateLimiterRegistryFetchAverageRate() {
return rateLimiterRegistryFetchAverageRate.get();
}
@Override
public int getRateLimiterFullFetchAverageRate() {
return rateLimiterFullFetchAverageRate.get();
}
@Override
public String getListAutoScalingGroupsRoleName() {
return listAutoScalingGroupsRoleName.get();
}
@Override
public int getRoute53BindRebindRetries() {
return configInstance.getIntProperty(
namespace + "route53BindRebindRetries", 3).get();
}
@Override
public int getRoute53BindingRetryIntervalMs() {
return configInstance.getIntProperty(
namespace + "route53BindRebindRetryIntervalMs", (5 * 60 * 1000))
.get();
}
@Override
public long getRoute53DomainTTL() {
return configInstance.getLongProperty(
namespace + "route53DomainTTL", 30l)
.get();
}
@Override
public AwsBindingStrategy getBindingStrategy() {
return AwsBindingStrategy.valueOf(configInstance.getStringProperty(namespace + "awsBindingStrategy", AwsBindingStrategy.EIP.name()).get().toUpperCase());
}
@Override
public String getExperimental(String name) {
return configInstance.getStringProperty(namespace + "experimental." + name, null).get();
}
@Override
public int getHealthStatusMinNumberOfAvailablePeers() {
return configInstance.getIntProperty(
namespace + "minAvailableInstancesForPeerReplication", -1).get();
}
@Override
public int getInitialCapacityOfResponseCache() {
return configInstance.getIntProperty(namespace + "initialCapacityOfResponseCache", 1000).get();
}
}
| 8,146 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/V1AwareInstanceInfoConverter.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.eureka;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import com.netflix.discovery.converters.Converters.InstanceInfoConverter;
import com.netflix.eureka.resources.CurrentRequestVersion;
/**
* Support for {@link Version#V1}. {@link Version#V2} introduces a new status
* {@link InstanceStatus#OUT_OF_SERVICE}.
*
* @author Karthik Ranganathan, Greg Kim
*
*/
public class V1AwareInstanceInfoConverter extends InstanceInfoConverter {
@Override
public String getStatus(InstanceInfo info) {
Version version = CurrentRequestVersion.get();
if (version == null || version == Version.V1) {
InstanceStatus status = info.getStatus();
switch (status) {
case DOWN:
case STARTING:
case UP:
break;
default:
// otherwise return DOWN
status = InstanceStatus.DOWN;
break;
}
return status.name();
} else {
return super.getStatus(info);
}
}
}
| 8,147 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/GzipEncodingEnforcingFilter.java | package com.netflix.eureka;
import javax.inject.Singleton;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.HttpHeaders;
import java.io.IOException;
import java.util.Enumeration;
import java.util.NoSuchElementException;
import java.util.concurrent.atomic.AtomicReference;
/**
* Originally Eureka supported non-compressed responses only. For large registries it was extremely
* inefficient, so gzip encoding was added. As nowadays all modern HTTP clients support gzip HTTP response
* transparently, there is no longer need to maintain uncompressed content. By adding this filter, Eureka
* server will accept only GET requests that explicitly support gzip encoding replies. In the coming minor release
* non-compressed replies will be dropped altogether, so this filter will become required.
*
* @author Tomasz Bak
*/
@Singleton
public class GzipEncodingEnforcingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
if ("GET".equals(httpRequest.getMethod())) {
String acceptEncoding = httpRequest.getHeader(HttpHeaders.ACCEPT_ENCODING);
if (acceptEncoding == null) {
chain.doFilter(addGzipAcceptEncoding(httpRequest), response);
return;
}
if (!acceptEncoding.contains("gzip")) {
((HttpServletResponse) response).setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
return;
}
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
private static HttpServletRequest addGzipAcceptEncoding(HttpServletRequest request) {
return new HttpServletRequestWrapper(request) {
@Override
public Enumeration<String> getHeaders(String name) {
if (HttpHeaders.ACCEPT_ENCODING.equals(name)) {
return new EnumWrapper<String>("gzip");
}
return super.getHeaders(name);
}
@Override
public Enumeration<String> getHeaderNames() {
return new EnumWrapper<String>(super.getHeaderNames(), HttpHeaders.ACCEPT_ENCODING);
}
@Override
public String getHeader(String name) {
if (HttpHeaders.ACCEPT_ENCODING.equals(name)) {
return "gzip";
}
return super.getHeader(name);
}
};
}
private static class EnumWrapper<E> implements Enumeration<E> {
private final Enumeration<E> delegate;
private final AtomicReference<E> extraElementRef;
private EnumWrapper(E extraElement) {
this(null, extraElement);
}
private EnumWrapper(Enumeration<E> delegate, E extraElement) {
this.delegate = delegate;
this.extraElementRef = new AtomicReference<>(extraElement);
}
@Override
public boolean hasMoreElements() {
return extraElementRef.get() != null || delegate != null && delegate.hasMoreElements();
}
@Override
public E nextElement() {
E extra = extraElementRef.getAndSet(null);
if (extra != null) {
return extra;
}
if (delegate == null) {
throw new NoSuchElementException();
}
return delegate.nextElement();
}
}
}
| 8,148 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/EurekaServerContextHolder.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.eureka;
/**
* A static holder for the server context for use in non-DI cases.
*
* @author David Liu
*/
public class EurekaServerContextHolder {
private final EurekaServerContext serverContext;
private EurekaServerContextHolder(EurekaServerContext serverContext) {
this.serverContext = serverContext;
}
public EurekaServerContext getServerContext() {
return this.serverContext;
}
private static EurekaServerContextHolder holder;
public static synchronized void initialize(EurekaServerContext serverContext) {
holder = new EurekaServerContextHolder(serverContext);
}
public static EurekaServerContextHolder getInstance() {
return holder;
}
}
| 8,149 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/StatusFilter.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.eureka;
import javax.inject.Singleton;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
/**
* Filter to check whether the eureka server is ready to take requests based on
* its {@link InstanceStatus}.
*/
@Singleton
public class StatusFilter implements Filter {
private static final int SC_TEMPORARY_REDIRECT = 307;
/*
* (non-Javadoc)
*
* @see javax.servlet.Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
* javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
InstanceInfo myInfo = ApplicationInfoManager.getInstance().getInfo();
InstanceStatus status = myInfo.getStatus();
if (status != InstanceStatus.UP && response instanceof HttpServletResponse) {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.sendError(SC_TEMPORARY_REDIRECT,
"Current node is currently not ready to serve requests -- current status: "
+ status + " - try another DS node: ");
}
chain.doFilter(request, response);
}
/*
* (non-Javadoc)
*
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
public void init(FilterConfig arg0) throws ServletException {
}
}
| 8,150 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/EurekaServerIdentity.java | package com.netflix.eureka;
import com.netflix.appinfo.AbstractEurekaIdentity;
/**
* This class holds metadata information related to eureka server auth with peer eureka servers
*/
public class EurekaServerIdentity extends AbstractEurekaIdentity {
public static final String DEFAULT_SERVER_NAME = "DefaultServer";
private final String serverVersion = "1.0";
private final String id;
public EurekaServerIdentity(String id) {
this.id = id;
}
@Override
public String getName() {
return DEFAULT_SERVER_NAME;
}
@Override
public String getVersion() {
return serverVersion;
}
@Override
public String getId() {
return id;
}
}
| 8,151 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/Version.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.eureka;
/**
* Supported versions for Eureka.
*
* <p>The latest versions are always recommended.</p>
*
* @author Karthik Ranganathan, Greg Kim
*
*/
public enum Version {
V1, V2;
public static Version toEnum(String v) {
for (Version version : Version.values()) {
if (version.name().equalsIgnoreCase(v)) {
return version;
}
}
//Defaults to v2
return V2;
}
}
| 8,152 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/cluster/InstanceReplicationTask.java | package com.netflix.eureka.cluster;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl.Action;
/**
* Base {@link ReplicationTask} class for instance related replication requests.
*
* @author Tomasz Bak
*/
public abstract class InstanceReplicationTask extends ReplicationTask {
/**
* For cancel request there may be no InstanceInfo object available so we need to store app/id pair
* explicitly.
*/
private final String appName;
private final String id;
private final InstanceInfo instanceInfo;
private final InstanceStatus overriddenStatus;
private final boolean replicateInstanceInfo;
protected InstanceReplicationTask(String peerNodeName, Action action, String appName, String id) {
super(peerNodeName, action);
this.appName = appName;
this.id = id;
this.instanceInfo = null;
this.overriddenStatus = null;
this.replicateInstanceInfo = false;
}
protected InstanceReplicationTask(String peerNodeName,
Action action,
InstanceInfo instanceInfo,
InstanceStatus overriddenStatus,
boolean replicateInstanceInfo) {
super(peerNodeName, action);
this.appName = instanceInfo.getAppName();
this.id = instanceInfo.getId();
this.instanceInfo = instanceInfo;
this.overriddenStatus = overriddenStatus;
this.replicateInstanceInfo = replicateInstanceInfo;
}
public String getTaskName() {
return appName + '/' + id + ':' + action + '@' + peerNodeName;
}
public String getAppName() {
return appName;
}
public String getId() {
return id;
}
public InstanceInfo getInstanceInfo() {
return instanceInfo;
}
public InstanceStatus getOverriddenStatus() {
return overriddenStatus;
}
public boolean shouldReplicateInstanceInfo() {
return replicateInstanceInfo;
}
}
| 8,153 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/cluster/PeerEurekaNodes.java | package com.netflix.eureka.cluster;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.discovery.endpoint.EndpointUtils;
import com.netflix.eureka.EurekaServerConfig;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
import com.netflix.eureka.resources.ServerCodecs;
import com.netflix.eureka.transport.JerseyReplicationClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Helper class to manage lifecycle of a collection of {@link PeerEurekaNode}s.
*
* @author Tomasz Bak
*/
@Singleton
public class PeerEurekaNodes {
private static final Logger logger = LoggerFactory.getLogger(PeerEurekaNodes.class);
protected final PeerAwareInstanceRegistry registry;
protected final EurekaServerConfig serverConfig;
protected final EurekaClientConfig clientConfig;
protected final ServerCodecs serverCodecs;
private final ApplicationInfoManager applicationInfoManager;
private volatile List<PeerEurekaNode> peerEurekaNodes = Collections.emptyList();
private volatile Set<String> peerEurekaNodeUrls = Collections.emptySet();
private ScheduledExecutorService taskExecutor;
@Inject
public PeerEurekaNodes(
PeerAwareInstanceRegistry registry,
EurekaServerConfig serverConfig,
EurekaClientConfig clientConfig,
ServerCodecs serverCodecs,
ApplicationInfoManager applicationInfoManager) {
this.registry = registry;
this.serverConfig = serverConfig;
this.clientConfig = clientConfig;
this.serverCodecs = serverCodecs;
this.applicationInfoManager = applicationInfoManager;
}
public List<PeerEurekaNode> getPeerNodesView() {
return Collections.unmodifiableList(peerEurekaNodes);
}
public List<PeerEurekaNode> getPeerEurekaNodes() {
return peerEurekaNodes;
}
public int getMinNumberOfAvailablePeers() {
return serverConfig.getHealthStatusMinNumberOfAvailablePeers();
}
public void start() {
taskExecutor = Executors.newSingleThreadScheduledExecutor(
new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r, "Eureka-PeerNodesUpdater");
thread.setDaemon(true);
return thread;
}
}
);
try {
updatePeerEurekaNodes(resolvePeerUrls());
Runnable peersUpdateTask = new Runnable() {
@Override
public void run() {
try {
updatePeerEurekaNodes(resolvePeerUrls());
} catch (Throwable e) {
logger.error("Cannot update the replica Nodes", e);
}
}
};
taskExecutor.scheduleWithFixedDelay(
peersUpdateTask,
serverConfig.getPeerEurekaNodesUpdateIntervalMs(),
serverConfig.getPeerEurekaNodesUpdateIntervalMs(),
TimeUnit.MILLISECONDS
);
} catch (Exception e) {
throw new IllegalStateException(e);
}
for (PeerEurekaNode node : peerEurekaNodes) {
logger.info("Replica node URL: {}", node.getServiceUrl());
}
}
public void shutdown() {
taskExecutor.shutdown();
List<PeerEurekaNode> toRemove = this.peerEurekaNodes;
this.peerEurekaNodes = Collections.emptyList();
this.peerEurekaNodeUrls = Collections.emptySet();
for (PeerEurekaNode node : toRemove) {
node.shutDown();
}
}
/**
* Resolve peer URLs.
*
* @return peer URLs with node's own URL filtered out
*/
protected List<String> resolvePeerUrls() {
InstanceInfo myInfo = applicationInfoManager.getInfo();
String zone = InstanceInfo.getZone(clientConfig.getAvailabilityZones(clientConfig.getRegion()), myInfo);
List<String> replicaUrls = EndpointUtils
.getDiscoveryServiceUrls(clientConfig, zone, new EndpointUtils.InstanceInfoBasedUrlRandomizer(myInfo));
int idx = 0;
while (idx < replicaUrls.size()) {
if (isThisMyUrl(replicaUrls.get(idx))) {
replicaUrls.remove(idx);
} else {
idx++;
}
}
return replicaUrls;
}
/**
* Given new set of replica URLs, destroy {@link PeerEurekaNode}s no longer available, and
* create new ones.
*
* @param newPeerUrls peer node URLs; this collection should have local node's URL filtered out
*/
protected void updatePeerEurekaNodes(List<String> newPeerUrls) {
if (newPeerUrls.isEmpty()) {
logger.warn("The replica size seems to be empty. Check the route 53 DNS Registry");
return;
}
Set<String> toShutdown = new HashSet<>(peerEurekaNodeUrls);
toShutdown.removeAll(newPeerUrls);
Set<String> toAdd = new HashSet<>(newPeerUrls);
toAdd.removeAll(peerEurekaNodeUrls);
if (toShutdown.isEmpty() && toAdd.isEmpty()) { // No change
return;
}
// Remove peers no long available
List<PeerEurekaNode> newNodeList = new ArrayList<>(peerEurekaNodes);
if (!toShutdown.isEmpty()) {
logger.info("Removing no longer available peer nodes {}", toShutdown);
int i = 0;
while (i < newNodeList.size()) {
PeerEurekaNode eurekaNode = newNodeList.get(i);
if (toShutdown.contains(eurekaNode.getServiceUrl())) {
newNodeList.remove(i);
eurekaNode.shutDown();
} else {
i++;
}
}
}
// Add new peers
if (!toAdd.isEmpty()) {
logger.info("Adding new peer nodes {}", toAdd);
for (String peerUrl : toAdd) {
newNodeList.add(createPeerEurekaNode(peerUrl));
}
}
this.peerEurekaNodes = newNodeList;
this.peerEurekaNodeUrls = new HashSet<>(newPeerUrls);
}
protected PeerEurekaNode createPeerEurekaNode(String peerEurekaNodeUrl) {
HttpReplicationClient replicationClient = JerseyReplicationClient.createReplicationClient(serverConfig, serverCodecs, peerEurekaNodeUrl);
String targetHost = hostFromUrl(peerEurekaNodeUrl);
if (targetHost == null) {
targetHost = "host";
}
return new PeerEurekaNode(registry, targetHost, peerEurekaNodeUrl, replicationClient, serverConfig);
}
/**
* @deprecated 2016-06-27 use instance version of {@link #isThisMyUrl(String)}
*
* Checks if the given service url contains the current host which is trying
* to replicate. Only after the EIP binding is done the host has a chance to
* identify itself in the list of replica nodes and needs to take itself out
* of replication traffic.
*
* @param url the service url of the replica node that the check is made.
* @return true, if the url represents the current node which is trying to
* replicate, false otherwise.
*/
public static boolean isThisMe(String url) {
InstanceInfo myInfo = ApplicationInfoManager.getInstance().getInfo();
String hostName = hostFromUrl(url);
return hostName != null && hostName.equals(myInfo.getHostName());
}
/**
* Checks if the given service url contains the current host which is trying
* to replicate. Only after the EIP binding is done the host has a chance to
* identify itself in the list of replica nodes and needs to take itself out
* of replication traffic.
*
* @param url the service url of the replica node that the check is made.
* @return true, if the url represents the current node which is trying to
* replicate, false otherwise.
*/
public boolean isThisMyUrl(String url) {
final String myUrlConfigured = serverConfig.getMyUrl();
if (myUrlConfigured != null) {
return myUrlConfigured.equals(url);
}
return isInstanceURL(url, applicationInfoManager.getInfo());
}
/**
* Checks if the given service url matches the supplied instance
*
* @param url the service url of the replica node that the check is made.
* @param instance the instance to check the service url against
* @return true, if the url represents the supplied instance, false otherwise.
*/
public boolean isInstanceURL(String url, InstanceInfo instance) {
String hostName = hostFromUrl(url);
String myInfoComparator = instance.getHostName();
if (clientConfig.getTransportConfig().applicationsResolverUseIp()) {
myInfoComparator = instance.getIPAddr();
}
return hostName != null && hostName.equals(myInfoComparator);
}
public static String hostFromUrl(String url) {
URI uri;
try {
uri = new URI(url);
} catch (URISyntaxException e) {
logger.warn("Cannot parse service URI {}", url, e);
return null;
}
return uri.getHost();
}
}
| 8,154 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/cluster/HttpReplicationClient.java | package com.netflix.eureka.cluster;
import com.netflix.discovery.shared.transport.EurekaHttpClient;
import com.netflix.discovery.shared.transport.EurekaHttpResponse;
import com.netflix.eureka.cluster.protocol.ReplicationList;
import com.netflix.eureka.cluster.protocol.ReplicationListResponse;
import com.netflix.eureka.resources.ASGResource.ASGStatus;
/**
* @author Tomasz Bak
*/
public interface HttpReplicationClient extends EurekaHttpClient {
EurekaHttpResponse<Void> statusUpdate(String asgName, ASGStatus newStatus);
EurekaHttpResponse<ReplicationListResponse> submitBatchUpdates(ReplicationList replicationList);
}
| 8,155 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/cluster/DynamicGZIPContentEncodingFilter.java | package com.netflix.eureka.cluster;
import javax.ws.rs.core.HttpHeaders;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import com.netflix.eureka.EurekaServerConfig;
import com.sun.jersey.api.client.AbstractClientRequestAdapter;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientRequest;
import com.sun.jersey.api.client.ClientRequestAdapter;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.filter.ClientFilter;
/**
* Eureka specific GZIP content filter handler.
*/
public class DynamicGZIPContentEncodingFilter extends ClientFilter {
private static final String GZIP_ENCODING = "gzip";
private final EurekaServerConfig config;
public DynamicGZIPContentEncodingFilter(EurekaServerConfig config) {
this.config = config;
}
@Override
public ClientResponse handle(ClientRequest request) {
// If 'Accept-Encoding' is not set, assume gzip as a default
if (!request.getHeaders().containsKey(HttpHeaders.ACCEPT_ENCODING)) {
request.getHeaders().add(HttpHeaders.ACCEPT_ENCODING, GZIP_ENCODING);
}
if (request.getEntity() != null) {
Object requestEncoding = request.getHeaders().getFirst(HttpHeaders.CONTENT_ENCODING);
if (GZIP_ENCODING.equals(requestEncoding)) {
request.setAdapter(new GzipAdapter(request.getAdapter()));
} else if (isCompressionEnabled()) {
request.getHeaders().add(HttpHeaders.CONTENT_ENCODING, GZIP_ENCODING);
request.setAdapter(new GzipAdapter(request.getAdapter()));
}
}
ClientResponse response = getNext().handle(request);
String responseEncoding = response.getHeaders().getFirst(HttpHeaders.CONTENT_ENCODING);
if (response.hasEntity() && GZIP_ENCODING.equals(responseEncoding)) {
response.getHeaders().remove(HttpHeaders.CONTENT_ENCODING);
decompressResponse(response);
}
return response;
}
private boolean isCompressionEnabled() {
return config.shouldEnableReplicatedRequestCompression();
}
private static void decompressResponse(ClientResponse response) {
InputStream entityInputStream = response.getEntityInputStream();
GZIPInputStream uncompressedIS;
try {
uncompressedIS = new GZIPInputStream(entityInputStream);
} catch (IOException ex) {
try {
entityInputStream.close();
} catch (IOException ignored) {
}
throw new ClientHandlerException(ex);
}
response.setEntityInputStream(uncompressedIS);
}
private static final class GzipAdapter extends AbstractClientRequestAdapter {
GzipAdapter(ClientRequestAdapter cra) {
super(cra);
}
@Override
public OutputStream adapt(ClientRequest request, OutputStream out) throws IOException {
return new GZIPOutputStream(getAdapter().adapt(request, out));
}
}
} | 8,156 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/cluster/AsgReplicationTask.java | package com.netflix.eureka.cluster;
import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl.Action;
import com.netflix.eureka.resources.ASGResource.ASGStatus;
/**
* Base {@link ReplicationTask} class for ASG related replication requests.
*
* @author Tomasz Bak
*/
public abstract class AsgReplicationTask extends ReplicationTask {
private final String asgName;
private final ASGStatus newStatus;
protected AsgReplicationTask(String peerNodeName, Action action, String asgName, ASGStatus newStatus) {
super(peerNodeName, action);
this.asgName = asgName;
this.newStatus = newStatus;
}
@Override
public String getTaskName() {
return asgName + ':' + action + '@' + peerNodeName;
}
public String getAsgName() {
return asgName;
}
public ASGStatus getNewStatus() {
return newStatus;
}
}
| 8,157 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/cluster/ReplicationTaskProcessor.java | package com.netflix.eureka.cluster;
import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.shared.transport.EurekaHttpResponse;
import com.netflix.eureka.cluster.protocol.ReplicationInstance;
import com.netflix.eureka.cluster.protocol.ReplicationInstance.ReplicationInstanceBuilder;
import com.netflix.eureka.cluster.protocol.ReplicationInstanceResponse;
import com.netflix.eureka.cluster.protocol.ReplicationList;
import com.netflix.eureka.cluster.protocol.ReplicationListResponse;
import com.netflix.eureka.util.batcher.TaskProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.netflix.eureka.cluster.protocol.ReplicationInstance.ReplicationInstanceBuilder.aReplicationInstance;
/**
* @author Tomasz Bak
*/
class ReplicationTaskProcessor implements TaskProcessor<ReplicationTask> {
private static final Logger logger = LoggerFactory.getLogger(ReplicationTaskProcessor.class);
private final HttpReplicationClient replicationClient;
private final String peerId;
private volatile long lastNetworkErrorTime;
private static final Pattern READ_TIME_OUT_PATTERN = Pattern.compile(".*read.*time.*out.*");
ReplicationTaskProcessor(String peerId, HttpReplicationClient replicationClient) {
this.replicationClient = replicationClient;
this.peerId = peerId;
}
@Override
public ProcessingResult process(ReplicationTask task) {
try {
EurekaHttpResponse<?> httpResponse = task.execute();
int statusCode = httpResponse.getStatusCode();
Object entity = httpResponse.getEntity();
if (logger.isDebugEnabled()) {
logger.debug("Replication task {} completed with status {}, (includes entity {})", task.getTaskName(), statusCode, entity != null);
}
if (isSuccess(statusCode)) {
task.handleSuccess();
} else if (statusCode == 503) {
logger.debug("Server busy (503) reply for task {}", task.getTaskName());
return ProcessingResult.Congestion;
} else {
task.handleFailure(statusCode, entity);
return ProcessingResult.PermanentError;
}
} catch (Throwable e) {
if (maybeReadTimeOut(e)) {
logger.error("It seems to be a socket read timeout exception, it will retry later. if it continues to happen and some eureka node occupied all the cpu time, you should set property 'eureka.server.peer-node-read-timeout-ms' to a bigger value", e);
//read timeout exception is more Congestion then TransientError, return Congestion for longer delay
return ProcessingResult.Congestion;
} else if (isNetworkConnectException(e)) {
logNetworkErrorSample(task, e);
return ProcessingResult.TransientError;
} else {
logger.error("{}: {} Not re-trying this exception because it does not seem to be a network exception",
peerId, task.getTaskName(), e);
return ProcessingResult.PermanentError;
}
}
return ProcessingResult.Success;
}
@Override
public ProcessingResult process(List<ReplicationTask> tasks) {
ReplicationList list = createReplicationListOf(tasks);
try {
EurekaHttpResponse<ReplicationListResponse> response = replicationClient.submitBatchUpdates(list);
int statusCode = response.getStatusCode();
if (!isSuccess(statusCode)) {
if (statusCode == 503) {
logger.warn("Server busy (503) HTTP status code received from the peer {}; rescheduling tasks after delay", peerId);
return ProcessingResult.Congestion;
} else {
// Unexpected error returned from the server. This should ideally never happen.
logger.error("Batch update failure with HTTP status code {}; discarding {} replication tasks", statusCode, tasks.size());
return ProcessingResult.PermanentError;
}
} else {
handleBatchResponse(tasks, response.getEntity().getResponseList());
}
} catch (Throwable e) {
if (maybeReadTimeOut(e)) {
logger.error("It seems to be a socket read timeout exception, it will retry later. if it continues to happen and some eureka node occupied all the cpu time, you should set property 'eureka.server.peer-node-read-timeout-ms' to a bigger value", e);
//read timeout exception is more Congestion then TransientError, return Congestion for longer delay
return ProcessingResult.Congestion;
} else if (isNetworkConnectException(e)) {
logNetworkErrorSample(null, e);
return ProcessingResult.TransientError;
} else {
logger.error("Not re-trying this exception because it does not seem to be a network exception", e);
return ProcessingResult.PermanentError;
}
}
return ProcessingResult.Success;
}
/**
* We want to retry eagerly, but without flooding log file with tons of error entries.
* As tasks are executed by a pool of threads the error logging multiplies. For example:
* 20 threads * 100ms delay == 200 error entries / sec worst case
* Still we would like to see the exception samples, so we print samples at regular intervals.
*/
private void logNetworkErrorSample(ReplicationTask task, Throwable e) {
long now = System.currentTimeMillis();
if (now - lastNetworkErrorTime > 10000) {
lastNetworkErrorTime = now;
StringBuilder sb = new StringBuilder();
sb.append("Network level connection to peer ").append(peerId);
if (task != null) {
sb.append(" for task ").append(task.getTaskName());
}
sb.append("; retrying after delay");
logger.error(sb.toString(), e);
}
}
private void handleBatchResponse(List<ReplicationTask> tasks, List<ReplicationInstanceResponse> responseList) {
if (tasks.size() != responseList.size()) {
// This should ideally never happen unless there is a bug in the software.
logger.error("Batch response size different from submitted task list ({} != {}); skipping response analysis", responseList.size(), tasks.size());
return;
}
for (int i = 0; i < tasks.size(); i++) {
handleBatchResponse(tasks.get(i), responseList.get(i));
}
}
private void handleBatchResponse(ReplicationTask task, ReplicationInstanceResponse response) {
int statusCode = response.getStatusCode();
if (isSuccess(statusCode)) {
task.handleSuccess();
return;
}
try {
task.handleFailure(response.getStatusCode(), response.getResponseEntity());
} catch (Throwable e) {
logger.error("Replication task {} error handler failure", task.getTaskName(), e);
}
}
private ReplicationList createReplicationListOf(List<ReplicationTask> tasks) {
ReplicationList list = new ReplicationList();
for (ReplicationTask task : tasks) {
// Only InstanceReplicationTask are batched.
list.addReplicationInstance(createReplicationInstanceOf((InstanceReplicationTask) task));
}
return list;
}
private static boolean isSuccess(int statusCode) {
return statusCode >= 200 && statusCode < 300;
}
/**
* Check if the exception is some sort of network timeout exception (ie)
* read,connect.
*
* @param e
* The exception for which the information needs to be found.
* @return true, if it is a network timeout, false otherwise.
*/
private static boolean isNetworkConnectException(Throwable e) {
do {
if (IOException.class.isInstance(e)) {
return true;
}
e = e.getCause();
} while (e != null);
return false;
}
/**
* Check if the exception is socket read time out exception
*
* @param e
* The exception for which the information needs to be found.
* @return true, if it may be a socket read time out exception.
*/
private static boolean maybeReadTimeOut(Throwable e) {
do {
if (IOException.class.isInstance(e)) {
String message = e.getMessage().toLowerCase();
Matcher matcher = READ_TIME_OUT_PATTERN.matcher(message);
if(matcher.find()) {
return true;
}
}
e = e.getCause();
} while (e != null);
return false;
}
private static ReplicationInstance createReplicationInstanceOf(InstanceReplicationTask task) {
ReplicationInstanceBuilder instanceBuilder = aReplicationInstance();
instanceBuilder.withAppName(task.getAppName());
instanceBuilder.withId(task.getId());
InstanceInfo instanceInfo = task.getInstanceInfo();
if (instanceInfo != null) {
String overriddenStatus = task.getOverriddenStatus() == null ? null : task.getOverriddenStatus().name();
instanceBuilder.withOverriddenStatus(overriddenStatus);
instanceBuilder.withLastDirtyTimestamp(instanceInfo.getLastDirtyTimestamp());
if (task.shouldReplicateInstanceInfo()) {
instanceBuilder.withInstanceInfo(instanceInfo);
}
String instanceStatus = instanceInfo.getStatus() == null ? null : instanceInfo.getStatus().name();
instanceBuilder.withStatus(instanceStatus);
}
instanceBuilder.withAction(task.getAction());
return instanceBuilder.build();
}
}
| 8,158 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/cluster/ReplicationTask.java | package com.netflix.eureka.cluster;
import com.netflix.discovery.shared.transport.EurekaHttpResponse;
import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl.Action;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Base class for all replication tasks.
*/
abstract class ReplicationTask {
private static final Logger logger = LoggerFactory.getLogger(ReplicationTask.class);
protected final String peerNodeName;
protected final Action action;
ReplicationTask(String peerNodeName, Action action) {
this.peerNodeName = peerNodeName;
this.action = action;
}
public abstract String getTaskName();
public Action getAction() {
return action;
}
public abstract EurekaHttpResponse<?> execute() throws Throwable;
public void handleSuccess() {
}
public void handleFailure(int statusCode, Object responseEntity) throws Throwable {
logger.warn("The replication of task {} failed with response code {}", getTaskName(), statusCode);
}
}
| 8,159 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/cluster/PeerEurekaNode.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.eureka.cluster;
import java.net.MalformedURLException;
import java.net.URL;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import com.netflix.discovery.shared.transport.EurekaHttpResponse;
import com.netflix.eureka.EurekaServerConfig;
import com.netflix.eureka.lease.Lease;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl.Action;
import com.netflix.eureka.resources.ASGResource.ASGStatus;
import com.netflix.eureka.util.batcher.TaskDispatcher;
import com.netflix.eureka.util.batcher.TaskDispatchers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The <code>PeerEurekaNode</code> represents a peer node to which information
* should be shared from this node.
*
* <p>
* This class handles replicating all update operations like
* <em>Register,Renew,Cancel,Expiration and Status Changes</em> to the eureka
* node it represents.
* <p>
*
* @author Karthik Ranganathan, Greg Kim
*
*/
public class PeerEurekaNode {
/**
* A time to wait before continuing work if there is network level error.
*/
private static final long RETRY_SLEEP_TIME_MS = 100;
/**
* A time to wait before continuing work if there is congestion on the server side.
*/
private static final long SERVER_UNAVAILABLE_SLEEP_TIME_MS = 1000;
/**
* Maximum amount of time in ms to wait for new items prior to dispatching a batch of tasks.
*/
private static final long MAX_BATCHING_DELAY_MS = 500;
/**
* Maximum batch size for batched requests.
*/
private static final int BATCH_SIZE = 250;
private static final Logger logger = LoggerFactory.getLogger(PeerEurekaNode.class);
public static final String BATCH_URL_PATH = "peerreplication/batch/";
public static final String HEADER_REPLICATION = "x-netflix-discovery-replication";
private final String serviceUrl;
private final EurekaServerConfig config;
private final long maxProcessingDelayMs;
private final PeerAwareInstanceRegistry registry;
private final String targetHost;
private final HttpReplicationClient replicationClient;
private final TaskDispatcher<String, ReplicationTask> batchingDispatcher;
private final TaskDispatcher<String, ReplicationTask> nonBatchingDispatcher;
public PeerEurekaNode(PeerAwareInstanceRegistry registry, String targetHost, String serviceUrl, HttpReplicationClient replicationClient, EurekaServerConfig config) {
this(registry, targetHost, serviceUrl, replicationClient, config, BATCH_SIZE, MAX_BATCHING_DELAY_MS, RETRY_SLEEP_TIME_MS, SERVER_UNAVAILABLE_SLEEP_TIME_MS);
}
/* For testing */ PeerEurekaNode(PeerAwareInstanceRegistry registry, String targetHost, String serviceUrl,
HttpReplicationClient replicationClient, EurekaServerConfig config,
int batchSize, long maxBatchingDelayMs,
long retrySleepTimeMs, long serverUnavailableSleepTimeMs) {
this.registry = registry;
this.targetHost = targetHost;
this.replicationClient = replicationClient;
this.serviceUrl = serviceUrl;
this.config = config;
this.maxProcessingDelayMs = config.getMaxTimeForReplication();
String batcherName = getBatcherName();
ReplicationTaskProcessor taskProcessor = new ReplicationTaskProcessor(targetHost, replicationClient);
this.batchingDispatcher = TaskDispatchers.createBatchingTaskDispatcher(
batcherName,
config.getMaxElementsInPeerReplicationPool(),
batchSize,
config.getMaxThreadsForPeerReplication(),
maxBatchingDelayMs,
serverUnavailableSleepTimeMs,
retrySleepTimeMs,
taskProcessor
);
this.nonBatchingDispatcher = TaskDispatchers.createNonBatchingTaskDispatcher(
targetHost,
config.getMaxElementsInStatusReplicationPool(),
config.getMaxThreadsForStatusReplication(),
maxBatchingDelayMs,
serverUnavailableSleepTimeMs,
retrySleepTimeMs,
taskProcessor
);
}
/**
* Sends the registration information of {@link InstanceInfo} receiving by
* this node to the peer node represented by this class.
*
* @param info
* the instance information {@link InstanceInfo} of any instance
* that is send to this instance.
* @throws Exception
*/
public void register(final InstanceInfo info) throws Exception {
long expiryTime = System.currentTimeMillis() + getLeaseRenewalOf(info);
batchingDispatcher.process(
taskId("register", info),
new InstanceReplicationTask(targetHost, Action.Register, info, null, true) {
public EurekaHttpResponse<Void> execute() {
return replicationClient.register(info);
}
},
expiryTime
);
}
/**
* Send the cancellation information of an instance to the node represented
* by this class.
*
* @param appName
* the application name of the instance.
* @param id
* the unique identifier of the instance.
* @throws Exception
*/
public void cancel(final String appName, final String id) throws Exception {
long expiryTime = System.currentTimeMillis() + maxProcessingDelayMs;
batchingDispatcher.process(
taskId("cancel", appName, id),
new InstanceReplicationTask(targetHost, Action.Cancel, appName, id) {
@Override
public EurekaHttpResponse<Void> execute() {
return replicationClient.cancel(appName, id);
}
@Override
public void handleFailure(int statusCode, Object responseEntity) throws Throwable {
super.handleFailure(statusCode, responseEntity);
if (statusCode == 404) {
logger.warn("{}: missing entry.", getTaskName());
}
}
},
expiryTime
);
}
/**
* Send the heartbeat information of an instance to the node represented by
* this class. If the instance does not exist the node, the instance
* registration information is sent again to the peer node.
*
* @param appName
* the application name of the instance.
* @param id
* the unique identifier of the instance.
* @param info
* the instance info {@link InstanceInfo} of the instance.
* @param overriddenStatus
* the overridden status information if any of the instance.
* @throws Throwable
*/
public void heartbeat(final String appName, final String id,
final InstanceInfo info, final InstanceStatus overriddenStatus,
boolean primeConnection) throws Throwable {
if (primeConnection) {
// We do not care about the result for priming request.
replicationClient.sendHeartBeat(appName, id, info, overriddenStatus);
return;
}
ReplicationTask replicationTask = new InstanceReplicationTask(targetHost, Action.Heartbeat, info, overriddenStatus, false) {
@Override
public EurekaHttpResponse<InstanceInfo> execute() throws Throwable {
return replicationClient.sendHeartBeat(appName, id, info, overriddenStatus);
}
@Override
public void handleFailure(int statusCode, Object responseEntity) throws Throwable {
super.handleFailure(statusCode, responseEntity);
if (statusCode == 404) {
logger.warn("{}: missing entry.", getTaskName());
if (info != null) {
logger.warn("{}: cannot find instance id {} and hence replicating the instance with status {}",
getTaskName(), info.getId(), info.getStatus());
register(info);
}
} else if (config.shouldSyncWhenTimestampDiffers()) {
InstanceInfo peerInstanceInfo = (InstanceInfo) responseEntity;
if (peerInstanceInfo != null) {
syncInstancesIfTimestampDiffers(appName, id, info, peerInstanceInfo);
}
}
}
};
long expiryTime = System.currentTimeMillis() + getLeaseRenewalOf(info);
batchingDispatcher.process(taskId("heartbeat", info), replicationTask, expiryTime);
}
/**
* Send the status information of of the ASG represented by the instance.
*
* <p>
* ASG (Autoscaling group) names are available for instances in AWS and the
* ASG information is used for determining if the instance should be
* registered as {@link InstanceStatus#DOWN} or {@link InstanceStatus#UP}.
*
* @param asgName
* the asg name if any of this instance.
* @param newStatus
* the new status of the ASG.
*/
public void statusUpdate(final String asgName, final ASGStatus newStatus) {
long expiryTime = System.currentTimeMillis() + maxProcessingDelayMs;
nonBatchingDispatcher.process(
asgName,
new AsgReplicationTask(targetHost, Action.StatusUpdate, asgName, newStatus) {
public EurekaHttpResponse<?> execute() {
return replicationClient.statusUpdate(asgName, newStatus);
}
},
expiryTime
);
}
/**
*
* Send the status update of the instance.
*
* @param appName
* the application name of the instance.
* @param id
* the unique identifier of the instance.
* @param newStatus
* the new status of the instance.
* @param info
* the instance information of the instance.
*/
public void statusUpdate(final String appName, final String id,
final InstanceStatus newStatus, final InstanceInfo info) {
long expiryTime = System.currentTimeMillis() + maxProcessingDelayMs;
batchingDispatcher.process(
taskId("statusUpdate", appName, id),
new InstanceReplicationTask(targetHost, Action.StatusUpdate, info, null, false) {
@Override
public EurekaHttpResponse<Void> execute() {
return replicationClient.statusUpdate(appName, id, newStatus, info);
}
},
expiryTime
);
}
/**
* Delete instance status override.
*
* @param appName
* the application name of the instance.
* @param id
* the unique identifier of the instance.
* @param info
* the instance information of the instance.
*/
public void deleteStatusOverride(final String appName, final String id, final InstanceInfo info) {
long expiryTime = System.currentTimeMillis() + maxProcessingDelayMs;
batchingDispatcher.process(
taskId("deleteStatusOverride", appName, id),
new InstanceReplicationTask(targetHost, Action.DeleteStatusOverride, info, null, false) {
@Override
public EurekaHttpResponse<Void> execute() {
return replicationClient.deleteStatusOverride(appName, id, info);
}
},
expiryTime);
}
/**
* Get the service Url of the peer eureka node.
*
* @return the service Url of the peer eureka node.
*/
public String getServiceUrl() {
return serviceUrl;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((serviceUrl == null) ? 0 : serviceUrl.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
PeerEurekaNode other = (PeerEurekaNode) obj;
if (serviceUrl == null) {
if (other.serviceUrl != null) {
return false;
}
} else if (!serviceUrl.equals(other.serviceUrl)) {
return false;
}
return true;
}
/**
* Shuts down all resources used for peer replication.
*/
public void shutDown() {
batchingDispatcher.shutdown();
nonBatchingDispatcher.shutdown();
replicationClient.shutdown();
}
/**
* Synchronize {@link InstanceInfo} information if the timestamp between
* this node and the peer eureka nodes vary.
*/
private void syncInstancesIfTimestampDiffers(String appName, String id, InstanceInfo info, InstanceInfo infoFromPeer) {
try {
if (infoFromPeer != null) {
logger.warn("Peer wants us to take the instance information from it, since the timestamp differs,"
+ "Id : {} My Timestamp : {}, Peer's timestamp: {}", id, info.getLastDirtyTimestamp(), infoFromPeer.getLastDirtyTimestamp());
if (infoFromPeer.getOverriddenStatus() != null && !InstanceStatus.UNKNOWN.equals(infoFromPeer.getOverriddenStatus())) {
logger.warn("Overridden Status info -id {}, mine {}, peer's {}", id, info.getOverriddenStatus(), infoFromPeer.getOverriddenStatus());
registry.storeOverriddenStatusIfRequired(appName, id, infoFromPeer.getOverriddenStatus());
}
registry.register(infoFromPeer, true);
}
} catch (Throwable e) {
logger.warn("Exception when trying to set information from peer :", e);
}
}
public String getBatcherName() {
String batcherName;
try {
batcherName = new URL(serviceUrl).getHost();
} catch (MalformedURLException e1) {
batcherName = serviceUrl;
}
return "target_" + batcherName;
}
private static String taskId(String requestType, String appName, String id) {
return requestType + '#' + appName + '/' + id;
}
private static String taskId(String requestType, InstanceInfo info) {
return taskId(requestType, info.getAppName(), info.getId());
}
private static int getLeaseRenewalOf(InstanceInfo info) {
return (info.getLeaseInfo() == null ? Lease.DEFAULT_DURATION_IN_SECS : info.getLeaseInfo().getRenewalIntervalInSecs()) * 1000;
}
}
| 8,160 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/cluster | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/cluster/protocol/ReplicationList.java | package com.netflix.eureka.cluster.protocol;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.netflix.discovery.provider.Serializer;
/**
* @author Tomasz Bak
*/
@Serializer("jackson") // For backwards compatibility with DiscoveryJerseyProvider
public class ReplicationList {
private final List<ReplicationInstance> replicationList;
public ReplicationList() {
this.replicationList = new ArrayList<>();
}
@JsonCreator
public ReplicationList(@JsonProperty("replicationList") List<ReplicationInstance> replicationList) {
this.replicationList = replicationList;
}
public ReplicationList(ReplicationInstance replicationInstance) {
this(Collections.singletonList(replicationInstance));
}
public void addReplicationInstance(ReplicationInstance instance) {
replicationList.add(instance);
}
public List<ReplicationInstance> getReplicationList() {
return this.replicationList;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
ReplicationList that = (ReplicationList) o;
return !(replicationList != null ? !replicationList.equals(that.replicationList) : that.replicationList != null);
}
@Override
public int hashCode() {
return replicationList != null ? replicationList.hashCode() : 0;
}
}
| 8,161 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/cluster | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/cluster/protocol/ReplicationInstanceResponse.java | package com.netflix.eureka.cluster.protocol;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.netflix.appinfo.InstanceInfo;
/**
* The jersey resource class that generates the replication indivdiual response.
*/
public class ReplicationInstanceResponse {
private final int statusCode;
private final InstanceInfo responseEntity;
@JsonCreator
public ReplicationInstanceResponse(
@JsonProperty("statusCode") int statusCode,
@JsonProperty("responseEntity") InstanceInfo responseEntity) {
this.statusCode = statusCode;
this.responseEntity = responseEntity;
}
public int getStatusCode() {
return statusCode;
}
public InstanceInfo getResponseEntity() {
return responseEntity;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
ReplicationInstanceResponse that = (ReplicationInstanceResponse) o;
if (statusCode != that.statusCode)
return false;
if (responseEntity != null ? !responseEntity.equals(that.responseEntity) : that.responseEntity != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = statusCode;
result = 31 * result + (responseEntity != null ? responseEntity.hashCode() : 0);
return result;
}
public static final class Builder {
private int statusCode;
private InstanceInfo responseEntity;
public Builder setStatusCode(int statusCode) {
this.statusCode = statusCode;
return this;
}
public Builder setResponseEntity(InstanceInfo entity) {
this.responseEntity = entity;
return this;
}
public ReplicationInstanceResponse build() {
return new ReplicationInstanceResponse(statusCode, responseEntity);
}
}
}
| 8,162 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/cluster | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/cluster/protocol/ReplicationListResponse.java | package com.netflix.eureka.cluster.protocol;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.netflix.discovery.provider.Serializer;
/**
* The jersey resource class that generates the replication batch response.
*/
@Serializer("jackson") // For backwards compatibility with DiscoveryJerseyProvider
public class ReplicationListResponse {
private List<ReplicationInstanceResponse> responseList;
public ReplicationListResponse() {
this.responseList = new ArrayList<ReplicationInstanceResponse>();
}
@JsonCreator
public ReplicationListResponse(@JsonProperty("responseList") List<ReplicationInstanceResponse> responseList) {
this.responseList = responseList;
}
public List<ReplicationInstanceResponse> getResponseList() {
return responseList;
}
public void addResponse(ReplicationInstanceResponse singleResponse) {
responseList.add(singleResponse);
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
ReplicationListResponse that = (ReplicationListResponse) o;
return !(responseList != null ? !responseList.equals(that.responseList) : that.responseList != null);
}
@Override
public int hashCode() {
return responseList != null ? responseList.hashCode() : 0;
}
}
| 8,163 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/cluster | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/cluster/protocol/ReplicationInstance.java | package com.netflix.eureka.cluster.protocol;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl.Action;
/**
* The jersey resource class that generates a particular replication event
*/
public class ReplicationInstance {
private String appName;
private String id;
private Long lastDirtyTimestamp;
private String overriddenStatus;
private String status;
private InstanceInfo instanceInfo;
private Action action;
@JsonCreator
public ReplicationInstance(@JsonProperty("appName") String appName,
@JsonProperty("id") String id,
@JsonProperty("lastDirtyTimestamp") Long lastDirtyTimestamp,
@JsonProperty("overriddenStatus") String overriddenStatus,
@JsonProperty("status") String status,
@JsonProperty("instanceInfo") InstanceInfo instanceInfo,
@JsonProperty("action") Action action) {
this.appName = appName;
this.id = id;
this.lastDirtyTimestamp = lastDirtyTimestamp;
this.overriddenStatus = overriddenStatus;
this.status = status;
this.instanceInfo = instanceInfo;
this.action = action;
}
public String getAppName() {
return appName;
}
public String getId() {
return id;
}
public Long getLastDirtyTimestamp() {
return lastDirtyTimestamp;
}
public String getOverriddenStatus() {
return overriddenStatus;
}
public String getStatus() {
return status;
}
public InstanceInfo getInstanceInfo() {
return instanceInfo;
}
public Action getAction() {
return action;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
ReplicationInstance that = (ReplicationInstance) o;
if (appName != null ? !appName.equals(that.appName) : that.appName != null)
return false;
if (id != null ? !id.equals(that.id) : that.id != null)
return false;
if (lastDirtyTimestamp != null ? !lastDirtyTimestamp.equals(that.lastDirtyTimestamp) : that.lastDirtyTimestamp != null)
return false;
if (overriddenStatus != null ? !overriddenStatus.equals(that.overriddenStatus) : that.overriddenStatus != null)
return false;
if (status != null ? !status.equals(that.status) : that.status != null)
return false;
if (instanceInfo != null ? !instanceInfo.equals(that.instanceInfo) : that.instanceInfo != null)
return false;
return action == that.action;
}
@Override
public int hashCode() {
int result = appName != null ? appName.hashCode() : 0;
result = 31 * result + (id != null ? id.hashCode() : 0);
result = 31 * result + (lastDirtyTimestamp != null ? lastDirtyTimestamp.hashCode() : 0);
result = 31 * result + (overriddenStatus != null ? overriddenStatus.hashCode() : 0);
result = 31 * result + (status != null ? status.hashCode() : 0);
result = 31 * result + (instanceInfo != null ? instanceInfo.hashCode() : 0);
result = 31 * result + (action != null ? action.hashCode() : 0);
return result;
}
public static ReplicationInstanceBuilder replicationInstance() {
return ReplicationInstanceBuilder.aReplicationInstance();
}
public static class ReplicationInstanceBuilder {
private String appName;
private String id;
private Long lastDirtyTimestamp;
private String overriddenStatus;
private String status;
private InstanceInfo instanceInfo;
private Action action;
private ReplicationInstanceBuilder() {
}
public static ReplicationInstanceBuilder aReplicationInstance() {
return new ReplicationInstanceBuilder();
}
public ReplicationInstanceBuilder withAppName(String appName) {
this.appName = appName;
return this;
}
public ReplicationInstanceBuilder withId(String id) {
this.id = id;
return this;
}
public ReplicationInstanceBuilder withLastDirtyTimestamp(Long lastDirtyTimestamp) {
this.lastDirtyTimestamp = lastDirtyTimestamp;
return this;
}
public ReplicationInstanceBuilder withOverriddenStatus(String overriddenStatus) {
this.overriddenStatus = overriddenStatus;
return this;
}
public ReplicationInstanceBuilder withStatus(String status) {
this.status = status;
return this;
}
public ReplicationInstanceBuilder withInstanceInfo(InstanceInfo instanceInfo) {
this.instanceInfo = instanceInfo;
return this;
}
public ReplicationInstanceBuilder withAction(Action action) {
this.action = action;
return this;
}
public ReplicationInstanceBuilder but() {
return aReplicationInstance().withAppName(appName).withId(id).withLastDirtyTimestamp(lastDirtyTimestamp).withOverriddenStatus(overriddenStatus).withStatus(status).withInstanceInfo(instanceInfo).withAction(action);
}
public ReplicationInstance build() {
return new ReplicationInstance(
appName,
id,
lastDirtyTimestamp,
overriddenStatus,
status,
instanceInfo,
action
);
}
}
}
| 8,164 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/transport/EurekaServerHttpClients.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.eureka.transport;
import com.netflix.discovery.shared.dns.DnsServiceImpl;
import com.netflix.discovery.shared.resolver.ClusterResolver;
import com.netflix.discovery.shared.resolver.EurekaEndpoint;
import com.netflix.discovery.shared.transport.EurekaHttpClient;
import com.netflix.discovery.shared.transport.EurekaTransportConfig;
import com.netflix.discovery.shared.transport.TransportClientFactory;
import com.netflix.discovery.shared.transport.decorator.MetricsCollectingEurekaHttpClient;
import com.netflix.discovery.shared.transport.decorator.SessionedEurekaHttpClient;
import com.netflix.discovery.shared.transport.decorator.RedirectingEurekaHttpClient;
import com.netflix.discovery.shared.transport.decorator.RetryableEurekaHttpClient;
import com.netflix.discovery.shared.transport.decorator.ServerStatusEvaluators;
import com.netflix.eureka.EurekaServerConfig;
import com.netflix.eureka.Names;
import com.netflix.eureka.resources.ServerCodecs;
/**
* @author Tomasz Bak
*/
public final class EurekaServerHttpClients {
public static final long RECONNECT_INTERVAL_MINUTES = 30;
private EurekaServerHttpClients() {
}
/**
* {@link EurekaHttpClient} for remote region replication.
*/
public static EurekaHttpClient createRemoteRegionClient(EurekaServerConfig serverConfig,
EurekaTransportConfig transportConfig,
ServerCodecs serverCodecs,
ClusterResolver<EurekaEndpoint> clusterResolver) {
JerseyRemoteRegionClientFactory jerseyFactory = new JerseyRemoteRegionClientFactory(serverConfig, serverCodecs, clusterResolver.getRegion());
TransportClientFactory metricsFactory = MetricsCollectingEurekaHttpClient.createFactory(jerseyFactory);
SessionedEurekaHttpClient client = new SessionedEurekaHttpClient(
Names.REMOTE,
RetryableEurekaHttpClient.createFactory(
Names.REMOTE,
transportConfig,
clusterResolver,
createFactory(metricsFactory),
ServerStatusEvaluators.legacyEvaluator()),
RECONNECT_INTERVAL_MINUTES * 60 * 1000
);
return client;
}
public static TransportClientFactory createFactory(final TransportClientFactory delegateFactory) {
final DnsServiceImpl dnsService = new DnsServiceImpl();
return new TransportClientFactory() {
@Override
public EurekaHttpClient newClient(EurekaEndpoint endpoint) {
return new RedirectingEurekaHttpClient(endpoint.getServiceUrl(), delegateFactory, dnsService);
}
@Override
public void shutdown() {
delegateFactory.shutdown();
}
};
}
}
| 8,165 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/transport/JerseyReplicationClient.java | package com.netflix.eureka.transport;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import com.netflix.discovery.EurekaIdentityHeaderFilter;
import com.netflix.discovery.shared.transport.EurekaHttpResponse;
import com.netflix.discovery.shared.transport.jersey.AbstractJerseyEurekaHttpClient;
import com.netflix.discovery.shared.transport.jersey.EurekaJerseyClient;
import com.netflix.discovery.shared.transport.jersey.EurekaJerseyClientImpl.EurekaJerseyClientBuilder;
import com.netflix.eureka.EurekaServerConfig;
import com.netflix.eureka.EurekaServerIdentity;
import com.netflix.eureka.cluster.DynamicGZIPContentEncodingFilter;
import com.netflix.eureka.cluster.HttpReplicationClient;
import com.netflix.eureka.cluster.PeerEurekaNode;
import com.netflix.eureka.cluster.protocol.ReplicationList;
import com.netflix.eureka.cluster.protocol.ReplicationListResponse;
import com.netflix.eureka.resources.ASGResource.ASGStatus;
import com.netflix.eureka.resources.ServerCodecs;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.api.client.filter.ClientFilter;
import com.sun.jersey.client.apache4.ApacheHttpClient4;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.netflix.discovery.shared.transport.EurekaHttpResponse.anEurekaHttpResponse;
/**
* @author Tomasz Bak
*/
public class JerseyReplicationClient extends AbstractJerseyEurekaHttpClient implements HttpReplicationClient {
private static final Logger logger = LoggerFactory.getLogger(JerseyReplicationClient.class);
private final EurekaJerseyClient jerseyClient;
private final ApacheHttpClient4 jerseyApacheClient;
public JerseyReplicationClient(EurekaJerseyClient jerseyClient, String serviceUrl) {
super(jerseyClient.getClient(), serviceUrl);
this.jerseyClient = jerseyClient;
this.jerseyApacheClient = jerseyClient.getClient();
}
@Override
protected void addExtraHeaders(Builder webResource) {
webResource.header(PeerEurekaNode.HEADER_REPLICATION, "true");
}
/**
* Compared to regular heartbeat, in the replication channel the server may return a more up to date
* instance copy.
*/
@Override
public EurekaHttpResponse<InstanceInfo> sendHeartBeat(String appName, String id, InstanceInfo info, InstanceStatus overriddenStatus) {
String urlPath = "apps/" + appName + '/' + id;
ClientResponse response = null;
try {
WebResource webResource = jerseyClient.getClient().resource(serviceUrl)
.path(urlPath)
.queryParam("status", info.getStatus().toString())
.queryParam("lastDirtyTimestamp", info.getLastDirtyTimestamp().toString());
if (overriddenStatus != null) {
webResource = webResource.queryParam("overriddenstatus", overriddenStatus.name());
}
Builder requestBuilder = webResource.getRequestBuilder();
addExtraHeaders(requestBuilder);
response = requestBuilder.accept(MediaType.APPLICATION_JSON_TYPE).put(ClientResponse.class);
InstanceInfo infoFromPeer = null;
if (response.getStatus() == Status.CONFLICT.getStatusCode() && response.hasEntity()) {
infoFromPeer = response.getEntity(InstanceInfo.class);
}
return anEurekaHttpResponse(response.getStatus(), infoFromPeer).type(MediaType.APPLICATION_JSON_TYPE).build();
} finally {
if (logger.isDebugEnabled()) {
logger.debug("[heartbeat] Jersey HTTP PUT {}; statusCode={}", urlPath, response == null ? "N/A" : response.getStatus());
}
if (response != null) {
response.close();
}
}
}
@Override
public EurekaHttpResponse<Void> statusUpdate(String asgName, ASGStatus newStatus) {
ClientResponse response = null;
try {
String urlPath = "asg/" + asgName + "/status";
response = jerseyApacheClient.resource(serviceUrl)
.path(urlPath)
.queryParam("value", newStatus.name())
.header(PeerEurekaNode.HEADER_REPLICATION, "true")
.put(ClientResponse.class);
return EurekaHttpResponse.status(response.getStatus());
} finally {
if (response != null) {
response.close();
}
}
}
@Override
public EurekaHttpResponse<ReplicationListResponse> submitBatchUpdates(ReplicationList replicationList) {
ClientResponse response = null;
try {
response = jerseyApacheClient.resource(serviceUrl)
.path(PeerEurekaNode.BATCH_URL_PATH)
.accept(MediaType.APPLICATION_JSON_TYPE)
.type(MediaType.APPLICATION_JSON_TYPE)
.post(ClientResponse.class, replicationList);
if (!isSuccess(response.getStatus())) {
return anEurekaHttpResponse(response.getStatus(), ReplicationListResponse.class).build();
}
ReplicationListResponse batchResponse = response.getEntity(ReplicationListResponse.class);
return anEurekaHttpResponse(response.getStatus(), batchResponse).type(MediaType.APPLICATION_JSON_TYPE).build();
} finally {
if (response != null) {
response.close();
}
}
}
public void addReplicationClientFilter(ClientFilter clientFilter) {
jerseyApacheClient.addFilter(clientFilter);
}
@Override
public void shutdown() {
super.shutdown();
jerseyClient.destroyResources();
}
public static JerseyReplicationClient createReplicationClient(EurekaServerConfig config, ServerCodecs serverCodecs, String serviceUrl) {
String name = JerseyReplicationClient.class.getSimpleName() + ": " + serviceUrl + "apps/: ";
EurekaJerseyClient jerseyClient;
try {
String hostname;
try {
hostname = new URL(serviceUrl).getHost();
} catch (MalformedURLException e) {
hostname = serviceUrl;
}
String jerseyClientName = "Discovery-PeerNodeClient-" + hostname;
EurekaJerseyClientBuilder clientBuilder = new EurekaJerseyClientBuilder()
.withClientName(jerseyClientName)
.withUserAgent("Java-EurekaClient-Replication")
.withEncoderWrapper(serverCodecs.getFullJsonCodec())
.withDecoderWrapper(serverCodecs.getFullJsonCodec())
.withConnectionTimeout(config.getPeerNodeConnectTimeoutMs())
.withReadTimeout(config.getPeerNodeReadTimeoutMs())
.withMaxConnectionsPerHost(config.getPeerNodeTotalConnectionsPerHost())
.withMaxTotalConnections(config.getPeerNodeTotalConnections())
.withConnectionIdleTimeout(config.getPeerNodeConnectionIdleTimeoutSeconds());
if (serviceUrl.startsWith("https://") &&
"true".equals(System.getProperty("com.netflix.eureka.shouldSSLConnectionsUseSystemSocketFactory"))) {
clientBuilder.withSystemSSLConfiguration();
}
jerseyClient = clientBuilder.build();
} catch (Throwable e) {
throw new RuntimeException("Cannot Create new Replica Node :" + name, e);
}
String ip = null;
try {
ip = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
logger.warn("Cannot find localhost ip", e);
}
ApacheHttpClient4 jerseyApacheClient = jerseyClient.getClient();
jerseyApacheClient.addFilter(new DynamicGZIPContentEncodingFilter(config));
EurekaServerIdentity identity = new EurekaServerIdentity(ip);
jerseyApacheClient.addFilter(new EurekaIdentityHeaderFilter(identity));
return new JerseyReplicationClient(jerseyClient, serviceUrl);
}
private static boolean isSuccess(int statusCode) {
return statusCode >= 200 && statusCode < 300;
}
}
| 8,166 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/transport/JerseyRemoteRegionClientFactory.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.eureka.transport;
import javax.inject.Inject;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collections;
import com.netflix.discovery.EurekaIdentityHeaderFilter;
import com.netflix.discovery.shared.resolver.EurekaEndpoint;
import com.netflix.discovery.shared.transport.EurekaHttpClient;
import com.netflix.discovery.shared.transport.TransportClientFactory;
import com.netflix.discovery.shared.transport.jersey.EurekaJerseyClient;
import com.netflix.discovery.shared.transport.jersey.EurekaJerseyClientImpl.EurekaJerseyClientBuilder;
import com.netflix.discovery.shared.transport.jersey.JerseyApplicationClient;
import com.netflix.eureka.EurekaServerConfig;
import com.netflix.eureka.EurekaServerIdentity;
import com.netflix.eureka.resources.ServerCodecs;
import com.sun.jersey.api.client.filter.GZIPContentEncodingFilter;
import com.sun.jersey.client.apache4.ApacheHttpClient4;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Tomasz Bak
*/
public class JerseyRemoteRegionClientFactory implements TransportClientFactory {
private static final Logger logger = LoggerFactory.getLogger(JerseyRemoteRegionClientFactory.class);
private final EurekaServerConfig serverConfig;
private final ServerCodecs serverCodecs;
private final String region;
private volatile EurekaJerseyClient jerseyClient;
private final Object lock = new Object();
@Inject
public JerseyRemoteRegionClientFactory(EurekaServerConfig serverConfig,
ServerCodecs serverCodecs,
String region) {
this.serverConfig = serverConfig;
this.serverCodecs = serverCodecs;
this.region = region;
}
@Override
public EurekaHttpClient newClient(EurekaEndpoint endpoint) {
return new JerseyApplicationClient(getOrCreateJerseyClient(region, endpoint).getClient(), endpoint.getServiceUrl(), Collections.<String, String>emptyMap());
}
@Override
public void shutdown() {
if (jerseyClient != null) {
jerseyClient.destroyResources();
}
}
private EurekaJerseyClient getOrCreateJerseyClient(String region, EurekaEndpoint endpoint) {
if (jerseyClient != null) {
return jerseyClient;
}
synchronized (lock) {
if (jerseyClient == null) {
EurekaJerseyClientBuilder clientBuilder = new EurekaJerseyClientBuilder()
.withUserAgent("Java-EurekaClient-RemoteRegion")
.withEncoderWrapper(serverCodecs.getFullJsonCodec())
.withDecoderWrapper(serverCodecs.getFullJsonCodec())
.withConnectionTimeout(serverConfig.getRemoteRegionConnectTimeoutMs())
.withReadTimeout(serverConfig.getRemoteRegionReadTimeoutMs())
.withMaxConnectionsPerHost(serverConfig.getRemoteRegionTotalConnectionsPerHost())
.withMaxTotalConnections(serverConfig.getRemoteRegionTotalConnections())
.withConnectionIdleTimeout(serverConfig.getRemoteRegionConnectionIdleTimeoutSeconds());
if (endpoint.isSecure()) {
clientBuilder.withClientName("Discovery-RemoteRegionClient-" + region);
} else if ("true".equals(System.getProperty("com.netflix.eureka.shouldSSLConnectionsUseSystemSocketFactory"))) {
clientBuilder.withClientName("Discovery-RemoteRegionSystemSecureClient-" + region)
.withSystemSSLConfiguration();
} else {
clientBuilder.withClientName("Discovery-RemoteRegionSecureClient-" + region)
.withTrustStoreFile(
serverConfig.getRemoteRegionTrustStore(),
serverConfig.getRemoteRegionTrustStorePassword()
);
}
jerseyClient = clientBuilder.build();
ApacheHttpClient4 discoveryApacheClient = jerseyClient.getClient();
// Add gzip content encoding support
boolean enableGZIPContentEncodingFilter = serverConfig.shouldGZipContentFromRemoteRegion();
if (enableGZIPContentEncodingFilter) {
discoveryApacheClient.addFilter(new GZIPContentEncodingFilter(false));
}
// always enable client identity headers
String ip = null;
try {
ip = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
logger.warn("Cannot find localhost ip", e);
}
EurekaServerIdentity identity = new EurekaServerIdentity(ip);
discoveryApacheClient.addFilter(new EurekaIdentityHeaderFilter(identity));
}
}
return jerseyClient;
}
}
| 8,167 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/util/StatusInfo.java | package com.netflix.eureka.util;
import java.lang.management.ManagementFactory;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.config.ConfigurationManager;
import com.netflix.discovery.provider.Serializer;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
/**
* An utility class for exposing status information of an instance.
*
* @author Greg Kim
*/
@Serializer("com.netflix.discovery.converters.EntityBodyConverter")
@XStreamAlias("status")
public class StatusInfo {
private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss Z";
private static final boolean ARCHAIUS_EXISTS = classExists("com.netflix.config.ConfigurationManager");
public static final class Builder {
@XStreamOmitField
private StatusInfo result;
private Builder() {
result = new StatusInfo();
}
public static Builder newBuilder() {
return new Builder();
}
public Builder isHealthy(boolean b) {
result.isHeathly = Boolean.valueOf(b);
return this;
}
public Builder withInstanceInfo(InstanceInfo instanceInfo) {
result.instanceInfo = instanceInfo;
return this;
}
/**
* Add any application specific status data.
*/
public Builder add(String key, String value) {
if (result.applicationStats == null) {
result.applicationStats = new HashMap<String, String>();
}
result.applicationStats.put(key, value);
return this;
}
/**
* Build the {@link StatusInfo}. General information are automatically
* built here too.
*/
public StatusInfo build() {
if (result.instanceInfo == null) {
throw new IllegalStateException("instanceInfo can not be null");
}
result.generalStats.put("server-uptime", getUpTime());
if (ARCHAIUS_EXISTS) {
result.generalStats.put("environment", ConfigurationManager
.getDeploymentContext().getDeploymentEnvironment());
}
Runtime runtime = Runtime.getRuntime();
int totalMem = (int) (runtime.totalMemory() / 1048576);
int freeMem = (int) (runtime.freeMemory() / 1048576);
int usedPercent = (int) (((float) totalMem - freeMem) / (totalMem) * 100.0);
result.generalStats.put("num-of-cpus",
String.valueOf(runtime.availableProcessors()));
result.generalStats.put("total-avail-memory",
String.valueOf(totalMem) + "mb");
result.generalStats.put("current-memory-usage",
String.valueOf(totalMem - freeMem) + "mb" + " ("
+ usedPercent + "%)");
return result;
}
}
private Map<String, String> generalStats = new HashMap<String, String>();
private Map<String, String> applicationStats;
private InstanceInfo instanceInfo;
private Boolean isHeathly;
private StatusInfo() {
}
public InstanceInfo getInstanceInfo() {
return instanceInfo;
}
public boolean isHealthy() {
return isHeathly.booleanValue();
}
public Map<String, String> getGeneralStats() {
return generalStats;
}
public Map<String, String> getApplicationStats() {
return applicationStats;
}
/**
* Output the amount of time that has elapsed since the given date in the
* format x days, xx:xx.
*
* @return A string representing the formatted interval.
*/
public static String getUpTime() {
long diff = ManagementFactory.getRuntimeMXBean().getUptime();
diff /= 1000 * 60;
long minutes = diff % 60;
diff /= 60;
long hours = diff % 24;
diff /= 24;
long days = diff;
StringBuilder buf = new StringBuilder();
if (days == 1) {
buf.append("1 day ");
} else if (days > 1) {
buf.append(Long.valueOf(days).toString()).append(" days ");
}
DecimalFormat format = new DecimalFormat();
format.setMinimumIntegerDigits(2);
buf.append(format.format(hours)).append(":")
.append(format.format(minutes));
return buf.toString();
}
public static String getCurrentTimeAsString() {
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
return format.format(new Date());
}
private static boolean classExists(String className) {
try {
Class.forName(className);
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
}
| 8,168 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/util/MeasuredRate.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.eureka.util;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicLong;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Utility class for getting a count in last X milliseconds.
*
* @author Karthik Ranganathan,Greg Kim
*/
public class MeasuredRate {
private static final Logger logger = LoggerFactory.getLogger(MeasuredRate.class);
private final AtomicLong lastBucket = new AtomicLong(0);
private final AtomicLong currentBucket = new AtomicLong(0);
private final long sampleInterval;
private final Timer timer;
private volatile boolean isActive;
/**
* @param sampleInterval in milliseconds
*/
public MeasuredRate(long sampleInterval) {
this.sampleInterval = sampleInterval;
this.timer = new Timer("Eureka-MeasureRateTimer", true);
this.isActive = false;
}
public synchronized void start() {
if (!isActive) {
timer.schedule(new TimerTask() {
@Override
public void run() {
try {
// Zero out the current bucket.
lastBucket.set(currentBucket.getAndSet(0));
} catch (Throwable e) {
logger.error("Cannot reset the Measured Rate", e);
}
}
}, sampleInterval, sampleInterval);
isActive = true;
}
}
public synchronized void stop() {
if (isActive) {
timer.cancel();
isActive = false;
}
}
/**
* Returns the count in the last sample interval.
*/
public long getCount() {
return lastBucket.get();
}
/**
* Increments the count in the current sample interval.
*/
public void increment() {
currentBucket.incrementAndGet();
}
}
| 8,169 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/util/ServoControl.java | package com.netflix.eureka.util;
import com.netflix.servo.monitor.MonitorConfig;
import com.netflix.servo.monitor.StatsTimer;
import com.netflix.servo.stats.StatsConfig;
/**
* The sole purpose of this class is shutting down the {@code protected} executor of {@link StatsTimer}
*/
public class ServoControl extends StatsTimer {
public ServoControl(MonitorConfig baseConfig, StatsConfig statsConfig) {
super(baseConfig, statsConfig);
throw new UnsupportedOperationException(getClass().getName() + " is not meant to be instantiated.");
}
public static void shutdown() {
DEFAULT_EXECUTOR.shutdown();
}
}
| 8,170 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/util/StatusUtil.java | package com.netflix.eureka.util;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.shared.Application;
import com.netflix.eureka.EurekaServerContext;
import com.netflix.eureka.cluster.PeerEurekaNode;
import com.netflix.eureka.cluster.PeerEurekaNodes;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URI;
/**
* @author David Liu
*/
public class StatusUtil {
private static final Logger logger = LoggerFactory.getLogger(StatusUtil.class);
private final String myAppName;
private final PeerAwareInstanceRegistry registry;
private final PeerEurekaNodes peerEurekaNodes;
private final InstanceInfo instanceInfo;
public StatusUtil(EurekaServerContext server) {
this.myAppName = server.getApplicationInfoManager().getInfo().getAppName();
this.registry = server.getRegistry();
this.peerEurekaNodes = server.getPeerEurekaNodes();
this.instanceInfo = server.getApplicationInfoManager().getInfo();
}
public StatusInfo getStatusInfo() {
StatusInfo.Builder builder = StatusInfo.Builder.newBuilder();
// Add application level status
int upReplicasCount = 0;
StringBuilder upReplicas = new StringBuilder();
StringBuilder downReplicas = new StringBuilder();
StringBuilder replicaHostNames = new StringBuilder();
for (PeerEurekaNode node : peerEurekaNodes.getPeerEurekaNodes()) {
if (replicaHostNames.length() > 0) {
replicaHostNames.append(", ");
}
replicaHostNames.append(node.getServiceUrl());
if (isReplicaAvailable(node.getServiceUrl())) {
upReplicas.append(node.getServiceUrl()).append(',');
upReplicasCount++;
} else {
downReplicas.append(node.getServiceUrl()).append(',');
}
}
builder.add("registered-replicas", replicaHostNames.toString());
builder.add("available-replicas", upReplicas.toString());
builder.add("unavailable-replicas", downReplicas.toString());
// Only set the healthy flag if a threshold has been configured.
if (peerEurekaNodes.getMinNumberOfAvailablePeers() > -1) {
builder.isHealthy(upReplicasCount >= peerEurekaNodes.getMinNumberOfAvailablePeers());
}
builder.withInstanceInfo(this.instanceInfo);
return builder.build();
}
private boolean isReplicaAvailable(String url) {
try {
Application app = registry.getApplication(myAppName, false);
if (app == null) {
return false;
}
for (InstanceInfo info : app.getInstances()) {
if (peerEurekaNodes.isInstanceURL(url, info)) {
return true;
}
}
} catch (Throwable e) {
logger.error("Could not determine if the replica is available ", e);
}
return false;
}
}
| 8,171 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/util/EurekaMonitors.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.eureka.util;
import java.util.concurrent.atomic.AtomicLong;
import com.netflix.appinfo.AmazonInfo;
import com.netflix.appinfo.AmazonInfo.MetaDataKey;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.DataCenterInfo;
import com.netflix.appinfo.DataCenterInfo.Name;
import com.netflix.servo.DefaultMonitorRegistry;
import com.netflix.servo.annotations.DataSourceType;
import com.netflix.servo.monitor.Monitors;
/**
* The enum that encapsulates all statistics monitored by Eureka.
*
* <p>
* Eureka Monitoring is done using <a href="https://github.com/Netflix/servo">Servo</a>. The
* users who wants to take advantage of the monitoring should read up on
* <tt>Servo</tt>
* <p>
*
* @author Karthik Ranganathan, Greg Kim
*
*/
public enum EurekaMonitors {
RENEW("renewCounter", "Number of total renews seen since startup"),
CANCEL("cancelCounter", "Number of total cancels seen since startup"),
GET_ALL_CACHE_MISS("getAllCacheMissCounter", "Number of total registry queries seen since startup"),
GET_ALL_CACHE_MISS_DELTA("getAllCacheMissDeltaCounter",
"Number of total registry queries for delta seen since startup"),
GET_ALL_WITH_REMOTE_REGIONS_CACHE_MISS("getAllWithRemoteRegionCacheMissCounter",
"Number of total registry with remote region queries seen since startup"),
GET_ALL_WITH_REMOTE_REGIONS_CACHE_MISS_DELTA("getAllWithRemoteRegionCacheMissDeltaCounter",
"Number of total registry queries for delta with remote region seen since startup"),
GET_ALL_DELTA("getAllDeltaCounter", "Number of total deltas since startup"),
GET_ALL_DELTA_WITH_REMOTE_REGIONS("getAllDeltaWithRemoteRegionCounter",
"Number of total deltas with remote regions since startup"),
GET_ALL("getAllCounter", "Number of total registry queries seen since startup"),
GET_ALL_WITH_REMOTE_REGIONS("getAllWithRemoteRegionCounter",
"Number of total registry queries with remote regions, seen since startup"),
GET_APPLICATION("getApplicationCounter", "Number of total application queries seen since startup"),
REGISTER("registerCounter", "Number of total registers seen since startup"),
EXPIRED("expiredCounter", "Number of total expired leases since startup"),
STATUS_UPDATE("statusUpdateCounter", "Number of total admin status updates since startup"),
STATUS_OVERRIDE_DELETE("statusOverrideDeleteCounter", "Number of status override removals"),
CANCEL_NOT_FOUND("cancelNotFoundCounter", "Number of total cancel requests on non-existing instance since startup"),
RENEW_NOT_FOUND("renewNotFoundexpiredCounter", "Number of total renew on non-existing instance since startup"),
REJECTED_REPLICATIONS("numOfRejectedReplications", "Number of replications rejected because of full queue"),
FAILED_REPLICATIONS("numOfFailedReplications", "Number of failed replications - likely from timeouts"),
RATE_LIMITED("numOfRateLimitedRequests", "Number of requests discarded by the rate limiter"),
RATE_LIMITED_CANDIDATES("numOfRateLimitedRequestCandidates", "Number of requests that would be discarded if the rate limiter's throttling is activated"),
RATE_LIMITED_FULL_FETCH("numOfRateLimitedFullFetchRequests", "Number of full registry fetch requests discarded by the rate limiter"),
RATE_LIMITED_FULL_FETCH_CANDIDATES("numOfRateLimitedFullFetchRequestCandidates", "Number of full registry fetch requests that would be discarded if the rate limiter's throttling is activated");
private final String name;
private final String myZoneCounterName;
private final String description;
private EurekaMonitors(String name, String description) {
this.name = name;
this.description = description;
DataCenterInfo dcInfo = ApplicationInfoManager.getInstance().getInfo().getDataCenterInfo();
if (dcInfo.getName() == Name.Amazon) {
myZoneCounterName = ((AmazonInfo) dcInfo).get(MetaDataKey.availabilityZone) + "." + name;
} else {
myZoneCounterName = "dcmaster." + name;
}
}
@com.netflix.servo.annotations.Monitor(name = "count", type = DataSourceType.COUNTER)
private final AtomicLong counter = new AtomicLong();
@com.netflix.servo.annotations.Monitor(name = "count-minus-replication", type = DataSourceType.COUNTER)
private final AtomicLong myZoneCounter = new AtomicLong();
/**
* Increment the counter for the given statistic.
*/
public void increment() {
increment(false);
}
/**
* Increment the counter for the given statistic based on whether this is
* because of replication from other eureka servers or it is a eureka client
* initiated action.
*
* @param isReplication
* true if this a replication, false otherwise.
*/
public void increment(boolean isReplication) {
counter.incrementAndGet();
if (!isReplication) {
myZoneCounter.incrementAndGet();
}
}
/**
* Gets the statistic name of this monitor.
*
* @return the statistic name.
*/
public String getName() {
return name;
}
/**
* Gets the zone specific statistic name of this monitor. Applies only for
* AWS cloud.
*
* @return the zone specific statistic name.
*/
public String getZoneSpecificName() {
return myZoneCounterName;
}
/**
* Gets the description of this statistic means.
*
* @return the description of this statistic means.
*/
public String getDescription() {
return description;
}
/**
* Gets the actual counter value for this statistic.
*
* @return the long value representing the number of times this statistic
* has occurred.
*/
public long getCount() {
return counter.get();
}
/**
* Gets the zone specific counter value for this statistic. This is
* application only for AWS cloud environment.
*
* @return the long value representing the number of times this statistic
* has occurred.
*/
public long getZoneSpecificCount() {
return myZoneCounter.get();
}
/**
* Register all statistics with <tt>Servo</tt>.
*/
public static void registerAllStats() {
for (EurekaMonitors c : EurekaMonitors.values()) {
Monitors.registerObject(c.getName(), c);
}
}
/**
* Unregister all statistics from <tt>Servo</tt>.
*/
public static void shutdown() {
for (EurekaMonitors c : EurekaMonitors.values()) {
DefaultMonitorRegistry.getInstance().unregister(Monitors.newObjectMonitor(c.getName(), c));
}
}
}
| 8,172 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/util | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/util/batcher/TaskDispatcher.java | package com.netflix.eureka.util.batcher;
/**
* Task dispatcher takes task from clients, and delegates their execution to a configurable number of workers.
* The task can be processed one at a time or in batches. Only non-expired tasks are executed, and if a newer
* task with the same id is scheduled for execution, the old one is deleted. Lazy dispatch of work (only on demand)
* to workers, guarantees that data are always up to date, and no stale task processing takes place.
* <h3>Task processor</h3>
* A client of this component must provide an implementation of {@link TaskProcessor} interface, which will do
* the actual work of task processing. This implementation must be thread safe, as it is called concurrently by
* multiple threads.
* <h3>Execution modes</h3>
* To create non batched executor call {@link TaskDispatchers#createNonBatchingTaskDispatcher(String, int, int, long, long, TaskProcessor)}
* method. Batched executor is created by {@link TaskDispatchers#createBatchingTaskDispatcher(String, int, int, int, long, long, TaskProcessor)}.
*
* @author Tomasz Bak
*/
public interface TaskDispatcher<ID, T> {
void process(ID id, T task, long expiryTime);
void shutdown();
}
| 8,173 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/util | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/util/batcher/AcceptorExecutor.java | package com.netflix.eureka.util.batcher;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import com.netflix.eureka.util.batcher.TaskProcessor.ProcessingResult;
import com.netflix.servo.annotations.DataSourceType;
import com.netflix.servo.annotations.Monitor;
import com.netflix.servo.monitor.MonitorConfig;
import com.netflix.servo.monitor.Monitors;
import com.netflix.servo.monitor.StatsTimer;
import com.netflix.servo.monitor.Timer;
import com.netflix.servo.stats.StatsConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.netflix.eureka.Names.METRIC_REPLICATION_PREFIX;
/**
* An active object with an internal thread accepting tasks from clients, and dispatching them to
* workers in a pull based manner. Workers explicitly request an item or a batch of items whenever they are
* available. This guarantees that data to be processed are always up to date, and no stale data processing is done.
*
* <h3>Task identification</h3>
* Each task passed for processing has a corresponding task id. This id is used to remove duplicates (replace
* older copies with newer ones).
*
* <h3>Re-processing</h3>
* If data processing by a worker failed, and the failure is transient in nature, the worker will put back the
* task(s) back to the {@link AcceptorExecutor}. This data will be merged with current workload, possibly discarded if
* a newer version has been already received.
*
* @author Tomasz Bak
*/
class AcceptorExecutor<ID, T> {
private static final Logger logger = LoggerFactory.getLogger(AcceptorExecutor.class);
private final String id;
private final int maxBufferSize;
private final int maxBatchingSize;
private final long maxBatchingDelay;
private final AtomicBoolean isShutdown = new AtomicBoolean(false);
private final BlockingQueue<TaskHolder<ID, T>> acceptorQueue = new LinkedBlockingQueue<>();
private final BlockingDeque<TaskHolder<ID, T>> reprocessQueue = new LinkedBlockingDeque<>();
private final Thread acceptorThread;
private final Map<ID, TaskHolder<ID, T>> pendingTasks = new HashMap<>();
private final Deque<ID> processingOrder = new LinkedList<>();
private final Semaphore singleItemWorkRequests = new Semaphore(0);
private final BlockingQueue<TaskHolder<ID, T>> singleItemWorkQueue = new LinkedBlockingQueue<>();
private final Semaphore batchWorkRequests = new Semaphore(0);
private final BlockingQueue<List<TaskHolder<ID, T>>> batchWorkQueue = new LinkedBlockingQueue<>();
private final TrafficShaper trafficShaper;
/*
* Metrics
*/
@Monitor(name = METRIC_REPLICATION_PREFIX + "acceptedTasks", description = "Number of accepted tasks", type = DataSourceType.COUNTER)
volatile long acceptedTasks;
@Monitor(name = METRIC_REPLICATION_PREFIX + "replayedTasks", description = "Number of replayedTasks tasks", type = DataSourceType.COUNTER)
volatile long replayedTasks;
@Monitor(name = METRIC_REPLICATION_PREFIX + "expiredTasks", description = "Number of expired tasks", type = DataSourceType.COUNTER)
volatile long expiredTasks;
@Monitor(name = METRIC_REPLICATION_PREFIX + "overriddenTasks", description = "Number of overridden tasks", type = DataSourceType.COUNTER)
volatile long overriddenTasks;
@Monitor(name = METRIC_REPLICATION_PREFIX + "queueOverflows", description = "Number of queue overflows", type = DataSourceType.COUNTER)
volatile long queueOverflows;
private final Timer batchSizeMetric;
AcceptorExecutor(String id,
int maxBufferSize,
int maxBatchingSize,
long maxBatchingDelay,
long congestionRetryDelayMs,
long networkFailureRetryMs) {
this.id = id;
this.maxBufferSize = maxBufferSize;
this.maxBatchingSize = maxBatchingSize;
this.maxBatchingDelay = maxBatchingDelay;
this.trafficShaper = new TrafficShaper(congestionRetryDelayMs, networkFailureRetryMs);
ThreadGroup threadGroup = new ThreadGroup("eurekaTaskExecutors");
this.acceptorThread = new Thread(threadGroup, new AcceptorRunner(), "TaskAcceptor-" + id);
this.acceptorThread.setDaemon(true);
this.acceptorThread.start();
final double[] percentiles = {50.0, 95.0, 99.0, 99.5};
final StatsConfig statsConfig = new StatsConfig.Builder()
.withSampleSize(1000)
.withPercentiles(percentiles)
.withPublishStdDev(true)
.build();
final MonitorConfig config = MonitorConfig.builder(METRIC_REPLICATION_PREFIX + "batchSize").build();
this.batchSizeMetric = new StatsTimer(config, statsConfig);
try {
Monitors.registerObject(id, this);
} catch (Throwable e) {
logger.warn("Cannot register servo monitor for this object", e);
}
}
void process(ID id, T task, long expiryTime) {
acceptorQueue.add(new TaskHolder<ID, T>(id, task, expiryTime));
acceptedTasks++;
}
void reprocess(List<TaskHolder<ID, T>> holders, ProcessingResult processingResult) {
reprocessQueue.addAll(holders);
replayedTasks += holders.size();
trafficShaper.registerFailure(processingResult);
}
void reprocess(TaskHolder<ID, T> taskHolder, ProcessingResult processingResult) {
reprocessQueue.add(taskHolder);
replayedTasks++;
trafficShaper.registerFailure(processingResult);
}
BlockingQueue<TaskHolder<ID, T>> requestWorkItem() {
singleItemWorkRequests.release();
return singleItemWorkQueue;
}
BlockingQueue<List<TaskHolder<ID, T>>> requestWorkItems() {
batchWorkRequests.release();
return batchWorkQueue;
}
void shutdown() {
if (isShutdown.compareAndSet(false, true)) {
Monitors.unregisterObject(id, this);
acceptorThread.interrupt();
}
}
@Monitor(name = METRIC_REPLICATION_PREFIX + "acceptorQueueSize", description = "Number of tasks waiting in the acceptor queue", type = DataSourceType.GAUGE)
public long getAcceptorQueueSize() {
return acceptorQueue.size();
}
@Monitor(name = METRIC_REPLICATION_PREFIX + "reprocessQueueSize", description = "Number of tasks waiting in the reprocess queue", type = DataSourceType.GAUGE)
public long getReprocessQueueSize() {
return reprocessQueue.size();
}
@Monitor(name = METRIC_REPLICATION_PREFIX + "queueSize", description = "Task queue size", type = DataSourceType.GAUGE)
public long getQueueSize() {
return pendingTasks.size();
}
@Monitor(name = METRIC_REPLICATION_PREFIX + "pendingJobRequests", description = "Number of worker threads awaiting job assignment", type = DataSourceType.GAUGE)
public long getPendingJobRequests() {
return singleItemWorkRequests.availablePermits() + batchWorkRequests.availablePermits();
}
@Monitor(name = METRIC_REPLICATION_PREFIX + "availableJobs", description = "Number of jobs ready to be taken by the workers", type = DataSourceType.GAUGE)
public long workerTaskQueueSize() {
return singleItemWorkQueue.size() + batchWorkQueue.size();
}
class AcceptorRunner implements Runnable {
@Override
public void run() {
long scheduleTime = 0;
while (!isShutdown.get()) {
try {
drainInputQueues();
int totalItems = processingOrder.size();
long now = System.currentTimeMillis();
if (scheduleTime < now) {
scheduleTime = now + trafficShaper.transmissionDelay();
}
if (scheduleTime <= now) {
assignBatchWork();
assignSingleItemWork();
}
// If no worker is requesting data or there is a delay injected by the traffic shaper,
// sleep for some time to avoid tight loop.
if (totalItems == processingOrder.size()) {
Thread.sleep(10);
}
} catch (InterruptedException ex) {
// Ignore
} catch (Throwable e) {
// Safe-guard, so we never exit this loop in an uncontrolled way.
logger.warn("Discovery AcceptorThread error", e);
}
}
}
private boolean isFull() {
return pendingTasks.size() >= maxBufferSize;
}
private void drainInputQueues() throws InterruptedException {
do {
drainReprocessQueue();
drainAcceptorQueue();
if (isShutdown.get()) {
break;
}
// If all queues are empty, block for a while on the acceptor queue
if (reprocessQueue.isEmpty() && acceptorQueue.isEmpty() && pendingTasks.isEmpty()) {
TaskHolder<ID, T> taskHolder = acceptorQueue.poll(10, TimeUnit.MILLISECONDS);
if (taskHolder != null) {
appendTaskHolder(taskHolder);
}
}
} while (!reprocessQueue.isEmpty() || !acceptorQueue.isEmpty() || pendingTasks.isEmpty());
}
private void drainAcceptorQueue() {
while (!acceptorQueue.isEmpty()) {
appendTaskHolder(acceptorQueue.poll());
}
}
private void drainReprocessQueue() {
long now = System.currentTimeMillis();
while (!reprocessQueue.isEmpty() && !isFull()) {
TaskHolder<ID, T> taskHolder = reprocessQueue.pollLast();
ID id = taskHolder.getId();
if (taskHolder.getExpiryTime() <= now) {
expiredTasks++;
} else if (pendingTasks.containsKey(id)) {
overriddenTasks++;
} else {
pendingTasks.put(id, taskHolder);
processingOrder.addFirst(id);
}
}
if (isFull()) {
queueOverflows += reprocessQueue.size();
reprocessQueue.clear();
}
}
private void appendTaskHolder(TaskHolder<ID, T> taskHolder) {
if (isFull()) {
pendingTasks.remove(processingOrder.poll());
queueOverflows++;
}
TaskHolder<ID, T> previousTask = pendingTasks.put(taskHolder.getId(), taskHolder);
if (previousTask == null) {
processingOrder.add(taskHolder.getId());
} else {
overriddenTasks++;
}
}
void assignSingleItemWork() {
if (!processingOrder.isEmpty()) {
if (singleItemWorkRequests.tryAcquire(1)) {
long now = System.currentTimeMillis();
while (!processingOrder.isEmpty()) {
ID id = processingOrder.poll();
TaskHolder<ID, T> holder = pendingTasks.remove(id);
if (holder.getExpiryTime() > now) {
singleItemWorkQueue.add(holder);
return;
}
expiredTasks++;
}
singleItemWorkRequests.release();
}
}
}
void assignBatchWork() {
if (hasEnoughTasksForNextBatch()) {
if (batchWorkRequests.tryAcquire(1)) {
long now = System.currentTimeMillis();
int len = Math.min(maxBatchingSize, processingOrder.size());
List<TaskHolder<ID, T>> holders = new ArrayList<>(len);
while (holders.size() < len && !processingOrder.isEmpty()) {
ID id = processingOrder.poll();
TaskHolder<ID, T> holder = pendingTasks.remove(id);
if (holder.getExpiryTime() > now) {
holders.add(holder);
} else {
expiredTasks++;
}
}
if (holders.isEmpty()) {
batchWorkRequests.release();
} else {
batchSizeMetric.record(holders.size(), TimeUnit.MILLISECONDS);
batchWorkQueue.add(holders);
}
}
}
}
private boolean hasEnoughTasksForNextBatch() {
if (processingOrder.isEmpty()) {
return false;
}
if (pendingTasks.size() >= maxBufferSize) {
return true;
}
TaskHolder<ID, T> nextHolder = pendingTasks.get(processingOrder.peek());
long delay = System.currentTimeMillis() - nextHolder.getSubmitTimestamp();
return delay >= maxBatchingDelay;
}
}
}
| 8,174 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/util | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/util/batcher/TaskDispatchers.java | package com.netflix.eureka.util.batcher;
/**
* See {@link TaskDispatcher} for an overview.
*
* @author Tomasz Bak
*/
public class TaskDispatchers {
public static <ID, T> TaskDispatcher<ID, T> createNonBatchingTaskDispatcher(String id,
int maxBufferSize,
int workerCount,
long maxBatchingDelay,
long congestionRetryDelayMs,
long networkFailureRetryMs,
TaskProcessor<T> taskProcessor) {
final AcceptorExecutor<ID, T> acceptorExecutor = new AcceptorExecutor<>(
id, maxBufferSize, 1, maxBatchingDelay, congestionRetryDelayMs, networkFailureRetryMs
);
final TaskExecutors<ID, T> taskExecutor = TaskExecutors.singleItemExecutors(id, workerCount, taskProcessor, acceptorExecutor);
return new TaskDispatcher<ID, T>() {
@Override
public void process(ID id, T task, long expiryTime) {
acceptorExecutor.process(id, task, expiryTime);
}
@Override
public void shutdown() {
acceptorExecutor.shutdown();
taskExecutor.shutdown();
}
};
}
public static <ID, T> TaskDispatcher<ID, T> createBatchingTaskDispatcher(String id,
int maxBufferSize,
int workloadSize,
int workerCount,
long maxBatchingDelay,
long congestionRetryDelayMs,
long networkFailureRetryMs,
TaskProcessor<T> taskProcessor) {
final AcceptorExecutor<ID, T> acceptorExecutor = new AcceptorExecutor<>(
id, maxBufferSize, workloadSize, maxBatchingDelay, congestionRetryDelayMs, networkFailureRetryMs
);
final TaskExecutors<ID, T> taskExecutor = TaskExecutors.batchExecutors(id, workerCount, taskProcessor, acceptorExecutor);
return new TaskDispatcher<ID, T>() {
@Override
public void process(ID id, T task, long expiryTime) {
acceptorExecutor.process(id, task, expiryTime);
}
@Override
public void shutdown() {
acceptorExecutor.shutdown();
taskExecutor.shutdown();
}
};
}
}
| 8,175 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/util | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/util/batcher/TaskHolder.java | package com.netflix.eureka.util.batcher;
/**
* @author Tomasz Bak
*/
class TaskHolder<ID, T> {
private final ID id;
private final T task;
private final long expiryTime;
private final long submitTimestamp;
TaskHolder(ID id, T task, long expiryTime) {
this.id = id;
this.expiryTime = expiryTime;
this.task = task;
this.submitTimestamp = System.currentTimeMillis();
}
public ID getId() {
return id;
}
public T getTask() {
return task;
}
public long getExpiryTime() {
return expiryTime;
}
public long getSubmitTimestamp() {
return submitTimestamp;
}
}
| 8,176 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/util | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/util/batcher/TaskExecutors.java | package com.netflix.eureka.util.batcher;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import com.netflix.eureka.util.batcher.TaskProcessor.ProcessingResult;
import com.netflix.servo.annotations.DataSourceType;
import com.netflix.servo.annotations.Monitor;
import com.netflix.servo.monitor.MonitorConfig;
import com.netflix.servo.monitor.Monitors;
import com.netflix.servo.monitor.StatsTimer;
import com.netflix.servo.stats.StatsConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.netflix.eureka.Names.METRIC_REPLICATION_PREFIX;
/**
* {@link TaskExecutors} instance holds a number of worker threads that cooperate with {@link AcceptorExecutor}.
* Each worker sends a job request to {@link AcceptorExecutor} whenever it is available, and processes it once
* provided with a task(s).
*
* @author Tomasz Bak
*/
class TaskExecutors<ID, T> {
private static final Logger logger = LoggerFactory.getLogger(TaskExecutors.class);
private static final Map<String, TaskExecutorMetrics> registeredMonitors = new HashMap<>();
private final AtomicBoolean isShutdown;
private final List<Thread> workerThreads;
TaskExecutors(WorkerRunnableFactory<ID, T> workerRunnableFactory, int workerCount, AtomicBoolean isShutdown) {
this.isShutdown = isShutdown;
this.workerThreads = new ArrayList<>();
ThreadGroup threadGroup = new ThreadGroup("eurekaTaskExecutors");
for (int i = 0; i < workerCount; i++) {
WorkerRunnable<ID, T> runnable = workerRunnableFactory.create(i);
Thread workerThread = new Thread(threadGroup, runnable, runnable.getWorkerName());
workerThreads.add(workerThread);
workerThread.setDaemon(true);
workerThread.start();
}
}
void shutdown() {
if (isShutdown.compareAndSet(false, true)) {
for (Thread workerThread : workerThreads) {
workerThread.interrupt();
}
registeredMonitors.forEach(Monitors::unregisterObject);
}
}
static <ID, T> TaskExecutors<ID, T> singleItemExecutors(final String name,
int workerCount,
final TaskProcessor<T> processor,
final AcceptorExecutor<ID, T> acceptorExecutor) {
final AtomicBoolean isShutdown = new AtomicBoolean();
final TaskExecutorMetrics metrics = new TaskExecutorMetrics(name);
registeredMonitors.put(name, metrics);
return new TaskExecutors<>(idx -> new SingleTaskWorkerRunnable<>("TaskNonBatchingWorker-" + name + '-' + idx, isShutdown, metrics, processor, acceptorExecutor), workerCount, isShutdown);
}
static <ID, T> TaskExecutors<ID, T> batchExecutors(final String name,
int workerCount,
final TaskProcessor<T> processor,
final AcceptorExecutor<ID, T> acceptorExecutor) {
final AtomicBoolean isShutdown = new AtomicBoolean();
final TaskExecutorMetrics metrics = new TaskExecutorMetrics(name);
registeredMonitors.put(name, metrics);
return new TaskExecutors<>(idx -> new BatchWorkerRunnable<>("TaskBatchingWorker-" + name + '-' + idx, isShutdown, metrics, processor, acceptorExecutor), workerCount, isShutdown);
}
static class TaskExecutorMetrics {
@Monitor(name = METRIC_REPLICATION_PREFIX + "numberOfSuccessfulExecutions", description = "Number of successful task executions", type = DataSourceType.COUNTER)
volatile long numberOfSuccessfulExecutions;
@Monitor(name = METRIC_REPLICATION_PREFIX + "numberOfTransientErrors", description = "Number of transient task execution errors", type = DataSourceType.COUNTER)
volatile long numberOfTransientError;
@Monitor(name = METRIC_REPLICATION_PREFIX + "numberOfPermanentErrors", description = "Number of permanent task execution errors", type = DataSourceType.COUNTER)
volatile long numberOfPermanentError;
@Monitor(name = METRIC_REPLICATION_PREFIX + "numberOfCongestionIssues", description = "Number of congestion issues during task execution", type = DataSourceType.COUNTER)
volatile long numberOfCongestionIssues;
final StatsTimer taskWaitingTimeForProcessing;
TaskExecutorMetrics(String id) {
final double[] percentiles = {50.0, 95.0, 99.0, 99.5};
final StatsConfig statsConfig = new StatsConfig.Builder()
.withSampleSize(1000)
.withPercentiles(percentiles)
.withPublishStdDev(true)
.build();
final MonitorConfig config = MonitorConfig.builder(METRIC_REPLICATION_PREFIX + "executionTime").build();
taskWaitingTimeForProcessing = new StatsTimer(config, statsConfig);
try {
Monitors.registerObject(id, this);
} catch (Throwable e) {
logger.warn("Cannot register servo monitor for this object", e);
}
}
void registerTaskResult(ProcessingResult result, int count) {
switch (result) {
case Success:
numberOfSuccessfulExecutions += count;
break;
case TransientError:
numberOfTransientError += count;
break;
case PermanentError:
numberOfPermanentError += count;
break;
case Congestion:
numberOfCongestionIssues += count;
break;
}
}
<ID, T> void registerExpiryTime(TaskHolder<ID, T> holder) {
taskWaitingTimeForProcessing.record(System.currentTimeMillis() - holder.getSubmitTimestamp(), TimeUnit.MILLISECONDS);
}
<ID, T> void registerExpiryTimes(List<TaskHolder<ID, T>> holders) {
long now = System.currentTimeMillis();
for (TaskHolder<ID, T> holder : holders) {
taskWaitingTimeForProcessing.record(now - holder.getSubmitTimestamp(), TimeUnit.MILLISECONDS);
}
}
}
interface WorkerRunnableFactory<ID, T> {
WorkerRunnable<ID, T> create(int idx);
}
abstract static class WorkerRunnable<ID, T> implements Runnable {
final String workerName;
final AtomicBoolean isShutdown;
final TaskExecutorMetrics metrics;
final TaskProcessor<T> processor;
final AcceptorExecutor<ID, T> taskDispatcher;
WorkerRunnable(String workerName,
AtomicBoolean isShutdown,
TaskExecutorMetrics metrics,
TaskProcessor<T> processor,
AcceptorExecutor<ID, T> taskDispatcher) {
this.workerName = workerName;
this.isShutdown = isShutdown;
this.metrics = metrics;
this.processor = processor;
this.taskDispatcher = taskDispatcher;
}
String getWorkerName() {
return workerName;
}
}
static class BatchWorkerRunnable<ID, T> extends WorkerRunnable<ID, T> {
BatchWorkerRunnable(String workerName,
AtomicBoolean isShutdown,
TaskExecutorMetrics metrics,
TaskProcessor<T> processor,
AcceptorExecutor<ID, T> acceptorExecutor) {
super(workerName, isShutdown, metrics, processor, acceptorExecutor);
}
@Override
public void run() {
try {
while (!isShutdown.get()) {
List<TaskHolder<ID, T>> holders = getWork();
metrics.registerExpiryTimes(holders);
List<T> tasks = getTasksOf(holders);
ProcessingResult result = processor.process(tasks);
switch (result) {
case Success:
break;
case Congestion:
case TransientError:
taskDispatcher.reprocess(holders, result);
break;
case PermanentError:
logger.warn("Discarding {} tasks of {} due to permanent error", holders.size(), workerName);
}
metrics.registerTaskResult(result, tasks.size());
}
} catch (InterruptedException e) {
// Ignore
} catch (Throwable e) {
// Safe-guard, so we never exit this loop in an uncontrolled way.
logger.warn("Discovery WorkerThread error", e);
}
}
private List<TaskHolder<ID, T>> getWork() throws InterruptedException {
BlockingQueue<List<TaskHolder<ID, T>>> workQueue = taskDispatcher.requestWorkItems();
List<TaskHolder<ID, T>> result;
do {
result = workQueue.poll(1, TimeUnit.SECONDS);
} while (!isShutdown.get() && result == null);
return (result == null) ? new ArrayList<>() : result;
}
private List<T> getTasksOf(List<TaskHolder<ID, T>> holders) {
List<T> tasks = new ArrayList<>(holders.size());
for (TaskHolder<ID, T> holder : holders) {
tasks.add(holder.getTask());
}
return tasks;
}
}
static class SingleTaskWorkerRunnable<ID, T> extends WorkerRunnable<ID, T> {
SingleTaskWorkerRunnable(String workerName,
AtomicBoolean isShutdown,
TaskExecutorMetrics metrics,
TaskProcessor<T> processor,
AcceptorExecutor<ID, T> acceptorExecutor) {
super(workerName, isShutdown, metrics, processor, acceptorExecutor);
}
@Override
public void run() {
try {
while (!isShutdown.get()) {
BlockingQueue<TaskHolder<ID, T>> workQueue = taskDispatcher.requestWorkItem();
TaskHolder<ID, T> taskHolder;
while ((taskHolder = workQueue.poll(1, TimeUnit.SECONDS)) == null) {
if (isShutdown.get()) {
return;
}
}
metrics.registerExpiryTime(taskHolder);
if (taskHolder != null) {
ProcessingResult result = processor.process(taskHolder.getTask());
switch (result) {
case Success:
break;
case Congestion:
case TransientError:
taskDispatcher.reprocess(taskHolder, result);
break;
case PermanentError:
logger.warn("Discarding a task of {} due to permanent error", workerName);
}
metrics.registerTaskResult(result, 1);
}
}
} catch (InterruptedException e) {
// Ignore
} catch (Throwable e) {
// Safe-guard, so we never exit this loop in an uncontrolled way.
logger.warn("Discovery WorkerThread error", e);
}
}
}
}
| 8,177 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/util | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/util/batcher/TaskProcessor.java | package com.netflix.eureka.util.batcher;
import java.util.List;
/**
* An interface to be implemented by clients for task execution.
*
* @author Tomasz Bak
*/
public interface TaskProcessor<T> {
/**
* A processed task/task list ends up in one of the following states:
* <ul>
* <li>{@code Success} processing finished successfully</li>
* <li>{@code TransientError} processing failed, but shall be retried later</li>
* <li>{@code PermanentError} processing failed, and is non recoverable</li>
* </ul>
*/
enum ProcessingResult {
Success, Congestion, TransientError, PermanentError
}
/**
* In non-batched mode a single task is processed at a time.
*/
ProcessingResult process(T task);
/**
* For batched mode a collection of tasks is run at a time. The result is provided for the aggregated result,
* and all tasks are handled in the same way according to what is returned (for example are rescheduled, if the
* error is transient).
*/
ProcessingResult process(List<T> tasks);
}
| 8,178 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/util | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/util/batcher/TrafficShaper.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.eureka.util.batcher;
import com.netflix.eureka.util.batcher.TaskProcessor.ProcessingResult;
/**
* {@link TrafficShaper} provides admission control policy prior to dispatching tasks to workers.
* It reacts to events coming via reprocess requests (transient failures, congestion), and delays the processing
* depending on this feedback.
*
* @author Tomasz Bak
*/
class TrafficShaper {
/**
* Upper bound on delay provided by configuration.
*/
private static final long MAX_DELAY = 30 * 1000;
private final long congestionRetryDelayMs;
private final long networkFailureRetryMs;
private volatile long lastCongestionError;
private volatile long lastNetworkFailure;
TrafficShaper(long congestionRetryDelayMs, long networkFailureRetryMs) {
this.congestionRetryDelayMs = Math.min(MAX_DELAY, congestionRetryDelayMs);
this.networkFailureRetryMs = Math.min(MAX_DELAY, networkFailureRetryMs);
}
void registerFailure(ProcessingResult processingResult) {
if (processingResult == ProcessingResult.Congestion) {
lastCongestionError = System.currentTimeMillis();
} else if (processingResult == ProcessingResult.TransientError) {
lastNetworkFailure = System.currentTimeMillis();
}
}
long transmissionDelay() {
if (lastCongestionError == -1 && lastNetworkFailure == -1) {
return 0;
}
long now = System.currentTimeMillis();
if (lastCongestionError != -1) {
long congestionDelay = now - lastCongestionError;
if (congestionDelay >= 0 && congestionDelay < congestionRetryDelayMs) {
return congestionRetryDelayMs - congestionDelay;
}
lastCongestionError = -1;
}
if (lastNetworkFailure != -1) {
long failureDelay = now - lastNetworkFailure;
if (failureDelay >= 0 && failureDelay < networkFailureRetryMs) {
return networkFailureRetryMs - failureDelay;
}
lastNetworkFailure = -1;
}
return 0;
}
}
| 8,179 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/resources/DefaultServerCodecs.java | package com.netflix.eureka.resources;
import com.netflix.appinfo.EurekaAccept;
import com.netflix.discovery.converters.wrappers.CodecWrapper;
import com.netflix.discovery.converters.wrappers.CodecWrappers;
import com.netflix.discovery.converters.wrappers.EncoderWrapper;
import com.netflix.eureka.EurekaServerConfig;
import com.netflix.eureka.registry.Key;
import javax.inject.Inject;
import javax.inject.Singleton;
/**
* @author David Liu
*/
@Singleton
public class DefaultServerCodecs implements ServerCodecs {
protected final CodecWrapper fullJsonCodec;
protected final CodecWrapper compactJsonCodec;
protected final CodecWrapper fullXmlCodec;
protected final CodecWrapper compactXmlCodec;
private static CodecWrapper getFullJson(EurekaServerConfig serverConfig) {
CodecWrapper codec = CodecWrappers.getCodec(serverConfig.getJsonCodecName());
return codec == null ? CodecWrappers.getCodec(CodecWrappers.LegacyJacksonJson.class) : codec;
}
private static CodecWrapper getFullXml(EurekaServerConfig serverConfig) {
CodecWrapper codec = CodecWrappers.getCodec(serverConfig.getXmlCodecName());
return codec == null ? CodecWrappers.getCodec(CodecWrappers.XStreamXml.class) : codec;
}
@Inject
public DefaultServerCodecs(EurekaServerConfig serverConfig) {
this (
getFullJson(serverConfig),
CodecWrappers.getCodec(CodecWrappers.JacksonJsonMini.class),
getFullXml(serverConfig),
CodecWrappers.getCodec(CodecWrappers.JacksonXmlMini.class)
);
}
protected DefaultServerCodecs(CodecWrapper fullJsonCodec,
CodecWrapper compactJsonCodec,
CodecWrapper fullXmlCodec,
CodecWrapper compactXmlCodec) {
this.fullJsonCodec = fullJsonCodec;
this.compactJsonCodec = compactJsonCodec;
this.fullXmlCodec = fullXmlCodec;
this.compactXmlCodec = compactXmlCodec;
}
@Override
public CodecWrapper getFullJsonCodec() {
return fullJsonCodec;
}
@Override
public CodecWrapper getCompactJsonCodec() {
return compactJsonCodec;
}
@Override
public CodecWrapper getFullXmlCodec() {
return fullXmlCodec;
}
@Override
public CodecWrapper getCompactXmlCodecr() {
return compactXmlCodec;
}
@Override
public EncoderWrapper getEncoder(Key.KeyType keyType, boolean compact) {
switch (keyType) {
case JSON:
return compact ? compactJsonCodec : fullJsonCodec;
case XML:
default:
return compact ? compactXmlCodec : fullXmlCodec;
}
}
@Override
public EncoderWrapper getEncoder(Key.KeyType keyType, EurekaAccept eurekaAccept) {
switch (eurekaAccept) {
case compact:
return getEncoder(keyType, true);
case full:
default:
return getEncoder(keyType, false);
}
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
protected CodecWrapper fullJsonCodec;
protected CodecWrapper compactJsonCodec;
protected CodecWrapper fullXmlCodec;
protected CodecWrapper compactXmlCodec;
protected Builder() {}
public Builder withFullJsonCodec(CodecWrapper fullJsonCodec) {
this.fullJsonCodec = fullJsonCodec;
return this;
}
public Builder withCompactJsonCodec(CodecWrapper compactJsonCodec) {
this.compactJsonCodec = compactJsonCodec;
return this;
}
public Builder withFullXmlCodec(CodecWrapper fullXmlCodec) {
this.fullXmlCodec = fullXmlCodec;
return this;
}
public Builder withCompactXmlCodec(CodecWrapper compactXmlEncoder) {
this.compactXmlCodec = compactXmlEncoder;
return this;
}
public Builder withEurekaServerConfig(EurekaServerConfig config) {
fullJsonCodec = CodecWrappers.getCodec(config.getJsonCodecName());
fullXmlCodec = CodecWrappers.getCodec(config.getXmlCodecName());
return this;
}
public ServerCodecs build() {
if (fullJsonCodec == null) {
fullJsonCodec = CodecWrappers.getCodec(CodecWrappers.LegacyJacksonJson.class);
}
if (compactJsonCodec == null) {
compactJsonCodec = CodecWrappers.getCodec(CodecWrappers.JacksonJsonMini.class);
}
if (fullXmlCodec == null) {
fullXmlCodec = CodecWrappers.getCodec(CodecWrappers.XStreamXml.class);
}
if (compactXmlCodec == null) {
compactXmlCodec = CodecWrappers.getCodec(CodecWrappers.JacksonXmlMini.class);
}
return new DefaultServerCodecs(
fullJsonCodec,
compactJsonCodec,
fullXmlCodec,
compactXmlCodec
);
}
}
}
| 8,180 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/resources/ServerInfoResource.java | package com.netflix.eureka.resources;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.eureka.EurekaServerContext;
import com.netflix.eureka.EurekaServerContextHolder;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import java.util.Map;
/**
* @author David Liu
*/
@Produces("application/json")
@Path("/serverinfo")
public class ServerInfoResource {
private final PeerAwareInstanceRegistry registry;
@Inject
ServerInfoResource(EurekaServerContext server) {
this.registry = server.getRegistry();
}
public ServerInfoResource() {
this(EurekaServerContextHolder.getInstance().getServerContext());
}
@GET
@Path("statusoverrides")
public Response getOverrides() throws Exception {
Map<String, InstanceInfo.InstanceStatus> result = registry.overriddenInstanceStatusesSnapshot();
ObjectMapper objectMapper = new ObjectMapper();
String responseStr = objectMapper.writeValueAsString(result);
return Response.ok(responseStr).build();
}
}
| 8,181 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/resources/VIPResource.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.eureka.resources;
import com.netflix.appinfo.EurekaAccept;
import com.netflix.eureka.EurekaServerContext;
import com.netflix.eureka.EurekaServerContextHolder;
import com.netflix.eureka.registry.Key;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
/**
* A <em>jersey</em> resource for retrieving all instances with a given VIP address.
*
* @author Karthik Ranganathan
*
*/
@Path("/{version}/vips")
@Produces({"application/xml", "application/json"})
public class VIPResource extends AbstractVIPResource {
@Inject
VIPResource(EurekaServerContext server) {
super(server);
}
public VIPResource() {
this(EurekaServerContextHolder.getInstance().getServerContext());
}
@GET
@Path("{vipAddress}")
public Response statusUpdate(@PathParam("version") String version,
@PathParam("vipAddress") String vipAddress,
@HeaderParam("Accept") final String acceptHeader,
@HeaderParam(EurekaAccept.HTTP_X_EUREKA_ACCEPT) String eurekaAccept) {
return getVipResponse(version, vipAddress, acceptHeader,
EurekaAccept.fromString(eurekaAccept), Key.EntityType.VIP);
}
}
| 8,182 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/resources/StatusResource.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.eureka.resources;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.netflix.eureka.EurekaServerContext;
import com.netflix.eureka.EurekaServerContextHolder;
import com.netflix.eureka.util.StatusInfo;
import com.netflix.eureka.util.StatusUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An utility class for exposing information about peer nodes.
*
* @author Karthik Ranganathan, Greg Kim
*/
@Path("/{version}/status")
@Produces({"application/xml", "application/json"})
public class StatusResource {
private static final Logger logger = LoggerFactory.getLogger(StatusResource.class);
private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss Z";
private final StatusUtil statusUtil;
@Inject
StatusResource(EurekaServerContext server) {
this.statusUtil = new StatusUtil(server);
}
public StatusResource() {
this(EurekaServerContextHolder.getInstance().getServerContext());
}
@GET
public StatusInfo getStatusInfo() {
return statusUtil.getStatusInfo();
}
public static String getCurrentTimeAsString() {
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
return format.format(new Date());
}
}
| 8,183 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/resources/SecureVIPResource.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.eureka.resources;
import com.netflix.appinfo.EurekaAccept;
import com.netflix.eureka.EurekaServerContext;
import com.netflix.eureka.EurekaServerContextHolder;
import com.netflix.eureka.registry.Key;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
/**
* A <em>jersey</em> resource for retrieving all instances with a given secure VIP address.
*
* @author Karthik Ranganathan
*
*/
@Path("/{version}/svips")
@Produces({"application/xml", "application/json"})
public class SecureVIPResource extends AbstractVIPResource {
@Inject
SecureVIPResource(EurekaServerContext server) {
super(server);
}
public SecureVIPResource() {
this(EurekaServerContextHolder.getInstance().getServerContext());
}
@GET
@Path("{svipAddress}")
public Response statusUpdate(@PathParam("version") String version,
@PathParam("svipAddress") String svipAddress,
@HeaderParam("Accept") final String acceptHeader,
@HeaderParam(EurekaAccept.HTTP_X_EUREKA_ACCEPT) String eurekaAccept) {
return getVipResponse(version, svipAddress, acceptHeader,
EurekaAccept.fromString(eurekaAccept), Key.EntityType.SVIP);
}
}
| 8,184 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/resources/InstanceResource.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.eureka.resources;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import com.netflix.eureka.EurekaServerConfig;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
import com.netflix.eureka.cluster.PeerEurekaNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A <em>jersey</em> resource that handles operations for a particular instance.
*
* @author Karthik Ranganathan, Greg Kim
*
*/
@Produces({"application/xml", "application/json"})
public class InstanceResource {
private static final Logger logger = LoggerFactory
.getLogger(InstanceResource.class);
private final PeerAwareInstanceRegistry registry;
private final EurekaServerConfig serverConfig;
private final String id;
private final ApplicationResource app;
InstanceResource(ApplicationResource app, String id, EurekaServerConfig serverConfig, PeerAwareInstanceRegistry registry) {
this.app = app;
this.id = id;
this.serverConfig = serverConfig;
this.registry = registry;
}
/**
* Get requests returns the information about the instance's
* {@link InstanceInfo}.
*
* @return response containing information about the the instance's
* {@link InstanceInfo}.
*/
@GET
public Response getInstanceInfo() {
InstanceInfo appInfo = registry
.getInstanceByAppAndId(app.getName(), id);
if (appInfo != null) {
logger.debug("Found: {} - {}", app.getName(), id);
return Response.ok(appInfo).build();
} else {
logger.debug("Not Found: {} - {}", app.getName(), id);
return Response.status(Status.NOT_FOUND).build();
}
}
/**
* A put request for renewing lease from a client instance.
*
* @param isReplication
* a header parameter containing information whether this is
* replicated from other nodes.
* @param overriddenStatus
* overridden status if any.
* @param status
* the {@link InstanceStatus} of the instance.
* @param lastDirtyTimestamp
* last timestamp when this instance information was updated.
* @return response indicating whether the operation was a success or
* failure.
*/
@PUT
public Response renewLease(
@HeaderParam(PeerEurekaNode.HEADER_REPLICATION) String isReplication,
@QueryParam("overriddenstatus") String overriddenStatus,
@QueryParam("status") String status,
@QueryParam("lastDirtyTimestamp") String lastDirtyTimestamp) {
boolean isFromReplicaNode = "true".equals(isReplication);
boolean isSuccess = registry.renew(app.getName(), id, isFromReplicaNode);
// Not found in the registry, immediately ask for a register
if (!isSuccess) {
logger.warn("Not Found (Renew): {} - {}", app.getName(), id);
return Response.status(Status.NOT_FOUND).build();
}
// Check if we need to sync based on dirty time stamp, the client
// instance might have changed some value
Response response;
if (lastDirtyTimestamp != null && serverConfig.shouldSyncWhenTimestampDiffers()) {
response = this.validateDirtyTimestamp(Long.valueOf(lastDirtyTimestamp), isFromReplicaNode);
// Store the overridden status since the validation found out the node that replicates wins
if (response.getStatus() == Response.Status.NOT_FOUND.getStatusCode()
&& (overriddenStatus != null)
&& !(InstanceStatus.UNKNOWN.name().equals(overriddenStatus))
&& isFromReplicaNode) {
registry.storeOverriddenStatusIfRequired(app.getAppName(), id, InstanceStatus.valueOf(overriddenStatus));
}
} else {
response = Response.ok().build();
}
logger.debug("Found (Renew): {} - {}; reply status={}", app.getName(), id, response.getStatus());
return response;
}
/**
* Handles {@link InstanceStatus} updates.
*
* <p>
* The status updates are normally done for administrative purposes to
* change the instance status between {@link InstanceStatus#UP} and
* {@link InstanceStatus#OUT_OF_SERVICE} to select or remove instances for
* receiving traffic.
* </p>
*
* @param newStatus
* the new status of the instance.
* @param isReplication
* a header parameter containing information whether this is
* replicated from other nodes.
* @param lastDirtyTimestamp
* last timestamp when this instance information was updated.
* @return response indicating whether the operation was a success or
* failure.
*/
@PUT
@Path("status")
public Response statusUpdate(
@QueryParam("value") String newStatus,
@HeaderParam(PeerEurekaNode.HEADER_REPLICATION) String isReplication,
@QueryParam("lastDirtyTimestamp") String lastDirtyTimestamp) {
try {
if (registry.getInstanceByAppAndId(app.getName(), id) == null) {
logger.warn("Instance not found: {}/{}", app.getName(), id);
return Response.status(Status.NOT_FOUND).build();
}
boolean isSuccess = registry.statusUpdate(app.getName(), id,
InstanceStatus.valueOf(newStatus), lastDirtyTimestamp,
"true".equals(isReplication));
if (isSuccess) {
logger.info("Status updated: {} - {} - {}", app.getName(), id, newStatus);
return Response.ok().build();
} else {
logger.warn("Unable to update status: {} - {} - {}", app.getName(), id, newStatus);
return Response.serverError().build();
}
} catch (Throwable e) {
logger.error("Error updating instance {} for status {}", id,
newStatus);
return Response.serverError().build();
}
}
/**
* Removes status override for an instance, set with
* {@link #statusUpdate(String, String, String)}.
*
* @param isReplication
* a header parameter containing information whether this is
* replicated from other nodes.
* @param lastDirtyTimestamp
* last timestamp when this instance information was updated.
* @return response indicating whether the operation was a success or
* failure.
*/
@DELETE
@Path("status")
public Response deleteStatusUpdate(
@HeaderParam(PeerEurekaNode.HEADER_REPLICATION) String isReplication,
@QueryParam("value") String newStatusValue,
@QueryParam("lastDirtyTimestamp") String lastDirtyTimestamp) {
try {
if (registry.getInstanceByAppAndId(app.getName(), id) == null) {
logger.warn("Instance not found: {}/{}", app.getName(), id);
return Response.status(Status.NOT_FOUND).build();
}
InstanceStatus newStatus = newStatusValue == null ? InstanceStatus.UNKNOWN : InstanceStatus.valueOf(newStatusValue);
boolean isSuccess = registry.deleteStatusOverride(app.getName(), id,
newStatus, lastDirtyTimestamp, "true".equals(isReplication));
if (isSuccess) {
logger.info("Status override removed: {} - {}", app.getName(), id);
return Response.ok().build();
} else {
logger.warn("Unable to remove status override: {} - {}", app.getName(), id);
return Response.serverError().build();
}
} catch (Throwable e) {
logger.error("Error removing instance's {} status override", id);
return Response.serverError().build();
}
}
/**
* Updates user-specific metadata information. If the key is already available, its value will be overwritten.
* If not, it will be added.
* @param uriInfo - URI information generated by jersey.
* @return response indicating whether the operation was a success or
* failure.
*/
@PUT
@Path("metadata")
public Response updateMetadata(@Context UriInfo uriInfo) {
try {
InstanceInfo instanceInfo = registry.getInstanceByAppAndId(app.getName(), id);
// ReplicationInstance information is not found, generate an error
if (instanceInfo == null) {
logger.warn("Cannot find instance while updating metadata for instance {}/{}", app.getName(), id);
return Response.status(Status.NOT_FOUND).build();
}
MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
Set<Entry<String, List<String>>> entrySet = queryParams.entrySet();
Map<String, String> metadataMap = instanceInfo.getMetadata();
// Metadata map is empty - create a new map
if (Collections.emptyMap().getClass().equals(metadataMap.getClass())) {
metadataMap = new ConcurrentHashMap<>();
InstanceInfo.Builder builder = new InstanceInfo.Builder(instanceInfo);
builder.setMetadata(metadataMap);
instanceInfo = builder.build();
}
// Add all the user supplied entries to the map
for (Entry<String, List<String>> entry : entrySet) {
metadataMap.put(entry.getKey(), entry.getValue().get(0));
}
registry.register(instanceInfo, false);
return Response.ok().build();
} catch (Throwable e) {
logger.error("Error updating metadata for instance {}", id, e);
return Response.serverError().build();
}
}
/**
* Handles cancellation of leases for this particular instance.
*
* @param isReplication
* a header parameter containing information whether this is
* replicated from other nodes.
* @return response indicating whether the operation was a success or
* failure.
*/
@DELETE
public Response cancelLease(
@HeaderParam(PeerEurekaNode.HEADER_REPLICATION) String isReplication) {
try {
boolean isSuccess = registry.cancel(app.getName(), id,
"true".equals(isReplication));
if (isSuccess) {
logger.debug("Found (Cancel): {} - {}", app.getName(), id);
return Response.ok().build();
} else {
logger.info("Not Found (Cancel): {} - {}", app.getName(), id);
return Response.status(Status.NOT_FOUND).build();
}
} catch (Throwable e) {
logger.error("Error (cancel): {} - {}", app.getName(), id, e);
return Response.serverError().build();
}
}
private Response validateDirtyTimestamp(Long lastDirtyTimestamp,
boolean isReplication) {
InstanceInfo appInfo = registry.getInstanceByAppAndId(app.getName(), id, false);
if (appInfo != null) {
if ((lastDirtyTimestamp != null) && (!lastDirtyTimestamp.equals(appInfo.getLastDirtyTimestamp()))) {
Object[] args = {id, appInfo.getLastDirtyTimestamp(), lastDirtyTimestamp, isReplication};
if (lastDirtyTimestamp > appInfo.getLastDirtyTimestamp()) {
logger.debug(
"Time to sync, since the last dirty timestamp differs -"
+ " ReplicationInstance id : {},Registry : {} Incoming: {} Replication: {}",
args);
return Response.status(Status.NOT_FOUND).build();
} else if (appInfo.getLastDirtyTimestamp() > lastDirtyTimestamp) {
// In the case of replication, send the current instance info in the registry for the
// replicating node to sync itself with this one.
if (isReplication) {
logger.debug(
"Time to sync, since the last dirty timestamp differs -"
+ " ReplicationInstance id : {},Registry : {} Incoming: {} Replication: {}",
args);
return Response.status(Status.CONFLICT).entity(appInfo).build();
} else {
return Response.ok().build();
}
}
}
}
return Response.ok().build();
}
}
| 8,185 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/resources/PeerReplicationResource.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.eureka.resources;
import javax.inject.Inject;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.eureka.EurekaServerContext;
import com.netflix.eureka.EurekaServerConfig;
import com.netflix.eureka.EurekaServerContextHolder;
import com.netflix.eureka.cluster.protocol.ReplicationInstance;
import com.netflix.eureka.cluster.protocol.ReplicationInstanceResponse;
import com.netflix.eureka.cluster.protocol.ReplicationInstanceResponse.Builder;
import com.netflix.eureka.cluster.protocol.ReplicationList;
import com.netflix.eureka.cluster.protocol.ReplicationListResponse;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A <em>jersey</em> resource that handles requests for replication purposes.
*
* @author Karthik Ranganathan
*
*/
@Path("/{version}/peerreplication")
@Produces({"application/xml", "application/json"})
public class PeerReplicationResource {
private static final Logger logger = LoggerFactory.getLogger(PeerReplicationResource.class);
private static final String REPLICATION = "true";
private final EurekaServerConfig serverConfig;
private final PeerAwareInstanceRegistry registry;
@Inject
PeerReplicationResource(EurekaServerContext server) {
this.serverConfig = server.getServerConfig();
this.registry = server.getRegistry();
}
public PeerReplicationResource() {
this(EurekaServerContextHolder.getInstance().getServerContext());
}
/**
* Process batched replication events from peer eureka nodes.
*
* <p>
* The batched events are delegated to underlying resources to generate a
* {@link ReplicationListResponse} containing the individual responses to the batched events
* </p>
*
* @param replicationList
* The List of replication events from peer eureka nodes
* @return A batched response containing the information about the responses of individual events
*/
@Path("batch")
@POST
public Response batchReplication(ReplicationList replicationList) {
try {
ReplicationListResponse batchResponse = new ReplicationListResponse();
for (ReplicationInstance instanceInfo : replicationList.getReplicationList()) {
try {
batchResponse.addResponse(dispatch(instanceInfo));
} catch (Exception e) {
batchResponse.addResponse(new ReplicationInstanceResponse(Status.INTERNAL_SERVER_ERROR.getStatusCode(), null));
logger.error("{} request processing failed for batch item {}/{}",
instanceInfo.getAction(), instanceInfo.getAppName(), instanceInfo.getId(), e);
}
}
return Response.ok(batchResponse).build();
} catch (Throwable e) {
logger.error("Cannot execute batch Request", e);
return Response.status(Status.INTERNAL_SERVER_ERROR).build();
}
}
private ReplicationInstanceResponse dispatch(ReplicationInstance instanceInfo) {
ApplicationResource applicationResource = createApplicationResource(instanceInfo);
InstanceResource resource = createInstanceResource(instanceInfo, applicationResource);
String lastDirtyTimestamp = toString(instanceInfo.getLastDirtyTimestamp());
String overriddenStatus = toString(instanceInfo.getOverriddenStatus());
String instanceStatus = toString(instanceInfo.getStatus());
Builder singleResponseBuilder = new Builder();
switch (instanceInfo.getAction()) {
case Register:
singleResponseBuilder = handleRegister(instanceInfo, applicationResource);
break;
case Heartbeat:
singleResponseBuilder = handleHeartbeat(serverConfig, resource, lastDirtyTimestamp, overriddenStatus, instanceStatus);
break;
case Cancel:
singleResponseBuilder = handleCancel(resource);
break;
case StatusUpdate:
singleResponseBuilder = handleStatusUpdate(instanceInfo, resource);
break;
case DeleteStatusOverride:
singleResponseBuilder = handleDeleteStatusOverride(instanceInfo, resource);
break;
}
return singleResponseBuilder.build();
}
/* Visible for testing */ ApplicationResource createApplicationResource(ReplicationInstance instanceInfo) {
return new ApplicationResource(instanceInfo.getAppName(), serverConfig, registry);
}
/* Visible for testing */ InstanceResource createInstanceResource(ReplicationInstance instanceInfo,
ApplicationResource applicationResource) {
return new InstanceResource(applicationResource, instanceInfo.getId(), serverConfig, registry);
}
private static Builder handleRegister(ReplicationInstance instanceInfo, ApplicationResource applicationResource) {
applicationResource.addInstance(instanceInfo.getInstanceInfo(), REPLICATION);
return new Builder().setStatusCode(Status.OK.getStatusCode());
}
private static Builder handleCancel(InstanceResource resource) {
Response response = resource.cancelLease(REPLICATION);
return new Builder().setStatusCode(response.getStatus());
}
private static Builder handleHeartbeat(EurekaServerConfig config, InstanceResource resource, String lastDirtyTimestamp, String overriddenStatus, String instanceStatus) {
Response response = resource.renewLease(REPLICATION, overriddenStatus, instanceStatus, lastDirtyTimestamp);
int responseStatus = response.getStatus();
Builder responseBuilder = new Builder().setStatusCode(responseStatus);
if ("false".equals(config.getExperimental("bugfix.934"))) {
if (responseStatus == Status.OK.getStatusCode() && response.getEntity() != null) {
responseBuilder.setResponseEntity((InstanceInfo) response.getEntity());
}
} else {
if ((responseStatus == Status.OK.getStatusCode() || responseStatus == Status.CONFLICT.getStatusCode())
&& response.getEntity() != null) {
responseBuilder.setResponseEntity((InstanceInfo) response.getEntity());
}
}
return responseBuilder;
}
private static Builder handleStatusUpdate(ReplicationInstance instanceInfo, InstanceResource resource) {
Response response = resource.statusUpdate(instanceInfo.getStatus(), REPLICATION, toString(instanceInfo.getLastDirtyTimestamp()));
return new Builder().setStatusCode(response.getStatus());
}
private static Builder handleDeleteStatusOverride(ReplicationInstance instanceInfo, InstanceResource resource) {
Response response = resource.deleteStatusUpdate(REPLICATION, instanceInfo.getStatus(),
instanceInfo.getLastDirtyTimestamp().toString());
return new Builder().setStatusCode(response.getStatus());
}
private static <T> String toString(T value) {
if (value == null) {
return null;
}
return value.toString();
}
}
| 8,186 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/resources/ApplicationsResource.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.eureka.resources;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import java.util.Arrays;
import com.netflix.appinfo.EurekaAccept;
import com.netflix.eureka.EurekaServerContext;
import com.netflix.eureka.EurekaServerContextHolder;
import com.netflix.eureka.registry.AbstractInstanceRegistry;
import com.netflix.eureka.EurekaServerConfig;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
import com.netflix.eureka.Version;
import com.netflix.eureka.registry.ResponseCache;
import com.netflix.eureka.registry.Key.KeyType;
import com.netflix.eureka.registry.ResponseCacheImpl;
import com.netflix.eureka.registry.Key;
import com.netflix.eureka.util.EurekaMonitors;
/**
* A <em>jersey</em> resource that handles request related to all
* {@link com.netflix.discovery.shared.Applications}.
*
* @author Karthik Ranganathan, Greg Kim
*
*/
@Path("/{version}/apps")
@Produces({"application/xml", "application/json"})
public class ApplicationsResource {
private static final String HEADER_ACCEPT = "Accept";
private static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
private static final String HEADER_CONTENT_ENCODING = "Content-Encoding";
private static final String HEADER_CONTENT_TYPE = "Content-Type";
private static final String HEADER_GZIP_VALUE = "gzip";
private static final String HEADER_JSON_VALUE = "json";
private final EurekaServerConfig serverConfig;
private final PeerAwareInstanceRegistry registry;
private final ResponseCache responseCache;
@Inject
ApplicationsResource(EurekaServerContext eurekaServer) {
this.serverConfig = eurekaServer.getServerConfig();
this.registry = eurekaServer.getRegistry();
this.responseCache = registry.getResponseCache();
}
public ApplicationsResource() {
this(EurekaServerContextHolder.getInstance().getServerContext());
}
/**
* Gets information about a particular {@link com.netflix.discovery.shared.Application}.
*
* @param version
* the version of the request.
* @param appId
* the unique application identifier (which is the name) of the
* application.
* @return information about a particular application.
*/
@Path("{appId}")
public ApplicationResource getApplicationResource(
@PathParam("version") String version,
@PathParam("appId") String appId) {
CurrentRequestVersion.set(Version.toEnum(version));
try {
return new ApplicationResource(appId, serverConfig, registry);
} finally {
CurrentRequestVersion.remove();
}
}
/**
* Get information about all {@link com.netflix.discovery.shared.Applications}.
*
* @param version the version of the request.
* @param acceptHeader the accept header to indicate whether to serve JSON or XML data.
* @param acceptEncoding the accept header to indicate whether to serve compressed or uncompressed data.
* @param eurekaAccept an eureka accept extension, see {@link com.netflix.appinfo.EurekaAccept}
* @param uriInfo the {@link java.net.URI} information of the request made.
* @param regionsStr A comma separated list of remote regions from which the instances will also be returned.
* The applications returned from the remote region can be limited to the applications
* returned by {@link EurekaServerConfig#getRemoteRegionAppWhitelist(String)}
*
* @return a response containing information about all {@link com.netflix.discovery.shared.Applications}
* from the {@link AbstractInstanceRegistry}.
*/
@GET
public Response getContainers(@PathParam("version") String version,
@HeaderParam(HEADER_ACCEPT) String acceptHeader,
@HeaderParam(HEADER_ACCEPT_ENCODING) String acceptEncoding,
@HeaderParam(EurekaAccept.HTTP_X_EUREKA_ACCEPT) String eurekaAccept,
@Context UriInfo uriInfo,
@Nullable @QueryParam("regions") String regionsStr) {
boolean isRemoteRegionRequested = null != regionsStr && !regionsStr.isEmpty();
String[] regions = null;
if (!isRemoteRegionRequested) {
EurekaMonitors.GET_ALL.increment();
} else {
regions = regionsStr.toLowerCase().split(",");
Arrays.sort(regions); // So we don't have different caches for same regions queried in different order.
EurekaMonitors.GET_ALL_WITH_REMOTE_REGIONS.increment();
}
// Check if the server allows the access to the registry. The server can
// restrict access if it is not
// ready to serve traffic depending on various reasons.
if (!registry.shouldAllowAccess(isRemoteRegionRequested)) {
return Response.status(Status.FORBIDDEN).build();
}
CurrentRequestVersion.set(Version.toEnum(version));
KeyType keyType = Key.KeyType.JSON;
String returnMediaType = MediaType.APPLICATION_JSON;
if (acceptHeader == null || !acceptHeader.contains(HEADER_JSON_VALUE)) {
keyType = Key.KeyType.XML;
returnMediaType = MediaType.APPLICATION_XML;
}
Key cacheKey = new Key(Key.EntityType.Application,
ResponseCacheImpl.ALL_APPS,
keyType, CurrentRequestVersion.get(), EurekaAccept.fromString(eurekaAccept), regions
);
Response response;
if (acceptEncoding != null && acceptEncoding.contains(HEADER_GZIP_VALUE)) {
response = Response.ok(responseCache.getGZIP(cacheKey))
.header(HEADER_CONTENT_ENCODING, HEADER_GZIP_VALUE)
.header(HEADER_CONTENT_TYPE, returnMediaType)
.build();
} else {
response = Response.ok(responseCache.get(cacheKey))
.build();
}
CurrentRequestVersion.remove();
return response;
}
/**
* Get information about all delta changes in {@link com.netflix.discovery.shared.Applications}.
*
* <p>
* The delta changes represent the registry information change for a period
* as configured by
* {@link EurekaServerConfig#getRetentionTimeInMSInDeltaQueue()}. The
* changes that can happen in a registry include
* <em>Registrations,Cancels,Status Changes and Expirations</em>. Normally
* the changes to the registry are infrequent and hence getting just the
* delta will be much more efficient than getting the complete registry.
* </p>
*
* <p>
* Since the delta information is cached over a period of time, the requests
* may return the same data multiple times within the window configured by
* {@link EurekaServerConfig#getRetentionTimeInMSInDeltaQueue()}.The clients
* are expected to handle this duplicate information.
* <p>
*
* @param version the version of the request.
* @param acceptHeader the accept header to indicate whether to serve JSON or XML data.
* @param acceptEncoding the accept header to indicate whether to serve compressed or uncompressed data.
* @param eurekaAccept an eureka accept extension, see {@link com.netflix.appinfo.EurekaAccept}
* @param uriInfo the {@link java.net.URI} information of the request made.
* @return response containing the delta information of the
* {@link AbstractInstanceRegistry}.
*/
@Path("delta")
@GET
public Response getContainerDifferential(
@PathParam("version") String version,
@HeaderParam(HEADER_ACCEPT) String acceptHeader,
@HeaderParam(HEADER_ACCEPT_ENCODING) String acceptEncoding,
@HeaderParam(EurekaAccept.HTTP_X_EUREKA_ACCEPT) String eurekaAccept,
@Context UriInfo uriInfo, @Nullable @QueryParam("regions") String regionsStr) {
boolean isRemoteRegionRequested = null != regionsStr && !regionsStr.isEmpty();
// If the delta flag is disabled in discovery or if the lease expiration
// has been disabled, redirect clients to get all instances
if ((serverConfig.shouldDisableDelta()) || (!registry.shouldAllowAccess(isRemoteRegionRequested))) {
return Response.status(Status.FORBIDDEN).build();
}
String[] regions = null;
if (!isRemoteRegionRequested) {
EurekaMonitors.GET_ALL_DELTA.increment();
} else {
regions = regionsStr.toLowerCase().split(",");
Arrays.sort(regions); // So we don't have different caches for same regions queried in different order.
EurekaMonitors.GET_ALL_DELTA_WITH_REMOTE_REGIONS.increment();
}
CurrentRequestVersion.set(Version.toEnum(version));
KeyType keyType = Key.KeyType.JSON;
String returnMediaType = MediaType.APPLICATION_JSON;
if (acceptHeader == null || !acceptHeader.contains(HEADER_JSON_VALUE)) {
keyType = Key.KeyType.XML;
returnMediaType = MediaType.APPLICATION_XML;
}
Key cacheKey = new Key(Key.EntityType.Application,
ResponseCacheImpl.ALL_APPS_DELTA,
keyType, CurrentRequestVersion.get(), EurekaAccept.fromString(eurekaAccept), regions
);
final Response response;
if (acceptEncoding != null && acceptEncoding.contains(HEADER_GZIP_VALUE)) {
response = Response.ok(responseCache.getGZIP(cacheKey))
.header(HEADER_CONTENT_ENCODING, HEADER_GZIP_VALUE)
.header(HEADER_CONTENT_TYPE, returnMediaType)
.build();
} else {
response = Response.ok(responseCache.get(cacheKey)).build();
}
CurrentRequestVersion.remove();
return response;
}
}
| 8,187 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/resources/InstancesResource.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.eureka.resources;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import java.util.List;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.eureka.EurekaServerContext;
import com.netflix.eureka.EurekaServerContextHolder;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
import com.netflix.eureka.Version;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A <em>jersey</em> resource that gets information about a particular instance.
*
* @author Karthik Ranganathan, Greg Kim
*
*/
@Produces({"application/xml", "application/json"})
@Path("/{version}/instances")
public class InstancesResource {
private static final Logger logger = LoggerFactory
.getLogger(InstancesResource.class);
private final PeerAwareInstanceRegistry registry;
@Inject
InstancesResource(EurekaServerContext server) {
this.registry = server.getRegistry();
}
public InstancesResource() {
this(EurekaServerContextHolder.getInstance().getServerContext());
}
@GET
@Path("{id}")
public Response getById(@PathParam("version") String version,
@PathParam("id") String id) {
CurrentRequestVersion.set(Version.toEnum(version));
List<InstanceInfo> list = registry.getInstancesById(id);
CurrentRequestVersion.remove();
if (list != null && !list.isEmpty()) {
return Response.ok(list.get(0)).build();
} else {
logger.info("Not Found: {}", id);
return Response.status(Status.NOT_FOUND).build();
}
}
}
| 8,188 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/resources/AbstractVIPResource.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.eureka.resources;
import javax.ws.rs.core.Response;
import com.netflix.appinfo.EurekaAccept;
import com.netflix.eureka.EurekaServerContext;
import com.netflix.eureka.EurekaServerContextHolder;
import com.netflix.eureka.Version;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
import com.netflix.eureka.registry.ResponseCache;
import com.netflix.eureka.registry.Key;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Abstract class for the common functionality of a VIP/SVIP resource.
*
* @author Nitesh Kant (nkant@netflix.com)
*/
abstract class AbstractVIPResource {
private static final Logger logger = LoggerFactory.getLogger(AbstractVIPResource.class);
private final PeerAwareInstanceRegistry registry;
private final ResponseCache responseCache;
AbstractVIPResource(EurekaServerContext server) {
this.registry = server.getRegistry();
this.responseCache = registry.getResponseCache();
}
AbstractVIPResource() {
this(EurekaServerContextHolder.getInstance().getServerContext());
}
protected Response getVipResponse(String version, String entityName, String acceptHeader,
EurekaAccept eurekaAccept, Key.EntityType entityType) {
if (!registry.shouldAllowAccess(false)) {
return Response.status(Response.Status.FORBIDDEN).build();
}
CurrentRequestVersion.set(Version.toEnum(version));
Key.KeyType keyType = Key.KeyType.JSON;
if (acceptHeader == null || !acceptHeader.contains("json")) {
keyType = Key.KeyType.XML;
}
Key cacheKey = new Key(
entityType,
entityName,
keyType,
CurrentRequestVersion.get(),
eurekaAccept
);
String payLoad = responseCache.get(cacheKey);
CurrentRequestVersion.remove();
if (payLoad != null) {
logger.debug("Found: {}", entityName);
return Response.ok(payLoad).build();
} else {
logger.debug("Not Found: {}", entityName);
return Response.status(Response.Status.NOT_FOUND).build();
}
}
}
| 8,189 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/resources/ASGResource.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.eureka.resources;
import javax.inject.Inject;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import com.netflix.eureka.EurekaServerContext;
import com.netflix.eureka.EurekaServerContextHolder;
import com.netflix.eureka.cluster.PeerEurekaNode;
import com.netflix.eureka.aws.AwsAsgUtil;
import com.netflix.eureka.registry.AwsInstanceRegistry;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A <em>jersey</em> resource for handling updates to {@link ASGStatus}.
*
* <p>
* The ASG status is used in <em>AWS</em> environments to automatically
* enable/disable instance registration based on the status of the ASG. This is
* particularly useful in <em>red/black</em> deployment scenarios where it is
* easy to switch to a new version and incase of problems switch back to the old
* versions of the deployment.
* </p>
*
* <p>
* During such a scenario, when an ASG is disabled and the instances go away and
* get refilled by an ASG - which is normal in AWS environments,the instances
* automatically go in the {@link com.netflix.appinfo.InstanceInfo.InstanceStatus#OUT_OF_SERVICE} state when they
* are refilled by the ASG and if the ASG is disabled by as indicated by a flag
* in the ASG as described in {@link AwsAsgUtil#isASGEnabled}
* </p>
*
* @author Karthik Ranganathan
*
*/
@Path("/{version}/asg")
@Produces({"application/xml", "application/json"})
public class ASGResource {
private static final Logger logger = LoggerFactory.getLogger(ASGResource.class);
public enum ASGStatus {
ENABLED, DISABLED;
public static ASGStatus toEnum(String s) {
for (ASGStatus e : ASGStatus.values()) {
if (e.name().equalsIgnoreCase(s)) {
return e;
}
}
throw new RuntimeException("Cannot find ASG enum for the given string " + s);
}
}
protected final PeerAwareInstanceRegistry registry;
protected final AwsAsgUtil awsAsgUtil;
@Inject
ASGResource(EurekaServerContext eurekaServer) {
this.registry = eurekaServer.getRegistry();
if (registry instanceof AwsInstanceRegistry) {
this.awsAsgUtil = ((AwsInstanceRegistry) registry).getAwsAsgUtil();
} else {
this.awsAsgUtil = null;
}
}
public ASGResource() {
this(EurekaServerContextHolder.getInstance().getServerContext());
}
/**
* Changes the status information of the ASG.
*
* @param asgName the name of the ASG for which the status needs to be changed.
* @param newStatus the new status {@link ASGStatus} of the ASG.
* @param isReplication a header parameter containing information whether this is replicated from other nodes.
*
* @return response which indicates if the operation succeeded or not.
*/
@PUT
@Path("{asgName}/status")
public Response statusUpdate(@PathParam("asgName") String asgName,
@QueryParam("value") String newStatus,
@HeaderParam(PeerEurekaNode.HEADER_REPLICATION) String isReplication) {
if (awsAsgUtil == null) {
return Response.status(400).build();
}
try {
logger.info("Trying to update ASG Status for ASG {} to {}", asgName, newStatus);
ASGStatus asgStatus = ASGStatus.valueOf(newStatus.toUpperCase());
awsAsgUtil.setStatus(asgName, (!ASGStatus.DISABLED.equals(asgStatus)));
registry.statusUpdate(asgName, asgStatus, Boolean.valueOf(isReplication));
logger.debug("Updated ASG Status for ASG {} to {}", asgName, asgStatus);
} catch (Throwable e) {
logger.error("Cannot update the status {} for the ASG {}", newStatus, asgName, e);
return Response.serverError().build();
}
return Response.ok().build();
}
}
| 8,190 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/resources/CurrentRequestVersion.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.eureka.resources;
import com.netflix.eureka.Version;
/**
* A thread-scoped value that holds the "current {@link com.netflix.eureka.Version}" for the
* request.
*
* <p>This is not intended as a general mechanism for passing data.
* Rather it is here to support those cases where someplace deep in
* a library we need to know about the context of the request that
* initially triggered the current request.</p>
*
* @author Karthik Ranganathan, Greg Kim
*/
public final class CurrentRequestVersion {
private static final ThreadLocal<Version> CURRENT_REQ_VERSION =
new ThreadLocal<>();
private CurrentRequestVersion() {
}
/**
* Gets the current {@link Version}
* Will return null if no current version has been set.
*/
public static Version get() {
return CURRENT_REQ_VERSION.get();
}
/**
* Sets the current {@link Version}.
*
* Use {@link #remove()} as soon as the version is no longer required
* in order to purge the ThreadLocal used for storing it.
*/
public static void set(Version version) {
CURRENT_REQ_VERSION.set(version);
}
/**
* Clears the {@link ThreadLocal} used to store the version.
*/
public static void remove() {
CURRENT_REQ_VERSION.remove();
}
}
| 8,191 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/resources/ServerCodecs.java | package com.netflix.eureka.resources;
import com.netflix.appinfo.EurekaAccept;
import com.netflix.discovery.converters.wrappers.CodecWrapper;
import com.netflix.discovery.converters.wrappers.EncoderWrapper;
import com.netflix.eureka.registry.Key;
/**
* @author David Liu
*/
public interface ServerCodecs {
CodecWrapper getFullJsonCodec();
CodecWrapper getCompactJsonCodec();
CodecWrapper getFullXmlCodec();
CodecWrapper getCompactXmlCodecr();
EncoderWrapper getEncoder(Key.KeyType keyType, boolean compact);
EncoderWrapper getEncoder(Key.KeyType keyType, EurekaAccept eurekaAccept);
}
| 8,192 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/resources/ApplicationResource.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.eureka.resources;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import com.netflix.appinfo.AmazonInfo;
import com.netflix.appinfo.DataCenterInfo;
import com.netflix.appinfo.EurekaAccept;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.UniqueIdentifier;
import com.netflix.eureka.EurekaServerConfig;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
import com.netflix.eureka.Version;
import com.netflix.eureka.cluster.PeerEurekaNode;
import com.netflix.eureka.registry.ResponseCache;
import com.netflix.eureka.registry.Key.KeyType;
import com.netflix.eureka.registry.Key;
import com.netflix.eureka.util.EurekaMonitors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A <em>jersey</em> resource that handles request related to a particular
* {@link com.netflix.discovery.shared.Application}.
*
* @author Karthik Ranganathan, Greg Kim
*
*/
@Produces({"application/xml", "application/json"})
public class ApplicationResource {
private static final Logger logger = LoggerFactory.getLogger(ApplicationResource.class);
private final String appName;
private final EurekaServerConfig serverConfig;
private final PeerAwareInstanceRegistry registry;
private final ResponseCache responseCache;
ApplicationResource(String appName,
EurekaServerConfig serverConfig,
PeerAwareInstanceRegistry registry) {
this.appName = appName.toUpperCase();
this.serverConfig = serverConfig;
this.registry = registry;
this.responseCache = registry.getResponseCache();
}
public String getAppName() {
return appName;
}
/**
* Gets information about a particular {@link com.netflix.discovery.shared.Application}.
*
* @param version
* the version of the request.
* @param acceptHeader
* the accept header of the request to indicate whether to serve
* JSON or XML data.
* @return the response containing information about a particular
* application.
*/
@GET
public Response getApplication(@PathParam("version") String version,
@HeaderParam("Accept") final String acceptHeader,
@HeaderParam(EurekaAccept.HTTP_X_EUREKA_ACCEPT) String eurekaAccept) {
if (!registry.shouldAllowAccess(false)) {
return Response.status(Status.FORBIDDEN).build();
}
EurekaMonitors.GET_APPLICATION.increment();
CurrentRequestVersion.set(Version.toEnum(version));
KeyType keyType = Key.KeyType.JSON;
if (acceptHeader == null || !acceptHeader.contains("json")) {
keyType = Key.KeyType.XML;
}
Key cacheKey = new Key(
Key.EntityType.Application,
appName,
keyType,
CurrentRequestVersion.get(),
EurekaAccept.fromString(eurekaAccept)
);
String payLoad = responseCache.get(cacheKey);
CurrentRequestVersion.remove();
if (payLoad != null) {
logger.debug("Found: {}", appName);
return Response.ok(payLoad).build();
} else {
logger.debug("Not Found: {}", appName);
return Response.status(Status.NOT_FOUND).build();
}
}
/**
* Gets information about a particular instance of an application.
*
* @param id
* the unique identifier of the instance.
* @return information about a particular instance.
*/
@Path("{id}")
public InstanceResource getInstanceInfo(@PathParam("id") String id) {
return new InstanceResource(this, id, serverConfig, registry);
}
/**
* Registers information about a particular instance for an
* {@link com.netflix.discovery.shared.Application}.
*
* @param info
* {@link InstanceInfo} information of the instance.
* @param isReplication
* a header parameter containing information whether this is
* replicated from other nodes.
*/
@POST
@Consumes({"application/json", "application/xml"})
public Response addInstance(InstanceInfo info,
@HeaderParam(PeerEurekaNode.HEADER_REPLICATION) String isReplication) {
logger.debug("Registering instance {} (replication={})", info.getId(), isReplication);
// validate that the instanceinfo contains all the necessary required fields
if (isBlank(info.getId())) {
return Response.status(400).entity("Missing instanceId").build();
} else if (isBlank(info.getHostName())) {
return Response.status(400).entity("Missing hostname").build();
} else if (isBlank(info.getIPAddr())) {
return Response.status(400).entity("Missing ip address").build();
} else if (isBlank(info.getAppName())) {
return Response.status(400).entity("Missing appName").build();
} else if (!appName.equals(info.getAppName())) {
return Response.status(400).entity("Mismatched appName, expecting " + appName + " but was " + info.getAppName()).build();
} else if (info.getDataCenterInfo() == null) {
return Response.status(400).entity("Missing dataCenterInfo").build();
} else if (info.getDataCenterInfo().getName() == null) {
return Response.status(400).entity("Missing dataCenterInfo Name").build();
}
// handle cases where clients may be registering with bad DataCenterInfo with missing data
DataCenterInfo dataCenterInfo = info.getDataCenterInfo();
if (dataCenterInfo instanceof UniqueIdentifier) {
String dataCenterInfoId = ((UniqueIdentifier) dataCenterInfo).getId();
if (isBlank(dataCenterInfoId)) {
boolean experimental = "true".equalsIgnoreCase(serverConfig.getExperimental("registration.validation.dataCenterInfoId"));
if (experimental) {
String entity = "DataCenterInfo of type " + dataCenterInfo.getClass() + " must contain a valid id";
return Response.status(400).entity(entity).build();
} else if (dataCenterInfo instanceof AmazonInfo) {
AmazonInfo amazonInfo = (AmazonInfo) dataCenterInfo;
String effectiveId = amazonInfo.get(AmazonInfo.MetaDataKey.instanceId);
if (effectiveId == null) {
amazonInfo.getMetadata().put(AmazonInfo.MetaDataKey.instanceId.getName(), info.getId());
}
} else {
logger.warn("Registering DataCenterInfo of type {} without an appropriate id", dataCenterInfo.getClass());
}
}
}
registry.register(info, "true".equals(isReplication));
return Response.status(204).build(); // 204 to be backwards compatible
}
/**
* Returns the application name of a particular application.
*
* @return the application name of a particular application.
*/
String getName() {
return appName;
}
private boolean isBlank(String str) {
return str == null || str.isEmpty();
}
}
| 8,193 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/lease/Lease.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.eureka.lease;
import com.netflix.eureka.registry.AbstractInstanceRegistry;
/**
* Describes a time-based availability of a {@link T}. Purpose is to avoid
* accumulation of instances in {@link AbstractInstanceRegistry} as result of ungraceful
* shutdowns that is not uncommon in AWS environments.
*
* If a lease elapses without renewals, it will eventually expire consequently
* marking the associated {@link T} for immediate eviction - this is similar to
* an explicit cancellation except that there is no communication between the
* {@link T} and {@link LeaseManager}.
*
* @author Karthik Ranganathan, Greg Kim
*/
public class Lease<T> {
enum Action {
Register, Cancel, Renew
};
public static final int DEFAULT_DURATION_IN_SECS = 90;
private T holder;
private long evictionTimestamp;
private long registrationTimestamp;
private long serviceUpTimestamp;
// Make it volatile so that the expiration task would see this quicker
private volatile long lastUpdateTimestamp;
private long duration;
public Lease(T r, int durationInSecs) {
holder = r;
registrationTimestamp = System.currentTimeMillis();
lastUpdateTimestamp = registrationTimestamp;
duration = (durationInSecs * 1000);
}
/**
* Renew the lease, use renewal duration if it was specified by the
* associated {@link T} during registration, otherwise default duration is
* {@link #DEFAULT_DURATION_IN_SECS}.
*/
public void renew() {
lastUpdateTimestamp = System.currentTimeMillis() + duration;
}
/**
* Cancels the lease by updating the eviction time.
*/
public void cancel() {
if (evictionTimestamp <= 0) {
evictionTimestamp = System.currentTimeMillis();
}
}
/**
* Mark the service as up. This will only take affect the first time called,
* subsequent calls will be ignored.
*/
public void serviceUp() {
if (serviceUpTimestamp == 0) {
serviceUpTimestamp = System.currentTimeMillis();
}
}
/**
* Set the leases service UP timestamp.
*/
public void setServiceUpTimestamp(long serviceUpTimestamp) {
this.serviceUpTimestamp = serviceUpTimestamp;
}
/**
* Checks if the lease of a given {@link com.netflix.appinfo.InstanceInfo} has expired or not.
*/
public boolean isExpired() {
return isExpired(0l);
}
/**
* Checks if the lease of a given {@link com.netflix.appinfo.InstanceInfo} has expired or not.
*
* Note that due to renew() doing the 'wrong" thing and setting lastUpdateTimestamp to +duration more than
* what it should be, the expiry will actually be 2 * duration. This is a minor bug and should only affect
* instances that ungracefully shutdown. Due to possible wide ranging impact to existing usage, this will
* not be fixed.
*
* @param additionalLeaseMs any additional lease time to add to the lease evaluation in ms.
*/
public boolean isExpired(long additionalLeaseMs) {
return (evictionTimestamp > 0 || System.currentTimeMillis() > (lastUpdateTimestamp + duration + additionalLeaseMs));
}
/**
* Gets the milliseconds since epoch when the lease was registered.
*
* @return the milliseconds since epoch when the lease was registered.
*/
public long getRegistrationTimestamp() {
return registrationTimestamp;
}
/**
* Gets the milliseconds since epoch when the lease was last renewed.
* Note that the value returned here is actually not the last lease renewal time but the renewal + duration.
*
* @return the milliseconds since epoch when the lease was last renewed.
*/
public long getLastRenewalTimestamp() {
return lastUpdateTimestamp;
}
/**
* Gets the milliseconds since epoch when the lease was evicted.
*
* @return the milliseconds since epoch when the lease was evicted.
*/
public long getEvictionTimestamp() {
return evictionTimestamp;
}
/**
* Gets the milliseconds since epoch when the service for the lease was marked as up.
*
* @return the milliseconds since epoch when the service for the lease was marked as up.
*/
public long getServiceUpTimestamp() {
return serviceUpTimestamp;
}
/**
* Returns the holder of the lease.
*/
public T getHolder() {
return holder;
}
}
| 8,194 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/lease/LeaseManager.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.eureka.lease;
import com.netflix.eureka.registry.AbstractInstanceRegistry;
/**
* This class is responsible for creating/renewing and evicting a <em>lease</em>
* for a particular instance.
*
* <p>
* Leases determine what instances receive traffic. When there is no renewal
* request from the client, the lease gets expired and the instances are evicted
* out of {@link AbstractInstanceRegistry}. This is key to instances receiving traffic
* or not.
* <p>
*
* @author Karthik Ranganathan, Greg Kim
*
* @param <T>
*/
public interface LeaseManager<T> {
/**
* Assign a new {@link Lease} to the passed in {@link T}.
*
* @param r
* - T to register
* @param leaseDuration
* @param isReplication
* - whether this is a replicated entry from another eureka node.
*/
void register(T r, int leaseDuration, boolean isReplication);
/**
* Cancel the {@link Lease} associated w/ the passed in <code>appName</code>
* and <code>id</code>.
*
* @param appName
* - unique id of the application.
* @param id
* - unique id within appName.
* @param isReplication
* - whether this is a replicated entry from another eureka node.
* @return true, if the operation was successful, false otherwise.
*/
boolean cancel(String appName, String id, boolean isReplication);
/**
* Renew the {@link Lease} associated w/ the passed in <code>appName</code>
* and <code>id</code>.
*
* @param id
* - unique id within appName
* @param isReplication
* - whether this is a replicated entry from another ds node
* @return whether the operation of successful
*/
boolean renew(String appName, String id, boolean isReplication);
/**
* Evict {@link T}s with expired {@link Lease}(s).
*/
void evict();
}
| 8,195 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/registry/PeerAwareInstanceRegistryImpl.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.eureka.registry;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import com.netflix.appinfo.AmazonInfo;
import com.netflix.appinfo.AmazonInfo.MetaDataKey;
import com.netflix.appinfo.ApplicationInfoManager;
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.LeaseInfo;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.discovery.shared.Application;
import com.netflix.discovery.shared.Applications;
import com.netflix.eureka.registry.rule.DownOrStartingRule;
import com.netflix.eureka.registry.rule.FirstMatchWinsCompositeRule;
import com.netflix.eureka.registry.rule.InstanceStatusOverrideRule;
import com.netflix.eureka.registry.rule.LeaseExistsRule;
import com.netflix.eureka.registry.rule.OverrideExistsRule;
import com.netflix.eureka.resources.CurrentRequestVersion;
import com.netflix.eureka.EurekaServerConfig;
import com.netflix.eureka.Version;
import com.netflix.eureka.cluster.PeerEurekaNode;
import com.netflix.eureka.cluster.PeerEurekaNodes;
import com.netflix.eureka.lease.Lease;
import com.netflix.eureka.resources.ASGResource.ASGStatus;
import com.netflix.eureka.resources.ServerCodecs;
import com.netflix.eureka.util.MeasuredRate;
import com.netflix.servo.DefaultMonitorRegistry;
import com.netflix.servo.annotations.DataSourceType;
import com.netflix.servo.monitor.Monitors;
import com.netflix.servo.monitor.Stopwatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Singleton;
import static com.netflix.eureka.Names.METRIC_REGISTRY_PREFIX;
/**
* Handles replication of all operations to {@link AbstractInstanceRegistry} to peer
* <em>Eureka</em> nodes to keep them all in sync.
*
* <p>
* Primary operations that are replicated are the
* <em>Registers,Renewals,Cancels,Expirations and Status Changes</em>
* </p>
*
* <p>
* When the eureka server starts up it tries to fetch all the registry
* information from the peer eureka nodes.If for some reason this operation
* fails, the server does not allow the user to get the registry information for
* a period specified in
* {@link com.netflix.eureka.EurekaServerConfig#getWaitTimeInMsWhenSyncEmpty()}.
* </p>
*
* <p>
* One important thing to note about <em>renewals</em>.If the renewal drops more
* than the specified threshold as specified in
* {@link com.netflix.eureka.EurekaServerConfig#getRenewalPercentThreshold()} within a period of
* {@link com.netflix.eureka.EurekaServerConfig#getRenewalThresholdUpdateIntervalMs()}, eureka
* perceives this as a danger and stops expiring instances.
* </p>
*
* @author Karthik Ranganathan, Greg Kim
*
*/
@Singleton
public class PeerAwareInstanceRegistryImpl extends AbstractInstanceRegistry implements PeerAwareInstanceRegistry {
private static final Logger logger = LoggerFactory.getLogger(PeerAwareInstanceRegistryImpl.class);
private static final String US_EAST_1 = "us-east-1";
private static final int PRIME_PEER_NODES_RETRY_MS = 30000;
private long startupTime = 0;
private boolean peerInstancesTransferEmptyOnStartup = true;
public enum Action {
Heartbeat, Register, Cancel, StatusUpdate, DeleteStatusOverride;
private com.netflix.servo.monitor.Timer timer = Monitors.newTimer(this.name());
public com.netflix.servo.monitor.Timer getTimer() {
return this.timer;
}
}
private static final Comparator<Application> APP_COMPARATOR = new Comparator<Application>() {
public int compare(Application l, Application r) {
return l.getName().compareTo(r.getName());
}
};
private final MeasuredRate numberOfReplicationsLastMin;
protected final EurekaClient eurekaClient;
protected volatile PeerEurekaNodes peerEurekaNodes;
private final InstanceStatusOverrideRule instanceStatusOverrideRule;
private Timer timer = new Timer(
"ReplicaAwareInstanceRegistry - RenewalThresholdUpdater", true);
@Inject
public PeerAwareInstanceRegistryImpl(
EurekaServerConfig serverConfig,
EurekaClientConfig clientConfig,
ServerCodecs serverCodecs,
EurekaClient eurekaClient
) {
super(serverConfig, clientConfig, serverCodecs);
this.eurekaClient = eurekaClient;
this.numberOfReplicationsLastMin = new MeasuredRate(1000 * 60 * 1);
// We first check if the instance is STARTING or DOWN, then we check explicit overrides,
// then we check the status of a potentially existing lease.
this.instanceStatusOverrideRule = new FirstMatchWinsCompositeRule(new DownOrStartingRule(),
new OverrideExistsRule(overriddenInstanceStatusMap), new LeaseExistsRule());
}
@Override
protected InstanceStatusOverrideRule getInstanceInfoOverrideRule() {
return this.instanceStatusOverrideRule;
}
@Override
public void init(PeerEurekaNodes peerEurekaNodes) throws Exception {
this.numberOfReplicationsLastMin.start();
this.peerEurekaNodes = peerEurekaNodes;
initializedResponseCache();
scheduleRenewalThresholdUpdateTask();
initRemoteRegionRegistry();
try {
Monitors.registerObject(this);
} catch (Throwable e) {
logger.warn("Cannot register the JMX monitor for the InstanceRegistry :", e);
}
}
/**
* Perform all cleanup and shutdown operations.
*/
@Override
public void shutdown() {
try {
DefaultMonitorRegistry.getInstance().unregister(Monitors.newObjectMonitor(this));
} catch (Throwable t) {
logger.error("Cannot shutdown monitor registry", t);
}
try {
peerEurekaNodes.shutdown();
} catch (Throwable t) {
logger.error("Cannot shutdown ReplicaAwareInstanceRegistry", t);
}
numberOfReplicationsLastMin.stop();
timer.cancel();
super.shutdown();
}
/**
* Schedule the task that updates <em>renewal threshold</em> periodically.
* The renewal threshold would be used to determine if the renewals drop
* dramatically because of network partition and to protect expiring too
* many instances at a time.
*
*/
private void scheduleRenewalThresholdUpdateTask() {
timer.schedule(new TimerTask() {
@Override
public void run() {
updateRenewalThreshold();
}
}, serverConfig.getRenewalThresholdUpdateIntervalMs(),
serverConfig.getRenewalThresholdUpdateIntervalMs());
}
/**
* Populates the registry information from a peer eureka node. This
* operation fails over to other nodes until the list is exhausted if the
* communication fails.
*/
@Override
public int syncUp() {
// Copy entire entry from neighboring DS node
int count = 0;
for (int i = 0; ((i < serverConfig.getRegistrySyncRetries()) && (count == 0)); i++) {
if (i > 0) {
try {
Thread.sleep(serverConfig.getRegistrySyncRetryWaitMs());
} catch (InterruptedException e) {
logger.warn("Interrupted during registry transfer..");
break;
}
}
Applications apps = eurekaClient.getApplications();
for (Application app : apps.getRegisteredApplications()) {
for (InstanceInfo instance : app.getInstances()) {
try {
if (isRegisterable(instance)) {
register(instance, instance.getLeaseInfo().getDurationInSecs(), true);
count++;
}
} catch (Throwable t) {
logger.error("During DS init copy", t);
}
}
}
}
return count;
}
@Override
public void openForTraffic(ApplicationInfoManager applicationInfoManager, int count) {
// Renewals happen every 30 seconds and for a minute it should be a factor of 2.
this.expectedNumberOfClientsSendingRenews = count;
updateRenewsPerMinThreshold();
logger.info("Got {} instances from neighboring DS node", count);
logger.info("Renew threshold is: {}", numberOfRenewsPerMinThreshold);
this.startupTime = System.currentTimeMillis();
if (count > 0) {
this.peerInstancesTransferEmptyOnStartup = false;
}
DataCenterInfo.Name selfName = applicationInfoManager.getInfo().getDataCenterInfo().getName();
boolean isAws = Name.Amazon == selfName;
if (isAws && serverConfig.shouldPrimeAwsReplicaConnections()) {
logger.info("Priming AWS connections for all replicas..");
primeAwsReplicas(applicationInfoManager);
}
logger.info("Changing status to UP");
applicationInfoManager.setInstanceStatus(InstanceStatus.UP);
super.postInit();
}
/**
* Prime connections for Aws replicas.
* <p>
* Sometimes when the eureka servers comes up, AWS firewall may not allow
* the network connections immediately. This will cause the outbound
* connections to fail, but the inbound connections continue to work. What
* this means is the clients would have switched to this node (after EIP
* binding) and so the other eureka nodes will expire all instances that
* have been switched because of the lack of outgoing heartbeats from this
* instance.
* </p>
* <p>
* The best protection in this scenario is to block and wait until we are
* able to ping all eureka nodes successfully atleast once. Until then we
* won't open up the traffic.
* </p>
*/
private void primeAwsReplicas(ApplicationInfoManager applicationInfoManager) {
boolean areAllPeerNodesPrimed = false;
while (!areAllPeerNodesPrimed) {
String peerHostName = null;
try {
Application eurekaApps = this.getApplication(applicationInfoManager.getInfo().getAppName(), false);
if (eurekaApps == null) {
areAllPeerNodesPrimed = true;
logger.info("No peers needed to prime.");
return;
}
for (PeerEurekaNode node : peerEurekaNodes.getPeerEurekaNodes()) {
for (InstanceInfo peerInstanceInfo : eurekaApps.getInstances()) {
LeaseInfo leaseInfo = peerInstanceInfo.getLeaseInfo();
// If the lease is expired - do not worry about priming
if (System.currentTimeMillis() > (leaseInfo
.getRenewalTimestamp() + (leaseInfo
.getDurationInSecs() * 1000))
+ (2 * 60 * 1000)) {
continue;
}
peerHostName = peerInstanceInfo.getHostName();
logger.info("Trying to send heartbeat for the eureka server at {} to make sure the " +
"network channels are open", peerHostName);
// Only try to contact the eureka nodes that are in this instance's registry - because
// the other instances may be legitimately down
if (peerHostName.equalsIgnoreCase(new URI(node.getServiceUrl()).getHost())) {
node.heartbeat(
peerInstanceInfo.getAppName(),
peerInstanceInfo.getId(),
peerInstanceInfo,
null,
true);
}
}
}
areAllPeerNodesPrimed = true;
} catch (Throwable e) {
logger.error("Could not contact {}", peerHostName, e);
try {
Thread.sleep(PRIME_PEER_NODES_RETRY_MS);
} catch (InterruptedException e1) {
logger.warn("Interrupted while priming : ", e1);
areAllPeerNodesPrimed = true;
}
}
}
}
/**
* Checks to see if the registry access is allowed or the server is in a
* situation where it does not all getting registry information. The server
* does not return registry information for a period specified in
* {@link EurekaServerConfig#getWaitTimeInMsWhenSyncEmpty()}, if it cannot
* get the registry information from the peer eureka nodes at start up.
*
* @return false - if the instances count from a replica transfer returned
* zero and if the wait time has not elapsed, otherwise returns true
*/
@Override
public boolean shouldAllowAccess(boolean remoteRegionRequired) {
if (this.peerInstancesTransferEmptyOnStartup) {
if (!(System.currentTimeMillis() > this.startupTime + serverConfig.getWaitTimeInMsWhenSyncEmpty())) {
return false;
}
}
if (remoteRegionRequired) {
for (RemoteRegionRegistry remoteRegionRegistry : this.regionNameVSRemoteRegistry.values()) {
if (!remoteRegionRegistry.isReadyForServingData()) {
return false;
}
}
}
return true;
}
public boolean shouldAllowAccess() {
return shouldAllowAccess(true);
}
@com.netflix.servo.annotations.Monitor(name = METRIC_REGISTRY_PREFIX + "shouldAllowAccess", type = DataSourceType.GAUGE)
public int shouldAllowAccessMetric() {
return shouldAllowAccess() ? 1 : 0;
}
/**
* @deprecated use {@link com.netflix.eureka.cluster.PeerEurekaNodes#getPeerEurekaNodes()} directly.
*
* Gets the list of peer eureka nodes which is the list to replicate
* information to.
*
* @return the list of replica nodes.
*/
@Deprecated
public List<PeerEurekaNode> getReplicaNodes() {
return Collections.unmodifiableList(peerEurekaNodes.getPeerEurekaNodes());
}
/*
* (non-Javadoc)
*
* @see com.netflix.eureka.registry.InstanceRegistry#cancel(java.lang.String,
* java.lang.String, long, boolean)
*/
@Override
public boolean cancel(final String appName, final String id,
final boolean isReplication) {
if (super.cancel(appName, id, isReplication)) {
replicateToPeers(Action.Cancel, appName, id, null, null, isReplication);
return true;
}
return false;
}
/**
* Registers the information about the {@link InstanceInfo} and replicates
* this information to all peer eureka nodes. If this is replication event
* from other replica nodes then it is not replicated.
*
* @param info
* the {@link InstanceInfo} to be registered and replicated.
* @param isReplication
* true if this is a replication event from other replica nodes,
* false otherwise.
*/
@Override
public void register(final InstanceInfo info, final boolean isReplication) {
int leaseDuration = Lease.DEFAULT_DURATION_IN_SECS;
if (info.getLeaseInfo() != null && info.getLeaseInfo().getDurationInSecs() > 0) {
leaseDuration = info.getLeaseInfo().getDurationInSecs();
}
super.register(info, leaseDuration, isReplication);
replicateToPeers(Action.Register, info.getAppName(), info.getId(), info, null, isReplication);
}
/*
* (non-Javadoc)
*
* @see com.netflix.eureka.registry.InstanceRegistry#renew(java.lang.String,
* java.lang.String, long, boolean)
*/
public boolean renew(final String appName, final String id, final boolean isReplication) {
if (super.renew(appName, id, isReplication)) {
replicateToPeers(Action.Heartbeat, appName, id, null, null, isReplication);
return true;
}
return false;
}
/*
* (non-Javadoc)
*
* @see com.netflix.eureka.registry.InstanceRegistry#statusUpdate(java.lang.String,
* java.lang.String, com.netflix.appinfo.InstanceInfo.InstanceStatus,
* java.lang.String, boolean)
*/
@Override
public boolean statusUpdate(final String appName, final String id,
final InstanceStatus newStatus, String lastDirtyTimestamp,
final boolean isReplication) {
if (super.statusUpdate(appName, id, newStatus, lastDirtyTimestamp, isReplication)) {
replicateToPeers(Action.StatusUpdate, appName, id, null, newStatus, isReplication);
return true;
}
return false;
}
@Override
public boolean deleteStatusOverride(String appName, String id,
InstanceStatus newStatus,
String lastDirtyTimestamp,
boolean isReplication) {
if (super.deleteStatusOverride(appName, id, newStatus, lastDirtyTimestamp, isReplication)) {
replicateToPeers(Action.DeleteStatusOverride, appName, id, null, null, isReplication);
return true;
}
return false;
}
/**
* Replicate the <em>ASG status</em> updates to peer eureka nodes. If this
* event is a replication from other nodes, then it is not replicated to
* other nodes.
*
* @param asgName the asg name for which the status needs to be replicated.
* @param newStatus the {@link ASGStatus} information that needs to be replicated.
* @param isReplication true if this is a replication event from other nodes, false otherwise.
*/
@Override
public void statusUpdate(final String asgName, final ASGStatus newStatus, final boolean isReplication) {
// If this is replicated from an other node, do not try to replicate again.
if (isReplication) {
return;
}
for (final PeerEurekaNode node : peerEurekaNodes.getPeerEurekaNodes()) {
replicateASGInfoToReplicaNodes(asgName, newStatus, node);
}
}
@Override
public boolean isLeaseExpirationEnabled() {
if (!isSelfPreservationModeEnabled()) {
// The self preservation mode is disabled, hence allowing the instances to expire.
return true;
}
return numberOfRenewsPerMinThreshold > 0 && getNumOfRenewsInLastMin() > numberOfRenewsPerMinThreshold;
}
@com.netflix.servo.annotations.Monitor(name = METRIC_REGISTRY_PREFIX + "isLeaseExpirationEnabled", type = DataSourceType.GAUGE)
public int isLeaseExpirationEnabledMetric() {
return isLeaseExpirationEnabled() ? 1 : 0;
}
/**
* Checks to see if the self-preservation mode is enabled.
*
* <p>
* The self-preservation mode is enabled if the expected number of renewals
* per minute {@link #getNumOfRenewsInLastMin()} is lesser than the expected
* threshold which is determined by {@link #getNumOfRenewsPerMinThreshold()}
* . Eureka perceives this as a danger and stops expiring instances as this
* is most likely because of a network event. The mode is disabled only when
* the renewals get back to above the threshold or if the flag
* {@link EurekaServerConfig#shouldEnableSelfPreservation()} is set to
* false.
* </p>
*
* @return true if the self-preservation mode is enabled, false otherwise.
*/
@Override
public boolean isSelfPreservationModeEnabled() {
return serverConfig.shouldEnableSelfPreservation();
}
@com.netflix.servo.annotations.Monitor(name = METRIC_REGISTRY_PREFIX + "isSelfPreservationModeEnabled", type = DataSourceType.GAUGE)
public int isSelfPreservationModeEnabledMetric() {
return isSelfPreservationModeEnabled() ? 1 : 0;
}
@Override
public InstanceInfo getNextServerFromEureka(String virtualHostname, boolean secure) {
// TODO Auto-generated method stub
return null;
}
/**
* Updates the <em>renewal threshold</em> based on the current number of
* renewals. The threshold is a percentage as specified in
* {@link EurekaServerConfig#getRenewalPercentThreshold()} of renewals
* received per minute {@link #getNumOfRenewsInLastMin()}.
*/
private void updateRenewalThreshold() {
try {
Applications apps = eurekaClient.getApplications();
int count = 0;
for (Application app : apps.getRegisteredApplications()) {
for (InstanceInfo instance : app.getInstances()) {
if (this.isRegisterable(instance)) {
++count;
}
}
}
synchronized (lock) {
// Update threshold only if the threshold is greater than the
// current expected threshold or if self preservation is disabled.
if ((count) > (serverConfig.getRenewalPercentThreshold() * expectedNumberOfClientsSendingRenews)
|| (!this.isSelfPreservationModeEnabled())) {
this.expectedNumberOfClientsSendingRenews = count;
updateRenewsPerMinThreshold();
}
}
logger.info("Current renewal threshold is : {}", numberOfRenewsPerMinThreshold);
} catch (Throwable e) {
logger.error("Cannot update renewal threshold", e);
}
}
/**
* Gets the list of all {@link Applications} from the registry in sorted
* lexical order of {@link Application#getName()}.
*
* @return the list of {@link Applications} in lexical order.
*/
@Override
public List<Application> getSortedApplications() {
List<Application> apps = new ArrayList<>(getApplications().getRegisteredApplications());
Collections.sort(apps, APP_COMPARATOR);
return apps;
}
/**
* Gets the number of <em>renewals</em> in the last minute.
*
* @return a long value representing the number of <em>renewals</em> in the last minute.
*/
@com.netflix.servo.annotations.Monitor(name = "numOfReplicationsInLastMin",
description = "Number of total replications received in the last minute",
type = com.netflix.servo.annotations.DataSourceType.GAUGE)
public long getNumOfReplicationsInLastMin() {
return numberOfReplicationsLastMin.getCount();
}
/**
* Checks if the number of renewals is lesser than threshold.
*
* @return 0 if the renewals are greater than threshold, 1 otherwise.
*/
@com.netflix.servo.annotations.Monitor(name = "isBelowRenewThreshold", description = "0 = false, 1 = true",
type = com.netflix.servo.annotations.DataSourceType.GAUGE)
@Override
public int isBelowRenewThresold() {
if ((getNumOfRenewsInLastMin() <= numberOfRenewsPerMinThreshold)
&&
((this.startupTime > 0) && (System.currentTimeMillis() > this.startupTime + (serverConfig.getWaitTimeInMsWhenSyncEmpty())))) {
return 1;
} else {
return 0;
}
}
/**
* Checks if an instance is registerable in this region. Instances from other regions are rejected.
*
* @param instanceInfo th instance info information of the instance
* @return true, if it can be registered in this server, false otherwise.
*/
public boolean isRegisterable(InstanceInfo instanceInfo) {
DataCenterInfo datacenterInfo = instanceInfo.getDataCenterInfo();
String serverRegion = clientConfig.getRegion();
if (AmazonInfo.class.isInstance(datacenterInfo)) {
AmazonInfo info = AmazonInfo.class.cast(instanceInfo.getDataCenterInfo());
String availabilityZone = info.get(MetaDataKey.availabilityZone);
// Can be null for dev environments in non-AWS data center
if (availabilityZone == null && US_EAST_1.equalsIgnoreCase(serverRegion)) {
return true;
} else if ((availabilityZone != null) && (availabilityZone.contains(serverRegion))) {
// If in the same region as server, then consider it registerable
return true;
}
}
return true; // Everything non-amazon is registrable.
}
/**
* Replicates all eureka actions to peer eureka nodes except for replication
* traffic to this node.
*
*/
private void replicateToPeers(Action action, String appName, String id,
InstanceInfo info /* optional */,
InstanceStatus newStatus /* optional */, boolean isReplication) {
Stopwatch tracer = action.getTimer().start();
try {
if (isReplication) {
numberOfReplicationsLastMin.increment();
}
// If it is a replication already, do not replicate again as this will create a poison replication
if (peerEurekaNodes == Collections.EMPTY_LIST || isReplication) {
return;
}
for (final PeerEurekaNode node : peerEurekaNodes.getPeerEurekaNodes()) {
// If the url represents this host, do not replicate to yourself.
if (peerEurekaNodes.isThisMyUrl(node.getServiceUrl())) {
continue;
}
replicateInstanceActionsToPeers(action, appName, id, info, newStatus, node);
}
} finally {
tracer.stop();
}
}
/**
* Replicates all instance changes to peer eureka nodes except for
* replication traffic to this node.
*
*/
private void replicateInstanceActionsToPeers(Action action, String appName,
String id, InstanceInfo info, InstanceStatus newStatus,
PeerEurekaNode node) {
try {
InstanceInfo infoFromRegistry;
CurrentRequestVersion.set(Version.V2);
switch (action) {
case Cancel:
node.cancel(appName, id);
break;
case Heartbeat:
InstanceStatus overriddenStatus = overriddenInstanceStatusMap.get(id);
infoFromRegistry = getInstanceByAppAndId(appName, id, false);
node.heartbeat(appName, id, infoFromRegistry, overriddenStatus, false);
break;
case Register:
node.register(info);
break;
case StatusUpdate:
infoFromRegistry = getInstanceByAppAndId(appName, id, false);
node.statusUpdate(appName, id, newStatus, infoFromRegistry);
break;
case DeleteStatusOverride:
infoFromRegistry = getInstanceByAppAndId(appName, id, false);
node.deleteStatusOverride(appName, id, infoFromRegistry);
break;
}
} catch (Throwable t) {
logger.error("Cannot replicate information to {} for action {}", node.getServiceUrl(), action.name(), t);
} finally {
CurrentRequestVersion.remove();
}
}
/**
* Replicates all ASG status changes to peer eureka nodes except for
* replication traffic to this node.
*/
private void replicateASGInfoToReplicaNodes(final String asgName,
final ASGStatus newStatus, final PeerEurekaNode node) {
CurrentRequestVersion.set(Version.V2);
try {
node.statusUpdate(asgName, newStatus);
} catch (Throwable e) {
logger.error("Cannot replicate ASG status information to {}", node.getServiceUrl(), e);
} finally {
CurrentRequestVersion.remove();
}
}
@Override
@com.netflix.servo.annotations.Monitor(name = "localRegistrySize",
description = "Current registry size", type = DataSourceType.GAUGE)
public long getLocalRegistrySize() {
return super.getLocalRegistrySize();
}
}
| 8,196 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/registry/RemoteRegionRegistry.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.eureka.registry;
import javax.inject.Inject;
import javax.ws.rs.core.MediaType;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.InstanceInfo.ActionType;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.discovery.EurekaIdentityHeaderFilter;
import com.netflix.discovery.TimedSupervisorTask;
import com.netflix.discovery.shared.Application;
import com.netflix.discovery.shared.Applications;
import com.netflix.discovery.shared.LookupService;
import com.netflix.discovery.shared.resolver.ClusterResolver;
import com.netflix.discovery.shared.resolver.StaticClusterResolver;
import com.netflix.discovery.shared.transport.EurekaHttpClient;
import com.netflix.discovery.shared.transport.EurekaHttpResponse;
import com.netflix.discovery.shared.transport.jersey.EurekaJerseyClient;
import com.netflix.discovery.shared.transport.jersey.EurekaJerseyClientImpl.EurekaJerseyClientBuilder;
import com.netflix.eureka.EurekaServerConfig;
import com.netflix.eureka.EurekaServerIdentity;
import com.netflix.eureka.resources.ServerCodecs;
import com.netflix.eureka.transport.EurekaServerHttpClients;
import com.netflix.servo.annotations.DataSourceType;
import com.netflix.servo.monitor.Monitors;
import com.netflix.servo.monitor.Stopwatch;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.filter.GZIPContentEncodingFilter;
import com.sun.jersey.client.apache4.ApacheHttpClient4;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.netflix.eureka.Names.METRIC_REGISTRY_PREFIX;
/**
* Handles all registry operations that needs to be done on a eureka service running in an other region.
*
* The primary operations include fetching registry information from remote region and fetching delta information
* on a periodic basis.
*
* TODO: a lot of the networking code in this class can be replaced by newer code in
* {@link com.netflix.discovery.DiscoveryClient}
*
* @author Karthik Ranganathan
*
*/
public class RemoteRegionRegistry implements LookupService<String> {
private static final Logger logger = LoggerFactory.getLogger(RemoteRegionRegistry.class);
private final ApacheHttpClient4 discoveryApacheClient;
private final EurekaJerseyClient discoveryJerseyClient;
private final com.netflix.servo.monitor.Timer fetchRegistryTimer;
private final URL remoteRegionURL;
private final ScheduledExecutorService scheduler;
// monotonically increasing generation counter to ensure stale threads do not reset registry to an older version
private final AtomicLong fetchRegistryGeneration = new AtomicLong(0);
private final Lock fetchRegistryUpdateLock = new ReentrantLock();
private final AtomicReference<Applications> applications = new AtomicReference<>(new Applications());
private final AtomicReference<Applications> applicationsDelta = new AtomicReference<>(new Applications());
private final EurekaServerConfig serverConfig;
private volatile boolean readyForServingData;
private final EurekaHttpClient eurekaHttpClient;
private long timeOfLastSuccessfulRemoteFetch = System.currentTimeMillis();
private long deltaSuccesses = 0;
private long deltaMismatches = 0;
@Inject
public RemoteRegionRegistry(EurekaServerConfig serverConfig,
EurekaClientConfig clientConfig,
ServerCodecs serverCodecs,
String regionName,
URL remoteRegionURL) {
this.serverConfig = serverConfig;
this.remoteRegionURL = remoteRegionURL;
this.fetchRegistryTimer = Monitors.newTimer(this.remoteRegionURL.toString() + "_FetchRegistry");
EurekaJerseyClientBuilder clientBuilder = new EurekaJerseyClientBuilder()
.withUserAgent("Java-EurekaClient-RemoteRegion")
.withEncoderWrapper(serverCodecs.getFullJsonCodec())
.withDecoderWrapper(serverCodecs.getFullJsonCodec())
.withConnectionTimeout(serverConfig.getRemoteRegionConnectTimeoutMs())
.withReadTimeout(serverConfig.getRemoteRegionReadTimeoutMs())
.withMaxConnectionsPerHost(serverConfig.getRemoteRegionTotalConnectionsPerHost())
.withMaxTotalConnections(serverConfig.getRemoteRegionTotalConnections())
.withConnectionIdleTimeout(serverConfig.getRemoteRegionConnectionIdleTimeoutSeconds());
if (remoteRegionURL.getProtocol().equals("http")) {
clientBuilder.withClientName("Discovery-RemoteRegionClient-" + regionName);
} else if ("true".equals(System.getProperty("com.netflix.eureka.shouldSSLConnectionsUseSystemSocketFactory"))) {
clientBuilder.withClientName("Discovery-RemoteRegionSystemSecureClient-" + regionName)
.withSystemSSLConfiguration();
} else {
clientBuilder.withClientName("Discovery-RemoteRegionSecureClient-" + regionName)
.withTrustStoreFile(
serverConfig.getRemoteRegionTrustStore(),
serverConfig.getRemoteRegionTrustStorePassword()
);
}
discoveryJerseyClient = clientBuilder.build();
discoveryApacheClient = discoveryJerseyClient.getClient();
// should we enable GZip decoding of responses based on Response Headers?
if (serverConfig.shouldGZipContentFromRemoteRegion()) {
// compressed only if there exists a 'Content-Encoding' header whose value is "gzip"
discoveryApacheClient.addFilter(new GZIPContentEncodingFilter(false));
}
String ip = null;
try {
ip = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
logger.warn("Cannot find localhost ip", e);
}
EurekaServerIdentity identity = new EurekaServerIdentity(ip);
discoveryApacheClient.addFilter(new EurekaIdentityHeaderFilter(identity));
// Configure new transport layer (candidate for injecting in the future)
EurekaHttpClient newEurekaHttpClient = null;
try {
ClusterResolver clusterResolver = StaticClusterResolver.fromURL(regionName, remoteRegionURL);
newEurekaHttpClient = EurekaServerHttpClients.createRemoteRegionClient(
serverConfig, clientConfig.getTransportConfig(), serverCodecs, clusterResolver);
} catch (Exception e) {
logger.warn("Transport initialization failure", e);
}
this.eurekaHttpClient = newEurekaHttpClient;
try {
if (fetchRegistry()) {
this.readyForServingData = true;
} else {
logger.warn("Failed to fetch remote registry. This means this eureka server is not ready for serving "
+ "traffic.");
}
} catch (Throwable e) {
logger.error("Problem fetching registry information :", e);
}
// remote region fetch
Runnable remoteRegionFetchTask = new Runnable() {
@Override
public void run() {
try {
if (fetchRegistry()) {
readyForServingData = true;
} else {
logger.warn("Failed to fetch remote registry. This means this eureka server is not "
+ "ready for serving traffic.");
}
} catch (Throwable e) {
logger.error(
"Error getting from remote registry :", e);
}
}
};
ThreadPoolExecutor remoteRegionFetchExecutor = new ThreadPoolExecutor(
1, serverConfig.getRemoteRegionFetchThreadPoolSize(), 0, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); // use direct handoff
scheduler = Executors.newScheduledThreadPool(1,
new ThreadFactoryBuilder()
.setNameFormat("Eureka-RemoteRegionCacheRefresher_" + regionName + "-%d")
.setDaemon(true)
.build());
scheduler.schedule(
new TimedSupervisorTask(
"RemoteRegionFetch_" + regionName,
scheduler,
remoteRegionFetchExecutor,
serverConfig.getRemoteRegionRegistryFetchInterval(),
TimeUnit.SECONDS,
5, // exponential backoff bound
remoteRegionFetchTask
),
serverConfig.getRemoteRegionRegistryFetchInterval(), TimeUnit.SECONDS);
try {
Monitors.registerObject(this);
} catch (Throwable e) {
logger.warn("Cannot register the JMX monitor for the RemoteRegionRegistry :", e);
}
}
/**
* Check if this registry is ready for serving data.
* @return true if ready, false otherwise.
*/
public boolean isReadyForServingData() {
return readyForServingData;
}
/**
* Fetch the registry information from the remote region.
* @return true, if the fetch was successful, false otherwise.
*/
private boolean fetchRegistry() {
boolean success;
Stopwatch tracer = fetchRegistryTimer.start();
try {
// If the delta is disabled or if it is the first time, get all applications
if (serverConfig.shouldDisableDeltaForRemoteRegions()
|| (getApplications() == null)
|| (getApplications().getRegisteredApplications().size() == 0)) {
logger.info("Disable delta property : {}", serverConfig.shouldDisableDeltaForRemoteRegions());
logger.info("Application is null : {}", getApplications() == null);
logger.info("Registered Applications size is zero : {}", getApplications().getRegisteredApplications().isEmpty());
success = storeFullRegistry();
} else {
success = fetchAndStoreDelta();
}
logTotalInstances();
} catch (Throwable e) {
logger.error("Unable to fetch registry information from the remote registry {}", this.remoteRegionURL, e);
return false;
} finally {
if (tracer != null) {
tracer.stop();
}
}
if (success) {
timeOfLastSuccessfulRemoteFetch = System.currentTimeMillis();
}
return success;
}
private boolean fetchAndStoreDelta() throws Throwable {
long currGeneration = fetchRegistryGeneration.get();
Applications delta = fetchRemoteRegistry(true);
if (delta == null) {
logger.error("The delta is null for some reason. Not storing this information");
} else if (fetchRegistryGeneration.compareAndSet(currGeneration, currGeneration + 1)) {
this.applicationsDelta.set(delta);
} else {
delta = null; // set the delta to null so we don't use it
logger.warn("Not updating delta as another thread is updating it already");
}
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.");
return storeFullRegistry();
} else {
String reconcileHashCode = "";
if (fetchRegistryUpdateLock.tryLock()) {
try {
updateDelta(delta);
reconcileHashCode = getApplications().getReconcileHashCode();
} finally {
fetchRegistryUpdateLock.unlock();
}
} else {
logger.warn("Cannot acquire update lock, aborting updateDelta operation of fetchAndStoreDelta");
}
// There is a diff in number of instances for some reason
if (!reconcileHashCode.equals(delta.getAppsHashCode())) {
deltaMismatches++;
return reconcileAndLogDifference(delta, reconcileHashCode);
} else {
deltaSuccesses++;
}
}
return delta != null;
}
/**
* 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()) {
++deltaCount;
if (ActionType.ADDED.equals(instance.getActionType())) {
Application existingApp = getApplications()
.getRegisteredApplications(instance.getAppName());
if (existingApp == null) {
getApplications().addApplication(app);
}
logger.debug("Added instance {} to the existing apps ",
instance.getId());
getApplications().getRegisteredApplications(
instance.getAppName()).addInstance(instance);
} else if (ActionType.MODIFIED.equals(instance.getActionType())) {
Application existingApp = getApplications()
.getRegisteredApplications(instance.getAppName());
if (existingApp == null) {
getApplications().addApplication(app);
}
logger.debug("Modified instance {} to the existing apps ",
instance.getId());
getApplications().getRegisteredApplications(
instance.getAppName()).addInstance(instance);
} else if (ActionType.DELETED.equals(instance.getActionType())) {
Application existingApp = getApplications()
.getRegisteredApplications(instance.getAppName());
if (existingApp == null) {
getApplications().addApplication(app);
}
logger.debug("Deleted instance {} to the existing apps ",
instance.getId());
getApplications().getRegisteredApplications(
instance.getAppName()).removeInstance(instance);
}
}
}
logger.debug(
"The total number of instances fetched by the delta processor : {}",
deltaCount);
}
/**
* Close HTTP response object and its respective resources.
*
* @param response
* the HttpResponse object.
*/
private void closeResponse(ClientResponse response) {
if (response != null) {
try {
response.close();
} catch (Throwable th) {
logger.error("Cannot release response resource :", th);
}
}
}
/**
* Gets the full registry information from the eureka server and stores it
* locally.
*
* @return the full registry information.
*/
public boolean storeFullRegistry() {
long currentGeneration = fetchRegistryGeneration.get();
Applications apps = fetchRemoteRegistry(false);
if (apps == null) {
logger.error("The application is null for some reason. Not storing this information");
} else if (fetchRegistryGeneration.compareAndSet(currentGeneration, currentGeneration + 1)) {
applications.set(apps);
applicationsDelta.set(apps);
logger.info("Successfully updated registry with the latest content");
return true;
} else {
logger.warn("Not updating applications as another thread is updating it already");
}
return false;
}
/**
* Fetch registry information from the remote region.
* @param delta - true, if the fetch needs to get deltas, false otherwise
* @return - response which has information about the data.
*/
private Applications fetchRemoteRegistry(boolean delta) {
logger.info("Getting instance registry info from the eureka server : {} , delta : {}", this.remoteRegionURL, delta);
if (shouldUseExperimentalTransport()) {
try {
EurekaHttpResponse<Applications> httpResponse = delta ? eurekaHttpClient.getDelta() : eurekaHttpClient.getApplications();
int httpStatus = httpResponse.getStatusCode();
if (httpStatus >= 200 && httpStatus < 300) {
logger.debug("Got the data successfully : {}", httpStatus);
return httpResponse.getEntity();
}
logger.warn("Cannot get the data from {} : {}", this.remoteRegionURL, httpStatus);
} catch (Throwable t) {
logger.error("Can't get a response from {}", this.remoteRegionURL, t);
}
} else {
ClientResponse response = null;
try {
String urlPath = delta ? "apps/delta" : "apps/";
response = discoveryApacheClient.resource(this.remoteRegionURL + urlPath)
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(ClientResponse.class);
int httpStatus = response.getStatus();
if (httpStatus >= 200 && httpStatus < 300) {
logger.debug("Got the data successfully : {}", httpStatus);
return response.getEntity(Applications.class);
}
logger.warn("Cannot get the data from {} : {}", this.remoteRegionURL, httpStatus);
} catch (Throwable t) {
logger.error("Can't get a response from {}", this.remoteRegionURL, t);
} finally {
closeResponse(response);
}
}
return null;
}
/**
* Reconciles the delta information fetched to see if the hashcodes match.
*
* @param delta - the delta information fetched previously for reconciliation.
* @param reconcileHashCode - the hashcode for comparison.
* @return - response
* @throws Throwable
*/
private boolean reconcileAndLogDifference(Applications delta, String reconcileHashCode) throws Throwable {
logger.warn("The Reconcile hashcodes do not match, client : {}, server : {}. Getting the full registry",
reconcileHashCode, delta.getAppsHashCode());
long currentGeneration = fetchRegistryGeneration.get();
Applications apps = this.fetchRemoteRegistry(false);
if (apps == null) {
logger.error("The application is null for some reason. Not storing this information");
return false;
}
if (fetchRegistryGeneration.compareAndSet(currentGeneration, currentGeneration + 1)) {
applications.set(apps);
applicationsDelta.set(apps);
logger.warn("The Reconcile hashcodes after complete sync up, client : {}, server : {}.",
getApplications().getReconcileHashCode(),
delta.getAppsHashCode());
return true;
}else {
logger.warn("Not setting the applications map as another thread has advanced the update generation");
return true; // still return true
}
}
/**
* Logs the total number of non-filtered instances stored locally.
*/
private void logTotalInstances() {
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);
}
@Override
public Applications getApplications() {
return applications.get();
}
@Override
public InstanceInfo getNextServerFromEureka(String arg0, boolean arg1) {
return null;
}
@Override
public Application getApplication(String appName) {
return this.applications.get().getRegisteredApplications(appName);
}
@Override
public List<InstanceInfo> getInstancesById(String id) {
List<InstanceInfo> list = new ArrayList<>(1);
for (Application app : applications.get().getRegisteredApplications()) {
InstanceInfo info = app.getByInstanceId(id);
if (info != null) {
list.add(info);
return list;
}
}
return Collections.emptyList();
}
public Applications getApplicationDeltas() {
return this.applicationsDelta.get();
}
private boolean shouldUseExperimentalTransport() {
if (eurekaHttpClient == null) {
return false;
}
String enabled = serverConfig.getExperimental("transport.enabled");
return enabled != null && "true".equalsIgnoreCase(enabled);
}
@com.netflix.servo.annotations.Monitor(name = METRIC_REGISTRY_PREFIX + "secondsSinceLastSuccessfulRemoteFetch", type = DataSourceType.GAUGE)
public long getTimeOfLastSuccessfulRemoteFetch() {
return (System.currentTimeMillis() - timeOfLastSuccessfulRemoteFetch) / 1000;
}
@com.netflix.servo.annotations.Monitor(name = METRIC_REGISTRY_PREFIX + "remoteDeltaSuccesses", type = DataSourceType.COUNTER)
public long getRemoteFetchSuccesses() {
return deltaSuccesses;
}
@com.netflix.servo.annotations.Monitor(name = METRIC_REGISTRY_PREFIX + "remoteDeltaMismatches", type = DataSourceType.COUNTER)
public long getRemoteFetchMismatches() {
return deltaMismatches;
}
}
| 8,197 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/registry/ResponseCache.java | package com.netflix.eureka.registry;
import javax.annotation.Nullable;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author David Liu
*/
public interface ResponseCache {
void invalidate(String appName, @Nullable String vipAddress, @Nullable String secureVipAddress);
AtomicLong getVersionDelta();
AtomicLong getVersionDeltaWithRegions();
/**
* Get the cached information about applications.
*
* <p>
* If the cached information is not available it is generated on the first
* request. After the first request, the information is then updated
* periodically by a background thread.
* </p>
*
* @param key the key for which the cached information needs to be obtained.
* @return payload which contains information about the applications.
*/
String get(Key key);
/**
* Get the compressed information about the applications.
*
* @param key the key for which the compressed cached information needs to be obtained.
* @return compressed payload which contains information about the applications.
*/
byte[] getGZIP(Key key);
/**
* Performs a shutdown of this cache by stopping internal threads and unregistering
* Servo monitors.
*/
void stop();
}
| 8,198 |
0 | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka | Create_ds/eureka/eureka-core/src/main/java/com/netflix/eureka/registry/PeerAwareInstanceRegistry.java | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.eureka.registry;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.shared.Application;
import com.netflix.eureka.cluster.PeerEurekaNodes;
import com.netflix.eureka.resources.ASGResource;
import java.util.List;
/**
* @author Tomasz Bak
*/
public interface PeerAwareInstanceRegistry extends InstanceRegistry {
void init(PeerEurekaNodes peerEurekaNodes) throws Exception;
/**
* Populates the registry information from a peer eureka node. This
* operation fails over to other nodes until the list is exhausted if the
* communication fails.
*/
int syncUp();
/**
* Checks to see if the registry access is allowed or the server is in a
* situation where it does not all getting registry information. The server
* does not return registry information for a period specified in
* {@link com.netflix.eureka.EurekaServerConfig#getWaitTimeInMsWhenSyncEmpty()}, if it cannot
* get the registry information from the peer eureka nodes at start up.
*
* @return false - if the instances count from a replica transfer returned
* zero and if the wait time has not elapsed, otherwise returns true
*/
boolean shouldAllowAccess(boolean remoteRegionRequired);
void register(InstanceInfo info, boolean isReplication);
void statusUpdate(final String asgName, final ASGResource.ASGStatus newStatus, final boolean isReplication);
}
| 8,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.